path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
ajax/libs/material-ui/4.9.3/es/Divider/Divider.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 '../styles/colorManipulator'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { height: 1, margin: 0, // Reset browser default style. border: 'none', flexShrink: 0, backgroundColor: theme.palette.divider }, /* Styles applied to the root element if `absolute={true}`. */ absolute: { position: 'absolute', bottom: 0, left: 0, width: '100%' }, /* Styles applied to the root element if `variant="inset"`. */ inset: { marginLeft: 72 }, /* Styles applied to the root element if `light={true}`. */ light: { backgroundColor: fade(theme.palette.divider, 0.08) }, /* Styles applied to the root element if `variant="middle"`. */ middle: { marginLeft: theme.spacing(2), marginRight: theme.spacing(2) }, /* Styles applied to the root element if `orientation="vertical"`. */ vertical: { height: '100%', width: 1 }, /* Styles applied to the root element if `flexItem={true}`. */ flexItem: { alignSelf: 'stretch', height: 'auto' } }); const Divider = React.forwardRef(function Divider(props, ref) { const { absolute = false, classes, className, component: Component = 'hr', flexItem = false, light = false, orientation = 'horizontal', role = Component !== 'hr' ? 'separator' : undefined, variant = 'fullWidth' } = props, other = _objectWithoutPropertiesLoose(props, ["absolute", "classes", "className", "component", "flexItem", "light", "orientation", "role", "variant"]); return React.createElement(Component, _extends({ className: clsx(classes.root, className, variant !== 'fullWidth' && classes[variant], absolute && classes.absolute, flexItem && classes.flexItem, light && classes.light, orientation === 'vertical' && classes.vertical), role: role, ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? Divider.propTypes = { /** * Absolutely position the element. */ absolute: PropTypes.bool, /** * 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`, a vertical divider will have the correct height when used in flex container. * (By default, a vertical divider will have a calculated height of `0px` if it is the child of a flex container.) */ flexItem: PropTypes.bool, /** * If `true`, the divider will have a lighter color. */ light: PropTypes.bool, /** * The divider orientation. */ orientation: PropTypes.oneOf(['horizontal', 'vertical']), /** * @ignore */ role: PropTypes.string, /** * The variant to use. */ variant: PropTypes.oneOf(['fullWidth', 'inset', 'middle']) } : void 0; export default withStyles(styles, { name: 'MuiDivider' })(Divider);
ajax/libs/react-native-web/0.11.7/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/primereact/6.5.0-rc.1/progressbar/progressbar.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); 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 ProgressBar = /*#__PURE__*/function (_Component) { _inherits(ProgressBar, _Component); var _super = _createSuper(ProgressBar); function ProgressBar() { _classCallCheck(this, ProgressBar); return _super.apply(this, arguments); } _createClass(ProgressBar, [{ key: "renderLabel", value: function renderLabel() { if (this.props.showValue && this.props.value != null) { var label = this.props.displayValueTemplate ? this.props.displayValueTemplate(this.props.value) : this.props.value + this.props.unit; return /*#__PURE__*/React.createElement("div", { className: "p-progressbar-label" }, label); } return null; } }, { key: "renderDeterminate", value: function renderDeterminate() { var className = classNames('p-progressbar p-component p-progressbar-determinate', this.props.className); var label = this.renderLabel(); return /*#__PURE__*/React.createElement("div", { role: "progressbar", id: this.props.id, className: className, style: this.props.style, "aria-valuemin": "0", "aria-valuenow": this.props.value, "aria-valuemax": "100", "aria-label": this.props.value }, /*#__PURE__*/React.createElement("div", { className: "p-progressbar-value p-progressbar-value-animate", style: { width: this.props.value + '%', display: 'block', backgroundColor: this.props.color } }), label); } }, { key: "renderIndeterminate", value: function renderIndeterminate() { var className = classNames('p-progressbar p-component p-progressbar-indeterminate', this.props.className); return /*#__PURE__*/React.createElement("div", { role: "progressbar", id: this.props.id, className: className, style: this.props.style }, /*#__PURE__*/React.createElement("div", { className: "p-progressbar-indeterminate-container" }, /*#__PURE__*/React.createElement("div", { className: "p-progressbar-value p-progressbar-value-animate", style: { backgroundColor: this.props.color } }))); } }, { key: "render", value: function render() { if (this.props.mode === 'determinate') return this.renderDeterminate();else if (this.props.mode === 'indeterminate') return this.renderIndeterminate();else throw new Error(this.props.mode + " is not a valid mode for the ProgressBar. Valid values are 'determinate' and 'indeterminate'"); } }]); return ProgressBar; }(Component); _defineProperty(ProgressBar, "defaultProps", { id: null, value: null, showValue: true, unit: '%', style: null, className: null, mode: 'determinate', displayValueTemplate: null, color: null }); _defineProperty(ProgressBar, "propTypes", { id: PropTypes.string, value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), showValue: PropTypes.bool, unit: PropTypes.string, style: PropTypes.object, className: PropTypes.string, mode: PropTypes.string, displayValueTemplate: PropTypes.func, color: PropTypes.string }); export { ProgressBar };
ajax/libs/react-native-web/0.13.17/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/7.0.0/badge/badge.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); 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 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 };
ajax/libs/react-instantsearch/6.0.0-beta.2/Dom.js
cdnjs/cdnjs
/*! React InstantSearch 6.0.0-beta.2 | © Algolia, inc. | https://github.com/algolia/react-instantsearch */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (global = global || self, factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Dom = {}), global.React)); }(this, function (exports, React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; 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 _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 _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 _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 _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 _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); } function _typeof(obj) { if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") { _typeof = function _typeof(obj) { return _typeof2(obj); }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(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 _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); } var isArray = Array.isArray; var keyList = Object.keys; var hasProp = Object.prototype.hasOwnProperty; var fastDeepEqual = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { var arrA = isArray(a) , arrB = isArray(b) , i , length , key; if (arrA && arrB) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!equal(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 = keyList(a); length = keys.length; if (length !== keyList(b).length) return false; for (i = length; i-- !== 0;) if (!hasProp.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { key = keys[i]; if (!equal(a[key], b[key])) return false; } return true; } return a!==a && b!==b; }; 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 isPlainObject = function isPlainObject(value) { return _typeof(value) === 'object' && value !== null && !Array.isArray(value); }; var removeEmptyKey = function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (!isPlainObject(value)) { return; } if (!objectHasKeys(value)) { delete obj[key]; } else { removeEmptyKey(value); } }); return obj; }; function addAbsolutePositions(hits, hitsPerPage, page) { return hits.map(function (hit, index) { return _objectSpread({}, hit, { __position: hitsPerPage * page + index + 1 }); }); } function addQueryID(hits, queryID) { if (!queryID) { return hits; } return hits.map(function (hit) { return _objectSpread({}, hit, { __queryID: queryID }); }); } function find(array, comparator) { if (!Array.isArray(array)) { return undefined; } for (var i = 0; i < array.length; i++) { if (comparator(array[i])) { return array[i]; } } return undefined; } function objectHasKeys(object) { return object && Object.keys(object).length > 0; } // https://github.com/babel/babel/blob/3aaafae053fa75febb3aa45d45b6f00646e30ba4/packages/babel-helpers/src/helpers.js#L604-L620 function omit(source, excluded) { if (source === null || source === undefined) { return {}; } var target = {}; var sourceKeys = Object.keys(source); for (var i = 0; i < sourceKeys.length; i++) { var _key = sourceKeys[i]; if (excluded.indexOf(_key) >= 0) { // eslint-disable-next-line no-continue continue; } target[_key] = source[_key]; } return target; } /** * Retrieve the value at a path of the object: * * @example * getPropertyByPath( * { test: { this: { function: [{ now: { everyone: true } }] } } }, * 'test.this.function[0].now.everyone' * ); // true * * getPropertyByPath( * { test: { this: { function: [{ now: { everyone: true } }] } } }, * ['test', 'this', 'function', 0, 'now', 'everyone'] * ); // true * * @param object Source object to query * @param path either an array of properties, or a string form of the properties, separated by . */ var getPropertyByPath = function getPropertyByPath(object, path) { return (Array.isArray(path) ? path : path.replace(/\[(\d+)]/g, '.$1').split('.')).reduce(function (current, key) { return current ? current[key] : undefined; }, object); }; var _createContext = React.createContext({ onInternalStateUpdate: function onInternalStateUpdate() { return undefined; }, createHrefForState: function createHrefForState() { return '#'; }, onSearchForFacetValues: function onSearchForFacetValues() { return undefined; }, onSearchStateChange: function onSearchStateChange() { return undefined; }, onSearchParameters: function onSearchParameters() { return undefined; }, store: {}, widgetsManager: {}, mainTargetedIndex: '' }), InstantSearchConsumer = _createContext.Consumer, InstantSearchProvider = _createContext.Provider; var _createContext2 = React.createContext(undefined), IndexConsumer = _createContext2.Consumer, IndexProvider = _createContext2.Provider; /** * 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 createConnectorWithoutContext(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var isWidget = typeof connectorDesc.getSearchParameters === 'function' || typeof connectorDesc.getMetadata === 'function' || typeof connectorDesc.transitionState === 'function'; return function (Composed) { var Connector = /*#__PURE__*/ function (_Component) { _inherits(Connector, _Component); function Connector(props) { var _this; _classCallCheck(this, Connector); _this = _possibleConstructorReturn(this, _getPrototypeOf(Connector).call(this, props)); _defineProperty(_assertThisInitialized(_this), "unsubscribe", void 0); _defineProperty(_assertThisInitialized(_this), "unregisterWidget", void 0); _defineProperty(_assertThisInitialized(_this), "isUnmounting", false); _defineProperty(_assertThisInitialized(_this), "state", { providedProps: _this.getProvidedProps(_this.props) }); _defineProperty(_assertThisInitialized(_this), "refine", function () { var _ref; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this.props.contextValue.onInternalStateUpdate( // refine will always be defined here because the prop is only given conditionally (_ref = connectorDesc.refine).call.apply(_ref, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args))); }); _defineProperty(_assertThisInitialized(_this), "createURL", function () { var _ref2; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return _this.props.contextValue.createHrefForState( // refine will always be defined here because the prop is only given conditionally (_ref2 = connectorDesc.refine).call.apply(_ref2, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args))); }); _defineProperty(_assertThisInitialized(_this), "searchForFacetValues", function () { var _ref3; for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } _this.props.contextValue.onSearchForFacetValues( // searchForFacetValues will always be defined here because the prop is only given conditionally (_ref3 = connectorDesc.searchForFacetValues).call.apply(_ref3, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args))); }); if (connectorDesc.getSearchParameters) { _this.props.contextValue.onSearchParameters(connectorDesc.getSearchParameters.bind(_assertThisInitialized(_this)), { ais: _this.props.contextValue, multiIndexContext: _this.props.indexContextValue }, _this.props); } return _this; } _createClass(Connector, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; this.unsubscribe = this.props.contextValue.store.subscribe(function () { if (!_this2.isUnmounting) { _this2.setState({ providedProps: _this2.getProvidedProps(_this2.props) }); } }); if (isWidget) { this.unregisterWidget = this.props.contextValue.widgetsManager.registerWidget(this); } } }, { key: "shouldComponentUpdate", value: function shouldComponentUpdate(nextProps, nextState) { if (typeof connectorDesc.shouldComponentUpdate === 'function') { return connectorDesc.shouldComponentUpdate.call(this, this.props, nextProps, this.state, nextState); } var propsEqual = shallowEqual(this.props, nextProps); if (this.state.providedProps === null || nextState.providedProps === null) { if (this.state.providedProps === nextState.providedProps) { return !propsEqual; } return true; } return !propsEqual || !shallowEqual(this.state.providedProps, nextState.providedProps); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (!fastDeepEqual(prevProps, this.props)) { this.setState({ providedProps: this.getProvidedProps(this.props) }); if (isWidget) { this.props.contextValue.widgetsManager.update(); if (typeof connectorDesc.transitionState === 'function') { this.props.contextValue.onSearchStateChange(connectorDesc.transitionState.call(this, this.props, this.props.contextValue.store.getState().widgets, this.props.contextValue.store.getState().widgets)); } } } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.isUnmounting = true; if (this.unsubscribe) { this.unsubscribe(); } if (this.unregisterWidget) { this.unregisterWidget(); if (typeof connectorDesc.cleanUp === 'function') { var nextState = connectorDesc.cleanUp.call(this, this.props, this.props.contextValue.store.getState().widgets); this.props.contextValue.store.setState(_objectSpread({}, this.props.contextValue.store.getState(), { widgets: nextState })); this.props.contextValue.onSearchStateChange(removeEmptyKey(nextState)); } } } }, { key: "getProvidedProps", value: function getProvidedProps(props) { var _this$props$contextVa = this.props.contextValue.store.getState(), widgets = _this$props$contextVa.widgets, results = _this$props$contextVa.results, resultsFacetValues = _this$props$contextVa.resultsFacetValues, searching = _this$props$contextVa.searching, searchingForFacetValues = _this$props$contextVa.searchingForFacetValues, isSearchStalled = _this$props$contextVa.isSearchStalled, metadata = _this$props$contextVa.metadata, error = _this$props$contextVa.error; var searchResults = { results: results, searching: searching, searchingForFacetValues: searchingForFacetValues, isSearchStalled: isSearchStalled, error: error }; return connectorDesc.getProvidedProps.call(this, props, widgets, searchResults, metadata, // @MAJOR: move this attribute on the `searchResults` it doesn't // makes sense to have it into a separate argument. The search // flags are on the object why not the results? resultsFacetValues); } }, { key: "getSearchParameters", value: function getSearchParameters(searchParameters) { if (typeof connectorDesc.getSearchParameters === 'function') { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.props.contextValue.store.getState().widgets); } return null; } }, { key: "getMetadata", value: function getMetadata(nextWidgetsState) { if (typeof connectorDesc.getMetadata === 'function') { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: "transitionState", value: function transitionState(prevWidgetsState, nextWidgetsState) { if (typeof connectorDesc.transitionState === 'function') { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { key: "render", value: function render() { var _this$props = this.props, contextValue = _this$props.contextValue, props = _objectWithoutProperties(_this$props, ["contextValue"]); var providedProps = this.state.providedProps; if (providedProps === null) { return null; } var refineProps = typeof connectorDesc.refine === 'function' ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = typeof connectorDesc.searchForFacetValues === 'function' ? { searchForItems: this.searchForFacetValues } : {}; return React__default.createElement(Composed, _extends({}, props, providedProps, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component); _defineProperty(Connector, "displayName", "".concat(connectorDesc.displayName, "(").concat(getDisplayName(Composed), ")")); _defineProperty(Connector, "propTypes", connectorDesc.propTypes); _defineProperty(Connector, "defaultProps", connectorDesc.defaultProps); return Connector; }; } var createConnectorWithContext = function createConnectorWithContext(connectorDesc) { return function (Composed) { var Connector = createConnectorWithoutContext(connectorDesc)(Composed); var ConnectorWrapper = function ConnectorWrapper(props) { return React__default.createElement(InstantSearchConsumer, null, function (contextValue) { return React__default.createElement(IndexConsumer, null, function (indexContextValue) { return React__default.createElement(Connector, _extends({ contextValue: contextValue, indexContextValue: indexContextValue }, props)); }); }); }; return ConnectorWrapper; }; }; 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, isHighlighted: boolean}. */ function parseHighlightedAttribute(_ref) { var preTag = _ref.preTag, postTag = _ref.postTag, _ref$highlightedValue = _ref.highlightedValue, highlightedValue = _ref$highlightedValue === void 0 ? '' : _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 * highlightPostTag 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 === void 0 ? '<em>' : _ref2$preTag, _ref2$postTag = _ref2.postTag, postTag = _ref2$postTag === void 0 ? '</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 = getPropertyByPath(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 version = '6.0.0-beta.2'; function translatable(defaultTranslations) { return function (Composed) { var Translatable = /*#__PURE__*/ function (_Component) { _inherits(Translatable, _Component); function Translatable() { var _getPrototypeOf2; var _this; _classCallCheck(this, Translatable); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Translatable)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "translate", function (key) { var translations = _this.props.translations; var translation = translations && translations.hasOwnProperty(key) ? translations[key] : defaultTranslations[key]; if (typeof translation === 'function') { for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { params[_key2 - 1] = arguments[_key2]; } return translation.apply(void 0, params); } return translation; }); return _this; } _createClass(Translatable, [{ key: "render", value: function render() { return React__default.createElement(Composed, _extends({ translate: this.translate }, this.props)); } }]); return Translatable; }(React.Component); var name = Composed.displayName || Composed.name || 'UnknownComponent'; Translatable.displayName = "Translatable(".concat(name, ")"); return Translatable; }; } function getIndexId(context) { return hasMultipleIndices(context) ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (searchResults.results) { if (searchResults.results.hits) { return searchResults.results; } var indexId = getIndexId(context); if (searchResults.results[indexId]) { return searchResults.results[indexId]; } } return null; } function hasMultipleIndices(context) { return context && context.multiIndexContext; } // eslint-disable-next-line max-params function refineValue(searchState, nextRefinement, context, resetPage, namespace) { if (hasMultipleIndices(context)) { var indexId = getIndexId(context); return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, indexId, 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, indexId, resetPage) { var page = resetPage ? { page: 1 } : undefined; var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], nextRefinement, page))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, nextRefinement, page))); return _objectSpread({}, searchState, { indices: state }); } function refineSingleIndex(searchState, nextRefinement, resetPage) { var page = resetPage ? { page: 1 } : undefined; return _objectSpread({}, searchState, nextRefinement, page); } // eslint-disable-next-line max-params function refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) { var _objectSpread4; var page = resetPage ? { page: 1 } : undefined; var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], (_objectSpread4 = {}, _defineProperty(_objectSpread4, namespace, _objectSpread({}, searchState.indices[indexId][namespace], nextRefinement)), _defineProperty(_objectSpread4, "page", 1), _objectSpread4)))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread(_defineProperty({}, namespace, nextRefinement), page))); return _objectSpread({}, searchState, { indices: state }); } function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) { var page = resetPage ? { page: 1 } : undefined; return _objectSpread({}, searchState, _defineProperty({}, namespace, _objectSpread({}, 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 }; } function hasRefinements(_ref) { var multiIndex = _ref.multiIndex, indexId = _ref.indexId, namespace = _ref.namespace, attributeName = _ref.attributeName, id = _ref.id, searchState = _ref.searchState; if (multiIndex && namespace) { return searchState.indices && searchState.indices[indexId] && searchState.indices[indexId][namespace] && Object.hasOwnProperty.call(searchState.indices[indexId][namespace], attributeName); } if (multiIndex) { return searchState.indices && searchState.indices[indexId] && Object.hasOwnProperty.call(searchState.indices[indexId], id); } if (namespace) { return searchState[namespace] && Object.hasOwnProperty.call(searchState[namespace], attributeName); } return Object.hasOwnProperty.call(searchState, id); } function getRefinements(_ref2) { var multiIndex = _ref2.multiIndex, indexId = _ref2.indexId, namespace = _ref2.namespace, attributeName = _ref2.attributeName, id = _ref2.id, searchState = _ref2.searchState; if (multiIndex && namespace) { return searchState.indices[indexId][namespace][attributeName]; } if (multiIndex) { return searchState.indices[indexId][id]; } if (namespace) { return searchState[namespace][attributeName]; } return searchState[id]; } function getCurrentRefinementValue(props, searchState, context, id, defaultValue) { var indexId = getIndexId(context); var _getNamespaceAndAttri = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri.namespace, attributeName = _getNamespaceAndAttri.attributeName; var multiIndex = hasMultipleIndices(context); var args = { multiIndex: multiIndex, indexId: indexId, namespace: namespace, attributeName: attributeName, id: id, searchState: searchState }; var hasRefinementsValue = hasRefinements(args); if (hasRefinementsValue) { return getRefinements(args); } if (props.defaultRefinement) { return props.defaultRefinement; } return defaultValue; } function cleanUpValue(searchState, context, id) { var indexId = getIndexId(context); var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri2.namespace, attributeName = _getNamespaceAndAttri2.attributeName; if (hasMultipleIndices(context) && Boolean(searchState.indices)) { return cleanUpValueWithMultiIndex({ attribute: attributeName, searchState: searchState, indexId: indexId, id: id, namespace: namespace }); } return cleanUpValueWithSingleIndex({ attribute: attributeName, searchState: searchState, id: id, namespace: namespace }); } function cleanUpValueWithSingleIndex(_ref3) { var searchState = _ref3.searchState, id = _ref3.id, namespace = _ref3.namespace, attribute = _ref3.attribute; if (namespace) { return _objectSpread({}, searchState, _defineProperty({}, namespace, omit(searchState[namespace], [attribute]))); } return omit(searchState, [id]); } function cleanUpValueWithMultiIndex(_ref4) { var searchState = _ref4.searchState, indexId = _ref4.indexId, id = _ref4.id, namespace = _ref4.namespace, attribute = _ref4.attribute; var indexSearchState = searchState.indices[indexId]; if (namespace && indexSearchState) { return _objectSpread({}, searchState, { indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, indexSearchState, _defineProperty({}, namespace, omit(indexSearchState[namespace], [attribute]))))) }); } if (indexSearchState) { return _objectSpread({}, searchState, { indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, omit(indexSearchState, [id]))) }); } return searchState; } function getId() { return 'configure'; } var connectConfigure = createConnectorWithContext({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var children = props.children, contextValue = props.contextValue, indexContextValue = props.indexContextValue, items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var children = props.children, contextValue = props.contextValue, indexContextValue = props.indexContextValue, items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]); var propKeys = Object.keys(props); var nonPresentKeys = this._props ? Object.keys(this._props).filter(function (prop) { return propKeys.indexOf(prop) === -1; }) : []; this._props = props; var nextValue = _defineProperty({}, id, _objectSpread({}, omit(nextSearchState[id], nonPresentKeys), items)); return refineValue(nextSearchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var indexId = getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }); var subState = hasMultipleIndices({ ais: props.contextValue, multiIndexContext: props.indexContextValue }) && searchState.indices ? searchState.indices[indexId] : 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({}, id, configureState); return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); /** * 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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Configure, Hits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Configure hitsPerPage={5} /> * <Hits /> * </InstantSearch> * ); */ var Configure = connectConfigure(function Configure() { return null; }); var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); if (typeof global$1.setTimeout === 'function') ; if (typeof global$1.clearTimeout === 'function') ; // 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() }; function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /* 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; function emptyFunction() {} var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret_1) { // 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, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; 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(); } }); function getIndexContext(props) { return { targetedIndex: props.indexId }; } /** * 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. * * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Index, SearchBox, Hits, Configure } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Configure hitsPerPage={5} /> * <SearchBox /> * <Index indexName="instant_search"> * <Hits /> * </Index> * <Index indexName="bestbuy"> * <Hits /> * </Index> * </InstantSearch> * ); */ var Index = /*#__PURE__*/ function (_Component) { _inherits(Index, _Component); _createClass(Index, null, [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(props) { return { indexContext: getIndexContext(props) }; } }]); function Index(props) { var _this; _classCallCheck(this, Index); _this = _possibleConstructorReturn(this, _getPrototypeOf(Index).call(this, props)); _defineProperty(_assertThisInitialized(_this), "state", { indexContext: getIndexContext(_this.props) }); _defineProperty(_assertThisInitialized(_this), "unregisterWidget", void 0); _this.props.contextValue.onSearchParameters(_this.getSearchParameters.bind(_assertThisInitialized(_this)), { ais: _this.props.contextValue, multiIndexContext: _this.state.indexContext }, _this.props); return _this; } _createClass(Index, [{ key: "componentDidMount", value: function componentDidMount() { this.unregisterWidget = this.props.contextValue.widgetsManager.registerWidget(this); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props.indexName !== prevProps.indexName) { this.props.contextValue.widgetsManager.update(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (typeof this.unregisterWidget === 'function') { this.unregisterWidget(); } } }, { 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); if (childrenCount === 0) { return null; } return React__default.createElement(IndexProvider, { value: this.state.indexContext }, this.props.children); } }]); return Index; }(React.Component); _defineProperty(Index, "propTypes", { indexName: propTypes.string.isRequired, indexId: propTypes.string.isRequired, children: propTypes.node }); var IndexWrapper = function IndexWrapper(props) { var inferredIndexId = props.indexName; return React__default.createElement(InstantSearchConsumer, null, function (contextValue) { return React__default.createElement(Index, _extends({ contextValue: contextValue, indexId: inferredIndexId }, props)); }); }; function clone(value) { if (_typeof(value) === 'object' && value !== null) { return _merge(Array.isArray(value) ? [] : {}, value); } return value; } function isObjectOrArrayOrFunction(value) { return typeof value === 'function' || Array.isArray(value) || Object.prototype.toString.call(value) === '[object Object]'; } function _merge(target, source) { if (target === source) { return target; } for (var key in source) { if (!Object.prototype.hasOwnProperty.call(source, key)) { continue; } var sourceVal = source[key]; var targetVal = target[key]; if (typeof targetVal !== 'undefined' && typeof sourceVal === 'undefined') { continue; } if (isObjectOrArrayOrFunction(targetVal) && isObjectOrArrayOrFunction(sourceVal)) { target[key] = _merge(targetVal, sourceVal); } else { target[key] = clone(sourceVal); } } return target; } /** * This method is like Object.assign, but recursively merges own and inherited * enumerable keyed properties of source objects into the destination object. * * NOTE: this behaves like lodash/merge, but: * - does mutate functions if they are a source * - treats non-plain objects as plain * - does not work for circular objects * - treats sparse arrays as sparse * - does not convert Array-like objects (Arguments, NodeLists, etc.) to arrays * * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. */ function merge(target) { if (!isObjectOrArrayOrFunction(target)) { target = {}; } for (var i = 1, l = arguments.length; i < l; i++) { var source = arguments[i]; if (isObjectOrArrayOrFunction(source)) { _merge(target, source); } } return target; } module.exports = merge; var merge$1 = /*#__PURE__*/Object.freeze({ }); var defaultsPure = function defaultsPure() { var sources = Array.prototype.slice.call(arguments); return sources.reduceRight(function (acc, source) { Object.keys(Object(source)).forEach(function (key) { if (source[key] !== undefined) { acc[key] = source[key]; } }); return acc; }, {}); }; function intersection(arr1, arr2) { return arr1.filter(function (value, index) { return arr2.indexOf(value) > -1 && arr1.indexOf(value) === index /* skips duplicates */ ; }); } var intersection_1 = intersection; var find$1 = function find(array, comparator) { if (!Array.isArray(array)) { return undefined; } for (var i = 0; i < array.length; i++) { if (comparator(array[i])) { return array[i]; } } }; function valToNumber(v) { if (typeof v === 'number') { return v; } else if (typeof v === 'string') { return parseFloat(v); } else if (Array.isArray(v)) { return v.map(valToNumber); } throw new Error('The value should be a number, a parsable string or an array of those.'); } var valToNumber_1 = valToNumber; function _objectWithoutPropertiesLoose$1(source, excluded) { if (source === null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key; var i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var omit$1 = _objectWithoutPropertiesLoose$1; function objectHasKeys$1(obj) { return obj && Object.keys(obj).length > 0; } var objectHasKeys_1 = objectHasKeys$1; /** * 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 defaultsPure({}, 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 (value === undefined) { // we use the "filter" form of clearRefinement, since it leaves empty values as-is // the form with a string will remove the attribute completely return lib.clearRefinement(refinementList, function (v, f) { return attribute === f; }); } 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 (value === undefined) 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 (attribute === undefined) { if (!objectHasKeys_1(refinementList)) { return refinementList; } return {}; } else if (typeof attribute === 'string') { if (!(refinementList[attribute] && refinementList[attribute].length > 0)) { return refinementList; } return omit$1(refinementList, attribute); } else if (typeof attribute === 'function') { var hasChanged = false; var newRefinementList = Object.keys(refinementList).reduce(function (memo, key) { var values = refinementList[key] || []; var facetList = values.filter(function (value) { return !attribute(value, key, refinementType); }); if (facetList.length !== values.length) { hasChanged = true; } memo[key] = facetList; 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 containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (refinementValue === undefined || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return refinementList[attribute].indexOf(refinementValueAsString) !== -1; } }; var RefinementList = lib; /** * isEqual, but only for numeric refinement values, possible values: * - 5 * - [5] * - [[5]] * - [[5,5],[4]] */ function isEqualNumericRefinement(a, b) { if (Array.isArray(a) && Array.isArray(b)) { return a.length === b.length && a.every(function (el, i) { return isEqualNumericRefinement(b[i], el); }); } return a === b; } /** * like _.find but using deep equality to be able to use it * to find arrays. * @private * @param {any[]} array array to search into (elements are base or array of base) * @param {any} searchedValue the value we're looking for (base or array of base) * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find$1(array, function (currentValue) { return isEqualNumericRefinement(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) : {}; /** * 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 || {}; var self = this; Object.keys(params).forEach(function (paramName) { var isKeyKnown = SearchParameters.PARAMETERS.indexOf(paramName) !== -1; var isValueDefined = params[paramName] !== undefined; if (!isKeyKnown && isValueDefined) { self[paramName] = params[paramName]; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = Object.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']; numberKeys.forEach(function (k) { var value = partialState[k]; if (typeof value === 'string') { var parsedValue = parseFloat(value); // global isNaN is ok to use here, value is only number or NaN 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 = {}; Object.keys(partialState.numericRefinements).forEach(function (attribute) { var operators = partialState.numericRefinements[attribute] || {}; numericRefinements[attribute] = {}; Object.keys(operators).forEach(function (operator) { var values = operators[operator]; var parsedValues = values.map(function (v) { if (Array.isArray(v)) { return v.map(function (vPrime) { if (typeof vPrime === 'string') { return parseFloat(vPrime); } return vPrime; }); } else if (typeof v === 'string') { 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); var hierarchicalFacets = newParameters.hierarchicalFacets || []; hierarchicalFacets.forEach(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 && objectHasKeys_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 (objectHasKeys_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 addNumericRefinement(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 getConjunctiveRefinements(facetName) { if (!this.isConjunctiveFacet(facetName)) { return []; } 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 getDisjunctiveRefinements(facetName) { if (!this.isDisjunctiveFacet(facetName)) { return []; } 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 getHierarchicalRefinement(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 getExcludeRefinements(facetName) { if (!this.isConjunctiveFacet(facetName)) { return []; } 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 removeNumericRefinement(attribute, operator, paramValue) { if (paramValue !== undefined) { if (!this.isNumericRefined(attribute, operator, paramValue)) { return this; } return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function (value, key) { return key === attribute && value.op === operator && isEqualNumericRefinement(value.val, valToNumber_1(paramValue)); }) }); } 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 getNumericRefinements(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 getNumericRefinement(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 (attribute === undefined) { if (!objectHasKeys_1(this.numericRefinements)) { return this.numericRefinements; } return {}; } else if (typeof attribute === 'string') { if (!objectHasKeys_1(this.numericRefinements[attribute])) { return this.numericRefinements; } return omit$1(this.numericRefinements, attribute); } else if (typeof attribute === 'function') { var hasChanged = false; var numericRefinements = this.numericRefinements; var newNumericRefinements = Object.keys(numericRefinements).reduce(function (memo, key) { var operators = numericRefinements[key]; var operatorList = {}; operators = operators || {}; Object.keys(operators).forEach(function (operator) { var values = operators[operator] || []; var outValues = []; values.forEach(function (value) { var predicateResult = attribute({ val: value, op: operator }, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (outValues.length !== values.length) { hasChanged = true; } operatorList[operator] = outValues; }); 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: this.facets.filter(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: this.disjunctiveFacets.filter(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: this.hierarchicalFacets.filter(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: this.tagRefinements.filter(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: defaultsPure({}, 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 addHierarchicalFacetRefinement(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } if (!this.isHierarchicalFacet(facet)) { throw new Error(facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaultsPure({}, 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 removeHierarchicalFacetRefinement(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaultsPure({}, 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 isDisjunctiveFacet(facet) { return this.disjunctiveFacets.indexOf(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 isHierarchicalFacet(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 isConjunctiveFacet(facet) { return this.facets.indexOf(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)) { return false; } 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)) { return false; } 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)) { return false; } 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)) { return false; } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return refinements.indexOf(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 (value === undefined && operator === undefined) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && this.numericRefinements[attribute][operator] !== undefined; if (value === undefined || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber_1(value); var isAttributeValueDefined = findArray(this.numericRefinements[attribute][operator], parsedValue) !== undefined; 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 this.tagRefinements.indexOf(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() { var self = this; // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection_1(Object.keys(this.numericRefinements).filter(function (facet) { return Object.keys(self.numericRefinements[facet]).length > 0; }), this.disjunctiveFacets); return Object.keys(this.disjunctiveFacetsRefinements).filter(function (facet) { return self.disjunctiveFacetsRefinements[facet].length > 0; }).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() { var self = this; return intersection_1( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index this.hierarchicalFacets.map(function (facet) { return facet.name; }), Object.keys(this.hierarchicalFacetsRefinements).filter(function (facet) { return self.hierarchicalFacetsRefinements[facet].length > 0; })); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function getUnrefinedDisjunctiveFacets() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return this.disjunctiveFacets.filter(function (f) { return refinedFacets.indexOf(f) === -1; }); }, managedParameters: ['index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; var self = this; Object.keys(this).forEach(function (paramName) { var paramValue = self[paramName]; if (managedParameters.indexOf(paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * 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 self = this; var nextWithNumbers = SearchParameters._parseNumbers(params); var previousPlainObject = Object.keys(this).reduce(function (acc, key) { acc[key] = self[key]; return acc; }, {}); var nextPlainObject = Object.keys(nextWithNumbers).reduce(function (previous, key) { var isPreviousValueDefined = previous[key] !== undefined; var isNextValueDefined = nextWithNumbers[key] !== undefined; if (isPreviousValueDefined && !isNextValueDefined) { return omit$1(previous, [key]); } if (isNextValueDefined) { previous[key] = nextWithNumbers[key]; } return previous; }, previousPlainObject); return new this.constructor(nextPlainObject); }, /** * Returns a new instance with the page reset. Two scenarios possible: * the page is omitted -> return the given instance * the page is set -> return a new instance with a page of 0 * @return {SearchParameters} a new updated instance */ resetPage: function resetPage() { if (this.page === undefined) { return this; } return this.setPage(0); }, /** * 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 _getHierarchicalFacetSortBy(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 _getHierarchicalFacetSeparator(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 _getHierarchicalRootPath(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 _getHierarchicalShowParentLevel(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 getHierarchicalFacetByName(hierarchicalFacetName) { return find$1(this.hierarchicalFacets, function (f) { return f.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 getHierarchicalFacetBreadcrumb(facetName) { if (!this.isHierarchicalFacet(facetName)) { return []; } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facetName)); var path = refinement.split(separator); return path.map(function (part) { return part.trim(); }); }, toString: function toString() { 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; function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined; var valIsNull = value === null; var othIsDefined = other !== undefined; var othIsNull = other === null; if (!othIsNull && value > other || valIsNull && othIsDefined || !valIsDefined) { return 1; } if (!valIsNull && value < other || othIsNull && valIsDefined || !othIsDefined) { return -1; } } return 0; } /** * @param {Array<object>} collection object with keys in attributes * @param {Array<string>} iteratees attributes * @param {Array<string>} orders asc | desc */ function orderBy(collection, iteratees, orders) { if (!Array.isArray(collection)) { return []; } if (!Array.isArray(orders)) { orders = []; } var result = collection.map(function (value, index) { return { criteria: iteratees.map(function (iteratee) { return value[iteratee]; }), index: index, value: value }; }); result.sort(function comparer(object, other) { var index = -1; while (++index < object.criteria.length) { var res = compareAscending(object.criteria[index], other.criteria[index]); if (res) { if (index >= orders.length) { return res; } if (orders[index] === 'desc') { return -res; } return res; } } // This 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; }); return result.map(function (res) { return res.value; }); } var orderBy_1 = orderBy; var compact = function compact(array) { if (!Array.isArray(array)) { return []; } return array.filter(Boolean); }; var findIndex = function find(array, comparator) { if (!Array.isArray(array)) { return -1; } for (var i = 0; i < array.length; i++) { if (comparator(array[i])) { return i; } } return -1; }; /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @param {string[]} [defaults] array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ var formatSort = function formatSort(sortBy, defaults) { var defaultInstructions = (defaults || []).map(function (sort) { return sort.split(':'); }); return sortBy.reduce(function preparePredicate(out, sort) { var sortInstruction = sort.split(':'); var matchingDefault = find$1(defaultInstructions, function (defaultInstruction) { return defaultInstruction[0] === sortInstruction[0]; }); if (sortInstruction.length > 1 || !matchingDefault) { out[0].push(sortInstruction[0]); out[1].push(sortInstruction[1]); return out; } out[0].push(matchingDefault[0]); out[1].push(matchingDefault[1]); return out; }, [[], []]); }; 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 rootExhaustive = hierarchicalFacetResult.every(function (facetResult) { return facetResult.exhaustive; }); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return results.reduce(generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path exhaustive: rootExhaustive, 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) { /** * @type {object[]]} hierarchical data */ var data = parent && Array.isArray(parent.data) ? parent.data : []; parent = find$1(data, function (subtree) { return subtree.isRefined; }); 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 picked = Object.keys(hierarchicalFacetResult.data).map(function (facetValue) { return [facetValue, hierarchicalFacetResult.data[facetValue]]; }).filter(function (tuple) { var facetValue = tuple[0]; return onlyMatchingTree(facetValue, parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); }); parent.data = orderBy_1(picked.map(function (tuple) { var facetValue = tuple[0]; var facetCount = tuple[1]; return format(facetCount, facetValue, hierarchicalSeparator, currentRefinement, hierarchicalFacetResult.exhaustive); }), sortBy[0], sortBy[1]); } return hierarchicalTree; }; } function onlyMatchingTree(facetValue, parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { // 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 format(facetCount, facetValue, hierarchicalSeparator, currentRefinement, exhaustive) { var parts = facetValue.split(hierarchicalSeparator); return { name: parts[parts.length - 1].trim(), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, exhaustive: exhaustive, 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 */ /** * @param {string[]} attributes */ function getIndices(attributes) { var indices = {}; attributes.forEach(function (val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } /** * @typedef {Object} HierarchicalFacet * @property {string} name * @property {string[]} attributes */ /** * @param {HierarchicalFacet[]} hierarchicalFacets * @param {string} hierarchicalAttributeName */ function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find$1(hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { var facetNames = hierarchicalFacet.attributes || []; return facetNames.indexOf(hierarchicalAttributeName) > -1; }); } /*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 = results.reduce(function (sum, result) { return result.processingTimeMS === undefined ? sum : sum + result.processingTimeMS; }, 0); /** * 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. * * getRankingInfo needs to be set to `true` for this to be returned * * @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 = state.hierarchicalFacets.map(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 information from the first, general, response. var mainFacets = mainSubResponse.facets || {}; Object.keys(mainFacets).forEach(function (facetKey) { var facetValueObject = mainFacets[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, function (f) { return f.name === hierarchicalFacet.name; }); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = state.disjunctiveFacets.indexOf(facetKey) !== -1; var isFacetConjunctive = state.facets.indexOf(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 disjunctiveFacets.forEach(function (disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var facets = result && result.facets ? result.facets : {}; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. Object.keys(facets).forEach(function (dfacet) { var facetResults = facets[dfacet]; var position; if (hierarchicalFacet) { position = findIndex(state.hierarchicalFacets, function (f) { return f.name === hierarchicalFacet.name; }); var attributeIndex = findIndex(self.hierarchicalFacets[position], function (f) { return f.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: defaultsPure({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { state.disjunctiveFacetsRefinements[dfacet].forEach(function (refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && state.disjunctiveFacetsRefinements[dfacet].indexOf(refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them state.getRefinedHierarchicalFacets().forEach(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]; var facets = result && result.facets ? result.facets : {}; Object.keys(facets).forEach(function (dfacet) { var facetResults = facets[dfacet]; var position = findIndex(state.hierarchicalFacets, function (f) { return f.name === hierarchicalFacet.name; }); var attributeIndex = findIndex(self.hierarchicalFacets[position], function (f) { return f.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 = defaultsPure(defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data); }); nextDisjunctiveResult++; }); // add the excludes Object.keys(state.facetsExcludes).forEach(function (facetName) { var excludes = state.facetsExcludes[facetName]; var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; excludes.forEach(function (facetValue) { self.facets[position] = self.facets[position] || { name: facetName }; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); /** * @type {Array} */ this.hierarchicalFacets = this.hierarchicalFacets.map(generateHierarchicalTree_1(state)); /** * @type {Array} */ this.facets = compact(this.facets); /** * @type {Array} */ this.disjunctiveFacets = compact(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) { function predicate(facet) { return facet.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) { function predicate(facet) { return facet.name === attribute; } if (results._state.isConjunctiveFacet(attribute)) { var facet = find$1(results.facets, predicate); if (!facet) return []; return Object.keys(facet.data).map(function (name) { return { name: name, count: facet.data[name], isRefined: results._state.isFacetRefined(attribute, name), isExcluded: results._state.isExcludeRefined(attribute, name) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find$1(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return Object.keys(disjunctiveFacet.data).map(function (name) { return { name: name, count: disjunctiveFacet.data[name], isRefined: results._state.isDisjunctiveFacetRefined(attribute, name) }; }); } 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 = node.data.map(function (childNode) { return recSort(sortFn, childNode); }); 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|undefined} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('result', function(event){ * //get values ordered only by name ascending using the string predicate * event.results.getFacetValues('city', {sortBy: ['name:asc']}); * //get values ordered only by count ascending using a function * event.results.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) { return undefined; } var options = defaultsPure({}, 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(function (hierarchicalFacetValues) { return orderBy_1(hierarchicalFacetValues, order[0], order[1]); }, facetValues); } else if (typeof options.sortBy === 'function') { 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(function (data) { return vanillaSortFn(options.sortBy, data); }, 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); } return undefined; }; /** * @typedef {Object} FacetListItem * @property {string} name */ /** * @param {FacetListItem[]} facetList (has more items, but enough for here) * @param {string} facetName */ function getFacetStatsIfAvailable(facetList, facetName) { var data = find$1(facetList, function (facet) { return facet.name === facetName; }); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhaustiveness for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * Note that for a numeric refinement, results are grouped per operator, this * means that it will return responses for operators which are empty. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function () { var state = this._state; var results = this; var res = []; Object.keys(state.facetsRefinements).forEach(function (attributeName) { state.facetsRefinements[attributeName].forEach(function (name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); Object.keys(state.facetsExcludes).forEach(function (attributeName) { state.facetsExcludes[attributeName].forEach(function (name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); Object.keys(state.disjunctiveFacetsRefinements).forEach(function (attributeName) { state.disjunctiveFacetsRefinements[attributeName].forEach(function (name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); Object.keys(state.hierarchicalFacetsRefinements).forEach(function (attributeName) { state.hierarchicalFacetsRefinements[attributeName].forEach(function (name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); Object.keys(state.numericRefinements).forEach(function (attributeName) { var operators = state.numericRefinements[attributeName]; Object.keys(operators).forEach(function (operator) { operators[operator].forEach(function (value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); state.tagRefinements.forEach(function (name) { res.push({ type: 'tag', attributeName: '_tags', name: name }); }); return res; }; /** * @typedef {Object} Facet * @property {string} name * @property {Object} data * @property {boolean} exhaustive */ /** * @param {*} state * @param {*} type * @param {string} attributeName * @param {*} name * @param {Facet[]} resultsFacets */ function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find$1(resultsFacets, function (f) { return f.name === attributeName; }); var count = facet && facet.data && facet.data[name] ? facet.data[name] : 0; var exhaustive = facet && facet.exhaustive || false; return { type: type, attributeName: attributeName, name: name, count: count, exhaustive: exhaustive }; } /** * @param {*} state * @param {string} attributeName * @param {*} name * @param {Facet[]} resultsFacets */ function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var separator = state._getHierarchicalFacetSeparator(facetDeclaration); var split = name.split(separator); var rootFacet = find$1(resultsFacets, function (facet) { return facet.name === attributeName; }); var facet = split.reduce(function (intermediateFacet, part) { var newFacet = intermediateFacet && find$1(intermediateFacet.data, function (f) { return f.name === part; }); return newFacet !== undefined ? newFacet : intermediateFacet; }, rootFacet); var count = facet && facet.count || 0; var exhaustive = facet && facet.exhaustive || false; var path = facet && facet.path || ''; return { type: 'hierarchical', attributeName: attributeName, name: path, count: count, exhaustive: exhaustive }; } var SearchResults_1 = SearchResults; // 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(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; } function inherits(ctor, superCtor) { ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } var inherits_1 = inherits; /** * 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; } inherits_1(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 state.getRefinedDisjunctiveFacets().forEach(function (refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated state.getRefinedHierarchicalFacets().forEach(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 _getHitsSearchParams(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 _getDisjunctiveFacetSearchParams(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 _getNumericFilters(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; Object.keys(state.numericRefinements).forEach(function (attribute) { var operators = state.numericRefinements[attribute] || {}; Object.keys(operators).forEach(function (operator) { var values = operators[operator] || []; if (facetName !== attribute) { values.forEach(function (value) { if (Array.isArray(value)) { var vs = value.map(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 _getTagFilters(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 _getFacetFilters(state, facet, hierarchicalRootLevel) { var facetFilters = []; var facetsRefinements = state.facetsRefinements || {}; Object.keys(facetsRefinements).forEach(function (facetName) { var facetValues = facetsRefinements[facetName] || []; facetValues.forEach(function (facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); var facetsExcludes = state.facetsExcludes || {}; Object.keys(facetsExcludes).forEach(function (facetName) { var facetValues = facetsExcludes[facetName] || []; facetValues.forEach(function (facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); var disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements || {}; Object.keys(disjunctiveFacetsRefinements).forEach(function (facetName) { var facetValues = disjunctiveFacetsRefinements[facetName] || []; if (facetName === facet || !facetValues || facetValues.length === 0) { return; } var orFilters = []; facetValues.forEach(function (facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); var hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements || {}; Object.keys(hierarchicalFacetsRefinements).forEach(function (facetName) { var facetValues = hierarchicalFacetsRefinements[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 _getHitsHierarchicalFacetsAttributes(state) { var out = []; return state.hierarchicalFacets.reduce( // 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 _getDisjunctiveHierarchicalFacetAttribute(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 getSearchForFacetQuery(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; } return merge$1({}, requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters); } }; var requestBuilder_1 = requestBuilder; var version$1 = '0.0.0-6ac260d'; /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {object} event * @property {SearchParameters} event.state the current parameters with the latest changes applied * @property {SearchResults} event.results the previous results received from Algolia. `null` before the first request * @example * helper.on('change', function(event) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when a main search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {object} event * @property {SearchParameters} event.state the parameters used for this search * @property {SearchResults} event.results the results from the previous search. `null` if it is the first search. * @example * helper.on('search', function(event) { * console.log('Search sent'); * }); */ /** * Event triggered when a search using `searchForFacetValues` is sent to Algolia * @event AlgoliaSearchHelper#event:searchForFacetValues * @property {object} event * @property {SearchParameters} event.state the parameters used for this search it is the first search. * @property {string} event.facet the facet searched into * @property {string} event.query the query used to search in the facets * @example * helper.on('searchForFacetValues', function(event) { * console.log('searchForFacetValues sent'); * }); */ /** * Event triggered when a search using `searchOnce` is sent to Algolia * @event AlgoliaSearchHelper#event:searchOnce * @property {object} event * @property {SearchParameters} event.state the parameters used for this search it is the first search. * @example * helper.on('searchOnce', function(event) { * console.log('searchOnce sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {object} event * @property {SearchResults} event.results the results received from Algolia * @property {SearchParameters} event.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(event) { * 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 {object} event * @property {Error} event.error the error returned by the Algolia. * @example * helper.on('error', function(event) { * 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 (typeof client.addAlgoliaAgent === 'function') { 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; } inherits_1(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({ onlyWithDerivedHelpers: false }); return this; }; AlgoliaSearchHelper.prototype.searchOnlyWithDerivedHelpers = function () { this._search({ onlyWithDerivedHelpers: true }); 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', { state: 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 clientHasSFFV = typeof this.client.searchForFacetValues === 'function'; if (!clientHasSFFV && typeof this.client.initIndex !== 'function') { throw new Error('search for facet values (searchable) was called, but this client does not have a function client.searchForFacetValues or client.initIndex(index).searchForFacetValues'); } 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: state, facet: facet, query: query }); var searchForFacetValuesPromise = clientHasSFFV ? 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(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({ state: this.state.resetPage().setQuery(q), isPageReset: true }); 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({ state: this.state.resetPage().clearRefinements(name), isPageReset: true }); 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({ state: this.state.resetPage().clearTags(), isPageReset: true }); 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({ state: this.state.resetPage().addDisjunctiveFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addHierarchicalFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addNumericRefinement(attribute, operator, value), isPageReset: true }); 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({ state: this.state.resetPage().addFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addExcludeRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addTagRefinement(tag), isPageReset: true }); 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({ state: this.state.resetPage().removeNumericRefinement(attribute, operator, value), isPageReset: true }); 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({ state: this.state.resetPage().removeDisjunctiveFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().removeHierarchicalFacetRefinement(facet), isPageReset: true }); 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({ state: this.state.resetPage().removeFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().removeExcludeRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().removeTagRefinement(tag), isPageReset: true }); 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({ state: this.state.resetPage().toggleExcludeFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().toggleFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().toggleTagRefinement(tag), isPageReset: true }); 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 () { var page = this.state.page || 0; return this.setPage(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 () { var page = this.state.page || 0; return this.setPage(page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this._change({ state: this.state.setPage(page), isPageReset: false }); 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({ state: this.state.resetPage().setIndex(name), isPageReset: true }); 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({ state: this.state.resetPage().setQueryParameter(parameter, value), isPageReset: true }); 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({ state: SearchParameters_1.make(newState), isPageReset: false }); return this; }; /** * 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; }; /** * 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 (objectHasKeys_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 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); conjRefinements.forEach(function (r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); excludeRefinements.forEach(function (r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); disjRefinements.forEach(function (r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); Object.keys(numericRefinements).forEach(function (operator) { var value = numericRefinements[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 (options) { var state = this.state; var states = []; var mainQueries = []; if (!options.onlyWithDerivedHelpers) { mainQueries = requestBuilder_1._getQueries(state.index, state); states.push({ state: state, queriesCount: mainQueries.length, helper: this }); this.emit('search', { state: state, results: this.lastResults }); } var derivedQueries = this.derivedHelpers.map(function (derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var derivedStateQueries = requestBuilder_1._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: derivedStateQueries.length, helper: derivedHelper }); derivedHelper.emit('search', { state: derivedState, results: derivedHelper.lastResults }); return derivedStateQueries; }); var queries = Array.prototype.concat.apply(mainQueries, 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 (error) { // If we reach this part, we're in an internal error state this.emit('error', { error: error }); } }; /** * 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.slice(); states.forEach(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', { results: formattedResponse, state: state }); }); }; AlgoliaSearchHelper.prototype._dispatchAlgoliaError = function (queryId, error) { if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= queryId - this._lastQueryIdReceived; this._lastQueryIdReceived = queryId; this.emit('error', { error: error }); 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 (event) { var state = event.state; var isPageReset = event.isPageReset; if (state !== this.state) { this.state = state; this.emit('change', { state: this.state, results: this.lastResults, isPageReset: isPageReset }); } }; /** * 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 (typeof newClient.addAlgoliaAgent === 'function') { 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' */ 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(event) { * console.log(event.results); * }); * helper * .toggleFacetRefinement('category', 'Movies & TV Shows') * .toggleFacetRefinement('shipping', '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; var algoliasearchHelper_1 = algoliasearchHelper; 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 = []; return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; listeners.forEach(function (listener) { return listener(); }); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubscribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } function addAlgoliaAgents(searchClient) { if (typeof searchClient.addAlgoliaAgent === 'function') { searchClient.addAlgoliaAgent("react (".concat(React.version, ")")); searchClient.addAlgoliaAgent("react-instantsearch (".concat(version, ")")); } } var isMultiIndexContext = function isMultiIndexContext(widget) { return hasMultipleIndices({ ais: widget.props.contextValue, multiIndexContext: widget.props.indexContextValue }); }; var isTargetedIndexEqualIndex = function isTargetedIndexEqualIndex(widget, indexId) { return widget.props.indexContextValue.targetedIndex === indexId; }; // Relying on the `indexId` is a bit brittle to detect the `Index` widget. // Since it's a class we could rely on `instanceof` or similar. We never // had an issue though. Works for now. var isIndexWidget = function isIndexWidget(widget) { return Boolean(widget.props.indexId); }; var isIndexWidgetEqualIndex = function isIndexWidgetEqualIndex(widget, indexId) { return widget.props.indexId === indexId; }; var sortIndexWidgetsFirst = function sortIndexWidgetsFirst(firstWidget, secondWidget) { if (isIndexWidget(firstWidget)) { return -1; } if (isIndexWidget(secondWidget)) { return 1; } return 0; }; /** * 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 === void 0 ? {} : _ref$initialState, searchClient = _ref.searchClient, resultsState = _ref.resultsState, stalledSearchDelay = _ref.stalledSearchDelay; var helper = algoliasearchHelper_1(searchClient, indexName, _objectSpread({}, HIGHLIGHT_TAGS)); addAlgoliaAgents(searchClient); helper.on('search', handleNewSearch).on('result', handleSearchSuccess({ indexId: indexName })).on('error', handleSearchError); var skip = false; var stalledSearchTimer = null; var initialSearchParameters = helper.state; var widgetsManager = createWidgetsManager(onWidgetsUpdate); hydrateSearchClient(searchClient, resultsState); var store = createStore({ widgets: initialState, metadata: [], results: hydrateResultsState(resultsState), error: null, searching: false, isSearchStalled: true, searchingForFacetValues: false }); function skipSearch() { skip = true; } function updateClient(client) { addAlgoliaAgents(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() { var sharedParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return !isMultiIndexContext(widget) && !isIndexWidget(widget); }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, initialSearchParameters); var mainParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { var targetedIndexEqualMainIndex = isMultiIndexContext(widget) && isTargetedIndexEqualIndex(widget, indexName); var subIndexEqualMainIndex = isIndexWidget(widget) && isIndexWidgetEqualIndex(widget, indexName); return targetedIndexEqualMainIndex || subIndexEqualMainIndex; }) // We have to sort the `Index` widgets first so the `index` parameter // is correctly set in the `reduce` function for the following widgets .sort(sortIndexWidgetsFirst).reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); var derivedIndices = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { var targetedIndexNotEqualMainIndex = isMultiIndexContext(widget) && !isTargetedIndexEqualIndex(widget, indexName); var subIndexNotEqualMainIndex = isIndexWidget(widget) && !isIndexWidgetEqualIndex(widget, indexName); return targetedIndexNotEqualMainIndex || subIndexNotEqualMainIndex; }) // We have to sort the `Index` widgets first so the `index` parameter // is correctly set in the `reduce` function for the following widgets .sort(sortIndexWidgetsFirst).reduce(function (indices, widget) { var indexId = isMultiIndexContext(widget) ? widget.props.indexContextValue.targetedIndex : widget.props.indexId; var widgets = indices[indexId] || []; return _objectSpread({}, indices, _defineProperty({}, indexId, widgets.concat(widget))); }, {}); var derivedParameters = Object.keys(derivedIndices).map(function (indexId) { return { parameters: derivedIndices[indexId].reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters), indexId: indexId }; }); return { mainParameters: mainParameters, derivedParameters: derivedParameters }; } function search() { if (!skip) { var _getSearchParameters = getSearchParameters(), mainParameters = _getSearchParameters.mainParameters, derivedParameters = _getSearchParameters.derivedParameters; // We have to call `slice` because the method `detach` on the derived // helpers mutates the value `derivedHelpers`. The `forEach` loop does // not iterate on each value and we're not able to correctly clear the // previous derived helpers (memory leak + useless requests). helper.derivedHelpers.slice().forEach(function (derivedHelper) { // Since we detach the derived helpers on **every** new search they // won't receive intermediate results in case of a stalled search. // Only the last result is dispatched by the derived helper because // they are not detached yet: // // - a -> main helper receives results // - ap -> main helper receives results // - app -> main helper + derived helpers receive results // // The quick fix is to avoid to detatch them on search but only once they // received the results. But it means that in case of a stalled search // all the derived helpers not detached yet register a new search inside // the helper. The number grows fast in case of a bad network and it's // not deterministic. derivedHelper.detach(); }); derivedParameters.forEach(function (_ref2) { var indexId = _ref2.indexId, parameters = _ref2.parameters; var derivedHelper = helper.derive(function () { return parameters; }); derivedHelper.on('result', handleSearchSuccess({ indexId: indexId })).on('error', handleSearchError); }); helper.setState(mainParameters); helper.search(); } } function handleSearchSuccess(_ref3) { var indexId = _ref3.indexId; return function (event) { var state = store.getState(); var isDerivedHelpersEmpty = !helper.derivedHelpers.length; var results = state.results ? state.results : {}; // Switching from mono index to multi index and vice versa must reset the // results to an empty object, otherwise we keep reference of stalled and // unused results. results = !isDerivedHelpersEmpty && results.getFacetByName ? {} : results; if (!isDerivedHelpersEmpty) { results[indexId] = event.results; } else { results = event.results; } var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); stalledSearchTimer = null; nextIsSearchStalled = false; } var resultsFacetValues = currentState.resultsFacetValues, partialState = _objectWithoutProperties(currentState, ["resultsFacetValues"]); store.setState(_objectSpread({}, partialState, { results: results, isSearchStalled: nextIsSearchStalled, searching: false, error: null })); }; } function handleSearchError(_ref4) { var error = _ref4.error; var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); nextIsSearchStalled = false; } var resultsFacetValues = currentState.resultsFacetValues, partialState = _objectWithoutProperties(currentState, ["resultsFacetValues"]); store.setState(_objectSpread({}, partialState, { isSearchStalled: nextIsSearchStalled, error: error, searching: false })); } function handleNewSearch() { if (!stalledSearchTimer) { stalledSearchTimer = setTimeout(function () { var _store$getState = store.getState(), resultsFacetValues = _store$getState.resultsFacetValues, partialState = _objectWithoutProperties(_store$getState, ["resultsFacetValues"]); store.setState(_objectSpread({}, partialState, { isSearchStalled: true })); }, stalledSearchDelay); } } function hydrateSearchClient(client, results) { if (!results) { return; } if (!client._useCache || typeof client.addAlgoliaAgent !== 'function') { // This condition avoids hydrating a `searchClient` different from the // Algolia one. We also avoid to hydrate the client when the cache is // disabled. The implementation is brittle but we don't have a proper way // to detect the Algolia client at the moment. return; } if (Array.isArray(results)) { hydrateSearchClientWithMultiIndexRequest(client, results); return; } hydrateSearchClientWithSingleIndexRequest(client, results); } function hydrateSearchClientWithMultiIndexRequest(client, results) { // At the moment we don't have a proper API to hydrate the client cache from // the outside (it should come with the V4). The following code populates the // cache with a multi-index results. You can find more information about the // computation of the key inside the client (see link below). // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240 var key = "/1/indexes/*/queries_body_".concat(JSON.stringify({ requests: results.reduce(function (acc, result) { return acc.concat(result.rawResults.map(function (request) { return { indexName: request.index, params: request.params }; })); }, []) })); client.cache = _objectSpread({}, client.cache, _defineProperty({}, key, JSON.stringify({ results: results.reduce(function (acc, result) { return acc.concat(result.rawResults); }, []) }))); } function hydrateSearchClientWithSingleIndexRequest(client, results) { // At the moment we don't have a proper API to hydrate the client cache from // the outside (it should come with the V4). The following code populates the // cache with a single-index result. You can find more information about the // computation of the key inside the client (see link below). // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240 var key = "/1/indexes/*/queries_body_".concat(JSON.stringify({ requests: results.rawResults.map(function (request) { return { indexName: request.index, params: request.params }; }) })); client.cache = _objectSpread({}, client.cache, _defineProperty({}, key, JSON.stringify({ results: results.rawResults }))); } function hydrateResultsState(results) { if (!results) { return null; } if (Array.isArray(results)) { return results.reduce(function (acc, result) { return _objectSpread({}, acc, _defineProperty({}, result._internalIndexId, new algoliasearchHelper_1.SearchResults(new algoliasearchHelper_1.SearchParameters(result.state), result.rawResults))); }, {}); } return new algoliasearchHelper_1.SearchResults(new algoliasearchHelper_1.SearchParameters(results.state), results.rawResults); } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_objectSpread({}, 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(_objectSpread({}, store.getState(), { widgets: nextSearchState, metadata: metadata, searching: true })); search(); } function onSearchForFacetValues(_ref5) { var facetName = _ref5.facetName, query = _ref5.query, _ref5$maxFacetHits = _ref5.maxFacetHits, maxFacetHits = _ref5$maxFacetHits === void 0 ? 10 : _ref5$maxFacetHits; // The values 1, 100 are the min / max values that the engine accepts. // see: https://www.algolia.com/doc/api-reference/api-parameters/maxFacetHits var maxFacetHitsWithinRange = Math.max(1, Math.min(maxFacetHits, 100)); store.setState(_objectSpread({}, store.getState(), { searchingForFacetValues: true })); helper.searchForFacetValues(facetName, query, maxFacetHitsWithinRange).then(function (content) { var _objectSpread6; store.setState(_objectSpread({}, store.getState(), { error: null, searchingForFacetValues: false, resultsFacetValues: _objectSpread({}, store.getState().resultsFacetValues, (_objectSpread6 = {}, _defineProperty(_objectSpread6, facetName, content.facetHits), _defineProperty(_objectSpread6, "query", query), _objectSpread6)) })); }, function (error) { store.setState(_objectSpread({}, store.getState(), { searchingForFacetValues: false, error: error })); }).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); // No need to trigger a new search here as the widgets will also update and trigger it if needed. } 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, getSearchParameters: getSearchParameters, onSearchForFacetValues: onSearchForFacetValues, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, updateClient: updateClient, updateIndex: updateIndex, clearCache: clearCache, skipSearch: skipSearch }; } function isControlled(props) { return Boolean(props.searchState); } /** * @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} 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} [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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox, Hits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); */ var InstantSearch = /*#__PURE__*/ function (_Component) { _inherits(InstantSearch, _Component); _createClass(InstantSearch, null, [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { var nextIsControlled = isControlled(nextProps); var previousSearchState = prevState.instantSearchManager.store.getState().widgets; var nextSearchState = nextProps.searchState; if (nextIsControlled && !fastDeepEqual(previousSearchState, nextSearchState)) { prevState.instantSearchManager.onExternalStateUpdate(nextProps.searchState); } return { isControlled: nextIsControlled, contextValue: _objectSpread({}, prevState.contextValue, { mainTargetedIndex: nextProps.indexName }) }; } }]); function InstantSearch(props) { var _this; _classCallCheck(this, InstantSearch); _this = _possibleConstructorReturn(this, _getPrototypeOf(InstantSearch).call(this, props)); _defineProperty(_assertThisInitialized(_this), "isUnmounting", false); var instantSearchManager = createInstantSearchManager({ indexName: _this.props.indexName, searchClient: _this.props.searchClient, initialState: _this.props.searchState || {}, resultsState: _this.props.resultsState, stalledSearchDelay: _this.props.stalledSearchDelay }); var contextValue = { store: instantSearchManager.store, widgetsManager: instantSearchManager.widgetsManager, mainTargetedIndex: _this.props.indexName, onInternalStateUpdate: _this.onWidgetsInternalStateUpdate.bind(_assertThisInitialized(_this)), createHrefForState: _this.createHrefForState.bind(_assertThisInitialized(_this)), onSearchForFacetValues: _this.onSearchForFacetValues.bind(_assertThisInitialized(_this)), onSearchStateChange: _this.onSearchStateChange.bind(_assertThisInitialized(_this)), onSearchParameters: _this.onSearchParameters.bind(_assertThisInitialized(_this)) }; _this.state = { isControlled: isControlled(_this.props), instantSearchManager: instantSearchManager, contextValue: contextValue }; return _this; } _createClass(InstantSearch, [{ key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var prevIsControlled = isControlled(prevProps); if (prevIsControlled && !this.state.isControlled) { throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled"); } if (!prevIsControlled && this.state.isControlled) { throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled"); } if (this.props.refresh !== prevProps.refresh && this.props.refresh) { this.state.instantSearchManager.clearCache(); } if (prevProps.indexName !== this.props.indexName) { this.state.instantSearchManager.updateIndex(this.props.indexName); } if (prevProps.searchClient !== this.props.searchClient) { this.state.instantSearchManager.updateClient(this.props.searchClient); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.isUnmounting = true; this.state.instantSearchManager.skipSearch(); } }, { key: "createHrefForState", value: function createHrefForState(searchState) { searchState = this.state.instantSearchManager.transitionState(searchState); return this.state.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: "onWidgetsInternalStateUpdate", value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.state.instantSearchManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.state.isControlled) { this.state.instantSearchManager.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.state.instantSearchManager.onSearchForFacetValues(searchState); } }, { key: "getKnownKeys", value: function getKnownKeys() { return this.state.instantSearchManager.getWidgetsIds(); } }, { key: "render", value: function render() { if (React.Children.count(this.props.children) === 0) { return null; } return React__default.createElement(InstantSearchProvider, { value: this.state.contextValue }, this.props.children); } }]); return InstantSearch; }(React.Component); _defineProperty(InstantSearch, "defaultProps", { stalledSearchDelay: 200, refresh: false }); _defineProperty(InstantSearch, "propTypes", { // @TODO: These props are currently constant. indexName: propTypes.string.isRequired, searchClient: propTypes.shape({ search: propTypes.func.isRequired, searchForFacetValues: propTypes.func, addAlgoliaAgent: propTypes.func, clearCache: propTypes.func }).isRequired, createURL: propTypes.func, refresh: propTypes.bool, searchState: propTypes.object, onSearchStateChange: propTypes.func, onSearchParameters: propTypes.func, resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]), children: propTypes.node, stalledSearchDelay: propTypes.number }); var getId$1 = function getId(props) { return props.attributes[0]; }; var namespace = 'hierarchicalMenu'; function _refine(props, searchState, nextRefinement, context) { var id = getId$1(props); var nextValue = _defineProperty({}, 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)); } } 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 = createConnectorWithContext({ 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 ".concat(propName, " supplied to ").concat(componentName, ". Expected an Array of Strings")); } return undefined; }, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var id = getId$1(props); var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); /** * 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 = createConnectorWithContext({ 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 _objectSpread({}, item, { id: meta.id, index: meta.index }); })); } } return res; }, []); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems, canRefine: transformedItems.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 getId$2 = function getId(props) { return props.attributes[0]; }; var namespace$1 = 'hierarchicalMenu'; function getCurrentRefinement(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$1, ".").concat(getId$2(props)), null); if (currentRefinement === '') { return null; } return currentRefinement; } function getValue(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; if (currentRefinement === null) { nextRefinement = path; } else { var tmpSearchParameters = new algoliasearchHelper_1.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$1(value, props, searchState, context) { return value.map(function (v) { return { label: v.name, value: getValue(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) ? _objectSpread({}, item, { items: truncate(item.items, limit) }) : item; }); }; function _refine$1(props, searchState, nextRefinement, context) { var id = getId$2(props); var nextValue = _defineProperty({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$1); } function _cleanUp(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$1, ".").concat(getId$2(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 path to use if the first level is not the root level. * @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 = createConnectorWithContext({ 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 ".concat(propName, " supplied to ").concat(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$2(props); var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: false }; } var itemsLimit = showMore ? showMoreLimit : limit; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue$1(value.data, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: truncate(transformedItems, itemsLimit), currentRefinement: getCurrentRefinement(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$1(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, 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, contextValue = props.contextValue; var id = getId$2(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(props, searchState, { ais: contextValue, multiIndexContext: props.indexContextValue }); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var rootAttribute = props.attributes[0]; var id = getId$2(props); var currentRefinement = getCurrentRefinement(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = !currentRefinement ? [] : [{ label: "".concat(rootAttribute, ": ").concat(currentRefinement), attribute: rootAttribute, value: function value(nextState) { return _refine$1(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: currentRefinement }]; return { id: id, index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: items }; } }); var highlight = function highlight(_ref) { var attribute = _ref.attribute, hit = _ref.hit, highlightProperty = _ref.highlightProperty, _ref$preTag = _ref.preTag, preTag = _ref$preTag === void 0 ? HIGHLIGHT_TAGS.highlightPreTag : _ref$preTag, _ref$postTag = _ref.postTag, postTag = _ref$postTag === void 0 ? 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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox, Hits, connectHighlight } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * 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 * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox defaultRefinement="pho" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var connectHighlight = createConnectorWithContext({ 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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Highlight, connectHits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * const CustomHits = connectHits(({ hits }) => ( * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attribute="name" hit={hit} /> * </p> * )} * </div> * )); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <CustomHits /> * </InstantSearch> * ); */ var connectHits = createConnectorWithContext({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (!results) { return { hits: [] }; } var hitsWithPositions = addAbsolutePositions(results.hits, results.hitsPerPage, results.page); var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID); return { hits: hitsWithPositionsAndQueryID }; }, /** * Hits needs to be considered as a widget to trigger a search, * even if no other widgets are used. * * To be considered as a widget you need either: * - getSearchParameters * - getMetadata * - transitionState * * See: createConnector.tsx */ getSearchParameters: function getSearchParameters(searchParameters) { return searchParameters; } }); function getId$3() { return 'hitsPerPage'; } function getCurrentRefinement$1(props, searchState, context) { var id = getId$3(); var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null); 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 = createConnectorWithContext({ 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$1(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = props.items.map(function (item) { return item.value === currentRefinement ? _objectSpread({}, item, { isRefined: true }) : _objectSpread({}, 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({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, getId$3()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement$1(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue })); }, getMetadata: function getMetadata() { return { id: getId$3() }; } }); function getId$4() { return 'page'; } function getCurrentRefinement$2(props, searchState, context) { var id = getId$4(); var page = 1; var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page); if (typeof currentRefinement === 'string') { return 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 = createConnectorWithContext({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var _this = this; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); this._allResults = this._allResults || []; this._prevState = this._prevState || {}; if (!results) { return { hits: [], hasPrevious: false, hasMore: false, refine: function refine() {}, refinePrevious: function refinePrevious() {}, refineNext: function refineNext() {} }; } var page = results.page, hits = results.hits, hitsPerPage = results.hitsPerPage, nbPages = results.nbPages, _results$_state = results._state; _results$_state = _results$_state === void 0 ? {} : _results$_state; var p = _results$_state.page, currentState = _objectWithoutProperties(_results$_state, ["page"]); var hitsWithPositions = addAbsolutePositions(hits, hitsPerPage, page); var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID); if (this._firstReceivedPage === undefined || !fastDeepEqual(currentState, this._prevState)) { this._allResults = _toConsumableArray(hitsWithPositionsAndQueryID); this._firstReceivedPage = page; this._lastReceivedPage = page; } else if (this._lastReceivedPage < page) { this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hitsWithPositionsAndQueryID)); this._lastReceivedPage = page; } else if (this._firstReceivedPage > page) { this._allResults = [].concat(_toConsumableArray(hitsWithPositionsAndQueryID), _toConsumableArray(this._allResults)); this._firstReceivedPage = page; } this._prevState = currentState; var hasPrevious = this._firstReceivedPage > 0; var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; var refinePrevious = function refinePrevious(event) { return _this.refine(event, _this._firstReceivedPage - 1); }; var refineNext = function refineNext(event) { return _this.refine(event, _this._lastReceivedPage + 1); }; return { hits: this._allResults, hasPrevious: hasPrevious, hasMore: hasMore, refinePrevious: refinePrevious, refineNext: refineNext }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQueryParameters({ page: getCurrentRefinement$2(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }) - 1 }); }, refine: function refine(props, searchState, event, index) { if (index === undefined && this._lastReceivedPage !== undefined) { index = this._lastReceivedPage + 1; } else if (index === undefined) { index = getCurrentRefinement$2(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } var id = getId$4(); var nextValue = _defineProperty({}, id, index + 1); var resetPage = false; return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, resetPage); } }); var namespace$2 = 'menu'; function getId$5(props) { return props.attribute; } function getCurrentRefinement$3(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$2, ".").concat(getId$5(props)), null); if (currentRefinement === '') { return null; } return currentRefinement; } function getValue$1(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$3(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$2(props, searchState, nextRefinement, context) { var id = getId$5(props); var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$2); } function _cleanUp$1(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$2, ".").concat(getId$5(props))); } var defaultSortBy = ['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 = createConnectorWithContext({ 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 attribute = props.attribute, searchable = props.searchable, indexContextValue = props.indexContextValue; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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 && indexContextValue) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isFromSearch: isFromSearch, searchable: searchable, canRefine: canRefine }; } var items; if (isFromSearch) { items = searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$1(v.value, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }); } else { items = results.getFacetValues(attribute, { sortBy: searchable ? undefined : defaultSortBy }).map(function (v) { return { label: v.name, value: getValue$1(v.name, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), count: v.count, isRefined: v.isRefined }; }); } var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit(props)), currentRefinement: getCurrentRefinement$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isFromSearch: isFromSearch, searchable: searchable, canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$2(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$1(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, 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$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId$5(props); var currentRefinement = getCurrentRefinement$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); return { id: id, index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: currentRefinement === null ? [] : [{ label: "".concat(props.attribute, ": ").concat(currentRefinement), attribute: props.attribute, value: function value(nextState) { return _refine$2(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: currentRefinement }] }; } }); function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(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"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function stringifyItem(item) { if (typeof item.start === 'undefined' && typeof item.end === 'undefined') { return ''; } return "".concat(item.start ? item.start : '', ":").concat(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$6(props) { return props.attribute; } function getCurrentRefinement$4(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, "".concat(namespace$3, ".").concat(getId$6(props)), ''); } 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$3(props, searchState, nextRefinement, context) { var nextValue = _defineProperty({}, getId$6(props), nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$3); } function _cleanUp$2(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$3, ".").concat(getId$6(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 = createConnectorWithContext({ 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$4(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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(attribute) ? results.getFacetStats(attribute) : null; var refinedItem = find(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: refinedItem === undefined, noRefinement: !stats, label: 'All' }); } var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems, currentRefinement: currentRefinement, canRefine: transformedItems.length > 0 && transformedItems.some(function (item) { return item.noRefinement === false; }) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$3(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$2(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; var _parseItem = parseItem(getCurrentRefinement$4(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue })), 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 id = getId$6(props); var value = getCurrentRefinement$4(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = []; var index = getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (value !== '') { var _find = find(props.items, function (item) { return stringifyItem(item) === value; }), label = _find.label; items.push({ label: "".concat(props.attribute, ": ").concat(label), attribute: props.attribute, currentRefinement: label, value: function value(nextState) { return _refine$3(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); } return { id: id, index: index, items: items }; } }); function getId$7() { return 'page'; } function getCurrentRefinement$5(props, searchState, context) { var id = getId$7(); var page = 1; var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page); if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; } function _refine$4(props, searchState, nextPage, context) { var id = getId$7(); var nextValue = _defineProperty({}, 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 = createConnectorWithContext({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement$5(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine$4(props, searchState, nextPage, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, getId$7()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement$5(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }) - 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 = createConnectorWithContext({ displayName: 'AlgoliaPoweredBy', getProvidedProps: function getProvidedProps() { var hostname = typeof window === 'undefined' ? '' : window.location.hostname; var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + "utm_content=".concat(hostname, "&") + 'utm_campaign=poweredby'; return { url: url }; } }); /** * 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$8(props) { return props.attribute; } var namespace$4 = 'range'; function getCurrentRange(boundaries, stats, precision) { var pow = Math.pow(10, precision); var min; if (typeof boundaries.min === 'number' && isFinite(boundaries.min)) { min = boundaries.min; } else if (typeof stats.min === 'number' && isFinite(stats.min)) { min = stats.min; } else { min = undefined; } var max; if (typeof boundaries.max === 'number' && isFinite(boundaries.max)) { max = boundaries.max; } else if (typeof stats.max === 'number' && 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$6(props, searchState, currentRange, context) { var _getCurrentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$4, ".").concat(getId$8(props)), {}), min = _getCurrentRefinement.min, max = _getCurrentRefinement.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); } var refinement = { 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; 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({}, 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$3(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$4, ".").concat(getId$8(props))); } var connectRange = createConnectorWithContext({ 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, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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 behavior 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$6(props, searchState, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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$5(props, searchState, nextRefinement, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attribute = props.attribute; var _getCurrentRefinement2 = getCurrentRefinement$6(props, searchState, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), min = _getCurrentRefinement2.min, max = _getCurrentRefinement2.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 _this$_currentRange = this._currentRange, minRange = _this$_currentRange.min, maxRange = _this$_currentRange.max; var _getCurrentRefinement3 = getCurrentRefinement$6(props, searchState, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), 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 ? "".concat(minValue, " <= ") : '', props.attribute, hasMax ? " <= ".concat(maxValue) : '']; items.push({ label: fragments.join(''), attribute: props.attribute, value: function value(nextState) { return _refine$5(props, nextState, {}, _this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: getCurrentRefinementWithRange({ min: minValue, max: maxValue }, { min: minRange, max: maxRange }) }); } return { id: getId$8(props), index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: items }; } }); var namespace$5 = 'refinementList'; function getId$9(props) { return props.attribute; } function getCurrentRefinement$7(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$5, ".").concat(getId$9(props)), []); if (typeof currentRefinement !== 'string') { return currentRefinement; } if (currentRefinement) { return [currentRefinement]; } return []; } function getValue$2(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$7(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$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({}, id, nextRefinement.length > 0 ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$5); } function _cleanUp$4(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$5, ".").concat(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 `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. * @providedPropType {boolean} canRefine - a boolean that says whether you can refine */ var sortBy$1 = ['isRefined', 'count:desc', 'name:asc']; var connectRefinementList = createConnectorWithContext({ 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 attribute = props.attribute, searchable = props.searchable, indexContextValue = props.indexContextValue; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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 && indexContextValue) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$7(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: canRefine, isFromSearch: isFromSearch, searchable: searchable }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$2(v.value, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), _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, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit$1(props)), currentRefinement: getCurrentRefinement$7(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isFromSearch: isFromSearch, searchable: searchable, canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$6(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit$1(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$4(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, operator = props.operator; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = "".concat(addKey, "Refinement"); searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props)) }); searchParameters = searchParameters[addKey](attribute); return getCurrentRefinement$7(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }).reduce(function (res, val) { return res[addRefinementKey](attribute, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId$9(props); var context = { ais: props.contextValue, multiIndexContext: props.indexContextValue }; return { id: id, index: getIndexId(context), items: getCurrentRefinement$7(props, searchState, context).length > 0 ? [{ attribute: props.attribute, label: "".concat(props.attribute, ": "), currentRefinement: getCurrentRefinement$7(props, searchState, context), value: function value(nextState) { return _refine$6(props, nextState, [], context); }, items: getCurrentRefinement$7(props, searchState, context).map(function (item) { return { label: "".concat(item), value: function value(nextState) { var nextSelectedItems = getCurrentRefinement$7(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 = createConnectorWithContext({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: propTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = getCurrentRefinementValue(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, id, null); if (!this._prevSearchState) { this._prevSearchState = {}; } // Get the subpart of the state that interest us if (hasMultipleIndices({ ais: props.contextValue, multiIndexContext: props.indexContextValue })) { searchState = searchState.indices ? searchState.indices[getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue })] : {}; } // 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 comparison 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(searchState, ['configure', id]); var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState); this._prevSearchState = cleanedSearchState; return { value: value, hasNotChanged: hasNotChanged }; } }); function getId$a() { return 'query'; } function getCurrentRefinement$8(props, searchState, context) { var id = getId$a(); var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, ''); if (currentRefinement) { return currentRefinement; } return ''; } function _refine$7(props, searchState, nextRefinement, context) { var id = getId$a(); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage); } function _cleanUp$5(props, searchState, context) { return cleanUpValue(searchState, context, getId$a()); } /** * connectSearchBox connector provides the logic to build a widget that will * let the user search for a query * @name connectSearchBox * @kind connector * @propType {string} [defaultRefinement] - Provide a default value for the query * @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 = createConnectorWithContext({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: propTypes.string }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { currentRefinement: getCurrentRefinement$8(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isSearchStalled: searchResults.isSearchStalled }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$7(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$5(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$8(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue })); }, getMetadata: function getMetadata(props, searchState) { var id = getId$a(); var currentRefinement = getCurrentRefinement$8(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); return { id: id, index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: currentRefinement === null ? [] : [{ label: "".concat(id, ": ").concat(currentRefinement), value: function value(nextState) { return _refine$7(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: currentRefinement }] }; } }); function getId$b() { return 'sortBy'; } function getCurrentRefinement$9(props, searchState, context) { var id = getId$b(); var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null); 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 = createConnectorWithContext({ 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$9(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = props.items.map(function (item) { return item.value === currentRefinement ? _objectSpread({}, item, { isRefined: true }) : _objectSpread({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId$b(); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, getId$b()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement$9(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId$b() }; } }); /** * 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 = createConnectorWithContext({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); function getId$c(props) { return props.attribute; } var namespace$6 = 'toggle'; var falsyStrings = ['0', 'false', 'null', 'undefined']; function getCurrentRefinement$a(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$6, ".").concat(getId$c(props)), false); if (falsyStrings.indexOf(currentRefinement) !== -1) { return false; } return Boolean(currentRefinement); } function _refine$8(props, searchState, nextRefinement, context) { var id = getId$c(props); var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : false); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$6); } function _cleanUp$6(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$6, ".").concat(getId$c(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 {boolean} currentRefinement - `true` when the refinement is applied, `false` otherwise * @providedPropType {object} count - an object that contains the count for `checked` and `unchecked` state * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state */ var connectToggleRefinement = createConnectorWithContext({ displayName: 'AlgoliaToggle', propTypes: { label: propTypes.string.isRequired, attribute: propTypes.string.isRequired, value: propTypes.any.isRequired, filter: propTypes.func, defaultRefinement: propTypes.bool }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute, value = props.value; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var currentRefinement = getCurrentRefinement$a(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var allFacetValues = results && results.getFacetByName(attribute) ? results.getFacetValues(attribute) : null; var facetValue = // Use null to always be consistent with type of the value // count: number | null allFacetValues && allFacetValues.length ? find(allFacetValues, function (item) { return item.name === value.toString(); }) : null; var facetValueCount = facetValue && facetValue.count; var allFacetValuesCount = // Use null to always be consistent with type of the value // count: number | null allFacetValues && allFacetValues.length ? allFacetValues.reduce(function (acc, item) { return acc + item.count; }, 0) : null; var canRefine = currentRefinement ? allFacetValuesCount !== null && allFacetValuesCount > 0 : facetValueCount !== null && facetValueCount > 0; var count = { checked: allFacetValuesCount, unchecked: facetValueCount }; return { currentRefinement: currentRefinement, canRefine: canRefine, count: count }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$8(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$6(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, value = props.value, filter = props.filter; var checked = getCurrentRefinement$a(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var nextSearchParameters = searchParameters.addDisjunctiveFacet(attribute); if (checked) { nextSearchParameters = nextSearchParameters.addDisjunctiveFacetRefinement(attribute, value); if (filter) { nextSearchParameters = filter(nextSearchParameters); } } return nextSearchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId$c(props); var checked = getCurrentRefinement$a(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = []; var index = getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (checked) { items.push({ label: props.label, currentRefinement: checked, attribute: props.attribute, value: function value(nextState) { return _refine$8(props, nextState, false, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); } return { id: id, index: index, items: items }; } }); var classnames = createCommonjsModule(function (module) { /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 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 ( module.exports) { module.exports = classNames; } else { window.classNames = classNames; } }()); }); var createClassNames = function createClassNames(block) { var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'ais'; return function () { for (var _len = arguments.length, elements = new Array(_len), _key = 0; _key < _len; _key++) { elements[_key] = arguments[_key]; } var suitElements = elements.filter(function (element) { return element || element === ''; }).map(function (element) { var baseClassName = "".concat(prefix, "-").concat(block); return element ? "".concat(baseClassName, "-").concat(element) : baseClassName; }); return classnames(suitElements); }; }; var isSpecialClick = function isSpecialClick(event) { var isMiddleClick = event.button === 1; return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey); }; var capitalize = function capitalize(key) { return key.length === 0 ? '' : "".concat(key[0].toUpperCase()).concat(key.slice(1)); }; // taken from InstantSearch.js/utils function range(_ref) { var _ref$start = _ref.start, start = _ref$start === void 0 ? 0 : _ref$start, end = _ref.end, _ref$step = _ref.step, step = _ref$step === void 0 ? 1 : _ref$step; // We can't divide by 0 so we re-assign the step to 1 if it happens. var limitStep = step === 0 ? 1 : step; // In some cases the array to create has a decimal length. // We therefore need to round the value. // Example: // { start: 1, end: 5000, step: 500 } // => Array length = (5000 - 1) / 500 = 9.998 var arrayLength = Math.round((end - start) / limitStep); return _toConsumableArray(Array(arrayLength)).map(function (_, current) { return (start + current) * limitStep; }); } function find$2(array, comparator) { if (!Array.isArray(array)) { return undefined; } for (var i = 0; i < array.length; i++) { if (comparator(array[i])) { return array[i]; } } return undefined; } var cx = createClassNames('Panel'); var _createContext$1 = React.createContext(function setCanRefine() {}), PanelConsumer = _createContext$1.Consumer, PanelProvider = _createContext$1.Provider; var Panel = /*#__PURE__*/ function (_Component) { _inherits(Panel, _Component); function Panel() { var _getPrototypeOf2; var _this; _classCallCheck(this, Panel); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Panel)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "state", { canRefine: true }); _defineProperty(_assertThisInitialized(_this), "setCanRefine", function (nextCanRefine) { _this.setState({ canRefine: nextCanRefine }); }); return _this; } _createClass(Panel, [{ key: "render", value: function render() { var _this$props = this.props, children = _this$props.children, className = _this$props.className, header = _this$props.header, footer = _this$props.footer; var canRefine = this.state.canRefine; return React__default.createElement("div", { className: classnames(cx('', !canRefine && '-noRefinement'), className) }, header && React__default.createElement("div", { className: cx('header') }, header), React__default.createElement("div", { className: cx('body') }, React__default.createElement(PanelProvider, { value: this.setCanRefine }, children)), footer && React__default.createElement("div", { className: cx('footer') }, footer)); } }]); return Panel; }(React.Component); _defineProperty(Panel, "propTypes", { children: propTypes.node.isRequired, className: propTypes.string, header: propTypes.node, footer: propTypes.node }); _defineProperty(Panel, "defaultProps", { className: '', header: null, footer: null }); var PanelCallbackHandler = /*#__PURE__*/ function (_Component) { _inherits(PanelCallbackHandler, _Component); function PanelCallbackHandler() { _classCallCheck(this, PanelCallbackHandler); return _possibleConstructorReturn(this, _getPrototypeOf(PanelCallbackHandler).apply(this, arguments)); } _createClass(PanelCallbackHandler, [{ key: "componentDidMount", value: function componentDidMount() { this.props.setCanRefine(this.props.canRefine); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.canRefine !== this.props.canRefine) { this.props.setCanRefine(this.props.canRefine); } } }, { key: "render", value: function render() { return this.props.children; } }]); return PanelCallbackHandler; }(React.Component); _defineProperty(PanelCallbackHandler, "propTypes", { children: propTypes.node.isRequired, canRefine: propTypes.bool.isRequired, setCanRefine: propTypes.func.isRequired }); var PanelWrapper = function PanelWrapper(_ref) { var canRefine = _ref.canRefine, children = _ref.children; return React__default.createElement(PanelConsumer, null, function (setCanRefine) { return React__default.createElement(PanelCallbackHandler, { setCanRefine: setCanRefine, canRefine: canRefine }, children); }); }; var Link = /*#__PURE__*/ function (_Component) { _inherits(Link, _Component); function Link() { var _getPrototypeOf2; var _this; _classCallCheck(this, Link); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Link)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "onClick", function (e) { if (isSpecialClick(e)) { return; } _this.props.onClick(); e.preventDefault(); }); return _this; } _createClass(Link, [{ key: "render", value: function render() { return React__default.createElement("a", _extends({}, this.props, { onClick: this.onClick })); } }]); return Link; }(React.Component); _defineProperty(Link, "propTypes", { onClick: propTypes.func.isRequired }); var cx$1 = createClassNames('Breadcrumb'); var itemsPropType = propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired })); var Breadcrumb = /*#__PURE__*/ function (_Component) { _inherits(Breadcrumb, _Component); function Breadcrumb() { _classCallCheck(this, Breadcrumb); return _possibleConstructorReturn(this, _getPrototypeOf(Breadcrumb).apply(this, arguments)); } _createClass(Breadcrumb, [{ key: "render", value: function render() { var _this$props = this.props, canRefine = _this$props.canRefine, createURL = _this$props.createURL, items = _this$props.items, refine = _this$props.refine, rootURL = _this$props.rootURL, separator = _this$props.separator, translate = _this$props.translate, className = _this$props.className; var rootPath = canRefine ? React__default.createElement("li", { className: cx$1('item') }, React__default.createElement(Link, { className: cx$1('link'), onClick: function onClick() { return !rootURL ? refine() : null; }, href: rootURL ? rootURL : createURL() }, translate('rootLabel'))) : null; var breadcrumb = items.map(function (item, idx) { var isLast = idx === items.length - 1; return React__default.createElement("li", { className: cx$1('item', isLast && 'item--selected'), key: idx }, React__default.createElement("span", { className: cx$1('separator') }, separator), !isLast ? React__default.createElement(Link, { className: cx$1('link'), onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }, item.label) : item.label); }); return React__default.createElement("div", { className: classnames(cx$1('', !canRefine && '-noRefinement'), className) }, React__default.createElement("ul", { className: cx$1('list') }, rootPath, breadcrumb)); } }]); return Breadcrumb; }(React.Component); _defineProperty(Breadcrumb, "propTypes", { canRefine: propTypes.bool.isRequired, createURL: propTypes.func.isRequired, items: itemsPropType, refine: propTypes.func.isRequired, rootURL: propTypes.string, separator: propTypes.node, translate: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(Breadcrumb, "defaultProps", { rootURL: null, separator: ' > ', className: '' }); var Breadcrumb$1 = translatable({ rootLabel: 'Home' })(Breadcrumb); /** * A breadcrumb is a secondary navigation scheme that allows the user to see where the current page * is in relation to the website or web application’s hierarchy. * In terms of usability, using a breadcrumb reduces the number of actions a visitor needs to take in * order to get to a higher-level page. * * If you want to select a specific refinement for your Breadcrumb component, you will need to * use a [Virtual Hierarchical Menu](https://community.algolia.com/react-instantsearch/guide/Virtual_widgets.html) * and set its defaultRefinement that will be then used by the Breadcrumb. * * @name Breadcrumb * @kind widget * @requirements Breadcrumbs are used for websites with a large amount of content organised in a hierarchical manner. * The typical example is an e-commerce website which has a large variety of products grouped into logical categories * (with categories, subcategories which also have subcategories).To use this widget, your attributes must be formatted in a specific way. * * Keep in mind that breadcrumbs shouldn’t replace effective primary navigation menus: * it is only an alternative way to navigate around the website. * * If, for instance, you would like 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. * * @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 {node} [separator='>'] - Symbol used for separating hyperlinks * @propType {string} [rootURL=null] - The originating page (homepage) * @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-Breadcrumb - the root div of the widget * @themeKey ais-Breadcrumb--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-Breadcrumb-list - the list of all breadcrumb items * @themeKey ais-Breadcrumb-item - the breadcrumb navigation item * @themeKey ais-Breadcrumb-item--selected - the selected breadcrumb item * @themeKey ais-Breadcrumb-separator - the separator of each breadcrumb item * @themeKey ais-Breadcrumb-link - the clickable breadcrumb element * @translationKey rootLabel - The root's label. Accepts a string * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { Breadcrumb, InstantSearch, HierarchicalMenu } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Breadcrumb * attributes={[ * 'hierarchicalCategories.lvl0', * 'hierarchicalCategories.lvl1', * 'hierarchicalCategories.lvl2', * ]} * /> * <HierarchicalMenu * defaultRefinement="Cameras & Camcorders" * attributes={[ * 'hierarchicalCategories.lvl0', * 'hierarchicalCategories.lvl1', * 'hierarchicalCategories.lvl2', * ]} * /> * </InstantSearch> * ); */ var BreadcrumbWidget = function BreadcrumbWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(Breadcrumb$1, props)); }; var Breadcrumb$2 = connectBreadcrumb(BreadcrumbWidget); var cx$2 = createClassNames('ClearRefinements'); var ClearRefinements = /*#__PURE__*/ function (_Component) { _inherits(ClearRefinements, _Component); function ClearRefinements() { _classCallCheck(this, ClearRefinements); return _possibleConstructorReturn(this, _getPrototypeOf(ClearRefinements).apply(this, arguments)); } _createClass(ClearRefinements, [{ key: "render", value: function render() { var _this$props = this.props, items = _this$props.items, canRefine = _this$props.canRefine, refine = _this$props.refine, translate = _this$props.translate, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$2(''), className) }, React__default.createElement("button", { className: cx$2('button', !canRefine && 'button--disabled'), onClick: function onClick() { return refine(items); }, disabled: !canRefine }, translate('reset'))); } }]); return ClearRefinements; }(React.Component); _defineProperty(ClearRefinements, "propTypes", { items: propTypes.arrayOf(propTypes.object).isRequired, canRefine: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(ClearRefinements, "defaultProps", { className: '' }); var ClearRefinements$1 = translatable({ reset: 'Clear all filters' })(ClearRefinements); /** * The ClearRefinements widget displays a button that lets the user clean every refinement applied * to the search. * @name ClearRefinements * @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-ClearRefinements - the root div of the widget * @themeKey ais-ClearRefinements-button - the clickable button * @themeKey ais-ClearRefinements-button--disabled - the disabled clickable button * @translationKey reset - the clear all button value * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, ClearRefinements, RefinementList } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <ClearRefinements /> * <RefinementList * attribute="brand" * defaultRefinement={['Apple']} * /> * </InstantSearch> * ); */ var ClearRefinementsWidget = function ClearRefinementsWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(ClearRefinements$1, props)); }; var ClearRefinements$2 = connectCurrentRefinements(ClearRefinementsWidget); var cx$3 = createClassNames('CurrentRefinements'); var CurrentRefinements = function CurrentRefinements(_ref) { var items = _ref.items, canRefine = _ref.canRefine, refine = _ref.refine, translate = _ref.translate, className = _ref.className; return React__default.createElement("div", { className: classnames(cx$3('', !canRefine && '-noRefinement'), className) }, React__default.createElement("ul", { className: cx$3('list', !canRefine && 'list--noRefinement') }, items.map(function (item) { return React__default.createElement("li", { key: item.label, className: cx$3('item') }, React__default.createElement("span", { className: cx$3('label') }, item.label), item.items ? item.items.map(function (nest) { return React__default.createElement("span", { key: nest.label, className: cx$3('category') }, React__default.createElement("span", { className: cx$3('categoryLabel') }, nest.label), React__default.createElement("button", { className: cx$3('delete'), onClick: function onClick() { return refine(nest.value); } }, translate('clearFilter', nest))); }) : React__default.createElement("span", { className: cx$3('category') }, React__default.createElement("button", { className: cx$3('delete'), onClick: function onClick() { return refine(item.value); } }, translate('clearFilter', item)))); }))); }; var itemPropTypes = propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.func.isRequired, items: function items() { return itemPropTypes.apply(void 0, arguments); } })); CurrentRefinements.defaultProps = { className: '' }; var CurrentRefinements$1 = translatable({ clearFilter: '✕' })(CurrentRefinements); /** * 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 - the root div of the widget * @themeKey ais-CurrentRefinements--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-CurrentRefinements-list - the list of all refined items * @themeKey ais-CurrentRefinements-list--noRefinement - the list of all refined items when there is no refinement * @themeKey ais-CurrentRefinements-item - the refined list item * @themeKey ais-CurrentRefinements-button - the button of each refined list item * @themeKey ais-CurrentRefinements-label - the refined list label * @themeKey ais-CurrentRefinements-category - the category of each item * @themeKey ais-CurrentRefinements-categoryLabel - the label of each catgory * @themeKey ais-CurrentRefinements-delete - the delete button of each label * @translationKey clearFilter - the remove filter button label * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, CurrentRefinements, RefinementList } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <CurrentRefinements /> * <RefinementList * attribute="brand" * defaultRefinement={['Colors']} * /> * </InstantSearch> * ); */ var CurrentRefinementsWidget = function CurrentRefinementsWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(CurrentRefinements$1, props)); }; var CurrentRefinements$2 = connectCurrentRefinements(CurrentRefinementsWidget); var cx$4 = createClassNames('SearchBox'); var defaultLoadingIndicator = React__default.createElement("svg", { width: "18", height: "18", viewBox: "0 0 38 38", xmlns: "http://www.w3.org/2000/svg", stroke: "#444", className: cx$4('loadingIcon') }, React__default.createElement("g", { fill: "none", fillRule: "evenodd" }, React__default.createElement("g", { transform: "translate(1 1)", strokeWidth: "2" }, React__default.createElement("circle", { strokeOpacity: ".5", cx: "18", cy: "18", r: "18" }), React__default.createElement("path", { d: "M36 18c0-9.94-8.06-18-18-18" }, React__default.createElement("animateTransform", { attributeName: "transform", type: "rotate", from: "0 18 18", to: "360 18 18", dur: "1s", repeatCount: "indefinite" }))))); var defaultReset = React__default.createElement("svg", { className: cx$4('resetIcon'), xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", width: "10", height: "10" }, React__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" })); var defaultSubmit = React__default.createElement("svg", { className: cx$4('submitIcon'), xmlns: "http://www.w3.org/2000/svg", width: "10", height: "10", viewBox: "0 0 40 40" }, React__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" })); var SearchBox = /*#__PURE__*/ function (_Component) { _inherits(SearchBox, _Component); function SearchBox(props) { var _this; _classCallCheck(this, SearchBox); _this = _possibleConstructorReturn(this, _getPrototypeOf(SearchBox).call(this)); _defineProperty(_assertThisInitialized(_this), "getQuery", function () { return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query; }); _defineProperty(_assertThisInitialized(_this), "onInputMount", function (input) { _this.input = input; if (_this.props.__inputRef) { _this.props.__inputRef(input); } }); _defineProperty(_assertThisInitialized(_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(); }); _defineProperty(_assertThisInitialized(_this), "onSubmit", function (e) { e.preventDefault(); e.stopPropagation(); _this.input.blur(); var _this$props = _this.props, refine = _this$props.refine, searchAsYouType = _this$props.searchAsYouType; if (!searchAsYouType) { refine(_this.getQuery()); } return false; }); _defineProperty(_assertThisInitialized(_this), "onChange", function (event) { var _this$props2 = _this.props, searchAsYouType = _this$props2.searchAsYouType, refine = _this$props2.refine, onChange = _this$props2.onChange; var value = event.target.value; if (searchAsYouType) { refine(value); } else { _this.setState({ query: value }); } if (onChange) { onChange(event); } }); _defineProperty(_assertThisInitialized(_this), "onReset", function (event) { var _this$props3 = _this.props, searchAsYouType = _this$props3.searchAsYouType, refine = _this$props3.refine, onReset = _this$props3.onReset; refine(''); _this.input.focus(); if (!searchAsYouType) { _this.setState({ query: '' }); } if (onReset) { onReset(event); } }); _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: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (!this.props.searchAsYouType && prevProps.currentRefinement !== this.props.currentRefinement) { this.setState({ query: this.props.currentRefinement }); } } }, { key: "render", value: function render() { var _this2 = this; var _this$props4 = this.props, className = _this$props4.className, translate = _this$props4.translate, autoFocus = _this$props4.autoFocus, loadingIndicator = _this$props4.loadingIndicator, submit = _this$props4.submit, reset = _this$props4.reset; var query = this.getQuery(); var searchInputEvents = Object.keys(this.props).reduce(function (props, prop) { if (['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) === -1 && prop.indexOf('on') === 0) { return _objectSpread({}, props, _defineProperty({}, prop, _this2.props[prop])); } return props; }, {}); var isSearchStalled = this.props.showLoadingIndicator && this.props.isSearchStalled; /* eslint-disable max-len */ return React__default.createElement("div", { className: classnames(cx$4(''), className) }, React__default.createElement("form", { noValidate: true, onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit, onReset: this.onReset, className: cx$4('form', isSearchStalled && 'form--stalledSearch'), action: "", role: "search" }, React__default.createElement("input", _extends({ ref: this.onInputMount, type: "search", placeholder: translate('placeholder'), autoFocus: autoFocus, autoComplete: "off", autoCorrect: "off", autoCapitalize: "off", spellCheck: "false", required: true, maxLength: "512", value: query, onChange: this.onChange }, searchInputEvents, { className: cx$4('input') })), React__default.createElement("button", { type: "submit", title: translate('submitTitle'), className: cx$4('submit') }, submit), React__default.createElement("button", { type: "reset", title: translate('resetTitle'), className: cx$4('reset'), hidden: !query || isSearchStalled }, reset), this.props.showLoadingIndicator && React__default.createElement("span", { hidden: !isSearchStalled, className: cx$4('loadingIndicator') }, loadingIndicator))); /* eslint-enable */ } }]); return SearchBox; }(React.Component); _defineProperty(SearchBox, "propTypes", { currentRefinement: propTypes.string, className: propTypes.string, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, loadingIndicator: propTypes.node, reset: propTypes.node, submit: propTypes.node, focusShortcuts: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), autoFocus: propTypes.bool, searchAsYouType: propTypes.bool, onSubmit: propTypes.func, onReset: propTypes.func, onChange: propTypes.func, isSearchStalled: propTypes.bool, showLoadingIndicator: propTypes.bool, // For testing purposes __inputRef: propTypes.func }); _defineProperty(SearchBox, "defaultProps", { currentRefinement: '', className: '', focusShortcuts: ['s', '/'], autoFocus: false, searchAsYouType: true, showLoadingIndicator: false, isSearchStalled: false, loadingIndicator: defaultLoadingIndicator, reset: defaultReset, submit: defaultSubmit }); var SearchBox$1 = translatable({ resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(SearchBox); var itemsPropType$1 = propTypes.arrayOf(propTypes.shape({ value: propTypes.any, label: propTypes.node.isRequired, items: function items() { return itemsPropType$1.apply(void 0, arguments); } })); var List = /*#__PURE__*/ function (_Component) { _inherits(List, _Component); function List() { var _this; _classCallCheck(this, List); _this = _possibleConstructorReturn(this, _getPrototypeOf(List).call(this)); _defineProperty(_assertThisInitialized(_this), "onShowMoreClick", function () { _this.setState(function (state) { return { extended: !state.extended }; }); }); _defineProperty(_assertThisInitialized(_this), "getLimit", function () { var _this$props = _this.props, limit = _this$props.limit, showMoreLimit = _this$props.showMoreLimit; var extended = _this.state.extended; return extended ? showMoreLimit : limit; }); _defineProperty(_assertThisInitialized(_this), "resetQuery", function () { _this.setState({ query: '' }); }); _defineProperty(_assertThisInitialized(_this), "renderItem", function (item, resetQuery) { var itemHasChildren = item.items && Boolean(item.items.length); return React__default.createElement("li", { key: item.key || item.label, className: _this.props.cx('item', item.isRefined && 'item--selected', item.noRefinement && 'item--noRefinement', itemHasChildren && 'item--parent') }, _this.props.renderItem(item, resetQuery), itemHasChildren && React__default.createElement("ul", { className: _this.props.cx('list', 'list--child') }, item.items.slice(0, _this.getLimit()).map(function (child) { return _this.renderItem(child, item); }))); }); _this.state = { extended: false, query: '' }; return _this; } _createClass(List, [{ key: "renderShowMore", value: function renderShowMore() { var _this$props2 = this.props, showMore = _this$props2.showMore, translate = _this$props2.translate, cx = _this$props2.cx; var extended = this.state.extended; var disabled = this.props.limit >= this.props.items.length; if (!showMore) { return null; } return React__default.createElement("button", { disabled: disabled, className: cx('showMore', disabled && 'showMore--disabled'), onClick: this.onShowMoreClick }, translate('showMore', extended)); } }, { key: "renderSearchBox", value: function renderSearchBox() { var _this2 = this; var _this$props3 = this.props, cx = _this$props3.cx, searchForItems = _this$props3.searchForItems, isFromSearch = _this$props3.isFromSearch, translate = _this$props3.translate, items = _this$props3.items, selectItem = _this$props3.selectItem; var noResults = items.length === 0 && this.state.query !== '' ? React__default.createElement("div", { className: cx('noResults') }, translate('noResults')) : null; return React__default.createElement("div", { className: cx('searchBox') }, React__default.createElement(SearchBox$1, { 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 _this$props4 = this.props, cx = _this$props4.cx, items = _this$props4.items, className = _this$props4.className, searchable = _this$props4.searchable, canRefine = _this$props4.canRefine; var searchBox = searchable ? this.renderSearchBox() : null; var rootClassName = classnames(cx('', !canRefine && '-noRefinement'), className); if (items.length === 0) { return React__default.createElement("div", { className: rootClassName }, 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. return React__default.createElement("div", { className: rootClassName }, searchBox, React__default.createElement("ul", { className: cx('list', !canRefine && 'list--noRefinement') }, items.slice(0, this.getLimit()).map(function (item) { return _this3.renderItem(item, _this3.resetQuery); })), this.renderShowMore()); } }]); return List; }(React.Component); _defineProperty(List, "propTypes", { cx: propTypes.func.isRequired, // Only required with showMore. translate: propTypes.func, items: itemsPropType$1, renderItem: propTypes.func.isRequired, selectItem: propTypes.func, className: propTypes.string, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, show: propTypes.func, searchForItems: propTypes.func, searchable: propTypes.bool, isFromSearch: propTypes.bool, canRefine: propTypes.bool }); _defineProperty(List, "defaultProps", { className: '', isFromSearch: false }); var cx$5 = createClassNames('HierarchicalMenu'); var itemsPropType$2 = propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string, count: propTypes.number.isRequired, items: function items() { return itemsPropType$2.apply(void 0, arguments); } })); var HierarchicalMenu = /*#__PURE__*/ function (_Component) { _inherits(HierarchicalMenu, _Component); function HierarchicalMenu() { var _getPrototypeOf2; var _this; _classCallCheck(this, HierarchicalMenu); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(HierarchicalMenu)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "renderItem", function (item) { var _this$props = _this.props, createURL = _this$props.createURL, refine = _this$props.refine; return React__default.createElement(Link, { className: cx$5('link'), onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }, React__default.createElement("span", { className: cx$5('label') }, item.label), ' ', React__default.createElement("span", { className: cx$5('count') }, item.count)); }); return _this; } _createClass(HierarchicalMenu, [{ key: "render", value: function render() { var _this$props2 = this.props, translate = _this$props2.translate, items = _this$props2.items, showMore = _this$props2.showMore, limit = _this$props2.limit, showMoreLimit = _this$props2.showMoreLimit, canRefine = _this$props2.canRefine, className = _this$props2.className; return React__default.createElement(List, { renderItem: this.renderItem, cx: cx$5, translate: translate, items: items, showMore: showMore, limit: limit, showMoreLimit: showMoreLimit, canRefine: canRefine, className: className }); } }]); return HierarchicalMenu; }(React.Component); _defineProperty(HierarchicalMenu, "propTypes", { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired, items: itemsPropType$2, showMore: propTypes.bool, className: propTypes.string, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func }); _defineProperty(HierarchicalMenu, "defaultProps", { className: '' }); var HierarchicalMenu$1 = translatable({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; } })(HierarchicalMenu); /** * 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 * [{ * "objectID": "321432", * "name": "lemon", * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * }, * { * "objectID": "8976987", * "name": "orange", * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * }] * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "objectID": "321432", * "name": "lemon", * "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 {array.<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 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 path to use if the first level is not the root level. * @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 - the root div of the widget * @themeKey ais-HierarchicalMenu-noRefinement - the root div of the widget when there is no refinement * @themeKey ais-HierarchicalMenu-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @themeKey ais-HierarchicalMenu-list - the list of menu items * @themeKey ais-HierarchicalMenu-list--child - the child list of menu items * @themeKey ais-HierarchicalMenu-item - the menu list item * @themeKey ais-HierarchicalMenu-item--selected - the selected menu list item * @themeKey ais-HierarchicalMenu-item--parent - the menu list item containing children * @themeKey ais-HierarchicalMenu-link - the clickable menu element * @themeKey ais-HierarchicalMenu-label - the label of each item * @themeKey ais-HierarchicalMenu-count - the count of values for each item * @themeKey ais-HierarchicalMenu-showMore - the button used to display more categories * @themeKey ais-HierarchicalMenu-showMore--disabled - the disabled button used to display more categories * @translationKey showMore - The label of the show more button. Accepts one parameter, a boolean that is true if the values are expanded * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, HierarchicalMenu } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <HierarchicalMenu * attributes={[ * 'hierarchicalCategories.lvl0', * 'hierarchicalCategories.lvl1', * 'hierarchicalCategories.lvl2', * ]} * /> * </InstantSearch> * ); */ var HierarchicalMenuWidget = function HierarchicalMenuWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(HierarchicalMenu$1, props)); }; var HierarchicalMenu$2 = connectHierarchicalMenu(HierarchicalMenuWidget); var Highlight = function Highlight(_ref) { var cx = _ref.cx, value = _ref.value, highlightedTagName = _ref.highlightedTagName, isHighlighted = _ref.isHighlighted, nonHighlightedTagName = _ref.nonHighlightedTagName; var TagName = isHighlighted ? highlightedTagName : nonHighlightedTagName; var className = isHighlighted ? 'highlighted' : 'nonHighlighted'; return React__default.createElement(TagName, { className: cx(className) }, value); }; var Highlighter = function Highlighter(_ref2) { var cx = _ref2.cx, hit = _ref2.hit, attribute = _ref2.attribute, highlight = _ref2.highlight, highlightProperty = _ref2.highlightProperty, tagName = _ref2.tagName, nonHighlightedTagName = _ref2.nonHighlightedTagName, separator = _ref2.separator, className = _ref2.className; var parsedHighlightedValue = highlight({ hit: hit, attribute: attribute, highlightProperty: highlightProperty }); return React__default.createElement("span", { className: classnames(cx(''), className) }, parsedHighlightedValue.map(function (item, i) { if (Array.isArray(item)) { var isLast = i === parsedHighlightedValue.length - 1; return React__default.createElement("span", { key: i }, item.map(function (element, index) { return React__default.createElement(Highlight, { cx: cx, key: index, value: element.value, highlightedTagName: tagName, nonHighlightedTagName: nonHighlightedTagName, isHighlighted: element.isHighlighted }); }), !isLast && React__default.createElement("span", { className: cx('separator') }, separator)); } return React__default.createElement(Highlight, { cx: cx, key: i, value: item.value, highlightedTagName: tagName, nonHighlightedTagName: nonHighlightedTagName, isHighlighted: item.isHighlighted }); })); }; Highlighter.defaultProps = { tagName: 'em', nonHighlightedTagName: 'span', className: '', separator: ', ' }; var cx$6 = createClassNames('Highlight'); var Highlight$1 = function Highlight(props) { return React__default.createElement(Highlighter, _extends({}, props, { highlightProperty: "_highlightResult", cx: cx$6 })); }; /** * Renders any attribute from a 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} attribute - location of the highlighted attribute in the hit (the corresponding element can be either a string or an array of strings) * @propType {object} hit - hit object containing the highlighted attribute * @propType {string} [tagName='em'] - tag to be used for highlighted parts of the hit * @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted * @propType {node} [separator=',<space>'] - symbol used to separate the elements of the array in case the attribute points to an array of strings. * @themeKey ais-Highlight - root of the component * @themeKey ais-Highlight-highlighted - part of the text which is highlighted * @themeKey ais-Highlight-nonHighlighted - part of the text that is not highlighted * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox, Hits, Highlight } from 'react-instantsearch-dom'; * * const Hit = ({ hit }) => ( * <div> * <Highlight attribute="name" hit={hit} /> * </div> * ); * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox defaultRefinement="Pho" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var Highlight$2 = connectHighlight(Highlight$1); var cx$7 = createClassNames('Hits'); var DefaultHitComponent = function DefaultHitComponent(props) { return React__default.createElement("div", { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px', wordBreak: 'break-all' } }, JSON.stringify(props).slice(0, 100), "..."); }; var Hits = function Hits(_ref) { var hits = _ref.hits, _ref$className = _ref.className, className = _ref$className === void 0 ? '' : _ref$className, _ref$hitComponent = _ref.hitComponent, HitComponent = _ref$hitComponent === void 0 ? DefaultHitComponent : _ref$hitComponent; return React__default.createElement("div", { className: classnames(cx$7(''), className) }, React__default.createElement("ul", { className: cx$7('list') }, hits.map(function (hit) { return React__default.createElement("li", { className: cx$7('item'), key: hit.objectID }, React__default.createElement(HitComponent, { hit: hit })); }))); }; var HitPropTypes = propTypes.shape({ objectID: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired }); /** * 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 - the root div of the widget * @themeKey ais-Hits-list - the list of results * @themeKey ais-Hits-item - the hit list item * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Hits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Hits /> * </InstantSearch> * ); */ var Hits$1 = connectHits(Hits); var Select = /*#__PURE__*/ function (_Component) { _inherits(Select, _Component); function Select() { var _getPrototypeOf2; var _this; _classCallCheck(this, Select); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Select)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "onChange", function (e) { _this.props.onSelect(e.target.value); }); return _this; } _createClass(Select, [{ key: "render", value: function render() { var _this$props = this.props, cx = _this$props.cx, items = _this$props.items, selectedItem = _this$props.selectedItem; return React__default.createElement("select", { className: cx('select'), value: selectedItem, onChange: this.onChange }, items.map(function (item) { return React__default.createElement("option", { className: cx('option'), key: item.key === undefined ? item.value : item.key, disabled: item.disabled, value: item.value }, item.label === undefined ? item.value : item.label); })); } }]); return Select; }(React.Component); _defineProperty(Select, "propTypes", { cx: propTypes.func.isRequired, onSelect: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ value: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired, key: propTypes.oneOfType([propTypes.string, propTypes.number]), label: propTypes.string, disabled: propTypes.bool })).isRequired, selectedItem: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired }); var cx$8 = createClassNames('HitsPerPage'); var HitsPerPage = /*#__PURE__*/ function (_Component) { _inherits(HitsPerPage, _Component); function HitsPerPage() { _classCallCheck(this, HitsPerPage); return _possibleConstructorReturn(this, _getPrototypeOf(HitsPerPage).apply(this, arguments)); } _createClass(HitsPerPage, [{ key: "render", value: function render() { var _this$props = this.props, items = _this$props.items, currentRefinement = _this$props.currentRefinement, refine = _this$props.refine, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$8(''), className) }, React__default.createElement(Select, { onSelect: refine, selectedItem: currentRefinement, items: items, cx: cx$8 })); } }]); return HitsPerPage; }(React.Component); _defineProperty(HitsPerPage, "propTypes", { items: propTypes.arrayOf(propTypes.shape({ value: propTypes.number.isRequired, label: propTypes.string })).isRequired, currentRefinement: propTypes.number.isRequired, refine: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(HitsPerPage, "defaultProps", { className: '' }); /** * 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 - the root div of the widget * @themeKey ais-HitsPerPage-select - the select * @themeKey ais-HitsPerPage-option - the select option * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, HitsPerPage, Hits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <HitsPerPage * defaultRefinement={5} * items={[ * { value: 5, label: 'Show 5 hits' }, * { value: 10, label: 'Show 10 hits' }, * ]} * /> * <Hits /> * </InstantSearch> * ); */ var HitsPerPage$1 = connectHitsPerPage(HitsPerPage); var cx$9 = createClassNames('InfiniteHits'); var InfiniteHits = /*#__PURE__*/ function (_Component) { _inherits(InfiniteHits, _Component); function InfiniteHits() { _classCallCheck(this, InfiniteHits); return _possibleConstructorReturn(this, _getPrototypeOf(InfiniteHits).apply(this, arguments)); } _createClass(InfiniteHits, [{ key: "render", value: function render() { var _this$props = this.props, HitComponent = _this$props.hitComponent, hits = _this$props.hits, showPrevious = _this$props.showPrevious, hasPrevious = _this$props.hasPrevious, hasMore = _this$props.hasMore, refinePrevious = _this$props.refinePrevious, refineNext = _this$props.refineNext, translate = _this$props.translate, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$9(''), className) }, showPrevious && React__default.createElement("button", { className: cx$9('loadPrevious', !hasPrevious && 'loadPrevious--disabled'), onClick: function onClick() { return refinePrevious(); }, disabled: !hasPrevious }, translate('loadPrevious')), React__default.createElement("ul", { className: cx$9('list') }, hits.map(function (hit) { return React__default.createElement("li", { key: hit.objectID, className: cx$9('item') }, React__default.createElement(HitComponent, { hit: hit })); })), React__default.createElement("button", { className: cx$9('loadMore', !hasMore && 'loadMore--disabled'), onClick: function onClick() { return refineNext(); }, disabled: !hasMore }, translate('loadMore'))); } }]); return InfiniteHits; }(React.Component); InfiniteHits.defaultProps = { className: '', showPrevious: false, hitComponent: function hitComponent(hit) { return React__default.createElement("div", { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px', wordBreak: 'break-all' } }, JSON.stringify(hit).slice(0, 100), "..."); } }; var InfiniteHits$1 = translatable({ loadPrevious: 'Load previous', loadMore: 'Load more' })(InfiniteHits); /** * 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 ais-InfiniteHits - the root div of the widget * @themeKey ais-InfiniteHits-list - the list of hits * @themeKey ais-InfiniteHits-item - the hit list item * @themeKey ais-InfiniteHits-loadMore - the button used to display more results * @themeKey ais-InfiniteHits-loadMore--disabled - the disabled button used to display more results * @translationKey loadMore - the label of load more button * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, InfiniteHits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <InfiniteHits /> * </InstantSearch> * ); */ var InfiniteHits$2 = connectInfiniteHits(InfiniteHits$1); var cx$a = createClassNames('Menu'); var Menu = /*#__PURE__*/ function (_Component) { _inherits(Menu, _Component); function Menu() { var _getPrototypeOf2; var _this; _classCallCheck(this, Menu); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Menu)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "renderItem", function (item, resetQuery) { var createURL = _this.props.createURL; var label = _this.props.isFromSearch ? React__default.createElement(Highlight$2, { attribute: "label", hit: item }) : item.label; return React__default.createElement(Link, { className: cx$a('link'), onClick: function onClick() { return _this.selectItem(item, resetQuery); }, href: createURL(item.value) }, React__default.createElement("span", { className: cx$a('label') }, label), ' ', React__default.createElement("span", { className: cx$a('count') }, item.count)); }); _defineProperty(_assertThisInitialized(_this), "selectItem", function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }); return _this; } _createClass(Menu, [{ key: "render", value: function render() { var _this$props = this.props, translate = _this$props.translate, items = _this$props.items, showMore = _this$props.showMore, limit = _this$props.limit, showMoreLimit = _this$props.showMoreLimit, isFromSearch = _this$props.isFromSearch, searchForItems = _this$props.searchForItems, searchable = _this$props.searchable, canRefine = _this$props.canRefine, className = _this$props.className; return React__default.createElement(List, { renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$a, translate: translate, items: items, showMore: showMore, limit: limit, showMoreLimit: showMoreLimit, isFromSearch: isFromSearch, searchForItems: searchForItems, searchable: searchable, canRefine: canRefine, className: className }); } }]); return Menu; }(React.Component); _defineProperty(Menu, "propTypes", { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, searchForItems: propTypes.func.isRequired, searchable: propTypes.bool, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired, count: propTypes.number.isRequired, isRefined: propTypes.bool.isRequired })), isFromSearch: propTypes.bool.isRequired, canRefine: propTypes.bool.isRequired, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func, className: propTypes.string }); _defineProperty(Menu, "defaultProps", { className: '' }); var Menu$1 = translatable({ 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); /** * 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 `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. * * If you are using the `searchable` prop, you'll also need to make the attribute searchable using * the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values). * @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 {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} [searchable=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/). * @themeKey ais-Menu - the root div of the widget * @themeKey ais-Menu-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @themeKey ais-Menu-list - the list of all menu items * @themeKey ais-Menu-item - the menu list item * @themeKey ais-Menu-item--selected - the selected menu list item * @themeKey ais-Menu-link - the clickable menu element * @themeKey ais-Menu-label - the label of each item * @themeKey ais-Menu-count - the count of values for each item * @themeKey ais-Menu-noResults - the div displayed when there are no results * @themeKey ais-Menu-showMore - the button used to display more categories * @themeKey ais-Menu-showMore--disabled - the disabled button used to display more categories * @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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Menu } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Menu attribute="categories" /> * </InstantSearch> * ); */ var MenuWidget = function MenuWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(Menu$1, props)); }; var Menu$2 = connectMenu(MenuWidget); var cx$b = createClassNames('MenuSelect'); var MenuSelect = /*#__PURE__*/ function (_Component) { _inherits(MenuSelect, _Component); function MenuSelect() { var _getPrototypeOf2; var _this; _classCallCheck(this, MenuSelect); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(MenuSelect)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "handleSelectChange", function (_ref) { var value = _ref.target.value; _this.props.refine(value === 'ais__see__all__option' ? '' : value); }); return _this; } _createClass(MenuSelect, [{ key: "render", value: function render() { var _this$props = this.props, items = _this$props.items, canRefine = _this$props.canRefine, translate = _this$props.translate, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$b('', !canRefine && '-noRefinement'), className) }, React__default.createElement("select", { value: this.selectedValue, onChange: this.handleSelectChange, className: cx$b('select') }, React__default.createElement("option", { value: "ais__see__all__option", className: cx$b('option') }, translate('seeAllOption')), items.map(function (item) { return React__default.createElement("option", { key: item.value, value: item.value, className: cx$b('option') }, item.label, " (", item.count, ")"); }))); } }, { key: "selectedValue", get: function get() { var _ref2 = find$2(this.props.items, function (item) { return item.isRefined === true; }) || { value: 'ais__see__all__option' }, value = _ref2.value; return value; } }]); return MenuSelect; }(React.Component); _defineProperty(MenuSelect, "propTypes", { items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired, count: propTypes.oneOfType([propTypes.number.isRequired, propTypes.string.isRequired]), isRefined: propTypes.bool.isRequired })).isRequired, canRefine: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(MenuSelect, "defaultProps", { className: '' }); var MenuSelect$1 = translatable({ seeAllOption: 'See all' })(MenuSelect); /** * The MenuSelect component displays a select that lets the user choose a single value for a specific attribute. * @name MenuSelect * @kind widget * @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 {string} [defaultRefinement] - the value of the item selected by default * @propType {number} [limit=10] - the minimum number of diplayed items * @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-MenuSelect - the root div of the widget * @themeKey ais-MenuSelect-noRefinement - the root div of the widget when there is no refinement * @themeKey ais-MenuSelect-select - the `<select>` * @themeKey ais-MenuSelect-option - the select `<option>` * @translationkey seeAllOption - The label of the option to select to remove the refinement * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, MenuSelect } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <MenuSelect attribute="categories" /> * </InstantSearch> * ); */ var MenuSelectWidget = function MenuSelectWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(MenuSelect$1, props)); }; var MenuSelect$2 = connectMenu(MenuSelectWidget); var cx$c = createClassNames('NumericMenu'); var NumericMenu = /*#__PURE__*/ function (_Component) { _inherits(NumericMenu, _Component); function NumericMenu() { var _getPrototypeOf2; var _this; _classCallCheck(this, NumericMenu); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(NumericMenu)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "renderItem", function (item) { var _this$props = _this.props, refine = _this$props.refine, translate = _this$props.translate; return React__default.createElement("label", { className: cx$c('label') }, React__default.createElement("input", { className: cx$c('radio'), type: "radio", checked: item.isRefined, disabled: item.noRefinement, onChange: function onChange() { return refine(item.value); } }), React__default.createElement("span", { className: cx$c('labelText') }, item.value === '' ? translate('all') : item.label)); }); return _this; } _createClass(NumericMenu, [{ key: "render", value: function render() { var _this$props2 = this.props, items = _this$props2.items, canRefine = _this$props2.canRefine, className = _this$props2.className; return React__default.createElement(List, { renderItem: this.renderItem, showMore: false, canRefine: canRefine, cx: cx$c, items: items.map(function (item) { return _objectSpread({}, item, { key: item.value }); }), className: className }); } }]); return NumericMenu; }(React.Component); _defineProperty(NumericMenu, "propTypes", { items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node.isRequired, value: propTypes.string.isRequired, isRefined: propTypes.bool.isRequired, noRefinement: propTypes.bool.isRequired })).isRequired, canRefine: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(NumericMenu, "defaultProps", { className: '' }); var NumericMenu$1 = translatable({ all: 'All' })(NumericMenu); /** * NumericMenu is a widget used for selecting the range value of a numeric attribute. * @name NumericMenu * @kind widget * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @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 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-NumericMenu - the root div of the widget * @themeKey ais-NumericMenu--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-NumericMenu-list - the list of all refinement items * @themeKey ais-NumericMenu-item - the refinement list item * @themeKey ais-NumericMenu-item--selected - the selected refinement list item * @themeKey ais-NumericMenu-label - the label of each refinement item * @themeKey ais-NumericMenu-radio - the radio input of each refinement item * @themeKey ais-NumericMenu-labelText - the label text of each refinement item * @translationkey all - The label of the largest range added automatically by react instantsearch * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, NumericMenu } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient * indexName="instant_search" * > * <NumericMenu * attribute="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> * ); */ var NumericMenuWidget = function NumericMenuWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(NumericMenu$1, props)); }; var NumericMenu$2 = connectNumericMenu(NumericMenuWidget); var LinkList = /*#__PURE__*/ function (_Component) { _inherits(LinkList, _Component); function LinkList() { _classCallCheck(this, LinkList); return _possibleConstructorReturn(this, _getPrototypeOf(LinkList).apply(this, arguments)); } _createClass(LinkList, [{ key: "render", value: function render() { var _this$props = this.props, cx = _this$props.cx, createURL = _this$props.createURL, items = _this$props.items, onSelect = _this$props.onSelect, canRefine = _this$props.canRefine; return React__default.createElement("ul", { className: cx('list', !canRefine && 'list--noRefinement') }, items.map(function (item) { return React__default.createElement("li", { key: item.key === undefined ? item.value : item.key, className: cx('item', item.selected && !item.disabled && 'item--selected', item.disabled && 'item--disabled', item.modifier) }, item.disabled ? React__default.createElement("span", { className: cx('link') }, item.label === undefined ? item.value : item.label) : React__default.createElement(Link, { className: cx('link', item.selected && 'link--selected'), "aria-label": item.ariaLabel, href: createURL(item.value), onClick: function onClick() { return onSelect(item.value); } }, item.label === undefined ? item.value : item.label)); })); } }]); return LinkList; }(React.Component); _defineProperty(LinkList, "propTypes", { cx: propTypes.func.isRequired, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ value: propTypes.oneOfType([propTypes.string, propTypes.number, propTypes.object]).isRequired, key: propTypes.oneOfType([propTypes.string, propTypes.number]), label: propTypes.node, modifier: propTypes.string, ariaLabel: propTypes.string, disabled: propTypes.bool })), onSelect: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired }); var cx$d = createClassNames('Pagination'); // Determines the size of the widget (the number of pages displayed - that the user can directly click on) function calculateSize(padding, maxPages) { return Math.min(2 * padding + 1, maxPages); } function calculatePaddingLeft(currentPage, padding, maxPages, size) { if (currentPage <= padding) { return currentPage; } if (currentPage >= maxPages - padding) { return size - (maxPages - currentPage); } return padding + 1; } // Retrieve the correct page range to populate the widget function getPages(currentPage, maxPages, padding) { var size = calculateSize(padding, maxPages); // If the widget size is equal to the max number of pages, return the entire page range if (size === maxPages) return range({ start: 1, end: maxPages + 1 }); var paddingLeft = calculatePaddingLeft(currentPage, padding, maxPages, size); var paddingRight = size - paddingLeft; var first = currentPage - paddingLeft; var last = currentPage + paddingRight; return range({ start: first + 1, end: last + 1 }); } var Pagination = /*#__PURE__*/ function (_Component) { _inherits(Pagination, _Component); function Pagination() { _classCallCheck(this, Pagination); return _possibleConstructorReturn(this, _getPrototypeOf(Pagination).apply(this, arguments)); } _createClass(Pagination, [{ key: "getItem", value: function getItem(modifier, translationKey, value) { var _this$props = this.props, nbPages = _this$props.nbPages, totalPages = _this$props.totalPages, translate = _this$props.translate; return { key: "".concat(modifier, ".").concat(value), modifier: modifier, disabled: value < 1 || value >= Math.min(totalPages, nbPages), label: translate(translationKey, value), value: value, ariaLabel: translate("aria".concat(capitalize(translationKey)), value) }; } }, { key: "render", value: function render() { var _this$props2 = this.props, ListComponent = _this$props2.listComponent, nbPages = _this$props2.nbPages, totalPages = _this$props2.totalPages, currentRefinement = _this$props2.currentRefinement, padding = _this$props2.padding, showFirst = _this$props2.showFirst, showPrevious = _this$props2.showPrevious, showNext = _this$props2.showNext, showLast = _this$props2.showLast, refine = _this$props2.refine, createURL = _this$props2.createURL, canRefine = _this$props2.canRefine, translate = _this$props2.translate, className = _this$props2.className, otherProps = _objectWithoutProperties(_this$props2, ["listComponent", "nbPages", "totalPages", "currentRefinement", "padding", "showFirst", "showPrevious", "showNext", "showLast", "refine", "createURL", "canRefine", "translate", "className"]); var maxPages = Math.min(nbPages, totalPages); var lastPage = maxPages; var items = []; if (showFirst) { items.push({ key: 'first', modifier: 'item--firstPage', disabled: currentRefinement === 1, label: translate('first'), value: 1, ariaLabel: translate('ariaFirst') }); } if (showPrevious) { items.push({ key: 'previous', modifier: 'item--previousPage', disabled: currentRefinement === 1, label: translate('previous'), value: currentRefinement - 1, ariaLabel: translate('ariaPrevious') }); } items = items.concat(getPages(currentRefinement, maxPages, padding).map(function (value) { return { key: value, modifier: 'item--page', label: translate('page', value), value: value, selected: value === currentRefinement, ariaLabel: translate('ariaPage', value) }; })); if (showNext) { items.push({ key: 'next', modifier: 'item--nextPage', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('next'), value: currentRefinement + 1, ariaLabel: translate('ariaNext') }); } if (showLast) { items.push({ key: 'last', modifier: 'item--lastPage', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('last'), value: lastPage, ariaLabel: translate('ariaLast') }); } return React__default.createElement("div", { className: classnames(cx$d('', !canRefine && '-noRefinement'), className) }, React__default.createElement(ListComponent, _extends({}, otherProps, { cx: cx$d, items: items, onSelect: refine, createURL: createURL, canRefine: canRefine }))); } }]); return Pagination; }(React.Component); _defineProperty(Pagination, "propTypes", { nbPages: propTypes.number.isRequired, currentRefinement: propTypes.number.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired, translate: propTypes.func.isRequired, listComponent: propTypes.func, showFirst: propTypes.bool, showPrevious: propTypes.bool, showNext: propTypes.bool, showLast: propTypes.bool, padding: propTypes.number, totalPages: propTypes.number, className: propTypes.string }); _defineProperty(Pagination, "defaultProps", { listComponent: LinkList, showFirst: true, showPrevious: true, showNext: true, showLast: false, padding: 3, totalPages: Infinity, className: '' }); var Pagination$1 = translatable({ 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 ".concat(currentRefinement.toString()); } })(Pagination); /** * 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} [padding=3] - How many page links to display around the current page. * @propType {number} [totalPages=Infinity] - Maximum number of pages to display. * @themeKey ais-Pagination - the root div of the widget * @themeKey ais-Pagination--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-Pagination-list - the list of all pagination items * @themeKey ais-Pagination-list--noRefinement - the list of all pagination items when there is no refinement * @themeKey ais-Pagination-item - the pagination list item * @themeKey ais-Pagination-item--firstPage - the "first" pagination list item * @themeKey ais-Pagination-item--lastPage - the "last" pagination list item * @themeKey ais-Pagination-item--previousPage - the "previous" pagination list item * @themeKey ais-Pagination-item--nextPage - the "next" pagination list item * @themeKey ais-Pagination-item--page - the "page" pagination list item * @themeKey ais-Pagination-item--selected - the selected pagination list item * @themeKey ais-Pagination-item--disabled - the disabled pagination list item * @themeKey ais-Pagination-link - the pagination clickable element * @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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Pagination } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Pagination /> * </InstantSearch> * ); */ var PaginationWidget = function PaginationWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(Pagination$1, props)); }; var Pagination$2 = connectPagination(PaginationWidget); var cx$e = createClassNames('PoweredBy'); /* eslint-disable max-len */ var AlgoliaLogo = function AlgoliaLogo() { return React__default.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", baseProfile: "basic", viewBox: "0 0 1366 362", width: "100", height: "27", className: cx$e('logo') }, React__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)" }, React__default.createElement("stop", { offset: "0", stopColor: "#00AEFF" }), React__default.createElement("stop", { offset: "1", stopColor: "#3369E7" })), React__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)" }), React__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" }), React__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 = /*#__PURE__*/ function (_Component) { _inherits(PoweredBy, _Component); function PoweredBy() { _classCallCheck(this, PoweredBy); return _possibleConstructorReturn(this, _getPrototypeOf(PoweredBy).apply(this, arguments)); } _createClass(PoweredBy, [{ key: "render", value: function render() { var _this$props = this.props, url = _this$props.url, translate = _this$props.translate, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$e(''), className) }, React__default.createElement("span", { className: cx$e('text') }, translate('searchBy')), ' ', React__default.createElement("a", { href: url, target: "_blank", className: cx$e('link'), "aria-label": "Algolia", rel: "noopener noreferrer" }, React__default.createElement(AlgoliaLogo, null))); } }]); return PoweredBy; }(React.Component); _defineProperty(PoweredBy, "propTypes", { url: propTypes.string.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }); var PoweredBy$1 = translatable({ searchBy: 'Search by' })(PoweredBy); /** * 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 - the root div of the widget * @themeKey ais-PoweredBy-text - the text of the widget * @themeKey ais-PoweredBy-link - the link of the logo * @themeKey ais-PoweredBy-logo - the logo of the widget * @translationKey searchBy - Label value for the powered by * @example * import React from 'react'; * import { InstantSearch, PoweredBy } from 'react-instantsearch-dom'; * import algoliasearch from 'algoliasearch/lite'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <PoweredBy /> * </InstantSearch> * ); */ var PoweredBy$2 = connectPoweredBy(PoweredBy$1); var cx$f = createClassNames('RangeInput'); var RawRangeInput = /*#__PURE__*/ function (_Component) { _inherits(RawRangeInput, _Component); function RawRangeInput(props) { var _this; _classCallCheck(this, RawRangeInput); _this = _possibleConstructorReturn(this, _getPrototypeOf(RawRangeInput).call(this, props)); _defineProperty(_assertThisInitialized(_this), "onSubmit", function (e) { e.preventDefault(); _this.props.refine({ min: _this.state.from, max: _this.state.to }); }); _this.state = _this.normalizeStateForRendering(props); return _this; } _createClass(RawRangeInput, [{ key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props.canRefine && (prevProps.currentRefinement.min !== this.props.currentRefinement.min || prevProps.currentRefinement.max !== this.props.currentRefinement.max)) { this.setState(this.normalizeStateForRendering(this.props)); } } }, { key: "normalizeStateForRendering", value: function normalizeStateForRendering(props) { var canRefine = props.canRefine, rangeMin = props.min, rangeMax = props.max; var _props$currentRefinem = props.currentRefinement, valueMin = _props$currentRefinem.min, valueMax = _props$currentRefinem.max; return { from: canRefine && valueMin !== undefined && valueMin !== rangeMin ? valueMin : '', to: canRefine && valueMax !== undefined && valueMax !== rangeMax ? valueMax : '' }; } }, { key: "normalizeRangeForRendering", value: function normalizeRangeForRendering(_ref) { var canRefine = _ref.canRefine, min = _ref.min, max = _ref.max; var hasMin = min !== undefined; var hasMax = max !== undefined; return { min: canRefine && hasMin && hasMax ? min : '', max: canRefine && hasMin && hasMax ? max : '' }; } }, { key: "render", value: function render() { var _this2 = this; var _this$state = this.state, from = _this$state.from, to = _this$state.to; var _this$props = this.props, precision = _this$props.precision, translate = _this$props.translate, canRefine = _this$props.canRefine, className = _this$props.className; var _this$normalizeRangeF = this.normalizeRangeForRendering(this.props), min = _this$normalizeRangeF.min, max = _this$normalizeRangeF.max; var step = 1 / Math.pow(10, precision); return React__default.createElement("div", { className: classnames(cx$f('', !canRefine && '-noRefinement'), className) }, React__default.createElement("form", { className: cx$f('form'), onSubmit: this.onSubmit }, React__default.createElement("input", { className: cx$f('input', 'input--min'), type: "number", min: min, max: max, value: from, step: step, placeholder: min, disabled: !canRefine, onChange: function onChange(e) { return _this2.setState({ from: e.currentTarget.value }); } }), React__default.createElement("span", { className: cx$f('separator') }, translate('separator')), React__default.createElement("input", { className: cx$f('input', 'input--max'), type: "number", min: min, max: max, value: to, step: step, placeholder: max, disabled: !canRefine, onChange: function onChange(e) { return _this2.setState({ to: e.currentTarget.value }); } }), React__default.createElement("button", { className: cx$f('submit'), type: "submit" }, translate('submit')))); } }]); return RawRangeInput; }(React.Component); _defineProperty(RawRangeInput, "propTypes", { canRefine: propTypes.bool.isRequired, precision: propTypes.number.isRequired, translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, min: propTypes.number, max: propTypes.number, currentRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }), className: propTypes.string }); _defineProperty(RawRangeInput, "defaultProps", { currentRefinement: {}, className: '' }); var RangeInput = translatable({ submit: 'ok', separator: 'to' })(RawRangeInput); /** * 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 `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 - 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. * @propType {number} [precision=0] - Number of digits after decimal point to use. * @themeKey ais-RangeInput - the root div of the widget * @themeKey ais-RangeInput-form - the wrapping form * @themeKey ais-RangeInput-label - the label wrapping inputs * @themeKey ais-RangeInput-input - the input (number) * @themeKey ais-RangeInput-input--min - the minimum input * @themeKey ais-RangeInput-input--max - the maximum input * @themeKey ais-RangeInput-separator - the separator word used between the two inputs * @themeKey ais-RangeInput-button - the submit button * @translationKey submit - Label value for the submit button * @translationKey separator - Label value for the input separator * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, RangeInput } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <RangeInput attribute="price" /> * </InstantSearch> * ); */ var RangeInputWidget = function RangeInputWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(RangeInput, props)); }; var RangeInput$1 = connectRange(RangeInputWidget); /** * 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. ⚠️ This example only works with the version 2.x of Rheostat. import React, {Component} from 'react'; import PropTypes from 'prop-types'; import Rheostat from 'rheostat'; import { connectRange } from 'react-instantsearch-dom'; 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 } }; componentDidUpdate(prevProps) { if ( this.props.canRefine && (prevProps.currentRefinement.min !== this.props.currentRefinement.min || prevProps.currentRefinement.max !== this.props.currentRefinement.max) ) { this.setState({ currentValues: { min: this.props.currentRefinement.min, max: this.props.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 className="ais-RangeSlider" 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); */ var RangeSlider = (function () { return React__default.createElement("div", null, "We do not provide any Slider, see the documentation to learn how to connect one easily:", React__default.createElement("a", { target: "_blank", rel: "noopener noreferrer", href: "https://www.algolia.com/doc/api-reference/widgets/range-slider/react/" }, "https://www.algolia.com/doc/api-reference/widgets/range-slider/react/")); }); var cx$g = createClassNames('RatingMenu'); var RatingMenu = /*#__PURE__*/ function (_Component) { _inherits(RatingMenu, _Component); function RatingMenu() { _classCallCheck(this, RatingMenu); return _possibleConstructorReturn(this, _getPrototypeOf(RatingMenu).apply(this, arguments)); } _createClass(RatingMenu, [{ 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, lowerBound = _ref.lowerBound, count = _ref.count, translate = _ref.translate, createURL = _ref.createURL, 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 = []; var rating = 0; for (var icon = 0; icon < max; icon++) { if (icon < lowerBound) { rating++; } icons.push([React__default.createElement("svg", { key: icon, className: cx$g('starIcon', icon >= lowerBound ? 'starIcon--empty' : 'starIcon--full'), "aria-hidden": "true", width: "24", height: "24" }, React__default.createElement("use", { xlinkHref: "#".concat(cx$g(icon >= lowerBound ? 'starEmptySymbol' : 'starSymbol')) })), ' ']); } // The last item of the list (the default item), should not // be clickable if it is selected. var isLastAndSelect = isLastSelectableItem && selected; var onClickHandler = disabled || isLastAndSelect ? {} : { href: createURL({ min: lowerBound, max: max }), onClick: this.onClick.bind(this, lowerBound, max) }; return React__default.createElement("li", { key: lowerBound, className: cx$g('item', selected && 'item--selected', disabled && 'item--disabled') }, React__default.createElement("a", _extends({ className: cx$g('link'), "aria-label": "".concat(rating).concat(translate('ratingLabel')) }, onClickHandler), icons, React__default.createElement("span", { className: cx$g('label'), "aria-hidden": "true" }, translate('ratingLabel')), ' ', React__default.createElement("span", { className: cx$g('count') }, count))); } }, { key: "render", value: function render() { var _this = this; var _this$props = this.props, min = _this$props.min, max = _this$props.max, translate = _this$props.translate, count = _this$props.count, createURL = _this$props.createURL, canRefine = _this$props.canRefine, className = _this$props.className; // min & max are always set when there is a results, otherwise it means // that we don't want to render anything since we don't have any values. var limitMin = min !== undefined && min >= 0 ? min : 1; var limitMax = max !== undefined && max >= 0 ? max : 0; var inclusiveLength = limitMax - limitMin + 1; var values = count.map(function (item) { return _objectSpread({}, item, { value: parseFloat(item.value) }); }).filter(function (item) { return item.value >= limitMin && item.value <= limitMax; }); var items = range({ start: 0, end: Math.max(inclusiveLength, 0) }).map(function (index) { var element = find$2(values, function (item) { return item.value === limitMax - index; }); var placeholder = { value: limitMax - index, count: 0, total: 0 }; return element || placeholder; }).reduce(function (acc, item, index) { return acc.concat(_objectSpread({}, item, { total: index === 0 ? item.count : acc[index - 1].total + item.count })); }, []).map(function (item, index, arr) { return _this.buildItem({ lowerBound: item.value, count: item.total, isLastSelectableItem: arr.length - 1 === index, max: limitMax, translate: translate, createURL: createURL }); }); return React__default.createElement("div", { className: classnames(cx$g('', !canRefine && '-noRefinement'), className) }, React__default.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", style: { display: 'none' } }, React__default.createElement("symbol", { id: cx$g('starSymbol'), viewBox: "0 0 24 24" }, React__default.createElement("path", { d: "M12 .288l2.833 8.718h9.167l-7.417 5.389 2.833 8.718-7.416-5.388-7.417 5.388 2.833-8.718-7.416-5.389h9.167z" })), React__default.createElement("symbol", { id: cx$g('starEmptySymbol'), viewBox: "0 0 24 24" }, React__default.createElement("path", { d: "M12 6.76l1.379 4.246h4.465l-3.612 2.625 1.379 4.246-3.611-2.625-3.612 2.625 1.379-4.246-3.612-2.625h4.465l1.38-4.246zm0-6.472l-2.833 8.718h-9.167l7.416 5.389-2.833 8.718 7.417-5.388 7.416 5.388-2.833-8.718 7.417-5.389h-9.167l-2.833-8.718z" }))), React__default.createElement("ul", { className: cx$g('list', !canRefine && 'list--noRefinement') }, items)); } }]); return RatingMenu; }(React.Component); _defineProperty(RatingMenu, "propTypes", { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, min: propTypes.number, max: propTypes.number, currentRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }), count: propTypes.arrayOf(propTypes.shape({ value: propTypes.string, count: propTypes.number })), canRefine: propTypes.bool.isRequired, className: propTypes.string }); _defineProperty(RatingMenu, "defaultProps", { className: '' }); var RatingMenu$1 = translatable({ ratingLabel: ' & Up' })(RatingMenu); /** * RatingMenu lets the user refine search results by clicking on stars. * * The stars are based on the selected `attribute`. * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @name RatingMenu * @kind widget * @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 - 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-RatingMenu - the root div of the widget * @themeKey ais-RatingMenu--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-RatingMenu-list - the list of ratings * @themeKey ais-RatingMenu-list--noRefinement - the list of ratings when there is no refinement * @themeKey ais-RatingMenu-item - the rating list item * @themeKey ais-RatingMenu-item--selected - the selected rating list item * @themeKey ais-RatingMenu-item--disabled - the disabled rating list item * @themeKey ais-RatingMenu-link - the rating clickable item * @themeKey ais-RatingMenu-starIcon - the star icon * @themeKey ais-RatingMenu-starIcon--full - the filled star icon * @themeKey ais-RatingMenu-starIcon--empty - the empty star icon * @themeKey ais-RatingMenu-label - the label used after the stars * @themeKey ais-RatingMenu-count - the count of ratings for a specific item * @translationKey ratingLabel - Label value for the rating link * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, RatingMenu } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <RatingMenu attribute="rating" /> * </InstantSearch> * ); */ var RatingMenuWidget = function RatingMenuWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(RatingMenu$1, props)); }; var RatingMenu$2 = connectRange(RatingMenuWidget); var cx$h = createClassNames('RefinementList'); var RefinementList$1 = /*#__PURE__*/ function (_Component) { _inherits(RefinementList, _Component); function RefinementList() { var _getPrototypeOf2; var _this; _classCallCheck(this, RefinementList); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(RefinementList)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "state", { query: '' }); _defineProperty(_assertThisInitialized(_this), "selectItem", function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }); _defineProperty(_assertThisInitialized(_this), "renderItem", function (item, resetQuery) { var label = _this.props.isFromSearch ? React__default.createElement(Highlight$2, { attribute: "label", hit: item }) : item.label; return React__default.createElement("label", { className: cx$h('label') }, React__default.createElement("input", { className: cx$h('checkbox'), type: "checkbox", checked: item.isRefined, onChange: function onChange() { return _this.selectItem(item, resetQuery); } }), React__default.createElement("span", { className: cx$h('labelText') }, label), ' ', React__default.createElement("span", { className: cx$h('count') }, item.count.toLocaleString())); }); return _this; } _createClass(RefinementList, [{ key: "render", value: function render() { var _this$props = this.props, translate = _this$props.translate, items = _this$props.items, showMore = _this$props.showMore, limit = _this$props.limit, showMoreLimit = _this$props.showMoreLimit, isFromSearch = _this$props.isFromSearch, searchForItems = _this$props.searchForItems, searchable = _this$props.searchable, canRefine = _this$props.canRefine, className = _this$props.className; return React__default.createElement(List, { renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$h, translate: translate, items: items, showMore: showMore, limit: limit, showMoreLimit: showMoreLimit, isFromSearch: isFromSearch, searchForItems: searchForItems, searchable: searchable, canRefine: canRefine, className: className, query: this.state.query }); } }]); return RefinementList; }(React.Component); _defineProperty(RefinementList$1, "propTypes", { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, searchForItems: propTypes.func.isRequired, searchable: propTypes.bool, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.arrayOf(propTypes.string).isRequired, count: propTypes.number.isRequired, isRefined: propTypes.bool.isRequired })), isFromSearch: propTypes.bool.isRequired, canRefine: propTypes.bool.isRequired, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func, className: propTypes.string }); _defineProperty(RefinementList$1, "defaultProps", { className: '' }); var RefinementList$2 = translatable({ 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$1); /** * The RefinementList component displays a list that let the end user choose multiple values for a specific facet. * @name RefinementList * @kind widget * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [searchable=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/). * @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 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 - the root div of the widget * @themeKey ais-RefinementList--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-RefinementList-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @themeKey ais-RefinementList-list - the list of refinement items * @themeKey ais-RefinementList-item - the refinement list item * @themeKey ais-RefinementList-item--selected - the refinement selected list item * @themeKey ais-RefinementList-label - the label of each refinement item * @themeKey ais-RefinementList-checkbox - the checkbox input of each refinement item * @themeKey ais-RefinementList-labelText - the label text of each refinement item * @themeKey ais-RefinementList-count - the count of values for each item * @themeKey ais-RefinementList-noResults - the div displayed when there are no results * @themeKey ais-RefinementList-showMore - the button used to display more categories * @themeKey ais-RefinementList-showMore--disabled - the disabled button used to display more categories * @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 `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. * * If you are using the `searchable` prop, you'll also need to make the attribute searchable using * the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values). * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, RefinementList } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <RefinementList attribute="brand" /> * </InstantSearch> * ); */ var RefinementListWidget = function RefinementListWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(RefinementList$2, props)); }; var RefinementList$3 = connectRefinementList(RefinementListWidget); var cx$i = createClassNames('ScrollTo'); var ScrollTo = /*#__PURE__*/ function (_Component) { _inherits(ScrollTo, _Component); function ScrollTo() { _classCallCheck(this, ScrollTo); return _possibleConstructorReturn(this, _getPrototypeOf(ScrollTo).apply(this, arguments)); } _createClass(ScrollTo, [{ key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var _this$props = this.props, value = _this$props.value, hasNotChanged = _this$props.hasNotChanged; if (value !== prevProps.value && hasNotChanged) { this.el.scrollIntoView(); } } }, { key: "render", value: function render() { var _this = this; return React__default.createElement("div", { ref: function ref(_ref) { return _this.el = _ref; }, className: cx$i('') }, this.props.children); } }]); return ScrollTo; }(React.Component); _defineProperty(ScrollTo, "propTypes", { value: propTypes.any, children: propTypes.node, hasNotChanged: propTypes.bool }); /** * The ScrollTo component will make 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. * @themeKey ais-ScrollTo - the root div of the widget * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, ScrollTo, Hits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <ScrollTo> * <Hits /> * </ScrollTo> * </InstantSearch> * ); */ var ScrollTo$1 = connectScrollTo(ScrollTo); /** * 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 from the search input itself. * @propType {node} [submit] - Change the apparence of the default submit button (magnifying glass). * @propType {node} [reset] - Change the apparence of the default reset button (cross). * @propType {node} [loadingIndicator] - Change the apparence of the default loading indicator (spinning circle). * @propType {string} [defaultRefinement] - Provide default refinement value when component is mounted. * @propType {boolean} [showLoadingIndicator=false] - Display that the search is loading. This only happens after a certain amount of time to avoid a blinking effect. This timer can be configured with `stalledSearchDelay` props on <InstantSearch>. By default, the value is 200ms. * @themeKey ais-SearchBox - the root div of the widget * @themeKey ais-SearchBox-form - the wrapping form * @themeKey ais-SearchBox-input - the search input * @themeKey ais-SearchBox-submit - the submit button * @themeKey ais-SearchBox-submitIcon - the default magnifier icon used with the search input * @themeKey ais-SearchBox-reset - the reset button used to clear the content of the input * @themeKey ais-SearchBox-resetIcon - the default reset icon used inside the reset button * @themeKey ais-SearchBox-loadingIndicator - the loading indicator container * @themeKey ais-SearchBox-loadingIcon - the default loading icon * @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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox /> * </InstantSearch> * ); */ var SearchBox$2 = connectSearchBox(SearchBox$1); var cx$j = createClassNames('Snippet'); var Snippet = function Snippet(props) { return React__default.createElement(Highlighter, _extends({}, props, { highlightProperty: "_snippetResult", cx: cx$j })); }; /** * 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 * @requirements To use this widget, the attribute name passed to the `attribute` prop must be * present in "Attributes to snippet" on the Algolia dashboard or configured as `attributesToSnippet` * via a set settings call to the Algolia API. * @propType {string} attribute - location of the highlighted snippet attribute in the hit (the corresponding element can be either a string or an array of strings) * @propType {object} hit - hit object containing the highlighted snippet attribute * @propType {string} [tagName='em'] - tag to be used for highlighted parts of the attribute * @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted * @propType {node} [separator=',<space>'] - symbol used to separate the elements of the array in case the attribute points to an array of strings. * @themeKey ais-Snippet - the root span of the widget * @themeKey ais-Snippet-highlighted - the highlighted text * @themeKey ais-Snippet-nonHighlighted - the normal text * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox, Hits, Snippet } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const Hit = ({ hit }) => ( * <div> * <Snippet attribute="description" hit={hit} /> * </div> * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox defaultRefinement="adjustable" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var Snippet$1 = connectHighlight(Snippet); var cx$k = createClassNames('SortBy'); var SortBy = /*#__PURE__*/ function (_Component) { _inherits(SortBy, _Component); function SortBy() { _classCallCheck(this, SortBy); return _possibleConstructorReturn(this, _getPrototypeOf(SortBy).apply(this, arguments)); } _createClass(SortBy, [{ key: "render", value: function render() { var _this$props = this.props, items = _this$props.items, currentRefinement = _this$props.currentRefinement, refine = _this$props.refine, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$k(''), className) }, React__default.createElement(Select, { cx: cx$k, items: items, selectedItem: currentRefinement, onSelect: refine })); } }]); return SortBy; }(React.Component); _defineProperty(SortBy, "propTypes", { items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, currentRefinement: propTypes.string.isRequired, refine: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(SortBy, "defaultProps", { className: '' }); /** * 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 - the root div of the widget * @themeKey ais-SortBy-select - the select * @themeKey ais-SortBy-option - the select option * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SortBy } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <SortBy * defaultRefinement="instant_search" * items={[ * { value: 'instant_search', label: 'Featured' }, * { value: 'instant_search_price_asc', label: 'Price asc.' }, * { value: 'instant_search_price_desc', label: 'Price desc.' }, * ]} * /> * </InstantSearch> * ); */ var SortBy$1 = connectSortBy(SortBy); var cx$l = createClassNames('Stats'); var Stats = /*#__PURE__*/ function (_Component) { _inherits(Stats, _Component); function Stats() { _classCallCheck(this, Stats); return _possibleConstructorReturn(this, _getPrototypeOf(Stats).apply(this, arguments)); } _createClass(Stats, [{ key: "render", value: function render() { var _this$props = this.props, translate = _this$props.translate, nbHits = _this$props.nbHits, processingTimeMS = _this$props.processingTimeMS, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$l(''), className) }, React__default.createElement("span", { className: cx$l('text') }, translate('stats', nbHits, processingTimeMS))); } }]); return Stats; }(React.Component); _defineProperty(Stats, "propTypes", { translate: propTypes.func.isRequired, nbHits: propTypes.number.isRequired, processingTimeMS: propTypes.number.isRequired, className: propTypes.string }); _defineProperty(Stats, "defaultProps", { className: '' }); var Stats$1 = translatable({ stats: function stats(n, ms) { return "".concat(n.toLocaleString(), " results found in ").concat(ms.toLocaleString(), "ms"); } })(Stats); /** * 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 - the root div of the widget * @themeKey ais-Stats-text - the text of the widget - the count of items for each item * @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 { InstantSearch, Stats, Hits } from 'react-instantsearch-dom'; * import algoliasearch from 'algoliasearch/lite'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Stats /> * <Hits /> * </InstantSearch> * ); */ var Stats$2 = connectStats(Stats$1); var cx$m = createClassNames('ToggleRefinement'); var ToggleRefinement = function ToggleRefinement(_ref) { var currentRefinement = _ref.currentRefinement, label = _ref.label, canRefine = _ref.canRefine, refine = _ref.refine, className = _ref.className; return React__default.createElement("div", { className: classnames(cx$m('', !canRefine && '-noRefinement'), className) }, React__default.createElement("label", { className: cx$m('label') }, React__default.createElement("input", { className: cx$m('checkbox'), type: "checkbox", checked: currentRefinement, onChange: function onChange(event) { return refine(event.target.checked); } }), React__default.createElement("span", { className: cx$m('labelText') }, label))); }; ToggleRefinement.defaultProps = { className: '' }; /** * The ToggleRefinement provides an on/off filtering feature based on an attribute value. * @name ToggleRefinement * @kind widget * @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 {any} value - Value of the refinement to apply on `attribute` when checked. * @propType {boolean} [defaultRefinement=false] - Default state of the widget. Should the toggle be checked by default? * @themeKey ais-ToggleRefinement - the root div of the widget * @themeKey ais-ToggleRefinement-list - the list of toggles * @themeKey ais-ToggleRefinement-item - the toggle list item * @themeKey ais-ToggleRefinement-label - the label of each toggle item * @themeKey ais-ToggleRefinement-checkbox - the checkbox input of each toggle item * @themeKey ais-ToggleRefinement-labelText - the label text of each toggle item * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, ToggleRefinement } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <ToggleRefinement * attribute="free_shipping" * label="Free Shipping" * value={true} * /> * </InstantSearch> * ); */ var ToggleRefinement$1 = connectToggleRefinement(ToggleRefinement); exports.Breadcrumb = Breadcrumb$2; exports.ClearRefinements = ClearRefinements$2; exports.Configure = Configure; exports.CurrentRefinements = CurrentRefinements$2; exports.HierarchicalMenu = HierarchicalMenu$2; exports.Highlight = Highlight$2; exports.Hits = Hits$1; exports.HitsPerPage = HitsPerPage$1; exports.Index = IndexWrapper; exports.InfiniteHits = InfiniteHits$2; exports.InstantSearch = InstantSearch; exports.Menu = Menu$2; exports.MenuSelect = MenuSelect$2; exports.NumericMenu = NumericMenu$2; exports.Pagination = Pagination$2; exports.Panel = Panel; exports.PoweredBy = PoweredBy$2; exports.RangeInput = RangeInput$1; exports.RangeSlider = RangeSlider; exports.RatingMenu = RatingMenu$2; exports.RefinementList = RefinementList$3; exports.ScrollTo = ScrollTo$1; exports.SearchBox = SearchBox$2; exports.Snippet = Snippet$1; exports.SortBy = SortBy$1; exports.Stats = Stats$2; exports.ToggleRefinement = ToggleRefinement$1; Object.defineProperty(exports, '__esModule', { value: true }); })); //# sourceMappingURL=Dom.js.map
ajax/libs/material-ui/5.0.0-alpha.17/legacy/styles/ThemeProvider.js
cdnjs/cdnjs
import _typeof from "@babel/runtime/helpers/esm/typeof"; 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) { var 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) { var children = props.children, localTheme = props.theme; 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/material-ui/5.0.0-alpha.22/legacy/styles/ThemeProvider.js
cdnjs/cdnjs
import _typeof from "@babel/runtime/helpers/esm/typeof"; 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) { var 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) { var children = props.children, localTheme = props.theme; 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.13.9/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/react-native-web/0.14.6/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/material-ui/4.9.4/es/DialogTitle/DialogTitle.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 Typography from '../Typography'; export const styles = { /* Styles applied to the root element. */ root: { margin: 0, padding: '16px 24px', flex: '0 0 auto' } }; const DialogTitle = React.forwardRef(function DialogTitle(props, ref) { const { children, classes, className, disableTypography = false } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "disableTypography"]); return React.createElement("div", _extends({ className: clsx(classes.root, className), ref: ref }, other), disableTypography ? children : React.createElement(Typography, { component: "h2", variant: "h6" }, children)); }); process.env.NODE_ENV !== "production" ? DialogTitle.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 children won't be wrapped by a typography component. * For instance, this can be useful to render an h4 instead of the default h2. */ disableTypography: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiDialogTitle' })(DialogTitle);
ajax/libs/material-ui/4.12.2/esm/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/react-native-web/0.15.2/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 ( /*#__PURE__*/ React.createElement(View, rest) ); } export default RefreshControl;
ajax/libs/react-native-web/0.11.4/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.3/esm/Snackbar/Snackbar.js
cdnjs/cdnjs
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; 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 { duration } from '../styles/transitions'; import ClickAwayListener from '../ClickAwayListener'; import useEventCallback from '../utils/useEventCallback'; import capitalize from '../utils/capitalize'; import createChainedFunction from '../utils/createChainedFunction'; import Grow from '../Grow'; import SnackbarContent from '../SnackbarContent'; export var styles = function styles(theme) { var top1 = { top: 8 }; var bottom1 = { bottom: 8 }; var right = { justifyContent: 'flex-end' }; var left = { justifyContent: 'flex-start' }; var top3 = { top: 24 }; var bottom3 = { bottom: 24 }; var right3 = { right: 24 }; var left3 = { left: 24 }; var center = { left: '50%', right: 'auto', transform: 'translateX(-50%)' }; return { /* Styles applied to the root element. */ root: { zIndex: theme.zIndex.snackbar, position: 'fixed', display: 'flex', left: 8, right: 8, justifyContent: 'center', alignItems: 'center' }, /* Styles applied to the root element if `anchorOrigin={{ 'top', 'center' }}`. */ anchorOriginTopCenter: _extends({}, top1, _defineProperty({}, theme.breakpoints.up('sm'), _extends({}, top3, {}, center))), /* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'center' }}`. */ anchorOriginBottomCenter: _extends({}, bottom1, _defineProperty({}, theme.breakpoints.up('sm'), _extends({}, bottom3, {}, center))), /* Styles applied to the root element if `anchorOrigin={{ 'top', 'right' }}`. */ anchorOriginTopRight: _extends({}, top1, {}, right, _defineProperty({}, theme.breakpoints.up('sm'), _extends({ left: 'auto' }, top3, {}, right3))), /* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'right' }}`. */ anchorOriginBottomRight: _extends({}, bottom1, {}, right, _defineProperty({}, theme.breakpoints.up('sm'), _extends({ left: 'auto' }, bottom3, {}, right3))), /* Styles applied to the root element if `anchorOrigin={{ 'top', 'left' }}`. */ anchorOriginTopLeft: _extends({}, top1, {}, left, _defineProperty({}, theme.breakpoints.up('sm'), _extends({ right: 'auto' }, top3, {}, left3))), /* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'left' }}`. */ anchorOriginBottomLeft: _extends({}, bottom1, {}, left, _defineProperty({}, theme.breakpoints.up('sm'), _extends({ right: 'auto' }, bottom3, {}, left3))) }; }; var Snackbar = React.forwardRef(function Snackbar(props, ref) { var action = props.action, _props$anchorOrigin = props.anchorOrigin; _props$anchorOrigin = _props$anchorOrigin === void 0 ? { vertical: 'bottom', horizontal: 'center' } : _props$anchorOrigin; var vertical = _props$anchorOrigin.vertical, horizontal = _props$anchorOrigin.horizontal, _props$autoHideDurati = props.autoHideDuration, autoHideDuration = _props$autoHideDurati === void 0 ? null : _props$autoHideDurati, children = props.children, classes = props.classes, className = props.className, ClickAwayListenerProps = props.ClickAwayListenerProps, ContentProps = props.ContentProps, _props$disableWindowB = props.disableWindowBlurListener, disableWindowBlurListener = _props$disableWindowB === void 0 ? false : _props$disableWindowB, message = props.message, onClose = props.onClose, onEnter = props.onEnter, onEntered = props.onEntered, onEntering = props.onEntering, onExit = props.onExit, onExited = props.onExited, onExiting = props.onExiting, onMouseEnter = props.onMouseEnter, onMouseLeave = props.onMouseLeave, open = props.open, resumeHideDuration = props.resumeHideDuration, _props$TransitionComp = props.TransitionComponent, TransitionComponent = _props$TransitionComp === void 0 ? Grow : _props$TransitionComp, _props$transitionDura = props.transitionDuration, transitionDuration = _props$transitionDura === void 0 ? { enter: duration.enteringScreen, exit: duration.leavingScreen } : _props$transitionDura, TransitionProps = props.TransitionProps, other = _objectWithoutProperties(props, ["action", "anchorOrigin", "autoHideDuration", "children", "classes", "className", "ClickAwayListenerProps", "ContentProps", "disableWindowBlurListener", "message", "onClose", "onEnter", "onEntered", "onEntering", "onExit", "onExited", "onExiting", "onMouseEnter", "onMouseLeave", "open", "resumeHideDuration", "TransitionComponent", "transitionDuration", "TransitionProps"]); var timerAutoHide = React.useRef(); var _React$useState = React.useState(true), exited = _React$useState[0], setExited = _React$useState[1]; var handleClose = useEventCallback(function () { if (onClose) { onClose.apply(void 0, arguments); } }); var setAutoHideTimer = useEventCallback(function (autoHideDurationParam) { if (!onClose || autoHideDurationParam == null) { return; } clearTimeout(timerAutoHide.current); timerAutoHide.current = setTimeout(function () { handleClose(null, 'timeout'); }, autoHideDurationParam); }); React.useEffect(function () { if (open) { setAutoHideTimer(autoHideDuration); } return function () { clearTimeout(timerAutoHide.current); }; }, [open, autoHideDuration, setAutoHideTimer]); // Pause the timer when the user is interacting with the Snackbar // or when the user hide the window. var handlePause = function handlePause() { clearTimeout(timerAutoHide.current); }; // Restart the timer when the user is no longer interacting with the Snackbar // or when the window is shown back. var handleResume = React.useCallback(function () { if (autoHideDuration != null) { setAutoHideTimer(resumeHideDuration != null ? resumeHideDuration : autoHideDuration * 0.5); } }, [autoHideDuration, resumeHideDuration, setAutoHideTimer]); var handleMouseEnter = function handleMouseEnter(event) { if (onMouseEnter) { onMouseEnter(event); } handlePause(); }; var handleMouseLeave = function handleMouseLeave(event) { if (onMouseLeave) { onMouseLeave(event); } handleResume(); }; var handleClickAway = function handleClickAway(event) { if (onClose) { onClose(event, 'clickaway'); } }; var handleExited = function handleExited() { setExited(true); }; var handleEnter = function handleEnter() { setExited(false); }; React.useEffect(function () { if (!disableWindowBlurListener && open) { window.addEventListener('focus', handleResume); window.addEventListener('blur', handlePause); return function () { window.removeEventListener('focus', handleResume); window.removeEventListener('blur', handlePause); }; } return undefined; }, [disableWindowBlurListener, handleResume, open]); // So we only render active snackbars. if (!open && exited) { return null; } return React.createElement(ClickAwayListener, _extends({ onClickAway: handleClickAway }, ClickAwayListenerProps), React.createElement("div", _extends({ className: clsx(classes.root, classes["anchorOrigin".concat(capitalize(vertical)).concat(capitalize(horizontal))], className), onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, ref: ref }, other), React.createElement(TransitionComponent, _extends({ appear: true, in: open, onEnter: createChainedFunction(handleEnter, onEnter), onEntered: onEntered, onEntering: onEntering, onExit: onExit, onExited: createChainedFunction(handleExited, onExited), onExiting: onExiting, timeout: transitionDuration, direction: vertical === 'top' ? 'down' : 'up' }, TransitionProps), children || React.createElement(SnackbarContent, _extends({ message: message, action: action }, ContentProps))))); }); process.env.NODE_ENV !== "production" ? Snackbar.propTypes = { /** * The action to display. It renders after the message, at the end of the snackbar. */ action: PropTypes.node, /** * The anchor of the `Snackbar`. */ anchorOrigin: PropTypes.shape({ horizontal: PropTypes.oneOf(['left', 'center', 'right']).isRequired, vertical: PropTypes.oneOf(['top', 'bottom']).isRequired }), /** * The number of milliseconds to wait before automatically calling the * `onClose` function. `onClose` should then set the state of the `open` * prop to hide the Snackbar. This behavior is disabled by default with * the `null` value. */ autoHideDuration: PropTypes.number, /** * Replace the `SnackbarContent` component. */ children: PropTypes.element, /** * 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, /** * Props applied to the `ClickAwayListener` element. */ ClickAwayListenerProps: PropTypes.object, /** * Props applied to the [`SnackbarContent`](/api/snackbar-content/) element. */ ContentProps: PropTypes.object, /** * If `true`, the `autoHideDuration` timer will expire even if the window is not focused. */ disableWindowBlurListener: PropTypes.bool, /** * When displaying multiple consecutive Snackbars from a parent rendering a single * <Snackbar/>, add the key prop to ensure independent treatment of each message. * e.g. <Snackbar key={message} />, otherwise, the message may update-in-place and * features such as autoHideDuration may be canceled. */ key: PropTypes.any, /** * The message to display. */ message: PropTypes.node, /** * Callback fired when the component requests to be closed. * Typically `onClose` is used to set state in the parent component, * which is used to control the `Snackbar` `open` prop. * The `reason` parameter can optionally be used to control the response to `onClose`, * for example ignoring `clickaway`. * * @param {object} event The event source of the callback. * @param {string} reason Can be: `"timeout"` (`autoHideDuration` expired), `"clickaway"`. */ onClose: PropTypes.func, /** * Callback fired before the transition is entering. */ onEnter: PropTypes.func, /** * Callback fired when the transition has entered. */ onEntered: PropTypes.func, /** * Callback fired when the transition is entering. */ onEntering: PropTypes.func, /** * Callback fired before the transition is exiting. */ onExit: PropTypes.func, /** * Callback fired when the transition has exited. */ onExited: PropTypes.func, /** * Callback fired when the transition is exiting. */ onExiting: PropTypes.func, /** * @ignore */ onMouseEnter: PropTypes.func, /** * @ignore */ onMouseLeave: PropTypes.func, /** * If `true`, `Snackbar` is open. */ open: PropTypes.bool, /** * The number of milliseconds to wait before dismissing after user interaction. * If `autoHideDuration` prop isn't specified, it does nothing. * If `autoHideDuration` prop is specified but `resumeHideDuration` isn't, * we default to `autoHideDuration / 2` ms. */ resumeHideDuration: PropTypes.number, /** * The component used for the transition. * [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component. */ TransitionComponent: PropTypes.elementType, /** * 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({ enter: PropTypes.number, exit: PropTypes.number })]), /** * Props applied to the [`Transition`](http://reactcommunity.org/react-transition-group/transition#Transition-props) element. */ TransitionProps: PropTypes.object } : void 0; export default withStyles(styles, { flip: false, name: 'MuiSnackbar' })(Snackbar);
ajax/libs/material-ui/4.9.3/es/ClickAwayListener/ClickAwayListener.js
cdnjs/cdnjs
import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import ownerDocument from '../utils/ownerDocument'; import useForkRef from '../utils/useForkRef'; import setRef from '../utils/setRef'; import useEventCallback from '../utils/useEventCallback'; import { elementAcceptingRef, exactProp } from '@material-ui/utils'; function mapEventPropToEvent(eventProp) { return eventProp.substring(2).toLowerCase(); } /** * Listen for click events that occur somewhere in the document, outside of the element itself. * For instance, if you need to hide a menu when people click anywhere else on your page. */ const ClickAwayListener = React.forwardRef(function ClickAwayListener(props, ref) { const { children, mouseEvent = 'onClick', touchEvent = 'onTouchEnd', onClickAway } = props; const movedRef = React.useRef(false); const nodeRef = React.useRef(null); const mountedRef = React.useRef(false); React.useEffect(() => { mountedRef.current = true; return () => { mountedRef.current = false; }; }, []); const handleNodeRef = useForkRef(nodeRef, ref); // can be removed once we drop support for non ref forwarding class components const handleOwnRef = React.useCallback(instance => { // #StrictMode ready setRef(handleNodeRef, ReactDOM.findDOMNode(instance)); }, [handleNodeRef]); const handleRef = useForkRef(children.ref, handleOwnRef); const handleClickAway = useEventCallback(event => { // The handler doesn't take event.defaultPrevented into account: // // event.preventDefault() is meant to stop default behaviours like // clicking a checkbox to check it, hitting a button to submit a form, // and hitting left arrow to move the cursor in a text input etc. // Only special HTML elements have these default behaviors. // IE 11 support, which trigger the handleClickAway even after the unbind if (!mountedRef.current) { return; } // Do not act if user performed touchmove if (movedRef.current) { movedRef.current = false; return; } // The child might render null. if (!nodeRef.current) { return; } // Multi window support const doc = ownerDocument(nodeRef.current); if (doc.documentElement && doc.documentElement.contains(event.target) && !nodeRef.current.contains(event.target)) { onClickAway(event); } }); const handleTouchMove = React.useCallback(() => { movedRef.current = true; }, []); React.useEffect(() => { if (touchEvent !== false) { const mappedTouchEvent = mapEventPropToEvent(touchEvent); const doc = ownerDocument(nodeRef.current); doc.addEventListener(mappedTouchEvent, handleClickAway); doc.addEventListener('touchmove', handleTouchMove); return () => { doc.removeEventListener(mappedTouchEvent, handleClickAway); doc.removeEventListener('touchmove', handleTouchMove); }; } return undefined; }, [handleClickAway, handleTouchMove, touchEvent]); React.useEffect(() => { if (mouseEvent !== false) { const mappedMouseEvent = mapEventPropToEvent(mouseEvent); const doc = ownerDocument(nodeRef.current); doc.addEventListener(mappedMouseEvent, handleClickAway); return () => { doc.removeEventListener(mappedMouseEvent, handleClickAway); }; } return undefined; }, [handleClickAway, mouseEvent]); return React.createElement(React.Fragment, null, React.cloneElement(children, { ref: handleRef })); }); process.env.NODE_ENV !== "production" ? ClickAwayListener.propTypes = { /** * The wrapped element. */ children: elementAcceptingRef.isRequired, /** * The mouse event to listen to. You can disable the listener by providing `false`. */ mouseEvent: PropTypes.oneOf(['onClick', 'onMouseDown', 'onMouseUp', false]), /** * Callback fired when a "click away" event is detected. */ onClickAway: PropTypes.func.isRequired, /** * The touch event to listen to. You can disable the listener by providing `false`. */ touchEvent: PropTypes.oneOf(['onTouchStart', 'onTouchEnd', false]) } : void 0; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line ClickAwayListener['propTypes' + ''] = exactProp(ClickAwayListener.propTypes); } export default ClickAwayListener;
ajax/libs/react-native-web/0.14.10/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/4.9.4/es/ExpansionPanelDetails/ExpansionPanelDetails.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', padding: '8px 24px 24px' } }; const ExpansionPanelDetails = React.forwardRef(function ExpansionPanelDetails(props, ref) { const { classes, className } = props, other = _objectWithoutPropertiesLoose(props, ["classes", "className"]); return React.createElement("div", _extends({ className: clsx(classes.root, className), ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? ExpansionPanelDetails.propTypes = { /** * The content of the expansion panel details. */ 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 } : void 0; export default withStyles(styles, { name: 'MuiExpansionPanelDetails' })(ExpansionPanelDetails);
ajax/libs/material-ui/4.9.2/es/RadioGroup/RadioGroup.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 FormGroup from '../FormGroup'; import useForkRef from '../utils/useForkRef'; import useControlled from '../utils/useControlled'; import RadioGroupContext from './RadioGroupContext'; const RadioGroup = React.forwardRef(function RadioGroup(props, ref) { const { actions, children, name, value: valueProp, onChange } = props, other = _objectWithoutPropertiesLoose(props, ["actions", "children", "name", "value", "onChange"]); const rootRef = React.useRef(null); const [value, setValue] = useControlled({ controlled: valueProp, default: props.defaultValue, name: 'RadioGroup' }); React.useImperativeHandle(actions, () => ({ focus: () => { let input = rootRef.current.querySelector('input:not(:disabled):checked'); if (!input) { input = rootRef.current.querySelector('input:not(:disabled)'); } if (input) { input.focus(); } } }), []); const handleRef = useForkRef(ref, rootRef); const handleChange = event => { setValue(event.target.value); if (onChange) { onChange(event, event.target.value); } }; return React.createElement(RadioGroupContext.Provider, { value: { name, onChange: handleChange, value } }, React.createElement(FormGroup, _extends({ role: "radiogroup", ref: handleRef }, other), children)); }); process.env.NODE_ENV !== "production" ? RadioGroup.propTypes = { /** * @ignore */ actions: PropTypes.shape({ current: PropTypes.object }), /** * The content of the component. */ children: PropTypes.node, /** * The default `input` element value. Use when the component is not controlled. */ defaultValue: PropTypes.any, /** * The name used to reference the value of the control. */ name: PropTypes.string, /** * @ignore */ onBlur: PropTypes.func, /** * Callback fired when a radio button 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, /** * @ignore */ onKeyDown: PropTypes.func, /** * Value of the selected radio button. The DOM API casts this to a string. */ value: PropTypes.any } : void 0; export default RadioGroup;
ajax/libs/material-ui/4.9.4/es/Card/Card.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 Paper from '../Paper'; import withStyles from '../styles/withStyles'; export const styles = { /* Styles applied to the root element. */ root: { overflow: 'hidden' } }; const Card = React.forwardRef(function Card(props, ref) { const { classes, className, raised = false } = props, other = _objectWithoutPropertiesLoose(props, ["classes", "className", "raised"]); return React.createElement(Paper, _extends({ className: clsx(classes.root, className), elevation: raised ? 8 : 1, ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? Card.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 card will use raised styling. */ raised: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiCard' })(Card);
ajax/libs/primereact/7.0.0-rc.1/terminal/terminal.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { TerminalService } from 'primereact/terminalservice'; import { classNames } 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 Terminal = /*#__PURE__*/function (_Component) { _inherits(Terminal, _Component); var _super = _createSuper(Terminal); function Terminal(props) { var _this; _classCallCheck(this, Terminal); _this = _super.call(this, props); _this.state = { commandText: '', commands: [], index: 0 }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onInputChange = _this.onInputChange.bind(_assertThisInitialized(_this)); _this.onInputKeyDown = _this.onInputKeyDown.bind(_assertThisInitialized(_this)); _this.response = _this.response.bind(_assertThisInitialized(_this)); _this.clear = _this.clear.bind(_assertThisInitialized(_this)); return _this; } _createClass(Terminal, [{ key: "onClick", value: function onClick() { this.input.focus(); } }, { key: "onInputChange", value: function onInputChange(e) { this.setState({ commandText: e.target.value }); } }, { key: "onInputKeyDown", value: function onInputKeyDown(e) { var code = e.which || e.keyCode; var commands = this.state.commands; switch (code) { //up case 38: if (commands && commands.length) { var prevIndex = this.state.index - 1 < 0 ? commands.length - 1 : this.state.index - 1; var command = commands[prevIndex]; this.setState({ index: prevIndex, commandText: command.text }); } break; //enter case 13: if (!!this.state.commandText) { var newCommands = _toConsumableArray(commands); var text = this.state.commandText; newCommands.push({ text: text }); this.setState(function (prevState) { return { index: prevState.index + 1, commandText: '', commands: newCommands }; }, function () { TerminalService.emit('command', text); }); } break; } } }, { key: "response", value: function response(res) { var commands = this.state.commands; if (commands && commands.length > 0) { var _commands = _toConsumableArray(commands); _commands[_commands.length - 1].response = res; this.setState({ commands: _commands }); } } }, { key: "clear", value: function clear() { this.setState({ commands: [], index: 0 }); } }, { key: "componentDidMount", value: function componentDidMount() { TerminalService.on('response', this.response); TerminalService.on('clear', this.clear); } }, { key: "componentDidUpdate", value: function componentDidUpdate() { this.container.scrollTop = this.container.scrollHeight; } }, { key: "componentWillUnmount", value: function componentWillUnmount() { TerminalService.off('response', this.response); TerminalService.off('clear', this.clear); } }, { key: "renderWelcomeMessage", value: function renderWelcomeMessage() { if (this.props.welcomeMessage) { return /*#__PURE__*/React.createElement("div", null, this.props.welcomeMessage); } return null; } }, { key: "renderCommand", value: function renderCommand(command, index) { var text = command.text, response = command.response; return /*#__PURE__*/React.createElement("div", { key: "".concat(text).concat(index) }, /*#__PURE__*/React.createElement("span", { className: "p-terminal-prompt" }, this.props.prompt, "\xA0"), /*#__PURE__*/React.createElement("span", { className: "p-terminal-command" }, text), /*#__PURE__*/React.createElement("div", { className: "p-terminal-response" }, response)); } }, { key: "renderContent", value: function renderContent() { var _this2 = this; var commands = this.state.commands.map(function (c, i) { return _this2.renderCommand(c, i); }); return /*#__PURE__*/React.createElement("div", { className: "p-terminal-content" }, commands); } }, { key: "renderPromptContainer", value: function renderPromptContainer() { var _this3 = this; return /*#__PURE__*/React.createElement("div", { className: "p-terminal-prompt-container" }, /*#__PURE__*/React.createElement("span", { className: "p-terminal-prompt" }, this.props.prompt, "\xA0"), /*#__PURE__*/React.createElement("input", { ref: function ref(el) { return _this3.input = el; }, type: "text", value: this.state.commandText, className: "p-terminal-input", autoComplete: "off", onChange: this.onInputChange, onKeyDown: this.onInputKeyDown })); } }, { key: "render", value: function render() { var _this4 = this; var className = classNames('p-terminal p-component', this.props.className); var welcomeMessage = this.renderWelcomeMessage(); var content = this.renderContent(); var prompt = this.renderPromptContainer(); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this4.container = el; }, id: this.props.id, className: className, style: this.props.style, onClick: this.onClick }, welcomeMessage, content, prompt); } }]); return Terminal; }(Component); _defineProperty(Terminal, "defaultProps", { id: null, style: null, className: null, welcomeMessage: null, prompt: null }); export { Terminal };
ajax/libs/react-instantsearch/6.0.0/Dom.js
cdnjs/cdnjs
/*! React InstantSearch 6.0.0 | © Algolia, inc. | https://github.com/algolia/react-instantsearch */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (global = global || self, factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Dom = {}), global.React)); }(this, function (exports, React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; 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 _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 _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 _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 _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 _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); } function _typeof(obj) { if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") { _typeof = function _typeof(obj) { return _typeof2(obj); }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(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 _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); } var isArray = Array.isArray; var keyList = Object.keys; var hasProp = Object.prototype.hasOwnProperty; var fastDeepEqual = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { var arrA = isArray(a) , arrB = isArray(b) , i , length , key; if (arrA && arrB) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!equal(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 = keyList(a); length = keys.length; if (length !== keyList(b).length) return false; for (i = length; i-- !== 0;) if (!hasProp.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { key = keys[i]; if (!equal(a[key], b[key])) return false; } return true; } return a!==a && b!==b; }; 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 isPlainObject = function isPlainObject(value) { return _typeof(value) === 'object' && value !== null && !Array.isArray(value); }; var removeEmptyKey = function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (!isPlainObject(value)) { return; } if (!objectHasKeys(value)) { delete obj[key]; } else { removeEmptyKey(value); } }); return obj; }; function addAbsolutePositions(hits, hitsPerPage, page) { return hits.map(function (hit, index) { return _objectSpread({}, hit, { __position: hitsPerPage * page + index + 1 }); }); } function addQueryID(hits, queryID) { if (!queryID) { return hits; } return hits.map(function (hit) { return _objectSpread({}, hit, { __queryID: queryID }); }); } function find(array, comparator) { if (!Array.isArray(array)) { return undefined; } for (var i = 0; i < array.length; i++) { if (comparator(array[i])) { return array[i]; } } return undefined; } function objectHasKeys(object) { return object && Object.keys(object).length > 0; } // https://github.com/babel/babel/blob/3aaafae053fa75febb3aa45d45b6f00646e30ba4/packages/babel-helpers/src/helpers.js#L604-L620 function omit(source, excluded) { if (source === null || source === undefined) { return {}; } var target = {}; var sourceKeys = Object.keys(source); for (var i = 0; i < sourceKeys.length; i++) { var _key = sourceKeys[i]; if (excluded.indexOf(_key) >= 0) { // eslint-disable-next-line no-continue continue; } target[_key] = source[_key]; } return target; } /** * Retrieve the value at a path of the object: * * @example * getPropertyByPath( * { test: { this: { function: [{ now: { everyone: true } }] } } }, * 'test.this.function[0].now.everyone' * ); // true * * getPropertyByPath( * { test: { this: { function: [{ now: { everyone: true } }] } } }, * ['test', 'this', 'function', 0, 'now', 'everyone'] * ); // true * * @param object Source object to query * @param path either an array of properties, or a string form of the properties, separated by . */ var getPropertyByPath = function getPropertyByPath(object, path) { return (Array.isArray(path) ? path : path.replace(/\[(\d+)]/g, '.$1').split('.')).reduce(function (current, key) { return current ? current[key] : undefined; }, object); }; var _createContext = React.createContext({ onInternalStateUpdate: function onInternalStateUpdate() { return undefined; }, createHrefForState: function createHrefForState() { return '#'; }, onSearchForFacetValues: function onSearchForFacetValues() { return undefined; }, onSearchStateChange: function onSearchStateChange() { return undefined; }, onSearchParameters: function onSearchParameters() { return undefined; }, store: {}, widgetsManager: {}, mainTargetedIndex: '' }), InstantSearchConsumer = _createContext.Consumer, InstantSearchProvider = _createContext.Provider; var _createContext2 = React.createContext(undefined), IndexConsumer = _createContext2.Consumer, IndexProvider = _createContext2.Provider; /** * 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 createConnectorWithoutContext(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var isWidget = typeof connectorDesc.getSearchParameters === 'function' || typeof connectorDesc.getMetadata === 'function' || typeof connectorDesc.transitionState === 'function'; return function (Composed) { var Connector = /*#__PURE__*/ function (_Component) { _inherits(Connector, _Component); function Connector(props) { var _this; _classCallCheck(this, Connector); _this = _possibleConstructorReturn(this, _getPrototypeOf(Connector).call(this, props)); _defineProperty(_assertThisInitialized(_this), "unsubscribe", void 0); _defineProperty(_assertThisInitialized(_this), "unregisterWidget", void 0); _defineProperty(_assertThisInitialized(_this), "isUnmounting", false); _defineProperty(_assertThisInitialized(_this), "state", { providedProps: _this.getProvidedProps(_this.props) }); _defineProperty(_assertThisInitialized(_this), "refine", function () { var _ref; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this.props.contextValue.onInternalStateUpdate( // refine will always be defined here because the prop is only given conditionally (_ref = connectorDesc.refine).call.apply(_ref, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args))); }); _defineProperty(_assertThisInitialized(_this), "createURL", function () { var _ref2; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return _this.props.contextValue.createHrefForState( // refine will always be defined here because the prop is only given conditionally (_ref2 = connectorDesc.refine).call.apply(_ref2, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args))); }); _defineProperty(_assertThisInitialized(_this), "searchForFacetValues", function () { var _ref3; for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } _this.props.contextValue.onSearchForFacetValues( // searchForFacetValues will always be defined here because the prop is only given conditionally (_ref3 = connectorDesc.searchForFacetValues).call.apply(_ref3, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args))); }); if (connectorDesc.getSearchParameters) { _this.props.contextValue.onSearchParameters(connectorDesc.getSearchParameters.bind(_assertThisInitialized(_this)), { ais: _this.props.contextValue, multiIndexContext: _this.props.indexContextValue }, _this.props); } return _this; } _createClass(Connector, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; this.unsubscribe = this.props.contextValue.store.subscribe(function () { if (!_this2.isUnmounting) { _this2.setState({ providedProps: _this2.getProvidedProps(_this2.props) }); } }); if (isWidget) { this.unregisterWidget = this.props.contextValue.widgetsManager.registerWidget(this); } } }, { key: "shouldComponentUpdate", value: function shouldComponentUpdate(nextProps, nextState) { if (typeof connectorDesc.shouldComponentUpdate === 'function') { return connectorDesc.shouldComponentUpdate.call(this, this.props, nextProps, this.state, nextState); } var propsEqual = shallowEqual(this.props, nextProps); if (this.state.providedProps === null || nextState.providedProps === null) { if (this.state.providedProps === nextState.providedProps) { return !propsEqual; } return true; } return !propsEqual || !shallowEqual(this.state.providedProps, nextState.providedProps); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (!fastDeepEqual(prevProps, this.props)) { this.setState({ providedProps: this.getProvidedProps(this.props) }); if (isWidget) { this.props.contextValue.widgetsManager.update(); if (typeof connectorDesc.transitionState === 'function') { this.props.contextValue.onSearchStateChange(connectorDesc.transitionState.call(this, this.props, this.props.contextValue.store.getState().widgets, this.props.contextValue.store.getState().widgets)); } } } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.isUnmounting = true; if (this.unsubscribe) { this.unsubscribe(); } if (this.unregisterWidget) { this.unregisterWidget(); if (typeof connectorDesc.cleanUp === 'function') { var nextState = connectorDesc.cleanUp.call(this, this.props, this.props.contextValue.store.getState().widgets); this.props.contextValue.store.setState(_objectSpread({}, this.props.contextValue.store.getState(), { widgets: nextState })); this.props.contextValue.onSearchStateChange(removeEmptyKey(nextState)); } } } }, { key: "getProvidedProps", value: function getProvidedProps(props) { var _this$props$contextVa = this.props.contextValue.store.getState(), widgets = _this$props$contextVa.widgets, results = _this$props$contextVa.results, resultsFacetValues = _this$props$contextVa.resultsFacetValues, searching = _this$props$contextVa.searching, searchingForFacetValues = _this$props$contextVa.searchingForFacetValues, isSearchStalled = _this$props$contextVa.isSearchStalled, metadata = _this$props$contextVa.metadata, error = _this$props$contextVa.error; var searchResults = { results: results, searching: searching, searchingForFacetValues: searchingForFacetValues, isSearchStalled: isSearchStalled, error: error }; return connectorDesc.getProvidedProps.call(this, props, widgets, searchResults, metadata, // @MAJOR: move this attribute on the `searchResults` it doesn't // makes sense to have it into a separate argument. The search // flags are on the object why not the results? resultsFacetValues); } }, { key: "getSearchParameters", value: function getSearchParameters(searchParameters) { if (typeof connectorDesc.getSearchParameters === 'function') { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.props.contextValue.store.getState().widgets); } return null; } }, { key: "getMetadata", value: function getMetadata(nextWidgetsState) { if (typeof connectorDesc.getMetadata === 'function') { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: "transitionState", value: function transitionState(prevWidgetsState, nextWidgetsState) { if (typeof connectorDesc.transitionState === 'function') { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { key: "render", value: function render() { var _this$props = this.props, contextValue = _this$props.contextValue, props = _objectWithoutProperties(_this$props, ["contextValue"]); var providedProps = this.state.providedProps; if (providedProps === null) { return null; } var refineProps = typeof connectorDesc.refine === 'function' ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = typeof connectorDesc.searchForFacetValues === 'function' ? { searchForItems: this.searchForFacetValues } : {}; return React__default.createElement(Composed, _extends({}, props, providedProps, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component); _defineProperty(Connector, "displayName", "".concat(connectorDesc.displayName, "(").concat(getDisplayName(Composed), ")")); _defineProperty(Connector, "propTypes", connectorDesc.propTypes); _defineProperty(Connector, "defaultProps", connectorDesc.defaultProps); return Connector; }; } var createConnectorWithContext = function createConnectorWithContext(connectorDesc) { return function (Composed) { var Connector = createConnectorWithoutContext(connectorDesc)(Composed); var ConnectorWrapper = function ConnectorWrapper(props) { return React__default.createElement(InstantSearchConsumer, null, function (contextValue) { return React__default.createElement(IndexConsumer, null, function (indexContextValue) { return React__default.createElement(Connector, _extends({ contextValue: contextValue, indexContextValue: indexContextValue }, props)); }); }); }; return ConnectorWrapper; }; }; 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, isHighlighted: boolean}. */ function parseHighlightedAttribute(_ref) { var preTag = _ref.preTag, postTag = _ref.postTag, _ref$highlightedValue = _ref.highlightedValue, highlightedValue = _ref$highlightedValue === void 0 ? '' : _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 * highlightPostTag 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 === void 0 ? '<em>' : _ref2$preTag, _ref2$postTag = _ref2.postTag, postTag = _ref2$postTag === void 0 ? '</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 = getPropertyByPath(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 version = '6.0.0'; function translatable(defaultTranslations) { return function (Composed) { var Translatable = /*#__PURE__*/ function (_Component) { _inherits(Translatable, _Component); function Translatable() { var _getPrototypeOf2; var _this; _classCallCheck(this, Translatable); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Translatable)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "translate", function (key) { var translations = _this.props.translations; var translation = translations && translations.hasOwnProperty(key) ? translations[key] : defaultTranslations[key]; if (typeof translation === 'function') { for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { params[_key2 - 1] = arguments[_key2]; } return translation.apply(void 0, params); } return translation; }); return _this; } _createClass(Translatable, [{ key: "render", value: function render() { return React__default.createElement(Composed, _extends({ translate: this.translate }, this.props)); } }]); return Translatable; }(React.Component); var name = Composed.displayName || Composed.name || 'UnknownComponent'; Translatable.displayName = "Translatable(".concat(name, ")"); return Translatable; }; } function getIndexId(context) { return hasMultipleIndices(context) ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (searchResults.results) { if (searchResults.results.hits) { return searchResults.results; } var indexId = getIndexId(context); if (searchResults.results[indexId]) { return searchResults.results[indexId]; } } return null; } function hasMultipleIndices(context) { return context && context.multiIndexContext; } // eslint-disable-next-line max-params function refineValue(searchState, nextRefinement, context, resetPage, namespace) { if (hasMultipleIndices(context)) { var indexId = getIndexId(context); return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, indexId, 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, indexId, resetPage) { var page = resetPage ? { page: 1 } : undefined; var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], nextRefinement, page))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, nextRefinement, page))); return _objectSpread({}, searchState, { indices: state }); } function refineSingleIndex(searchState, nextRefinement, resetPage) { var page = resetPage ? { page: 1 } : undefined; return _objectSpread({}, searchState, nextRefinement, page); } // eslint-disable-next-line max-params function refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) { var _objectSpread4; var page = resetPage ? { page: 1 } : undefined; var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], (_objectSpread4 = {}, _defineProperty(_objectSpread4, namespace, _objectSpread({}, searchState.indices[indexId][namespace], nextRefinement)), _defineProperty(_objectSpread4, "page", 1), _objectSpread4)))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread(_defineProperty({}, namespace, nextRefinement), page))); return _objectSpread({}, searchState, { indices: state }); } function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) { var page = resetPage ? { page: 1 } : undefined; return _objectSpread({}, searchState, _defineProperty({}, namespace, _objectSpread({}, 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 }; } function hasRefinements(_ref) { var multiIndex = _ref.multiIndex, indexId = _ref.indexId, namespace = _ref.namespace, attributeName = _ref.attributeName, id = _ref.id, searchState = _ref.searchState; if (multiIndex && namespace) { return searchState.indices && searchState.indices[indexId] && searchState.indices[indexId][namespace] && Object.hasOwnProperty.call(searchState.indices[indexId][namespace], attributeName); } if (multiIndex) { return searchState.indices && searchState.indices[indexId] && Object.hasOwnProperty.call(searchState.indices[indexId], id); } if (namespace) { return searchState[namespace] && Object.hasOwnProperty.call(searchState[namespace], attributeName); } return Object.hasOwnProperty.call(searchState, id); } function getRefinements(_ref2) { var multiIndex = _ref2.multiIndex, indexId = _ref2.indexId, namespace = _ref2.namespace, attributeName = _ref2.attributeName, id = _ref2.id, searchState = _ref2.searchState; if (multiIndex && namespace) { return searchState.indices[indexId][namespace][attributeName]; } if (multiIndex) { return searchState.indices[indexId][id]; } if (namespace) { return searchState[namespace][attributeName]; } return searchState[id]; } function getCurrentRefinementValue(props, searchState, context, id, defaultValue) { var indexId = getIndexId(context); var _getNamespaceAndAttri = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri.namespace, attributeName = _getNamespaceAndAttri.attributeName; var multiIndex = hasMultipleIndices(context); var args = { multiIndex: multiIndex, indexId: indexId, namespace: namespace, attributeName: attributeName, id: id, searchState: searchState }; var hasRefinementsValue = hasRefinements(args); if (hasRefinementsValue) { return getRefinements(args); } if (props.defaultRefinement) { return props.defaultRefinement; } return defaultValue; } function cleanUpValue(searchState, context, id) { var indexId = getIndexId(context); var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri2.namespace, attributeName = _getNamespaceAndAttri2.attributeName; if (hasMultipleIndices(context) && Boolean(searchState.indices)) { return cleanUpValueWithMultiIndex({ attribute: attributeName, searchState: searchState, indexId: indexId, id: id, namespace: namespace }); } return cleanUpValueWithSingleIndex({ attribute: attributeName, searchState: searchState, id: id, namespace: namespace }); } function cleanUpValueWithSingleIndex(_ref3) { var searchState = _ref3.searchState, id = _ref3.id, namespace = _ref3.namespace, attribute = _ref3.attribute; if (namespace) { return _objectSpread({}, searchState, _defineProperty({}, namespace, omit(searchState[namespace], [attribute]))); } return omit(searchState, [id]); } function cleanUpValueWithMultiIndex(_ref4) { var searchState = _ref4.searchState, indexId = _ref4.indexId, id = _ref4.id, namespace = _ref4.namespace, attribute = _ref4.attribute; var indexSearchState = searchState.indices[indexId]; if (namespace && indexSearchState) { return _objectSpread({}, searchState, { indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, indexSearchState, _defineProperty({}, namespace, omit(indexSearchState[namespace], [attribute]))))) }); } if (indexSearchState) { return _objectSpread({}, searchState, { indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, omit(indexSearchState, [id]))) }); } return searchState; } function getId() { return 'configure'; } var connectConfigure = createConnectorWithContext({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var children = props.children, contextValue = props.contextValue, indexContextValue = props.indexContextValue, items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var children = props.children, contextValue = props.contextValue, indexContextValue = props.indexContextValue, items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]); var propKeys = Object.keys(props); var nonPresentKeys = this._props ? Object.keys(this._props).filter(function (prop) { return propKeys.indexOf(prop) === -1; }) : []; this._props = props; var nextValue = _defineProperty({}, id, _objectSpread({}, omit(nextSearchState[id], nonPresentKeys), items)); return refineValue(nextSearchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var indexId = getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }); var subState = hasMultipleIndices({ ais: props.contextValue, multiIndexContext: props.indexContextValue }) && searchState.indices ? searchState.indices[indexId] : 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({}, id, configureState); return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); /** * 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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Configure, Hits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Configure hitsPerPage={5} /> * <Hits /> * </InstantSearch> * ); */ var Configure = connectConfigure(function Configure() { return null; }); var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); if (typeof global$1.setTimeout === 'function') ; if (typeof global$1.clearTimeout === 'function') ; // 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() }; function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /* 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; function emptyFunction() {} var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret_1) { // 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, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; 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(); } }); function getIndexContext(props) { return { targetedIndex: props.indexId }; } /** * 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. * * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Index, SearchBox, Hits, Configure } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Configure hitsPerPage={5} /> * <SearchBox /> * <Index indexName="instant_search"> * <Hits /> * </Index> * <Index indexName="bestbuy"> * <Hits /> * </Index> * </InstantSearch> * ); */ var Index = /*#__PURE__*/ function (_Component) { _inherits(Index, _Component); _createClass(Index, null, [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(props) { return { indexContext: getIndexContext(props) }; } }]); function Index(props) { var _this; _classCallCheck(this, Index); _this = _possibleConstructorReturn(this, _getPrototypeOf(Index).call(this, props)); _defineProperty(_assertThisInitialized(_this), "state", { indexContext: getIndexContext(_this.props) }); _defineProperty(_assertThisInitialized(_this), "unregisterWidget", void 0); _this.props.contextValue.onSearchParameters(_this.getSearchParameters.bind(_assertThisInitialized(_this)), { ais: _this.props.contextValue, multiIndexContext: _this.state.indexContext }, _this.props); return _this; } _createClass(Index, [{ key: "componentDidMount", value: function componentDidMount() { this.unregisterWidget = this.props.contextValue.widgetsManager.registerWidget(this); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props.indexName !== prevProps.indexName) { this.props.contextValue.widgetsManager.update(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (typeof this.unregisterWidget === 'function') { this.unregisterWidget(); } } }, { 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); if (childrenCount === 0) { return null; } return React__default.createElement(IndexProvider, { value: this.state.indexContext }, this.props.children); } }]); return Index; }(React.Component); _defineProperty(Index, "propTypes", { indexName: propTypes.string.isRequired, indexId: propTypes.string.isRequired, children: propTypes.node }); var IndexWrapper = function IndexWrapper(props) { var inferredIndexId = props.indexName; return React__default.createElement(InstantSearchConsumer, null, function (contextValue) { return React__default.createElement(Index, _extends({ contextValue: contextValue, indexId: inferredIndexId }, props)); }); }; function clone(value) { if (_typeof(value) === 'object' && value !== null) { return _merge(Array.isArray(value) ? [] : {}, value); } return value; } function isObjectOrArrayOrFunction(value) { return typeof value === 'function' || Array.isArray(value) || Object.prototype.toString.call(value) === '[object Object]'; } function _merge(target, source) { if (target === source) { return target; } for (var key in source) { if (!Object.prototype.hasOwnProperty.call(source, key)) { continue; } var sourceVal = source[key]; var targetVal = target[key]; if (typeof targetVal !== 'undefined' && typeof sourceVal === 'undefined') { continue; } if (isObjectOrArrayOrFunction(targetVal) && isObjectOrArrayOrFunction(sourceVal)) { target[key] = _merge(targetVal, sourceVal); } else { target[key] = clone(sourceVal); } } return target; } /** * This method is like Object.assign, but recursively merges own and inherited * enumerable keyed properties of source objects into the destination object. * * NOTE: this behaves like lodash/merge, but: * - does mutate functions if they are a source * - treats non-plain objects as plain * - does not work for circular objects * - treats sparse arrays as sparse * - does not convert Array-like objects (Arguments, NodeLists, etc.) to arrays * * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. */ function merge(target) { if (!isObjectOrArrayOrFunction(target)) { target = {}; } for (var i = 1, l = arguments.length; i < l; i++) { var source = arguments[i]; if (isObjectOrArrayOrFunction(source)) { _merge(target, source); } } return target; } module.exports = merge; var merge$1 = /*#__PURE__*/Object.freeze({ }); var defaultsPure = function defaultsPure() { var sources = Array.prototype.slice.call(arguments); return sources.reduceRight(function (acc, source) { Object.keys(Object(source)).forEach(function (key) { if (source[key] !== undefined) { acc[key] = source[key]; } }); return acc; }, {}); }; function intersection(arr1, arr2) { return arr1.filter(function (value, index) { return arr2.indexOf(value) > -1 && arr1.indexOf(value) === index /* skips duplicates */ ; }); } var intersection_1 = intersection; var find$1 = function find(array, comparator) { if (!Array.isArray(array)) { return undefined; } for (var i = 0; i < array.length; i++) { if (comparator(array[i])) { return array[i]; } } }; function valToNumber(v) { if (typeof v === 'number') { return v; } else if (typeof v === 'string') { return parseFloat(v); } else if (Array.isArray(v)) { return v.map(valToNumber); } throw new Error('The value should be a number, a parsable string or an array of those.'); } var valToNumber_1 = valToNumber; function _objectWithoutPropertiesLoose$1(source, excluded) { if (source === null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key; var i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var omit$1 = _objectWithoutPropertiesLoose$1; function objectHasKeys$1(obj) { return obj && Object.keys(obj).length > 0; } var objectHasKeys_1 = objectHasKeys$1; /** * 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 defaultsPure({}, 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 (value === undefined) { // we use the "filter" form of clearRefinement, since it leaves empty values as-is // the form with a string will remove the attribute completely return lib.clearRefinement(refinementList, function (v, f) { return attribute === f; }); } 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 (value === undefined) 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 (attribute === undefined) { if (!objectHasKeys_1(refinementList)) { return refinementList; } return {}; } else if (typeof attribute === 'string') { if (!(refinementList[attribute] && refinementList[attribute].length > 0)) { return refinementList; } return omit$1(refinementList, attribute); } else if (typeof attribute === 'function') { var hasChanged = false; var newRefinementList = Object.keys(refinementList).reduce(function (memo, key) { var values = refinementList[key] || []; var facetList = values.filter(function (value) { return !attribute(value, key, refinementType); }); if (facetList.length !== values.length) { hasChanged = true; } memo[key] = facetList; 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 containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (refinementValue === undefined || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return refinementList[attribute].indexOf(refinementValueAsString) !== -1; } }; var RefinementList = lib; /** * isEqual, but only for numeric refinement values, possible values: * - 5 * - [5] * - [[5]] * - [[5,5],[4]] */ function isEqualNumericRefinement(a, b) { if (Array.isArray(a) && Array.isArray(b)) { return a.length === b.length && a.every(function (el, i) { return isEqualNumericRefinement(b[i], el); }); } return a === b; } /** * like _.find but using deep equality to be able to use it * to find arrays. * @private * @param {any[]} array array to search into (elements are base or array of base) * @param {any} searchedValue the value we're looking for (base or array of base) * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find$1(array, function (currentValue) { return isEqualNumericRefinement(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) : {}; /** * 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 || {}; var self = this; Object.keys(params).forEach(function (paramName) { var isKeyKnown = SearchParameters.PARAMETERS.indexOf(paramName) !== -1; var isValueDefined = params[paramName] !== undefined; if (!isKeyKnown && isValueDefined) { self[paramName] = params[paramName]; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = Object.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']; numberKeys.forEach(function (k) { var value = partialState[k]; if (typeof value === 'string') { var parsedValue = parseFloat(value); // global isNaN is ok to use here, value is only number or NaN 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 = {}; Object.keys(partialState.numericRefinements).forEach(function (attribute) { var operators = partialState.numericRefinements[attribute] || {}; numericRefinements[attribute] = {}; Object.keys(operators).forEach(function (operator) { var values = operators[operator]; var parsedValues = values.map(function (v) { if (Array.isArray(v)) { return v.map(function (vPrime) { if (typeof vPrime === 'string') { return parseFloat(vPrime); } return vPrime; }); } else if (typeof v === 'string') { 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); var hierarchicalFacets = newParameters.hierarchicalFacets || []; hierarchicalFacets.forEach(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 && objectHasKeys_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 (objectHasKeys_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 addNumericRefinement(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 getConjunctiveRefinements(facetName) { if (!this.isConjunctiveFacet(facetName)) { return []; } 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 getDisjunctiveRefinements(facetName) { if (!this.isDisjunctiveFacet(facetName)) { return []; } 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 getHierarchicalRefinement(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 getExcludeRefinements(facetName) { if (!this.isConjunctiveFacet(facetName)) { return []; } 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 removeNumericRefinement(attribute, operator, paramValue) { if (paramValue !== undefined) { if (!this.isNumericRefined(attribute, operator, paramValue)) { return this; } return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function (value, key) { return key === attribute && value.op === operator && isEqualNumericRefinement(value.val, valToNumber_1(paramValue)); }) }); } 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 getNumericRefinements(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 getNumericRefinement(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 (attribute === undefined) { if (!objectHasKeys_1(this.numericRefinements)) { return this.numericRefinements; } return {}; } else if (typeof attribute === 'string') { if (!objectHasKeys_1(this.numericRefinements[attribute])) { return this.numericRefinements; } return omit$1(this.numericRefinements, attribute); } else if (typeof attribute === 'function') { var hasChanged = false; var numericRefinements = this.numericRefinements; var newNumericRefinements = Object.keys(numericRefinements).reduce(function (memo, key) { var operators = numericRefinements[key]; var operatorList = {}; operators = operators || {}; Object.keys(operators).forEach(function (operator) { var values = operators[operator] || []; var outValues = []; values.forEach(function (value) { var predicateResult = attribute({ val: value, op: operator }, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (outValues.length !== values.length) { hasChanged = true; } operatorList[operator] = outValues; }); 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: this.facets.filter(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: this.disjunctiveFacets.filter(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: this.hierarchicalFacets.filter(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: this.tagRefinements.filter(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: defaultsPure({}, 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 addHierarchicalFacetRefinement(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } if (!this.isHierarchicalFacet(facet)) { throw new Error(facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaultsPure({}, 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 removeHierarchicalFacetRefinement(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaultsPure({}, 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 isDisjunctiveFacet(facet) { return this.disjunctiveFacets.indexOf(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 isHierarchicalFacet(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 isConjunctiveFacet(facet) { return this.facets.indexOf(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)) { return false; } 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)) { return false; } 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)) { return false; } 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)) { return false; } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return refinements.indexOf(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 (value === undefined && operator === undefined) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && this.numericRefinements[attribute][operator] !== undefined; if (value === undefined || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber_1(value); var isAttributeValueDefined = findArray(this.numericRefinements[attribute][operator], parsedValue) !== undefined; 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 this.tagRefinements.indexOf(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() { var self = this; // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection_1(Object.keys(this.numericRefinements).filter(function (facet) { return Object.keys(self.numericRefinements[facet]).length > 0; }), this.disjunctiveFacets); return Object.keys(this.disjunctiveFacetsRefinements).filter(function (facet) { return self.disjunctiveFacetsRefinements[facet].length > 0; }).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() { var self = this; return intersection_1( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index this.hierarchicalFacets.map(function (facet) { return facet.name; }), Object.keys(this.hierarchicalFacetsRefinements).filter(function (facet) { return self.hierarchicalFacetsRefinements[facet].length > 0; })); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function getUnrefinedDisjunctiveFacets() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return this.disjunctiveFacets.filter(function (f) { return refinedFacets.indexOf(f) === -1; }); }, managedParameters: ['index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; var self = this; Object.keys(this).forEach(function (paramName) { var paramValue = self[paramName]; if (managedParameters.indexOf(paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * 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 self = this; var nextWithNumbers = SearchParameters._parseNumbers(params); var previousPlainObject = Object.keys(this).reduce(function (acc, key) { acc[key] = self[key]; return acc; }, {}); var nextPlainObject = Object.keys(nextWithNumbers).reduce(function (previous, key) { var isPreviousValueDefined = previous[key] !== undefined; var isNextValueDefined = nextWithNumbers[key] !== undefined; if (isPreviousValueDefined && !isNextValueDefined) { return omit$1(previous, [key]); } if (isNextValueDefined) { previous[key] = nextWithNumbers[key]; } return previous; }, previousPlainObject); return new this.constructor(nextPlainObject); }, /** * Returns a new instance with the page reset. Two scenarios possible: * the page is omitted -> return the given instance * the page is set -> return a new instance with a page of 0 * @return {SearchParameters} a new updated instance */ resetPage: function resetPage() { if (this.page === undefined) { return this; } return this.setPage(0); }, /** * 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 _getHierarchicalFacetSortBy(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 _getHierarchicalFacetSeparator(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 _getHierarchicalRootPath(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 _getHierarchicalShowParentLevel(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 getHierarchicalFacetByName(hierarchicalFacetName) { return find$1(this.hierarchicalFacets, function (f) { return f.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 getHierarchicalFacetBreadcrumb(facetName) { if (!this.isHierarchicalFacet(facetName)) { return []; } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facetName)); var path = refinement.split(separator); return path.map(function (part) { return part.trim(); }); }, toString: function toString() { 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; function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined; var valIsNull = value === null; var othIsDefined = other !== undefined; var othIsNull = other === null; if (!othIsNull && value > other || valIsNull && othIsDefined || !valIsDefined) { return 1; } if (!valIsNull && value < other || othIsNull && valIsDefined || !othIsDefined) { return -1; } } return 0; } /** * @param {Array<object>} collection object with keys in attributes * @param {Array<string>} iteratees attributes * @param {Array<string>} orders asc | desc */ function orderBy(collection, iteratees, orders) { if (!Array.isArray(collection)) { return []; } if (!Array.isArray(orders)) { orders = []; } var result = collection.map(function (value, index) { return { criteria: iteratees.map(function (iteratee) { return value[iteratee]; }), index: index, value: value }; }); result.sort(function comparer(object, other) { var index = -1; while (++index < object.criteria.length) { var res = compareAscending(object.criteria[index], other.criteria[index]); if (res) { if (index >= orders.length) { return res; } if (orders[index] === 'desc') { return -res; } return res; } } // This 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; }); return result.map(function (res) { return res.value; }); } var orderBy_1 = orderBy; var compact = function compact(array) { if (!Array.isArray(array)) { return []; } return array.filter(Boolean); }; var findIndex = function find(array, comparator) { if (!Array.isArray(array)) { return -1; } for (var i = 0; i < array.length; i++) { if (comparator(array[i])) { return i; } } return -1; }; /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @param {string[]} [defaults] array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ var formatSort = function formatSort(sortBy, defaults) { var defaultInstructions = (defaults || []).map(function (sort) { return sort.split(':'); }); return sortBy.reduce(function preparePredicate(out, sort) { var sortInstruction = sort.split(':'); var matchingDefault = find$1(defaultInstructions, function (defaultInstruction) { return defaultInstruction[0] === sortInstruction[0]; }); if (sortInstruction.length > 1 || !matchingDefault) { out[0].push(sortInstruction[0]); out[1].push(sortInstruction[1]); return out; } out[0].push(matchingDefault[0]); out[1].push(matchingDefault[1]); return out; }, [[], []]); }; 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 rootExhaustive = hierarchicalFacetResult.every(function (facetResult) { return facetResult.exhaustive; }); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return results.reduce(generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path exhaustive: rootExhaustive, 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) { /** * @type {object[]]} hierarchical data */ var data = parent && Array.isArray(parent.data) ? parent.data : []; parent = find$1(data, function (subtree) { return subtree.isRefined; }); 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 picked = Object.keys(hierarchicalFacetResult.data).map(function (facetValue) { return [facetValue, hierarchicalFacetResult.data[facetValue]]; }).filter(function (tuple) { var facetValue = tuple[0]; return onlyMatchingTree(facetValue, parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); }); parent.data = orderBy_1(picked.map(function (tuple) { var facetValue = tuple[0]; var facetCount = tuple[1]; return format(facetCount, facetValue, hierarchicalSeparator, currentRefinement, hierarchicalFacetResult.exhaustive); }), sortBy[0], sortBy[1]); } return hierarchicalTree; }; } function onlyMatchingTree(facetValue, parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { // 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 format(facetCount, facetValue, hierarchicalSeparator, currentRefinement, exhaustive) { var parts = facetValue.split(hierarchicalSeparator); return { name: parts[parts.length - 1].trim(), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, exhaustive: exhaustive, 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 */ /** * @param {string[]} attributes */ function getIndices(attributes) { var indices = {}; attributes.forEach(function (val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } /** * @typedef {Object} HierarchicalFacet * @property {string} name * @property {string[]} attributes */ /** * @param {HierarchicalFacet[]} hierarchicalFacets * @param {string} hierarchicalAttributeName */ function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find$1(hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { var facetNames = hierarchicalFacet.attributes || []; return facetNames.indexOf(hierarchicalAttributeName) > -1; }); } /*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 = results.reduce(function (sum, result) { return result.processingTimeMS === undefined ? sum : sum + result.processingTimeMS; }, 0); /** * 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. * * getRankingInfo needs to be set to `true` for this to be returned * * @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 = state.hierarchicalFacets.map(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 information from the first, general, response. var mainFacets = mainSubResponse.facets || {}; Object.keys(mainFacets).forEach(function (facetKey) { var facetValueObject = mainFacets[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, function (f) { return f.name === hierarchicalFacet.name; }); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = state.disjunctiveFacets.indexOf(facetKey) !== -1; var isFacetConjunctive = state.facets.indexOf(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 disjunctiveFacets.forEach(function (disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var facets = result && result.facets ? result.facets : {}; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. Object.keys(facets).forEach(function (dfacet) { var facetResults = facets[dfacet]; var position; if (hierarchicalFacet) { position = findIndex(state.hierarchicalFacets, function (f) { return f.name === hierarchicalFacet.name; }); var attributeIndex = findIndex(self.hierarchicalFacets[position], function (f) { return f.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: defaultsPure({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { state.disjunctiveFacetsRefinements[dfacet].forEach(function (refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && state.disjunctiveFacetsRefinements[dfacet].indexOf(refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them state.getRefinedHierarchicalFacets().forEach(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]; var facets = result && result.facets ? result.facets : {}; Object.keys(facets).forEach(function (dfacet) { var facetResults = facets[dfacet]; var position = findIndex(state.hierarchicalFacets, function (f) { return f.name === hierarchicalFacet.name; }); var attributeIndex = findIndex(self.hierarchicalFacets[position], function (f) { return f.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 = defaultsPure(defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data); }); nextDisjunctiveResult++; }); // add the excludes Object.keys(state.facetsExcludes).forEach(function (facetName) { var excludes = state.facetsExcludes[facetName]; var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; excludes.forEach(function (facetValue) { self.facets[position] = self.facets[position] || { name: facetName }; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); /** * @type {Array} */ this.hierarchicalFacets = this.hierarchicalFacets.map(generateHierarchicalTree_1(state)); /** * @type {Array} */ this.facets = compact(this.facets); /** * @type {Array} */ this.disjunctiveFacets = compact(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) { function predicate(facet) { return facet.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) { function predicate(facet) { return facet.name === attribute; } if (results._state.isConjunctiveFacet(attribute)) { var facet = find$1(results.facets, predicate); if (!facet) return []; return Object.keys(facet.data).map(function (name) { return { name: name, count: facet.data[name], isRefined: results._state.isFacetRefined(attribute, name), isExcluded: results._state.isExcludeRefined(attribute, name) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find$1(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return Object.keys(disjunctiveFacet.data).map(function (name) { return { name: name, count: disjunctiveFacet.data[name], isRefined: results._state.isDisjunctiveFacetRefined(attribute, name) }; }); } 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 = node.data.map(function (childNode) { return recSort(sortFn, childNode); }); 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|undefined} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('result', function(event){ * //get values ordered only by name ascending using the string predicate * event.results.getFacetValues('city', {sortBy: ['name:asc']}); * //get values ordered only by count ascending using a function * event.results.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) { return undefined; } var options = defaultsPure({}, 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(function (hierarchicalFacetValues) { return orderBy_1(hierarchicalFacetValues, order[0], order[1]); }, facetValues); } else if (typeof options.sortBy === 'function') { 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(function (data) { return vanillaSortFn(options.sortBy, data); }, 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); } return undefined; }; /** * @typedef {Object} FacetListItem * @property {string} name */ /** * @param {FacetListItem[]} facetList (has more items, but enough for here) * @param {string} facetName */ function getFacetStatsIfAvailable(facetList, facetName) { var data = find$1(facetList, function (facet) { return facet.name === facetName; }); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhaustiveness for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * Note that for a numeric refinement, results are grouped per operator, this * means that it will return responses for operators which are empty. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function () { var state = this._state; var results = this; var res = []; Object.keys(state.facetsRefinements).forEach(function (attributeName) { state.facetsRefinements[attributeName].forEach(function (name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); Object.keys(state.facetsExcludes).forEach(function (attributeName) { state.facetsExcludes[attributeName].forEach(function (name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); Object.keys(state.disjunctiveFacetsRefinements).forEach(function (attributeName) { state.disjunctiveFacetsRefinements[attributeName].forEach(function (name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); Object.keys(state.hierarchicalFacetsRefinements).forEach(function (attributeName) { state.hierarchicalFacetsRefinements[attributeName].forEach(function (name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); Object.keys(state.numericRefinements).forEach(function (attributeName) { var operators = state.numericRefinements[attributeName]; Object.keys(operators).forEach(function (operator) { operators[operator].forEach(function (value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); state.tagRefinements.forEach(function (name) { res.push({ type: 'tag', attributeName: '_tags', name: name }); }); return res; }; /** * @typedef {Object} Facet * @property {string} name * @property {Object} data * @property {boolean} exhaustive */ /** * @param {*} state * @param {*} type * @param {string} attributeName * @param {*} name * @param {Facet[]} resultsFacets */ function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find$1(resultsFacets, function (f) { return f.name === attributeName; }); var count = facet && facet.data && facet.data[name] ? facet.data[name] : 0; var exhaustive = facet && facet.exhaustive || false; return { type: type, attributeName: attributeName, name: name, count: count, exhaustive: exhaustive }; } /** * @param {*} state * @param {string} attributeName * @param {*} name * @param {Facet[]} resultsFacets */ function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var separator = state._getHierarchicalFacetSeparator(facetDeclaration); var split = name.split(separator); var rootFacet = find$1(resultsFacets, function (facet) { return facet.name === attributeName; }); var facet = split.reduce(function (intermediateFacet, part) { var newFacet = intermediateFacet && find$1(intermediateFacet.data, function (f) { return f.name === part; }); return newFacet !== undefined ? newFacet : intermediateFacet; }, rootFacet); var count = facet && facet.count || 0; var exhaustive = facet && facet.exhaustive || false; var path = facet && facet.path || ''; return { type: 'hierarchical', attributeName: attributeName, name: path, count: count, exhaustive: exhaustive }; } var SearchResults_1 = SearchResults; // 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(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; } function inherits(ctor, superCtor) { ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } var inherits_1 = inherits; /** * 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; } inherits_1(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 state.getRefinedDisjunctiveFacets().forEach(function (refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated state.getRefinedHierarchicalFacets().forEach(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 _getHitsSearchParams(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 _getDisjunctiveFacetSearchParams(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 _getNumericFilters(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; Object.keys(state.numericRefinements).forEach(function (attribute) { var operators = state.numericRefinements[attribute] || {}; Object.keys(operators).forEach(function (operator) { var values = operators[operator] || []; if (facetName !== attribute) { values.forEach(function (value) { if (Array.isArray(value)) { var vs = value.map(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 _getTagFilters(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 _getFacetFilters(state, facet, hierarchicalRootLevel) { var facetFilters = []; var facetsRefinements = state.facetsRefinements || {}; Object.keys(facetsRefinements).forEach(function (facetName) { var facetValues = facetsRefinements[facetName] || []; facetValues.forEach(function (facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); var facetsExcludes = state.facetsExcludes || {}; Object.keys(facetsExcludes).forEach(function (facetName) { var facetValues = facetsExcludes[facetName] || []; facetValues.forEach(function (facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); var disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements || {}; Object.keys(disjunctiveFacetsRefinements).forEach(function (facetName) { var facetValues = disjunctiveFacetsRefinements[facetName] || []; if (facetName === facet || !facetValues || facetValues.length === 0) { return; } var orFilters = []; facetValues.forEach(function (facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); var hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements || {}; Object.keys(hierarchicalFacetsRefinements).forEach(function (facetName) { var facetValues = hierarchicalFacetsRefinements[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 _getHitsHierarchicalFacetsAttributes(state) { var out = []; return state.hierarchicalFacets.reduce( // 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 _getDisjunctiveHierarchicalFacetAttribute(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 getSearchForFacetQuery(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; } return merge$1({}, requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters); } }; var requestBuilder_1 = requestBuilder; var version$1 = '0.0.0-6ac260d'; /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {object} event * @property {SearchParameters} event.state the current parameters with the latest changes applied * @property {SearchResults} event.results the previous results received from Algolia. `null` before the first request * @example * helper.on('change', function(event) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when a main search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {object} event * @property {SearchParameters} event.state the parameters used for this search * @property {SearchResults} event.results the results from the previous search. `null` if it is the first search. * @example * helper.on('search', function(event) { * console.log('Search sent'); * }); */ /** * Event triggered when a search using `searchForFacetValues` is sent to Algolia * @event AlgoliaSearchHelper#event:searchForFacetValues * @property {object} event * @property {SearchParameters} event.state the parameters used for this search it is the first search. * @property {string} event.facet the facet searched into * @property {string} event.query the query used to search in the facets * @example * helper.on('searchForFacetValues', function(event) { * console.log('searchForFacetValues sent'); * }); */ /** * Event triggered when a search using `searchOnce` is sent to Algolia * @event AlgoliaSearchHelper#event:searchOnce * @property {object} event * @property {SearchParameters} event.state the parameters used for this search it is the first search. * @example * helper.on('searchOnce', function(event) { * console.log('searchOnce sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {object} event * @property {SearchResults} event.results the results received from Algolia * @property {SearchParameters} event.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(event) { * 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 {object} event * @property {Error} event.error the error returned by the Algolia. * @example * helper.on('error', function(event) { * 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 (typeof client.addAlgoliaAgent === 'function') { 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; } inherits_1(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({ onlyWithDerivedHelpers: false }); return this; }; AlgoliaSearchHelper.prototype.searchOnlyWithDerivedHelpers = function () { this._search({ onlyWithDerivedHelpers: true }); 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', { state: 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 clientHasSFFV = typeof this.client.searchForFacetValues === 'function'; if (!clientHasSFFV && typeof this.client.initIndex !== 'function') { throw new Error('search for facet values (searchable) was called, but this client does not have a function client.searchForFacetValues or client.initIndex(index).searchForFacetValues'); } 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: state, facet: facet, query: query }); var searchForFacetValuesPromise = clientHasSFFV ? 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(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({ state: this.state.resetPage().setQuery(q), isPageReset: true }); 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({ state: this.state.resetPage().clearRefinements(name), isPageReset: true }); 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({ state: this.state.resetPage().clearTags(), isPageReset: true }); 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({ state: this.state.resetPage().addDisjunctiveFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addHierarchicalFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addNumericRefinement(attribute, operator, value), isPageReset: true }); 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({ state: this.state.resetPage().addFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addExcludeRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addTagRefinement(tag), isPageReset: true }); 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({ state: this.state.resetPage().removeNumericRefinement(attribute, operator, value), isPageReset: true }); 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({ state: this.state.resetPage().removeDisjunctiveFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().removeHierarchicalFacetRefinement(facet), isPageReset: true }); 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({ state: this.state.resetPage().removeFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().removeExcludeRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().removeTagRefinement(tag), isPageReset: true }); 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({ state: this.state.resetPage().toggleExcludeFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().toggleFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().toggleTagRefinement(tag), isPageReset: true }); 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 () { var page = this.state.page || 0; return this.setPage(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 () { var page = this.state.page || 0; return this.setPage(page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this._change({ state: this.state.setPage(page), isPageReset: false }); 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({ state: this.state.resetPage().setIndex(name), isPageReset: true }); 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({ state: this.state.resetPage().setQueryParameter(parameter, value), isPageReset: true }); 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({ state: SearchParameters_1.make(newState), isPageReset: false }); return this; }; /** * 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; }; /** * 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 (objectHasKeys_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 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); conjRefinements.forEach(function (r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); excludeRefinements.forEach(function (r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); disjRefinements.forEach(function (r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); Object.keys(numericRefinements).forEach(function (operator) { var value = numericRefinements[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 (options) { var state = this.state; var states = []; var mainQueries = []; if (!options.onlyWithDerivedHelpers) { mainQueries = requestBuilder_1._getQueries(state.index, state); states.push({ state: state, queriesCount: mainQueries.length, helper: this }); this.emit('search', { state: state, results: this.lastResults }); } var derivedQueries = this.derivedHelpers.map(function (derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var derivedStateQueries = requestBuilder_1._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: derivedStateQueries.length, helper: derivedHelper }); derivedHelper.emit('search', { state: derivedState, results: derivedHelper.lastResults }); return derivedStateQueries; }); var queries = Array.prototype.concat.apply(mainQueries, 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 (error) { // If we reach this part, we're in an internal error state this.emit('error', { error: error }); } }; /** * 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.slice(); states.forEach(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', { results: formattedResponse, state: state }); }); }; AlgoliaSearchHelper.prototype._dispatchAlgoliaError = function (queryId, error) { if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= queryId - this._lastQueryIdReceived; this._lastQueryIdReceived = queryId; this.emit('error', { error: error }); 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 (event) { var state = event.state; var isPageReset = event.isPageReset; if (state !== this.state) { this.state = state; this.emit('change', { state: this.state, results: this.lastResults, isPageReset: isPageReset }); } }; /** * 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 (typeof newClient.addAlgoliaAgent === 'function') { 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' */ 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(event) { * console.log(event.results); * }); * helper * .toggleFacetRefinement('category', 'Movies & TV Shows') * .toggleFacetRefinement('shipping', '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; var algoliasearchHelper_1 = algoliasearchHelper; 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 = []; return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; listeners.forEach(function (listener) { return listener(); }); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubscribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } function addAlgoliaAgents(searchClient) { if (typeof searchClient.addAlgoliaAgent === 'function') { searchClient.addAlgoliaAgent("react (".concat(React.version, ")")); searchClient.addAlgoliaAgent("react-instantsearch (".concat(version, ")")); } } var isMultiIndexContext = function isMultiIndexContext(widget) { return hasMultipleIndices({ ais: widget.props.contextValue, multiIndexContext: widget.props.indexContextValue }); }; var isTargetedIndexEqualIndex = function isTargetedIndexEqualIndex(widget, indexId) { return widget.props.indexContextValue.targetedIndex === indexId; }; // Relying on the `indexId` is a bit brittle to detect the `Index` widget. // Since it's a class we could rely on `instanceof` or similar. We never // had an issue though. Works for now. var isIndexWidget = function isIndexWidget(widget) { return Boolean(widget.props.indexId); }; var isIndexWidgetEqualIndex = function isIndexWidgetEqualIndex(widget, indexId) { return widget.props.indexId === indexId; }; var sortIndexWidgetsFirst = function sortIndexWidgetsFirst(firstWidget, secondWidget) { if (isIndexWidget(firstWidget)) { return -1; } if (isIndexWidget(secondWidget)) { return 1; } return 0; }; /** * 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 === void 0 ? {} : _ref$initialState, searchClient = _ref.searchClient, resultsState = _ref.resultsState, stalledSearchDelay = _ref.stalledSearchDelay; var helper = algoliasearchHelper_1(searchClient, indexName, _objectSpread({}, HIGHLIGHT_TAGS)); addAlgoliaAgents(searchClient); helper.on('search', handleNewSearch).on('result', handleSearchSuccess({ indexId: indexName })).on('error', handleSearchError); var skip = false; var stalledSearchTimer = null; var initialSearchParameters = helper.state; var widgetsManager = createWidgetsManager(onWidgetsUpdate); hydrateSearchClient(searchClient, resultsState); var store = createStore({ widgets: initialState, metadata: [], results: hydrateResultsState(resultsState), error: null, searching: false, isSearchStalled: true, searchingForFacetValues: false }); function skipSearch() { skip = true; } function updateClient(client) { addAlgoliaAgents(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() { var sharedParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return !isMultiIndexContext(widget) && !isIndexWidget(widget); }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, initialSearchParameters); var mainParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { var targetedIndexEqualMainIndex = isMultiIndexContext(widget) && isTargetedIndexEqualIndex(widget, indexName); var subIndexEqualMainIndex = isIndexWidget(widget) && isIndexWidgetEqualIndex(widget, indexName); return targetedIndexEqualMainIndex || subIndexEqualMainIndex; }) // We have to sort the `Index` widgets first so the `index` parameter // is correctly set in the `reduce` function for the following widgets .sort(sortIndexWidgetsFirst).reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); var derivedIndices = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { var targetedIndexNotEqualMainIndex = isMultiIndexContext(widget) && !isTargetedIndexEqualIndex(widget, indexName); var subIndexNotEqualMainIndex = isIndexWidget(widget) && !isIndexWidgetEqualIndex(widget, indexName); return targetedIndexNotEqualMainIndex || subIndexNotEqualMainIndex; }) // We have to sort the `Index` widgets first so the `index` parameter // is correctly set in the `reduce` function for the following widgets .sort(sortIndexWidgetsFirst).reduce(function (indices, widget) { var indexId = isMultiIndexContext(widget) ? widget.props.indexContextValue.targetedIndex : widget.props.indexId; var widgets = indices[indexId] || []; return _objectSpread({}, indices, _defineProperty({}, indexId, widgets.concat(widget))); }, {}); var derivedParameters = Object.keys(derivedIndices).map(function (indexId) { return { parameters: derivedIndices[indexId].reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters), indexId: indexId }; }); return { mainParameters: mainParameters, derivedParameters: derivedParameters }; } function search() { if (!skip) { var _getSearchParameters = getSearchParameters(), mainParameters = _getSearchParameters.mainParameters, derivedParameters = _getSearchParameters.derivedParameters; // We have to call `slice` because the method `detach` on the derived // helpers mutates the value `derivedHelpers`. The `forEach` loop does // not iterate on each value and we're not able to correctly clear the // previous derived helpers (memory leak + useless requests). helper.derivedHelpers.slice().forEach(function (derivedHelper) { // Since we detach the derived helpers on **every** new search they // won't receive intermediate results in case of a stalled search. // Only the last result is dispatched by the derived helper because // they are not detached yet: // // - a -> main helper receives results // - ap -> main helper receives results // - app -> main helper + derived helpers receive results // // The quick fix is to avoid to detatch them on search but only once they // received the results. But it means that in case of a stalled search // all the derived helpers not detached yet register a new search inside // the helper. The number grows fast in case of a bad network and it's // not deterministic. derivedHelper.detach(); }); derivedParameters.forEach(function (_ref2) { var indexId = _ref2.indexId, parameters = _ref2.parameters; var derivedHelper = helper.derive(function () { return parameters; }); derivedHelper.on('result', handleSearchSuccess({ indexId: indexId })).on('error', handleSearchError); }); helper.setState(mainParameters); helper.search(); } } function handleSearchSuccess(_ref3) { var indexId = _ref3.indexId; return function (event) { var state = store.getState(); var isDerivedHelpersEmpty = !helper.derivedHelpers.length; var results = state.results ? state.results : {}; // Switching from mono index to multi index and vice versa must reset the // results to an empty object, otherwise we keep reference of stalled and // unused results. results = !isDerivedHelpersEmpty && results.getFacetByName ? {} : results; if (!isDerivedHelpersEmpty) { results[indexId] = event.results; } else { results = event.results; } var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); stalledSearchTimer = null; nextIsSearchStalled = false; } var resultsFacetValues = currentState.resultsFacetValues, partialState = _objectWithoutProperties(currentState, ["resultsFacetValues"]); store.setState(_objectSpread({}, partialState, { results: results, isSearchStalled: nextIsSearchStalled, searching: false, error: null })); }; } function handleSearchError(_ref4) { var error = _ref4.error; var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); nextIsSearchStalled = false; } var resultsFacetValues = currentState.resultsFacetValues, partialState = _objectWithoutProperties(currentState, ["resultsFacetValues"]); store.setState(_objectSpread({}, partialState, { isSearchStalled: nextIsSearchStalled, error: error, searching: false })); } function handleNewSearch() { if (!stalledSearchTimer) { stalledSearchTimer = setTimeout(function () { var _store$getState = store.getState(), resultsFacetValues = _store$getState.resultsFacetValues, partialState = _objectWithoutProperties(_store$getState, ["resultsFacetValues"]); store.setState(_objectSpread({}, partialState, { isSearchStalled: true })); }, stalledSearchDelay); } } function hydrateSearchClient(client, results) { if (!results) { return; } if (!client._useCache || typeof client.addAlgoliaAgent !== 'function') { // This condition avoids hydrating a `searchClient` different from the // Algolia one. We also avoid to hydrate the client when the cache is // disabled. The implementation is brittle but we don't have a proper way // to detect the Algolia client at the moment. return; } if (Array.isArray(results)) { hydrateSearchClientWithMultiIndexRequest(client, results); return; } hydrateSearchClientWithSingleIndexRequest(client, results); } function hydrateSearchClientWithMultiIndexRequest(client, results) { // At the moment we don't have a proper API to hydrate the client cache from // the outside (it should come with the V4). The following code populates the // cache with a multi-index results. You can find more information about the // computation of the key inside the client (see link below). // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240 var key = "/1/indexes/*/queries_body_".concat(JSON.stringify({ requests: results.reduce(function (acc, result) { return acc.concat(result.rawResults.map(function (request) { return { indexName: request.index, params: request.params }; })); }, []) })); client.cache = _objectSpread({}, client.cache, _defineProperty({}, key, JSON.stringify({ results: results.reduce(function (acc, result) { return acc.concat(result.rawResults); }, []) }))); } function hydrateSearchClientWithSingleIndexRequest(client, results) { // At the moment we don't have a proper API to hydrate the client cache from // the outside (it should come with the V4). The following code populates the // cache with a single-index result. You can find more information about the // computation of the key inside the client (see link below). // https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240 var key = "/1/indexes/*/queries_body_".concat(JSON.stringify({ requests: results.rawResults.map(function (request) { return { indexName: request.index, params: request.params }; }) })); client.cache = _objectSpread({}, client.cache, _defineProperty({}, key, JSON.stringify({ results: results.rawResults }))); } function hydrateResultsState(results) { if (!results) { return null; } if (Array.isArray(results)) { return results.reduce(function (acc, result) { return _objectSpread({}, acc, _defineProperty({}, result._internalIndexId, new algoliasearchHelper_1.SearchResults(new algoliasearchHelper_1.SearchParameters(result.state), result.rawResults))); }, {}); } return new algoliasearchHelper_1.SearchResults(new algoliasearchHelper_1.SearchParameters(results.state), results.rawResults); } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_objectSpread({}, 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(_objectSpread({}, store.getState(), { widgets: nextSearchState, metadata: metadata, searching: true })); search(); } function onSearchForFacetValues(_ref5) { var facetName = _ref5.facetName, query = _ref5.query, _ref5$maxFacetHits = _ref5.maxFacetHits, maxFacetHits = _ref5$maxFacetHits === void 0 ? 10 : _ref5$maxFacetHits; // The values 1, 100 are the min / max values that the engine accepts. // see: https://www.algolia.com/doc/api-reference/api-parameters/maxFacetHits var maxFacetHitsWithinRange = Math.max(1, Math.min(maxFacetHits, 100)); store.setState(_objectSpread({}, store.getState(), { searchingForFacetValues: true })); helper.searchForFacetValues(facetName, query, maxFacetHitsWithinRange).then(function (content) { var _objectSpread6; store.setState(_objectSpread({}, store.getState(), { error: null, searchingForFacetValues: false, resultsFacetValues: _objectSpread({}, store.getState().resultsFacetValues, (_objectSpread6 = {}, _defineProperty(_objectSpread6, facetName, content.facetHits), _defineProperty(_objectSpread6, "query", query), _objectSpread6)) })); }, function (error) { store.setState(_objectSpread({}, store.getState(), { searchingForFacetValues: false, error: error })); }).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); // No need to trigger a new search here as the widgets will also update and trigger it if needed. } 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, getSearchParameters: getSearchParameters, onSearchForFacetValues: onSearchForFacetValues, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, updateClient: updateClient, updateIndex: updateIndex, clearCache: clearCache, skipSearch: skipSearch }; } function isControlled(props) { return Boolean(props.searchState); } /** * @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} 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} [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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox, Hits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); */ var InstantSearch = /*#__PURE__*/ function (_Component) { _inherits(InstantSearch, _Component); _createClass(InstantSearch, null, [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { var nextIsControlled = isControlled(nextProps); var previousSearchState = prevState.instantSearchManager.store.getState().widgets; var nextSearchState = nextProps.searchState; if (nextIsControlled && !fastDeepEqual(previousSearchState, nextSearchState)) { prevState.instantSearchManager.onExternalStateUpdate(nextProps.searchState); } return { isControlled: nextIsControlled, contextValue: _objectSpread({}, prevState.contextValue, { mainTargetedIndex: nextProps.indexName }) }; } }]); function InstantSearch(props) { var _this; _classCallCheck(this, InstantSearch); _this = _possibleConstructorReturn(this, _getPrototypeOf(InstantSearch).call(this, props)); _defineProperty(_assertThisInitialized(_this), "isUnmounting", false); var instantSearchManager = createInstantSearchManager({ indexName: _this.props.indexName, searchClient: _this.props.searchClient, initialState: _this.props.searchState || {}, resultsState: _this.props.resultsState, stalledSearchDelay: _this.props.stalledSearchDelay }); var contextValue = { store: instantSearchManager.store, widgetsManager: instantSearchManager.widgetsManager, mainTargetedIndex: _this.props.indexName, onInternalStateUpdate: _this.onWidgetsInternalStateUpdate.bind(_assertThisInitialized(_this)), createHrefForState: _this.createHrefForState.bind(_assertThisInitialized(_this)), onSearchForFacetValues: _this.onSearchForFacetValues.bind(_assertThisInitialized(_this)), onSearchStateChange: _this.onSearchStateChange.bind(_assertThisInitialized(_this)), onSearchParameters: _this.onSearchParameters.bind(_assertThisInitialized(_this)) }; _this.state = { isControlled: isControlled(_this.props), instantSearchManager: instantSearchManager, contextValue: contextValue }; return _this; } _createClass(InstantSearch, [{ key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var prevIsControlled = isControlled(prevProps); if (prevIsControlled && !this.state.isControlled) { throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled"); } if (!prevIsControlled && this.state.isControlled) { throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled"); } if (this.props.refresh !== prevProps.refresh && this.props.refresh) { this.state.instantSearchManager.clearCache(); } if (prevProps.indexName !== this.props.indexName) { this.state.instantSearchManager.updateIndex(this.props.indexName); } if (prevProps.searchClient !== this.props.searchClient) { this.state.instantSearchManager.updateClient(this.props.searchClient); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.isUnmounting = true; this.state.instantSearchManager.skipSearch(); } }, { key: "createHrefForState", value: function createHrefForState(searchState) { searchState = this.state.instantSearchManager.transitionState(searchState); return this.state.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: "onWidgetsInternalStateUpdate", value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.state.instantSearchManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.state.isControlled) { this.state.instantSearchManager.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.state.instantSearchManager.onSearchForFacetValues(searchState); } }, { key: "getKnownKeys", value: function getKnownKeys() { return this.state.instantSearchManager.getWidgetsIds(); } }, { key: "render", value: function render() { if (React.Children.count(this.props.children) === 0) { return null; } return React__default.createElement(InstantSearchProvider, { value: this.state.contextValue }, this.props.children); } }]); return InstantSearch; }(React.Component); _defineProperty(InstantSearch, "defaultProps", { stalledSearchDelay: 200, refresh: false }); _defineProperty(InstantSearch, "propTypes", { // @TODO: These props are currently constant. indexName: propTypes.string.isRequired, searchClient: propTypes.shape({ search: propTypes.func.isRequired, searchForFacetValues: propTypes.func, addAlgoliaAgent: propTypes.func, clearCache: propTypes.func }).isRequired, createURL: propTypes.func, refresh: propTypes.bool, searchState: propTypes.object, onSearchStateChange: propTypes.func, onSearchParameters: propTypes.func, resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]), children: propTypes.node, stalledSearchDelay: propTypes.number }); var getId$1 = function getId(props) { return props.attributes[0]; }; var namespace = 'hierarchicalMenu'; function _refine(props, searchState, nextRefinement, context) { var id = getId$1(props); var nextValue = _defineProperty({}, 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)); } } 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 = createConnectorWithContext({ 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 ".concat(propName, " supplied to ").concat(componentName, ". Expected an Array of Strings")); } return undefined; }, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var id = getId$1(props); var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); /** * 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 = createConnectorWithContext({ 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 _objectSpread({}, item, { id: meta.id, index: meta.index }); })); } } return res; }, []); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems, canRefine: transformedItems.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 getId$2 = function getId(props) { return props.attributes[0]; }; var namespace$1 = 'hierarchicalMenu'; function getCurrentRefinement(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$1, ".").concat(getId$2(props)), null); if (currentRefinement === '') { return null; } return currentRefinement; } function getValue(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; if (currentRefinement === null) { nextRefinement = path; } else { var tmpSearchParameters = new algoliasearchHelper_1.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$1(value, props, searchState, context) { return value.map(function (v) { return { label: v.name, value: getValue(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) ? _objectSpread({}, item, { items: truncate(item.items, limit) }) : item; }); }; function _refine$1(props, searchState, nextRefinement, context) { var id = getId$2(props); var nextValue = _defineProperty({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$1); } function _cleanUp(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$1, ".").concat(getId$2(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 path to use if the first level is not the root level. * @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 = createConnectorWithContext({ 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 ".concat(propName, " supplied to ").concat(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$2(props); var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: false }; } var itemsLimit = showMore ? showMoreLimit : limit; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue$1(value.data, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: truncate(transformedItems, itemsLimit), currentRefinement: getCurrentRefinement(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$1(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, 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, contextValue = props.contextValue; var id = getId$2(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(props, searchState, { ais: contextValue, multiIndexContext: props.indexContextValue }); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var rootAttribute = props.attributes[0]; var id = getId$2(props); var currentRefinement = getCurrentRefinement(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = !currentRefinement ? [] : [{ label: "".concat(rootAttribute, ": ").concat(currentRefinement), attribute: rootAttribute, value: function value(nextState) { return _refine$1(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: currentRefinement }]; return { id: id, index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: items }; } }); var highlight = function highlight(_ref) { var attribute = _ref.attribute, hit = _ref.hit, highlightProperty = _ref.highlightProperty, _ref$preTag = _ref.preTag, preTag = _ref$preTag === void 0 ? HIGHLIGHT_TAGS.highlightPreTag : _ref$preTag, _ref$postTag = _ref.postTag, postTag = _ref$postTag === void 0 ? 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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox, Hits, connectHighlight } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * 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 * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox defaultRefinement="pho" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var connectHighlight = createConnectorWithContext({ 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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Highlight, connectHits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * const CustomHits = connectHits(({ hits }) => ( * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attribute="name" hit={hit} /> * </p> * )} * </div> * )); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <CustomHits /> * </InstantSearch> * ); */ var connectHits = createConnectorWithContext({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (!results) { return { hits: [] }; } var hitsWithPositions = addAbsolutePositions(results.hits, results.hitsPerPage, results.page); var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID); return { hits: hitsWithPositionsAndQueryID }; }, /** * Hits needs to be considered as a widget to trigger a search, * even if no other widgets are used. * * To be considered as a widget you need either: * - getSearchParameters * - getMetadata * - transitionState * * See: createConnector.tsx */ getSearchParameters: function getSearchParameters(searchParameters) { return searchParameters; } }); function getId$3() { return 'hitsPerPage'; } function getCurrentRefinement$1(props, searchState, context) { var id = getId$3(); var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null); 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 = createConnectorWithContext({ 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$1(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = props.items.map(function (item) { return item.value === currentRefinement ? _objectSpread({}, item, { isRefined: true }) : _objectSpread({}, 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({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, getId$3()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement$1(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue })); }, getMetadata: function getMetadata() { return { id: getId$3() }; } }); function getId$4() { return 'page'; } function getCurrentRefinement$2(props, searchState, context) { var id = getId$4(); var page = 1; var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page); if (typeof currentRefinement === 'string') { return 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 = createConnectorWithContext({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var _this = this; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); this._allResults = this._allResults || []; this._prevState = this._prevState || {}; if (!results) { return { hits: [], hasPrevious: false, hasMore: false, refine: function refine() {}, refinePrevious: function refinePrevious() {}, refineNext: function refineNext() {} }; } var page = results.page, hits = results.hits, hitsPerPage = results.hitsPerPage, nbPages = results.nbPages, _results$_state = results._state; _results$_state = _results$_state === void 0 ? {} : _results$_state; var p = _results$_state.page, currentState = _objectWithoutProperties(_results$_state, ["page"]); var hitsWithPositions = addAbsolutePositions(hits, hitsPerPage, page); var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID); if (this._firstReceivedPage === undefined || !fastDeepEqual(currentState, this._prevState)) { this._allResults = _toConsumableArray(hitsWithPositionsAndQueryID); this._firstReceivedPage = page; this._lastReceivedPage = page; } else if (this._lastReceivedPage < page) { this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hitsWithPositionsAndQueryID)); this._lastReceivedPage = page; } else if (this._firstReceivedPage > page) { this._allResults = [].concat(_toConsumableArray(hitsWithPositionsAndQueryID), _toConsumableArray(this._allResults)); this._firstReceivedPage = page; } this._prevState = currentState; var hasPrevious = this._firstReceivedPage > 0; var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; var refinePrevious = function refinePrevious(event) { return _this.refine(event, _this._firstReceivedPage - 1); }; var refineNext = function refineNext(event) { return _this.refine(event, _this._lastReceivedPage + 1); }; return { hits: this._allResults, hasPrevious: hasPrevious, hasMore: hasMore, refinePrevious: refinePrevious, refineNext: refineNext }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQueryParameters({ page: getCurrentRefinement$2(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }) - 1 }); }, refine: function refine(props, searchState, event, index) { if (index === undefined && this._lastReceivedPage !== undefined) { index = this._lastReceivedPage + 1; } else if (index === undefined) { index = getCurrentRefinement$2(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } var id = getId$4(); var nextValue = _defineProperty({}, id, index + 1); var resetPage = false; return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, resetPage); } }); var namespace$2 = 'menu'; function getId$5(props) { return props.attribute; } function getCurrentRefinement$3(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$2, ".").concat(getId$5(props)), null); if (currentRefinement === '') { return null; } return currentRefinement; } function getValue$1(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$3(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$2(props, searchState, nextRefinement, context) { var id = getId$5(props); var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$2); } function _cleanUp$1(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$2, ".").concat(getId$5(props))); } var defaultSortBy = ['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 = createConnectorWithContext({ 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 attribute = props.attribute, searchable = props.searchable, indexContextValue = props.indexContextValue; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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 && indexContextValue) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isFromSearch: isFromSearch, searchable: searchable, canRefine: canRefine }; } var items; if (isFromSearch) { items = searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$1(v.value, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }); } else { items = results.getFacetValues(attribute, { sortBy: searchable ? undefined : defaultSortBy }).map(function (v) { return { label: v.name, value: getValue$1(v.name, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), count: v.count, isRefined: v.isRefined }; }); } var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit(props)), currentRefinement: getCurrentRefinement$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isFromSearch: isFromSearch, searchable: searchable, canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$2(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$1(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, 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$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId$5(props); var currentRefinement = getCurrentRefinement$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); return { id: id, index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: currentRefinement === null ? [] : [{ label: "".concat(props.attribute, ": ").concat(currentRefinement), attribute: props.attribute, value: function value(nextState) { return _refine$2(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: currentRefinement }] }; } }); function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(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"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function stringifyItem(item) { if (typeof item.start === 'undefined' && typeof item.end === 'undefined') { return ''; } return "".concat(item.start ? item.start : '', ":").concat(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$6(props) { return props.attribute; } function getCurrentRefinement$4(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, "".concat(namespace$3, ".").concat(getId$6(props)), ''); } 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$3(props, searchState, nextRefinement, context) { var nextValue = _defineProperty({}, getId$6(props), nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$3); } function _cleanUp$2(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$3, ".").concat(getId$6(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 = createConnectorWithContext({ 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$4(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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(attribute) ? results.getFacetStats(attribute) : null; var refinedItem = find(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: refinedItem === undefined, noRefinement: !stats, label: 'All' }); } var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems, currentRefinement: currentRefinement, canRefine: transformedItems.length > 0 && transformedItems.some(function (item) { return item.noRefinement === false; }) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$3(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$2(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; var _parseItem = parseItem(getCurrentRefinement$4(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue })), 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 id = getId$6(props); var value = getCurrentRefinement$4(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = []; var index = getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (value !== '') { var _find = find(props.items, function (item) { return stringifyItem(item) === value; }), label = _find.label; items.push({ label: "".concat(props.attribute, ": ").concat(label), attribute: props.attribute, currentRefinement: label, value: function value(nextState) { return _refine$3(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); } return { id: id, index: index, items: items }; } }); function getId$7() { return 'page'; } function getCurrentRefinement$5(props, searchState, context) { var id = getId$7(); var page = 1; var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page); if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; } function _refine$4(props, searchState, nextPage, context) { var id = getId$7(); var nextValue = _defineProperty({}, 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 = createConnectorWithContext({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement$5(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine$4(props, searchState, nextPage, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, getId$7()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement$5(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }) - 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 = createConnectorWithContext({ displayName: 'AlgoliaPoweredBy', getProvidedProps: function getProvidedProps() { var hostname = typeof window === 'undefined' ? '' : window.location.hostname; var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + "utm_content=".concat(hostname, "&") + 'utm_campaign=poweredby'; return { url: url }; } }); /** * 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$8(props) { return props.attribute; } var namespace$4 = 'range'; function getCurrentRange(boundaries, stats, precision) { var pow = Math.pow(10, precision); var min; if (typeof boundaries.min === 'number' && isFinite(boundaries.min)) { min = boundaries.min; } else if (typeof stats.min === 'number' && isFinite(stats.min)) { min = stats.min; } else { min = undefined; } var max; if (typeof boundaries.max === 'number' && isFinite(boundaries.max)) { max = boundaries.max; } else if (typeof stats.max === 'number' && 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$6(props, searchState, currentRange, context) { var _getCurrentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$4, ".").concat(getId$8(props)), {}), min = _getCurrentRefinement.min, max = _getCurrentRefinement.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); } var refinement = { 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; 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({}, 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$3(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$4, ".").concat(getId$8(props))); } var connectRange = createConnectorWithContext({ 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, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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 behavior 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$6(props, searchState, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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$5(props, searchState, nextRefinement, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attribute = props.attribute; var _getCurrentRefinement2 = getCurrentRefinement$6(props, searchState, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), min = _getCurrentRefinement2.min, max = _getCurrentRefinement2.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 _this$_currentRange = this._currentRange, minRange = _this$_currentRange.min, maxRange = _this$_currentRange.max; var _getCurrentRefinement3 = getCurrentRefinement$6(props, searchState, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), 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 ? "".concat(minValue, " <= ") : '', props.attribute, hasMax ? " <= ".concat(maxValue) : '']; items.push({ label: fragments.join(''), attribute: props.attribute, value: function value(nextState) { return _refine$5(props, nextState, {}, _this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: getCurrentRefinementWithRange({ min: minValue, max: maxValue }, { min: minRange, max: maxRange }) }); } return { id: getId$8(props), index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: items }; } }); var namespace$5 = 'refinementList'; function getId$9(props) { return props.attribute; } function getCurrentRefinement$7(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$5, ".").concat(getId$9(props)), []); if (typeof currentRefinement !== 'string') { return currentRefinement; } if (currentRefinement) { return [currentRefinement]; } return []; } function getValue$2(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$7(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$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({}, id, nextRefinement.length > 0 ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$5); } function _cleanUp$4(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$5, ".").concat(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 `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. * @providedPropType {boolean} canRefine - a boolean that says whether you can refine */ var sortBy$1 = ['isRefined', 'count:desc', 'name:asc']; var connectRefinementList = createConnectorWithContext({ 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 attribute = props.attribute, searchable = props.searchable, indexContextValue = props.indexContextValue; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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 && indexContextValue) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$7(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: canRefine, isFromSearch: isFromSearch, searchable: searchable }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$2(v.value, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), _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, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit$1(props)), currentRefinement: getCurrentRefinement$7(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isFromSearch: isFromSearch, searchable: searchable, canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$6(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit$1(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$4(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, operator = props.operator; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = "".concat(addKey, "Refinement"); searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props)) }); searchParameters = searchParameters[addKey](attribute); return getCurrentRefinement$7(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }).reduce(function (res, val) { return res[addRefinementKey](attribute, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId$9(props); var context = { ais: props.contextValue, multiIndexContext: props.indexContextValue }; return { id: id, index: getIndexId(context), items: getCurrentRefinement$7(props, searchState, context).length > 0 ? [{ attribute: props.attribute, label: "".concat(props.attribute, ": "), currentRefinement: getCurrentRefinement$7(props, searchState, context), value: function value(nextState) { return _refine$6(props, nextState, [], context); }, items: getCurrentRefinement$7(props, searchState, context).map(function (item) { return { label: "".concat(item), value: function value(nextState) { var nextSelectedItems = getCurrentRefinement$7(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 = createConnectorWithContext({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: propTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = getCurrentRefinementValue(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, id, null); if (!this._prevSearchState) { this._prevSearchState = {}; } // Get the subpart of the state that interest us if (hasMultipleIndices({ ais: props.contextValue, multiIndexContext: props.indexContextValue })) { searchState = searchState.indices ? searchState.indices[getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue })] : {}; } // 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 comparison 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(searchState, ['configure', id]); var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState); this._prevSearchState = cleanedSearchState; return { value: value, hasNotChanged: hasNotChanged }; } }); function getId$a() { return 'query'; } function getCurrentRefinement$8(props, searchState, context) { var id = getId$a(); var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, ''); if (currentRefinement) { return currentRefinement; } return ''; } function _refine$7(props, searchState, nextRefinement, context) { var id = getId$a(); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage); } function _cleanUp$5(props, searchState, context) { return cleanUpValue(searchState, context, getId$a()); } /** * connectSearchBox connector provides the logic to build a widget that will * let the user search for a query * @name connectSearchBox * @kind connector * @propType {string} [defaultRefinement] - Provide a default value for the query * @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 = createConnectorWithContext({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: propTypes.string }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { currentRefinement: getCurrentRefinement$8(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isSearchStalled: searchResults.isSearchStalled }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$7(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$5(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$8(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue })); }, getMetadata: function getMetadata(props, searchState) { var id = getId$a(); var currentRefinement = getCurrentRefinement$8(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); return { id: id, index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: currentRefinement === null ? [] : [{ label: "".concat(id, ": ").concat(currentRefinement), value: function value(nextState) { return _refine$7(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: currentRefinement }] }; } }); function getId$b() { return 'sortBy'; } function getCurrentRefinement$9(props, searchState, context) { var id = getId$b(); var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null); 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 = createConnectorWithContext({ 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$9(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = props.items.map(function (item) { return item.value === currentRefinement ? _objectSpread({}, item, { isRefined: true }) : _objectSpread({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId$b(); var nextValue = _defineProperty({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, getId$b()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement$9(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId$b() }; } }); /** * 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 = createConnectorWithContext({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); function getId$c(props) { return props.attribute; } var namespace$6 = 'toggle'; var falsyStrings = ['0', 'false', 'null', 'undefined']; function getCurrentRefinement$a(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$6, ".").concat(getId$c(props)), false); if (falsyStrings.indexOf(currentRefinement) !== -1) { return false; } return Boolean(currentRefinement); } function _refine$8(props, searchState, nextRefinement, context) { var id = getId$c(props); var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : false); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$6); } function _cleanUp$6(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$6, ".").concat(getId$c(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 {boolean} currentRefinement - `true` when the refinement is applied, `false` otherwise * @providedPropType {object} count - an object that contains the count for `checked` and `unchecked` state * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state */ var connectToggleRefinement = createConnectorWithContext({ displayName: 'AlgoliaToggle', propTypes: { label: propTypes.string.isRequired, attribute: propTypes.string.isRequired, value: propTypes.any.isRequired, filter: propTypes.func, defaultRefinement: propTypes.bool }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute, value = props.value; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var currentRefinement = getCurrentRefinement$a(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var allFacetValues = results && results.getFacetByName(attribute) ? results.getFacetValues(attribute) : null; var facetValue = // Use null to always be consistent with type of the value // count: number | null allFacetValues && allFacetValues.length ? find(allFacetValues, function (item) { return item.name === value.toString(); }) : null; var facetValueCount = facetValue && facetValue.count; var allFacetValuesCount = // Use null to always be consistent with type of the value // count: number | null allFacetValues && allFacetValues.length ? allFacetValues.reduce(function (acc, item) { return acc + item.count; }, 0) : null; var canRefine = currentRefinement ? allFacetValuesCount !== null && allFacetValuesCount > 0 : facetValueCount !== null && facetValueCount > 0; var count = { checked: allFacetValuesCount, unchecked: facetValueCount }; return { currentRefinement: currentRefinement, canRefine: canRefine, count: count }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$8(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$6(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, value = props.value, filter = props.filter; var checked = getCurrentRefinement$a(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var nextSearchParameters = searchParameters.addDisjunctiveFacet(attribute); if (checked) { nextSearchParameters = nextSearchParameters.addDisjunctiveFacetRefinement(attribute, value); if (filter) { nextSearchParameters = filter(nextSearchParameters); } } return nextSearchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId$c(props); var checked = getCurrentRefinement$a(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = []; var index = getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (checked) { items.push({ label: props.label, currentRefinement: checked, attribute: props.attribute, value: function value(nextState) { return _refine$8(props, nextState, false, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); } return { id: id, index: index, items: items }; } }); var classnames = createCommonjsModule(function (module) { /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 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 ( module.exports) { module.exports = classNames; } else { window.classNames = classNames; } }()); }); var createClassNames = function createClassNames(block) { var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'ais'; return function () { for (var _len = arguments.length, elements = new Array(_len), _key = 0; _key < _len; _key++) { elements[_key] = arguments[_key]; } var suitElements = elements.filter(function (element) { return element || element === ''; }).map(function (element) { var baseClassName = "".concat(prefix, "-").concat(block); return element ? "".concat(baseClassName, "-").concat(element) : baseClassName; }); return classnames(suitElements); }; }; var isSpecialClick = function isSpecialClick(event) { var isMiddleClick = event.button === 1; return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey); }; var capitalize = function capitalize(key) { return key.length === 0 ? '' : "".concat(key[0].toUpperCase()).concat(key.slice(1)); }; // taken from InstantSearch.js/utils function range(_ref) { var _ref$start = _ref.start, start = _ref$start === void 0 ? 0 : _ref$start, end = _ref.end, _ref$step = _ref.step, step = _ref$step === void 0 ? 1 : _ref$step; // We can't divide by 0 so we re-assign the step to 1 if it happens. var limitStep = step === 0 ? 1 : step; // In some cases the array to create has a decimal length. // We therefore need to round the value. // Example: // { start: 1, end: 5000, step: 500 } // => Array length = (5000 - 1) / 500 = 9.998 var arrayLength = Math.round((end - start) / limitStep); return _toConsumableArray(Array(arrayLength)).map(function (_, current) { return (start + current) * limitStep; }); } function find$2(array, comparator) { if (!Array.isArray(array)) { return undefined; } for (var i = 0; i < array.length; i++) { if (comparator(array[i])) { return array[i]; } } return undefined; } var cx = createClassNames('Panel'); var _createContext$1 = React.createContext(function setCanRefine() {}), PanelConsumer = _createContext$1.Consumer, PanelProvider = _createContext$1.Provider; var Panel = /*#__PURE__*/ function (_Component) { _inherits(Panel, _Component); function Panel() { var _getPrototypeOf2; var _this; _classCallCheck(this, Panel); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Panel)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "state", { canRefine: true }); _defineProperty(_assertThisInitialized(_this), "setCanRefine", function (nextCanRefine) { _this.setState({ canRefine: nextCanRefine }); }); return _this; } _createClass(Panel, [{ key: "render", value: function render() { var _this$props = this.props, children = _this$props.children, className = _this$props.className, header = _this$props.header, footer = _this$props.footer; var canRefine = this.state.canRefine; return React__default.createElement("div", { className: classnames(cx('', !canRefine && '-noRefinement'), className) }, header && React__default.createElement("div", { className: cx('header') }, header), React__default.createElement("div", { className: cx('body') }, React__default.createElement(PanelProvider, { value: this.setCanRefine }, children)), footer && React__default.createElement("div", { className: cx('footer') }, footer)); } }]); return Panel; }(React.Component); _defineProperty(Panel, "propTypes", { children: propTypes.node.isRequired, className: propTypes.string, header: propTypes.node, footer: propTypes.node }); _defineProperty(Panel, "defaultProps", { className: '', header: null, footer: null }); var PanelCallbackHandler = /*#__PURE__*/ function (_Component) { _inherits(PanelCallbackHandler, _Component); function PanelCallbackHandler() { _classCallCheck(this, PanelCallbackHandler); return _possibleConstructorReturn(this, _getPrototypeOf(PanelCallbackHandler).apply(this, arguments)); } _createClass(PanelCallbackHandler, [{ key: "componentDidMount", value: function componentDidMount() { this.props.setCanRefine(this.props.canRefine); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.canRefine !== this.props.canRefine) { this.props.setCanRefine(this.props.canRefine); } } }, { key: "render", value: function render() { return this.props.children; } }]); return PanelCallbackHandler; }(React.Component); _defineProperty(PanelCallbackHandler, "propTypes", { children: propTypes.node.isRequired, canRefine: propTypes.bool.isRequired, setCanRefine: propTypes.func.isRequired }); var PanelWrapper = function PanelWrapper(_ref) { var canRefine = _ref.canRefine, children = _ref.children; return React__default.createElement(PanelConsumer, null, function (setCanRefine) { return React__default.createElement(PanelCallbackHandler, { setCanRefine: setCanRefine, canRefine: canRefine }, children); }); }; var Link = /*#__PURE__*/ function (_Component) { _inherits(Link, _Component); function Link() { var _getPrototypeOf2; var _this; _classCallCheck(this, Link); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Link)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "onClick", function (e) { if (isSpecialClick(e)) { return; } _this.props.onClick(); e.preventDefault(); }); return _this; } _createClass(Link, [{ key: "render", value: function render() { return React__default.createElement("a", _extends({}, this.props, { onClick: this.onClick })); } }]); return Link; }(React.Component); _defineProperty(Link, "propTypes", { onClick: propTypes.func.isRequired }); var cx$1 = createClassNames('Breadcrumb'); var itemsPropType = propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired })); var Breadcrumb = /*#__PURE__*/ function (_Component) { _inherits(Breadcrumb, _Component); function Breadcrumb() { _classCallCheck(this, Breadcrumb); return _possibleConstructorReturn(this, _getPrototypeOf(Breadcrumb).apply(this, arguments)); } _createClass(Breadcrumb, [{ key: "render", value: function render() { var _this$props = this.props, canRefine = _this$props.canRefine, createURL = _this$props.createURL, items = _this$props.items, refine = _this$props.refine, rootURL = _this$props.rootURL, separator = _this$props.separator, translate = _this$props.translate, className = _this$props.className; var rootPath = canRefine ? React__default.createElement("li", { className: cx$1('item') }, React__default.createElement(Link, { className: cx$1('link'), onClick: function onClick() { return !rootURL ? refine() : null; }, href: rootURL ? rootURL : createURL() }, translate('rootLabel'))) : null; var breadcrumb = items.map(function (item, idx) { var isLast = idx === items.length - 1; return React__default.createElement("li", { className: cx$1('item', isLast && 'item--selected'), key: idx }, React__default.createElement("span", { className: cx$1('separator') }, separator), !isLast ? React__default.createElement(Link, { className: cx$1('link'), onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }, item.label) : item.label); }); return React__default.createElement("div", { className: classnames(cx$1('', !canRefine && '-noRefinement'), className) }, React__default.createElement("ul", { className: cx$1('list') }, rootPath, breadcrumb)); } }]); return Breadcrumb; }(React.Component); _defineProperty(Breadcrumb, "propTypes", { canRefine: propTypes.bool.isRequired, createURL: propTypes.func.isRequired, items: itemsPropType, refine: propTypes.func.isRequired, rootURL: propTypes.string, separator: propTypes.node, translate: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(Breadcrumb, "defaultProps", { rootURL: null, separator: ' > ', className: '' }); var Breadcrumb$1 = translatable({ rootLabel: 'Home' })(Breadcrumb); /** * A breadcrumb is a secondary navigation scheme that allows the user to see where the current page * is in relation to the website or web application’s hierarchy. * In terms of usability, using a breadcrumb reduces the number of actions a visitor needs to take in * order to get to a higher-level page. * * If you want to select a specific refinement for your Breadcrumb component, you will need to * use a [Virtual Hierarchical Menu](https://community.algolia.com/react-instantsearch/guide/Virtual_widgets.html) * and set its defaultRefinement that will be then used by the Breadcrumb. * * @name Breadcrumb * @kind widget * @requirements Breadcrumbs are used for websites with a large amount of content organised in a hierarchical manner. * The typical example is an e-commerce website which has a large variety of products grouped into logical categories * (with categories, subcategories which also have subcategories).To use this widget, your attributes must be formatted in a specific way. * * Keep in mind that breadcrumbs shouldn’t replace effective primary navigation menus: * it is only an alternative way to navigate around the website. * * If, for instance, you would like 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. * * @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 {node} [separator='>'] - Symbol used for separating hyperlinks * @propType {string} [rootURL=null] - The originating page (homepage) * @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-Breadcrumb - the root div of the widget * @themeKey ais-Breadcrumb--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-Breadcrumb-list - the list of all breadcrumb items * @themeKey ais-Breadcrumb-item - the breadcrumb navigation item * @themeKey ais-Breadcrumb-item--selected - the selected breadcrumb item * @themeKey ais-Breadcrumb-separator - the separator of each breadcrumb item * @themeKey ais-Breadcrumb-link - the clickable breadcrumb element * @translationKey rootLabel - The root's label. Accepts a string * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { Breadcrumb, InstantSearch, HierarchicalMenu } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Breadcrumb * attributes={[ * 'hierarchicalCategories.lvl0', * 'hierarchicalCategories.lvl1', * 'hierarchicalCategories.lvl2', * ]} * /> * <HierarchicalMenu * defaultRefinement="Cameras & Camcorders" * attributes={[ * 'hierarchicalCategories.lvl0', * 'hierarchicalCategories.lvl1', * 'hierarchicalCategories.lvl2', * ]} * /> * </InstantSearch> * ); */ var BreadcrumbWidget = function BreadcrumbWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(Breadcrumb$1, props)); }; var Breadcrumb$2 = connectBreadcrumb(BreadcrumbWidget); var cx$2 = createClassNames('ClearRefinements'); var ClearRefinements = /*#__PURE__*/ function (_Component) { _inherits(ClearRefinements, _Component); function ClearRefinements() { _classCallCheck(this, ClearRefinements); return _possibleConstructorReturn(this, _getPrototypeOf(ClearRefinements).apply(this, arguments)); } _createClass(ClearRefinements, [{ key: "render", value: function render() { var _this$props = this.props, items = _this$props.items, canRefine = _this$props.canRefine, refine = _this$props.refine, translate = _this$props.translate, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$2(''), className) }, React__default.createElement("button", { className: cx$2('button', !canRefine && 'button--disabled'), onClick: function onClick() { return refine(items); }, disabled: !canRefine }, translate('reset'))); } }]); return ClearRefinements; }(React.Component); _defineProperty(ClearRefinements, "propTypes", { items: propTypes.arrayOf(propTypes.object).isRequired, canRefine: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(ClearRefinements, "defaultProps", { className: '' }); var ClearRefinements$1 = translatable({ reset: 'Clear all filters' })(ClearRefinements); /** * The ClearRefinements widget displays a button that lets the user clean every refinement applied * to the search. * @name ClearRefinements * @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-ClearRefinements - the root div of the widget * @themeKey ais-ClearRefinements-button - the clickable button * @themeKey ais-ClearRefinements-button--disabled - the disabled clickable button * @translationKey reset - the clear all button value * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, ClearRefinements, RefinementList } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <ClearRefinements /> * <RefinementList * attribute="brand" * defaultRefinement={['Apple']} * /> * </InstantSearch> * ); */ var ClearRefinementsWidget = function ClearRefinementsWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(ClearRefinements$1, props)); }; var ClearRefinements$2 = connectCurrentRefinements(ClearRefinementsWidget); var cx$3 = createClassNames('CurrentRefinements'); var CurrentRefinements = function CurrentRefinements(_ref) { var items = _ref.items, canRefine = _ref.canRefine, refine = _ref.refine, translate = _ref.translate, className = _ref.className; return React__default.createElement("div", { className: classnames(cx$3('', !canRefine && '-noRefinement'), className) }, React__default.createElement("ul", { className: cx$3('list', !canRefine && 'list--noRefinement') }, items.map(function (item) { return React__default.createElement("li", { key: item.label, className: cx$3('item') }, React__default.createElement("span", { className: cx$3('label') }, item.label), item.items ? item.items.map(function (nest) { return React__default.createElement("span", { key: nest.label, className: cx$3('category') }, React__default.createElement("span", { className: cx$3('categoryLabel') }, nest.label), React__default.createElement("button", { className: cx$3('delete'), onClick: function onClick() { return refine(nest.value); } }, translate('clearFilter', nest))); }) : React__default.createElement("span", { className: cx$3('category') }, React__default.createElement("button", { className: cx$3('delete'), onClick: function onClick() { return refine(item.value); } }, translate('clearFilter', item)))); }))); }; var itemPropTypes = propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.func.isRequired, items: function items() { return itemPropTypes.apply(void 0, arguments); } })); CurrentRefinements.defaultProps = { className: '' }; var CurrentRefinements$1 = translatable({ clearFilter: '✕' })(CurrentRefinements); /** * 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 - the root div of the widget * @themeKey ais-CurrentRefinements--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-CurrentRefinements-list - the list of all refined items * @themeKey ais-CurrentRefinements-list--noRefinement - the list of all refined items when there is no refinement * @themeKey ais-CurrentRefinements-item - the refined list item * @themeKey ais-CurrentRefinements-button - the button of each refined list item * @themeKey ais-CurrentRefinements-label - the refined list label * @themeKey ais-CurrentRefinements-category - the category of each item * @themeKey ais-CurrentRefinements-categoryLabel - the label of each catgory * @themeKey ais-CurrentRefinements-delete - the delete button of each label * @translationKey clearFilter - the remove filter button label * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, CurrentRefinements, RefinementList } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <CurrentRefinements /> * <RefinementList * attribute="brand" * defaultRefinement={['Colors']} * /> * </InstantSearch> * ); */ var CurrentRefinementsWidget = function CurrentRefinementsWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(CurrentRefinements$1, props)); }; var CurrentRefinements$2 = connectCurrentRefinements(CurrentRefinementsWidget); var cx$4 = createClassNames('SearchBox'); var defaultLoadingIndicator = React__default.createElement("svg", { width: "18", height: "18", viewBox: "0 0 38 38", xmlns: "http://www.w3.org/2000/svg", stroke: "#444", className: cx$4('loadingIcon') }, React__default.createElement("g", { fill: "none", fillRule: "evenodd" }, React__default.createElement("g", { transform: "translate(1 1)", strokeWidth: "2" }, React__default.createElement("circle", { strokeOpacity: ".5", cx: "18", cy: "18", r: "18" }), React__default.createElement("path", { d: "M36 18c0-9.94-8.06-18-18-18" }, React__default.createElement("animateTransform", { attributeName: "transform", type: "rotate", from: "0 18 18", to: "360 18 18", dur: "1s", repeatCount: "indefinite" }))))); var defaultReset = React__default.createElement("svg", { className: cx$4('resetIcon'), xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", width: "10", height: "10" }, React__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" })); var defaultSubmit = React__default.createElement("svg", { className: cx$4('submitIcon'), xmlns: "http://www.w3.org/2000/svg", width: "10", height: "10", viewBox: "0 0 40 40" }, React__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" })); var SearchBox = /*#__PURE__*/ function (_Component) { _inherits(SearchBox, _Component); function SearchBox(props) { var _this; _classCallCheck(this, SearchBox); _this = _possibleConstructorReturn(this, _getPrototypeOf(SearchBox).call(this)); _defineProperty(_assertThisInitialized(_this), "getQuery", function () { return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query; }); _defineProperty(_assertThisInitialized(_this), "onInputMount", function (input) { _this.input = input; if (_this.props.__inputRef) { _this.props.__inputRef(input); } }); _defineProperty(_assertThisInitialized(_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(); }); _defineProperty(_assertThisInitialized(_this), "onSubmit", function (e) { e.preventDefault(); e.stopPropagation(); _this.input.blur(); var _this$props = _this.props, refine = _this$props.refine, searchAsYouType = _this$props.searchAsYouType; if (!searchAsYouType) { refine(_this.getQuery()); } return false; }); _defineProperty(_assertThisInitialized(_this), "onChange", function (event) { var _this$props2 = _this.props, searchAsYouType = _this$props2.searchAsYouType, refine = _this$props2.refine, onChange = _this$props2.onChange; var value = event.target.value; if (searchAsYouType) { refine(value); } else { _this.setState({ query: value }); } if (onChange) { onChange(event); } }); _defineProperty(_assertThisInitialized(_this), "onReset", function (event) { var _this$props3 = _this.props, searchAsYouType = _this$props3.searchAsYouType, refine = _this$props3.refine, onReset = _this$props3.onReset; refine(''); _this.input.focus(); if (!searchAsYouType) { _this.setState({ query: '' }); } if (onReset) { onReset(event); } }); _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: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (!this.props.searchAsYouType && prevProps.currentRefinement !== this.props.currentRefinement) { this.setState({ query: this.props.currentRefinement }); } } }, { key: "render", value: function render() { var _this2 = this; var _this$props4 = this.props, className = _this$props4.className, translate = _this$props4.translate, autoFocus = _this$props4.autoFocus, loadingIndicator = _this$props4.loadingIndicator, submit = _this$props4.submit, reset = _this$props4.reset; var query = this.getQuery(); var searchInputEvents = Object.keys(this.props).reduce(function (props, prop) { if (['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) === -1 && prop.indexOf('on') === 0) { return _objectSpread({}, props, _defineProperty({}, prop, _this2.props[prop])); } return props; }, {}); var isSearchStalled = this.props.showLoadingIndicator && this.props.isSearchStalled; /* eslint-disable max-len */ return React__default.createElement("div", { className: classnames(cx$4(''), className) }, React__default.createElement("form", { noValidate: true, onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit, onReset: this.onReset, className: cx$4('form', isSearchStalled && 'form--stalledSearch'), action: "", role: "search" }, React__default.createElement("input", _extends({ ref: this.onInputMount, type: "search", placeholder: translate('placeholder'), autoFocus: autoFocus, autoComplete: "off", autoCorrect: "off", autoCapitalize: "off", spellCheck: "false", required: true, maxLength: "512", value: query, onChange: this.onChange }, searchInputEvents, { className: cx$4('input') })), React__default.createElement("button", { type: "submit", title: translate('submitTitle'), className: cx$4('submit') }, submit), React__default.createElement("button", { type: "reset", title: translate('resetTitle'), className: cx$4('reset'), hidden: !query || isSearchStalled }, reset), this.props.showLoadingIndicator && React__default.createElement("span", { hidden: !isSearchStalled, className: cx$4('loadingIndicator') }, loadingIndicator))); /* eslint-enable */ } }]); return SearchBox; }(React.Component); _defineProperty(SearchBox, "propTypes", { currentRefinement: propTypes.string, className: propTypes.string, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, loadingIndicator: propTypes.node, reset: propTypes.node, submit: propTypes.node, focusShortcuts: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), autoFocus: propTypes.bool, searchAsYouType: propTypes.bool, onSubmit: propTypes.func, onReset: propTypes.func, onChange: propTypes.func, isSearchStalled: propTypes.bool, showLoadingIndicator: propTypes.bool, // For testing purposes __inputRef: propTypes.func }); _defineProperty(SearchBox, "defaultProps", { currentRefinement: '', className: '', focusShortcuts: ['s', '/'], autoFocus: false, searchAsYouType: true, showLoadingIndicator: false, isSearchStalled: false, loadingIndicator: defaultLoadingIndicator, reset: defaultReset, submit: defaultSubmit }); var SearchBox$1 = translatable({ resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(SearchBox); var itemsPropType$1 = propTypes.arrayOf(propTypes.shape({ value: propTypes.any, label: propTypes.node.isRequired, items: function items() { return itemsPropType$1.apply(void 0, arguments); } })); var List = /*#__PURE__*/ function (_Component) { _inherits(List, _Component); function List() { var _this; _classCallCheck(this, List); _this = _possibleConstructorReturn(this, _getPrototypeOf(List).call(this)); _defineProperty(_assertThisInitialized(_this), "onShowMoreClick", function () { _this.setState(function (state) { return { extended: !state.extended }; }); }); _defineProperty(_assertThisInitialized(_this), "getLimit", function () { var _this$props = _this.props, limit = _this$props.limit, showMoreLimit = _this$props.showMoreLimit; var extended = _this.state.extended; return extended ? showMoreLimit : limit; }); _defineProperty(_assertThisInitialized(_this), "resetQuery", function () { _this.setState({ query: '' }); }); _defineProperty(_assertThisInitialized(_this), "renderItem", function (item, resetQuery) { var itemHasChildren = item.items && Boolean(item.items.length); return React__default.createElement("li", { key: item.key || item.label, className: _this.props.cx('item', item.isRefined && 'item--selected', item.noRefinement && 'item--noRefinement', itemHasChildren && 'item--parent') }, _this.props.renderItem(item, resetQuery), itemHasChildren && React__default.createElement("ul", { className: _this.props.cx('list', 'list--child') }, item.items.slice(0, _this.getLimit()).map(function (child) { return _this.renderItem(child, item); }))); }); _this.state = { extended: false, query: '' }; return _this; } _createClass(List, [{ key: "renderShowMore", value: function renderShowMore() { var _this$props2 = this.props, showMore = _this$props2.showMore, translate = _this$props2.translate, cx = _this$props2.cx; var extended = this.state.extended; var disabled = this.props.limit >= this.props.items.length; if (!showMore) { return null; } return React__default.createElement("button", { disabled: disabled, className: cx('showMore', disabled && 'showMore--disabled'), onClick: this.onShowMoreClick }, translate('showMore', extended)); } }, { key: "renderSearchBox", value: function renderSearchBox() { var _this2 = this; var _this$props3 = this.props, cx = _this$props3.cx, searchForItems = _this$props3.searchForItems, isFromSearch = _this$props3.isFromSearch, translate = _this$props3.translate, items = _this$props3.items, selectItem = _this$props3.selectItem; var noResults = items.length === 0 && this.state.query !== '' ? React__default.createElement("div", { className: cx('noResults') }, translate('noResults')) : null; return React__default.createElement("div", { className: cx('searchBox') }, React__default.createElement(SearchBox$1, { 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 _this$props4 = this.props, cx = _this$props4.cx, items = _this$props4.items, className = _this$props4.className, searchable = _this$props4.searchable, canRefine = _this$props4.canRefine; var searchBox = searchable ? this.renderSearchBox() : null; var rootClassName = classnames(cx('', !canRefine && '-noRefinement'), className); if (items.length === 0) { return React__default.createElement("div", { className: rootClassName }, 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. return React__default.createElement("div", { className: rootClassName }, searchBox, React__default.createElement("ul", { className: cx('list', !canRefine && 'list--noRefinement') }, items.slice(0, this.getLimit()).map(function (item) { return _this3.renderItem(item, _this3.resetQuery); })), this.renderShowMore()); } }]); return List; }(React.Component); _defineProperty(List, "propTypes", { cx: propTypes.func.isRequired, // Only required with showMore. translate: propTypes.func, items: itemsPropType$1, renderItem: propTypes.func.isRequired, selectItem: propTypes.func, className: propTypes.string, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, show: propTypes.func, searchForItems: propTypes.func, searchable: propTypes.bool, isFromSearch: propTypes.bool, canRefine: propTypes.bool }); _defineProperty(List, "defaultProps", { className: '', isFromSearch: false }); var cx$5 = createClassNames('HierarchicalMenu'); var itemsPropType$2 = propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string, count: propTypes.number.isRequired, items: function items() { return itemsPropType$2.apply(void 0, arguments); } })); var HierarchicalMenu = /*#__PURE__*/ function (_Component) { _inherits(HierarchicalMenu, _Component); function HierarchicalMenu() { var _getPrototypeOf2; var _this; _classCallCheck(this, HierarchicalMenu); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(HierarchicalMenu)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "renderItem", function (item) { var _this$props = _this.props, createURL = _this$props.createURL, refine = _this$props.refine; return React__default.createElement(Link, { className: cx$5('link'), onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }, React__default.createElement("span", { className: cx$5('label') }, item.label), ' ', React__default.createElement("span", { className: cx$5('count') }, item.count)); }); return _this; } _createClass(HierarchicalMenu, [{ key: "render", value: function render() { var _this$props2 = this.props, translate = _this$props2.translate, items = _this$props2.items, showMore = _this$props2.showMore, limit = _this$props2.limit, showMoreLimit = _this$props2.showMoreLimit, canRefine = _this$props2.canRefine, className = _this$props2.className; return React__default.createElement(List, { renderItem: this.renderItem, cx: cx$5, translate: translate, items: items, showMore: showMore, limit: limit, showMoreLimit: showMoreLimit, canRefine: canRefine, className: className }); } }]); return HierarchicalMenu; }(React.Component); _defineProperty(HierarchicalMenu, "propTypes", { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired, items: itemsPropType$2, showMore: propTypes.bool, className: propTypes.string, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func }); _defineProperty(HierarchicalMenu, "defaultProps", { className: '' }); var HierarchicalMenu$1 = translatable({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; } })(HierarchicalMenu); /** * 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 * [{ * "objectID": "321432", * "name": "lemon", * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * }, * { * "objectID": "8976987", * "name": "orange", * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * }] * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "objectID": "321432", * "name": "lemon", * "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 {array.<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 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 path to use if the first level is not the root level. * @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 - the root div of the widget * @themeKey ais-HierarchicalMenu-noRefinement - the root div of the widget when there is no refinement * @themeKey ais-HierarchicalMenu-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @themeKey ais-HierarchicalMenu-list - the list of menu items * @themeKey ais-HierarchicalMenu-list--child - the child list of menu items * @themeKey ais-HierarchicalMenu-item - the menu list item * @themeKey ais-HierarchicalMenu-item--selected - the selected menu list item * @themeKey ais-HierarchicalMenu-item--parent - the menu list item containing children * @themeKey ais-HierarchicalMenu-link - the clickable menu element * @themeKey ais-HierarchicalMenu-label - the label of each item * @themeKey ais-HierarchicalMenu-count - the count of values for each item * @themeKey ais-HierarchicalMenu-showMore - the button used to display more categories * @themeKey ais-HierarchicalMenu-showMore--disabled - the disabled button used to display more categories * @translationKey showMore - The label of the show more button. Accepts one parameter, a boolean that is true if the values are expanded * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, HierarchicalMenu } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <HierarchicalMenu * attributes={[ * 'hierarchicalCategories.lvl0', * 'hierarchicalCategories.lvl1', * 'hierarchicalCategories.lvl2', * ]} * /> * </InstantSearch> * ); */ var HierarchicalMenuWidget = function HierarchicalMenuWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(HierarchicalMenu$1, props)); }; var HierarchicalMenu$2 = connectHierarchicalMenu(HierarchicalMenuWidget); var Highlight = function Highlight(_ref) { var cx = _ref.cx, value = _ref.value, highlightedTagName = _ref.highlightedTagName, isHighlighted = _ref.isHighlighted, nonHighlightedTagName = _ref.nonHighlightedTagName; var TagName = isHighlighted ? highlightedTagName : nonHighlightedTagName; var className = isHighlighted ? 'highlighted' : 'nonHighlighted'; return React__default.createElement(TagName, { className: cx(className) }, value); }; var Highlighter = function Highlighter(_ref2) { var cx = _ref2.cx, hit = _ref2.hit, attribute = _ref2.attribute, highlight = _ref2.highlight, highlightProperty = _ref2.highlightProperty, tagName = _ref2.tagName, nonHighlightedTagName = _ref2.nonHighlightedTagName, separator = _ref2.separator, className = _ref2.className; var parsedHighlightedValue = highlight({ hit: hit, attribute: attribute, highlightProperty: highlightProperty }); return React__default.createElement("span", { className: classnames(cx(''), className) }, parsedHighlightedValue.map(function (item, i) { if (Array.isArray(item)) { var isLast = i === parsedHighlightedValue.length - 1; return React__default.createElement("span", { key: i }, item.map(function (element, index) { return React__default.createElement(Highlight, { cx: cx, key: index, value: element.value, highlightedTagName: tagName, nonHighlightedTagName: nonHighlightedTagName, isHighlighted: element.isHighlighted }); }), !isLast && React__default.createElement("span", { className: cx('separator') }, separator)); } return React__default.createElement(Highlight, { cx: cx, key: i, value: item.value, highlightedTagName: tagName, nonHighlightedTagName: nonHighlightedTagName, isHighlighted: item.isHighlighted }); })); }; Highlighter.defaultProps = { tagName: 'em', nonHighlightedTagName: 'span', className: '', separator: ', ' }; var cx$6 = createClassNames('Highlight'); var Highlight$1 = function Highlight(props) { return React__default.createElement(Highlighter, _extends({}, props, { highlightProperty: "_highlightResult", cx: cx$6 })); }; /** * Renders any attribute from a 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} attribute - location of the highlighted attribute in the hit (the corresponding element can be either a string or an array of strings) * @propType {object} hit - hit object containing the highlighted attribute * @propType {string} [tagName='em'] - tag to be used for highlighted parts of the hit * @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted * @propType {node} [separator=',<space>'] - symbol used to separate the elements of the array in case the attribute points to an array of strings. * @themeKey ais-Highlight - root of the component * @themeKey ais-Highlight-highlighted - part of the text which is highlighted * @themeKey ais-Highlight-nonHighlighted - part of the text that is not highlighted * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox, Hits, Highlight } from 'react-instantsearch-dom'; * * const Hit = ({ hit }) => ( * <div> * <Highlight attribute="name" hit={hit} /> * </div> * ); * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox defaultRefinement="Pho" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var Highlight$2 = connectHighlight(Highlight$1); var cx$7 = createClassNames('Hits'); var DefaultHitComponent = function DefaultHitComponent(props) { return React__default.createElement("div", { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px', wordBreak: 'break-all' } }, JSON.stringify(props).slice(0, 100), "..."); }; var Hits = function Hits(_ref) { var hits = _ref.hits, _ref$className = _ref.className, className = _ref$className === void 0 ? '' : _ref$className, _ref$hitComponent = _ref.hitComponent, HitComponent = _ref$hitComponent === void 0 ? DefaultHitComponent : _ref$hitComponent; return React__default.createElement("div", { className: classnames(cx$7(''), className) }, React__default.createElement("ul", { className: cx$7('list') }, hits.map(function (hit) { return React__default.createElement("li", { className: cx$7('item'), key: hit.objectID }, React__default.createElement(HitComponent, { hit: hit })); }))); }; var HitPropTypes = propTypes.shape({ objectID: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired }); /** * 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 - the root div of the widget * @themeKey ais-Hits-list - the list of results * @themeKey ais-Hits-item - the hit list item * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Hits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Hits /> * </InstantSearch> * ); */ var Hits$1 = connectHits(Hits); var Select = /*#__PURE__*/ function (_Component) { _inherits(Select, _Component); function Select() { var _getPrototypeOf2; var _this; _classCallCheck(this, Select); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Select)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "onChange", function (e) { _this.props.onSelect(e.target.value); }); return _this; } _createClass(Select, [{ key: "render", value: function render() { var _this$props = this.props, cx = _this$props.cx, items = _this$props.items, selectedItem = _this$props.selectedItem; return React__default.createElement("select", { className: cx('select'), value: selectedItem, onChange: this.onChange }, items.map(function (item) { return React__default.createElement("option", { className: cx('option'), key: item.key === undefined ? item.value : item.key, disabled: item.disabled, value: item.value }, item.label === undefined ? item.value : item.label); })); } }]); return Select; }(React.Component); _defineProperty(Select, "propTypes", { cx: propTypes.func.isRequired, onSelect: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ value: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired, key: propTypes.oneOfType([propTypes.string, propTypes.number]), label: propTypes.string, disabled: propTypes.bool })).isRequired, selectedItem: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired }); var cx$8 = createClassNames('HitsPerPage'); var HitsPerPage = /*#__PURE__*/ function (_Component) { _inherits(HitsPerPage, _Component); function HitsPerPage() { _classCallCheck(this, HitsPerPage); return _possibleConstructorReturn(this, _getPrototypeOf(HitsPerPage).apply(this, arguments)); } _createClass(HitsPerPage, [{ key: "render", value: function render() { var _this$props = this.props, items = _this$props.items, currentRefinement = _this$props.currentRefinement, refine = _this$props.refine, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$8(''), className) }, React__default.createElement(Select, { onSelect: refine, selectedItem: currentRefinement, items: items, cx: cx$8 })); } }]); return HitsPerPage; }(React.Component); _defineProperty(HitsPerPage, "propTypes", { items: propTypes.arrayOf(propTypes.shape({ value: propTypes.number.isRequired, label: propTypes.string })).isRequired, currentRefinement: propTypes.number.isRequired, refine: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(HitsPerPage, "defaultProps", { className: '' }); /** * 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 - the root div of the widget * @themeKey ais-HitsPerPage-select - the select * @themeKey ais-HitsPerPage-option - the select option * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, HitsPerPage, Hits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <HitsPerPage * defaultRefinement={5} * items={[ * { value: 5, label: 'Show 5 hits' }, * { value: 10, label: 'Show 10 hits' }, * ]} * /> * <Hits /> * </InstantSearch> * ); */ var HitsPerPage$1 = connectHitsPerPage(HitsPerPage); var cx$9 = createClassNames('InfiniteHits'); var InfiniteHits = /*#__PURE__*/ function (_Component) { _inherits(InfiniteHits, _Component); function InfiniteHits() { _classCallCheck(this, InfiniteHits); return _possibleConstructorReturn(this, _getPrototypeOf(InfiniteHits).apply(this, arguments)); } _createClass(InfiniteHits, [{ key: "render", value: function render() { var _this$props = this.props, HitComponent = _this$props.hitComponent, hits = _this$props.hits, showPrevious = _this$props.showPrevious, hasPrevious = _this$props.hasPrevious, hasMore = _this$props.hasMore, refinePrevious = _this$props.refinePrevious, refineNext = _this$props.refineNext, translate = _this$props.translate, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$9(''), className) }, showPrevious && React__default.createElement("button", { className: cx$9('loadPrevious', !hasPrevious && 'loadPrevious--disabled'), onClick: function onClick() { return refinePrevious(); }, disabled: !hasPrevious }, translate('loadPrevious')), React__default.createElement("ul", { className: cx$9('list') }, hits.map(function (hit) { return React__default.createElement("li", { key: hit.objectID, className: cx$9('item') }, React__default.createElement(HitComponent, { hit: hit })); })), React__default.createElement("button", { className: cx$9('loadMore', !hasMore && 'loadMore--disabled'), onClick: function onClick() { return refineNext(); }, disabled: !hasMore }, translate('loadMore'))); } }]); return InfiniteHits; }(React.Component); InfiniteHits.defaultProps = { className: '', showPrevious: false, hitComponent: function hitComponent(hit) { return React__default.createElement("div", { style: { borderBottom: '1px solid #bbb', paddingBottom: '5px', marginBottom: '5px', wordBreak: 'break-all' } }, JSON.stringify(hit).slice(0, 100), "..."); } }; var InfiniteHits$1 = translatable({ loadPrevious: 'Load previous', loadMore: 'Load more' })(InfiniteHits); /** * 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 ais-InfiniteHits - the root div of the widget * @themeKey ais-InfiniteHits-list - the list of hits * @themeKey ais-InfiniteHits-item - the hit list item * @themeKey ais-InfiniteHits-loadMore - the button used to display more results * @themeKey ais-InfiniteHits-loadMore--disabled - the disabled button used to display more results * @translationKey loadMore - the label of load more button * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, InfiniteHits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <InfiniteHits /> * </InstantSearch> * ); */ var InfiniteHits$2 = connectInfiniteHits(InfiniteHits$1); var cx$a = createClassNames('Menu'); var Menu = /*#__PURE__*/ function (_Component) { _inherits(Menu, _Component); function Menu() { var _getPrototypeOf2; var _this; _classCallCheck(this, Menu); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Menu)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "renderItem", function (item, resetQuery) { var createURL = _this.props.createURL; var label = _this.props.isFromSearch ? React__default.createElement(Highlight$2, { attribute: "label", hit: item }) : item.label; return React__default.createElement(Link, { className: cx$a('link'), onClick: function onClick() { return _this.selectItem(item, resetQuery); }, href: createURL(item.value) }, React__default.createElement("span", { className: cx$a('label') }, label), ' ', React__default.createElement("span", { className: cx$a('count') }, item.count)); }); _defineProperty(_assertThisInitialized(_this), "selectItem", function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }); return _this; } _createClass(Menu, [{ key: "render", value: function render() { var _this$props = this.props, translate = _this$props.translate, items = _this$props.items, showMore = _this$props.showMore, limit = _this$props.limit, showMoreLimit = _this$props.showMoreLimit, isFromSearch = _this$props.isFromSearch, searchForItems = _this$props.searchForItems, searchable = _this$props.searchable, canRefine = _this$props.canRefine, className = _this$props.className; return React__default.createElement(List, { renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$a, translate: translate, items: items, showMore: showMore, limit: limit, showMoreLimit: showMoreLimit, isFromSearch: isFromSearch, searchForItems: searchForItems, searchable: searchable, canRefine: canRefine, className: className }); } }]); return Menu; }(React.Component); _defineProperty(Menu, "propTypes", { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, searchForItems: propTypes.func.isRequired, searchable: propTypes.bool, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired, count: propTypes.number.isRequired, isRefined: propTypes.bool.isRequired })), isFromSearch: propTypes.bool.isRequired, canRefine: propTypes.bool.isRequired, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func, className: propTypes.string }); _defineProperty(Menu, "defaultProps", { className: '' }); var Menu$1 = translatable({ 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); /** * 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 `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. * * If you are using the `searchable` prop, you'll also need to make the attribute searchable using * the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values). * @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 {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} [searchable=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/). * @themeKey ais-Menu - the root div of the widget * @themeKey ais-Menu-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @themeKey ais-Menu-list - the list of all menu items * @themeKey ais-Menu-item - the menu list item * @themeKey ais-Menu-item--selected - the selected menu list item * @themeKey ais-Menu-link - the clickable menu element * @themeKey ais-Menu-label - the label of each item * @themeKey ais-Menu-count - the count of values for each item * @themeKey ais-Menu-noResults - the div displayed when there are no results * @themeKey ais-Menu-showMore - the button used to display more categories * @themeKey ais-Menu-showMore--disabled - the disabled button used to display more categories * @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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Menu } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Menu attribute="categories" /> * </InstantSearch> * ); */ var MenuWidget = function MenuWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(Menu$1, props)); }; var Menu$2 = connectMenu(MenuWidget); var cx$b = createClassNames('MenuSelect'); var MenuSelect = /*#__PURE__*/ function (_Component) { _inherits(MenuSelect, _Component); function MenuSelect() { var _getPrototypeOf2; var _this; _classCallCheck(this, MenuSelect); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(MenuSelect)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "handleSelectChange", function (_ref) { var value = _ref.target.value; _this.props.refine(value === 'ais__see__all__option' ? '' : value); }); return _this; } _createClass(MenuSelect, [{ key: "render", value: function render() { var _this$props = this.props, items = _this$props.items, canRefine = _this$props.canRefine, translate = _this$props.translate, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$b('', !canRefine && '-noRefinement'), className) }, React__default.createElement("select", { value: this.selectedValue, onChange: this.handleSelectChange, className: cx$b('select') }, React__default.createElement("option", { value: "ais__see__all__option", className: cx$b('option') }, translate('seeAllOption')), items.map(function (item) { return React__default.createElement("option", { key: item.value, value: item.value, className: cx$b('option') }, item.label, " (", item.count, ")"); }))); } }, { key: "selectedValue", get: function get() { var _ref2 = find$2(this.props.items, function (item) { return item.isRefined === true; }) || { value: 'ais__see__all__option' }, value = _ref2.value; return value; } }]); return MenuSelect; }(React.Component); _defineProperty(MenuSelect, "propTypes", { items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.string.isRequired, count: propTypes.oneOfType([propTypes.number.isRequired, propTypes.string.isRequired]), isRefined: propTypes.bool.isRequired })).isRequired, canRefine: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(MenuSelect, "defaultProps", { className: '' }); var MenuSelect$1 = translatable({ seeAllOption: 'See all' })(MenuSelect); /** * The MenuSelect component displays a select that lets the user choose a single value for a specific attribute. * @name MenuSelect * @kind widget * @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 {string} [defaultRefinement] - the value of the item selected by default * @propType {number} [limit=10] - the minimum number of diplayed items * @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-MenuSelect - the root div of the widget * @themeKey ais-MenuSelect-noRefinement - the root div of the widget when there is no refinement * @themeKey ais-MenuSelect-select - the `<select>` * @themeKey ais-MenuSelect-option - the select `<option>` * @translationkey seeAllOption - The label of the option to select to remove the refinement * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, MenuSelect } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <MenuSelect attribute="categories" /> * </InstantSearch> * ); */ var MenuSelectWidget = function MenuSelectWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(MenuSelect$1, props)); }; var MenuSelect$2 = connectMenu(MenuSelectWidget); var cx$c = createClassNames('NumericMenu'); var NumericMenu = /*#__PURE__*/ function (_Component) { _inherits(NumericMenu, _Component); function NumericMenu() { var _getPrototypeOf2; var _this; _classCallCheck(this, NumericMenu); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(NumericMenu)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "renderItem", function (item) { var _this$props = _this.props, refine = _this$props.refine, translate = _this$props.translate; return React__default.createElement("label", { className: cx$c('label') }, React__default.createElement("input", { className: cx$c('radio'), type: "radio", checked: item.isRefined, disabled: item.noRefinement, onChange: function onChange() { return refine(item.value); } }), React__default.createElement("span", { className: cx$c('labelText') }, item.value === '' ? translate('all') : item.label)); }); return _this; } _createClass(NumericMenu, [{ key: "render", value: function render() { var _this$props2 = this.props, items = _this$props2.items, canRefine = _this$props2.canRefine, className = _this$props2.className; return React__default.createElement(List, { renderItem: this.renderItem, showMore: false, canRefine: canRefine, cx: cx$c, items: items.map(function (item) { return _objectSpread({}, item, { key: item.value }); }), className: className }); } }]); return NumericMenu; }(React.Component); _defineProperty(NumericMenu, "propTypes", { items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node.isRequired, value: propTypes.string.isRequired, isRefined: propTypes.bool.isRequired, noRefinement: propTypes.bool.isRequired })).isRequired, canRefine: propTypes.bool.isRequired, refine: propTypes.func.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(NumericMenu, "defaultProps", { className: '' }); var NumericMenu$1 = translatable({ all: 'All' })(NumericMenu); /** * NumericMenu is a widget used for selecting the range value of a numeric attribute. * @name NumericMenu * @kind widget * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @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 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-NumericMenu - the root div of the widget * @themeKey ais-NumericMenu--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-NumericMenu-list - the list of all refinement items * @themeKey ais-NumericMenu-item - the refinement list item * @themeKey ais-NumericMenu-item--selected - the selected refinement list item * @themeKey ais-NumericMenu-label - the label of each refinement item * @themeKey ais-NumericMenu-radio - the radio input of each refinement item * @themeKey ais-NumericMenu-labelText - the label text of each refinement item * @translationkey all - The label of the largest range added automatically by react instantsearch * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, NumericMenu } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient * indexName="instant_search" * > * <NumericMenu * attribute="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> * ); */ var NumericMenuWidget = function NumericMenuWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(NumericMenu$1, props)); }; var NumericMenu$2 = connectNumericMenu(NumericMenuWidget); var LinkList = /*#__PURE__*/ function (_Component) { _inherits(LinkList, _Component); function LinkList() { _classCallCheck(this, LinkList); return _possibleConstructorReturn(this, _getPrototypeOf(LinkList).apply(this, arguments)); } _createClass(LinkList, [{ key: "render", value: function render() { var _this$props = this.props, cx = _this$props.cx, createURL = _this$props.createURL, items = _this$props.items, onSelect = _this$props.onSelect, canRefine = _this$props.canRefine; return React__default.createElement("ul", { className: cx('list', !canRefine && 'list--noRefinement') }, items.map(function (item) { return React__default.createElement("li", { key: item.key === undefined ? item.value : item.key, className: cx('item', item.selected && !item.disabled && 'item--selected', item.disabled && 'item--disabled', item.modifier) }, item.disabled ? React__default.createElement("span", { className: cx('link') }, item.label === undefined ? item.value : item.label) : React__default.createElement(Link, { className: cx('link', item.selected && 'link--selected'), "aria-label": item.ariaLabel, href: createURL(item.value), onClick: function onClick() { return onSelect(item.value); } }, item.label === undefined ? item.value : item.label)); })); } }]); return LinkList; }(React.Component); _defineProperty(LinkList, "propTypes", { cx: propTypes.func.isRequired, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ value: propTypes.oneOfType([propTypes.string, propTypes.number, propTypes.object]).isRequired, key: propTypes.oneOfType([propTypes.string, propTypes.number]), label: propTypes.node, modifier: propTypes.string, ariaLabel: propTypes.string, disabled: propTypes.bool })), onSelect: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired }); var cx$d = createClassNames('Pagination'); // Determines the size of the widget (the number of pages displayed - that the user can directly click on) function calculateSize(padding, maxPages) { return Math.min(2 * padding + 1, maxPages); } function calculatePaddingLeft(currentPage, padding, maxPages, size) { if (currentPage <= padding) { return currentPage; } if (currentPage >= maxPages - padding) { return size - (maxPages - currentPage); } return padding + 1; } // Retrieve the correct page range to populate the widget function getPages(currentPage, maxPages, padding) { var size = calculateSize(padding, maxPages); // If the widget size is equal to the max number of pages, return the entire page range if (size === maxPages) return range({ start: 1, end: maxPages + 1 }); var paddingLeft = calculatePaddingLeft(currentPage, padding, maxPages, size); var paddingRight = size - paddingLeft; var first = currentPage - paddingLeft; var last = currentPage + paddingRight; return range({ start: first + 1, end: last + 1 }); } var Pagination = /*#__PURE__*/ function (_Component) { _inherits(Pagination, _Component); function Pagination() { _classCallCheck(this, Pagination); return _possibleConstructorReturn(this, _getPrototypeOf(Pagination).apply(this, arguments)); } _createClass(Pagination, [{ key: "getItem", value: function getItem(modifier, translationKey, value) { var _this$props = this.props, nbPages = _this$props.nbPages, totalPages = _this$props.totalPages, translate = _this$props.translate; return { key: "".concat(modifier, ".").concat(value), modifier: modifier, disabled: value < 1 || value >= Math.min(totalPages, nbPages), label: translate(translationKey, value), value: value, ariaLabel: translate("aria".concat(capitalize(translationKey)), value) }; } }, { key: "render", value: function render() { var _this$props2 = this.props, ListComponent = _this$props2.listComponent, nbPages = _this$props2.nbPages, totalPages = _this$props2.totalPages, currentRefinement = _this$props2.currentRefinement, padding = _this$props2.padding, showFirst = _this$props2.showFirst, showPrevious = _this$props2.showPrevious, showNext = _this$props2.showNext, showLast = _this$props2.showLast, refine = _this$props2.refine, createURL = _this$props2.createURL, canRefine = _this$props2.canRefine, translate = _this$props2.translate, className = _this$props2.className, otherProps = _objectWithoutProperties(_this$props2, ["listComponent", "nbPages", "totalPages", "currentRefinement", "padding", "showFirst", "showPrevious", "showNext", "showLast", "refine", "createURL", "canRefine", "translate", "className"]); var maxPages = Math.min(nbPages, totalPages); var lastPage = maxPages; var items = []; if (showFirst) { items.push({ key: 'first', modifier: 'item--firstPage', disabled: currentRefinement === 1, label: translate('first'), value: 1, ariaLabel: translate('ariaFirst') }); } if (showPrevious) { items.push({ key: 'previous', modifier: 'item--previousPage', disabled: currentRefinement === 1, label: translate('previous'), value: currentRefinement - 1, ariaLabel: translate('ariaPrevious') }); } items = items.concat(getPages(currentRefinement, maxPages, padding).map(function (value) { return { key: value, modifier: 'item--page', label: translate('page', value), value: value, selected: value === currentRefinement, ariaLabel: translate('ariaPage', value) }; })); if (showNext) { items.push({ key: 'next', modifier: 'item--nextPage', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('next'), value: currentRefinement + 1, ariaLabel: translate('ariaNext') }); } if (showLast) { items.push({ key: 'last', modifier: 'item--lastPage', disabled: currentRefinement === lastPage || lastPage <= 1, label: translate('last'), value: lastPage, ariaLabel: translate('ariaLast') }); } return React__default.createElement("div", { className: classnames(cx$d('', !canRefine && '-noRefinement'), className) }, React__default.createElement(ListComponent, _extends({}, otherProps, { cx: cx$d, items: items, onSelect: refine, createURL: createURL, canRefine: canRefine }))); } }]); return Pagination; }(React.Component); _defineProperty(Pagination, "propTypes", { nbPages: propTypes.number.isRequired, currentRefinement: propTypes.number.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, canRefine: propTypes.bool.isRequired, translate: propTypes.func.isRequired, listComponent: propTypes.func, showFirst: propTypes.bool, showPrevious: propTypes.bool, showNext: propTypes.bool, showLast: propTypes.bool, padding: propTypes.number, totalPages: propTypes.number, className: propTypes.string }); _defineProperty(Pagination, "defaultProps", { listComponent: LinkList, showFirst: true, showPrevious: true, showNext: true, showLast: false, padding: 3, totalPages: Infinity, className: '' }); var Pagination$1 = translatable({ 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 ".concat(currentRefinement.toString()); } })(Pagination); /** * 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} [padding=3] - How many page links to display around the current page. * @propType {number} [totalPages=Infinity] - Maximum number of pages to display. * @themeKey ais-Pagination - the root div of the widget * @themeKey ais-Pagination--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-Pagination-list - the list of all pagination items * @themeKey ais-Pagination-list--noRefinement - the list of all pagination items when there is no refinement * @themeKey ais-Pagination-item - the pagination list item * @themeKey ais-Pagination-item--firstPage - the "first" pagination list item * @themeKey ais-Pagination-item--lastPage - the "last" pagination list item * @themeKey ais-Pagination-item--previousPage - the "previous" pagination list item * @themeKey ais-Pagination-item--nextPage - the "next" pagination list item * @themeKey ais-Pagination-item--page - the "page" pagination list item * @themeKey ais-Pagination-item--selected - the selected pagination list item * @themeKey ais-Pagination-item--disabled - the disabled pagination list item * @themeKey ais-Pagination-link - the pagination clickable element * @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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Pagination } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Pagination /> * </InstantSearch> * ); */ var PaginationWidget = function PaginationWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(Pagination$1, props)); }; var Pagination$2 = connectPagination(PaginationWidget); var cx$e = createClassNames('PoweredBy'); /* eslint-disable max-len */ var AlgoliaLogo = function AlgoliaLogo() { return React__default.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", baseProfile: "basic", viewBox: "0 0 1366 362", width: "100", height: "27", className: cx$e('logo') }, React__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)" }, React__default.createElement("stop", { offset: "0", stopColor: "#00AEFF" }), React__default.createElement("stop", { offset: "1", stopColor: "#3369E7" })), React__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)" }), React__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" }), React__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 = /*#__PURE__*/ function (_Component) { _inherits(PoweredBy, _Component); function PoweredBy() { _classCallCheck(this, PoweredBy); return _possibleConstructorReturn(this, _getPrototypeOf(PoweredBy).apply(this, arguments)); } _createClass(PoweredBy, [{ key: "render", value: function render() { var _this$props = this.props, url = _this$props.url, translate = _this$props.translate, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$e(''), className) }, React__default.createElement("span", { className: cx$e('text') }, translate('searchBy')), ' ', React__default.createElement("a", { href: url, target: "_blank", className: cx$e('link'), "aria-label": "Algolia", rel: "noopener noreferrer" }, React__default.createElement(AlgoliaLogo, null))); } }]); return PoweredBy; }(React.Component); _defineProperty(PoweredBy, "propTypes", { url: propTypes.string.isRequired, translate: propTypes.func.isRequired, className: propTypes.string }); var PoweredBy$1 = translatable({ searchBy: 'Search by' })(PoweredBy); /** * 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 - the root div of the widget * @themeKey ais-PoweredBy-text - the text of the widget * @themeKey ais-PoweredBy-link - the link of the logo * @themeKey ais-PoweredBy-logo - the logo of the widget * @translationKey searchBy - Label value for the powered by * @example * import React from 'react'; * import { InstantSearch, PoweredBy } from 'react-instantsearch-dom'; * import algoliasearch from 'algoliasearch/lite'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <PoweredBy /> * </InstantSearch> * ); */ var PoweredBy$2 = connectPoweredBy(PoweredBy$1); var cx$f = createClassNames('RangeInput'); var RawRangeInput = /*#__PURE__*/ function (_Component) { _inherits(RawRangeInput, _Component); function RawRangeInput(props) { var _this; _classCallCheck(this, RawRangeInput); _this = _possibleConstructorReturn(this, _getPrototypeOf(RawRangeInput).call(this, props)); _defineProperty(_assertThisInitialized(_this), "onSubmit", function (e) { e.preventDefault(); _this.props.refine({ min: _this.state.from, max: _this.state.to }); }); _this.state = _this.normalizeStateForRendering(props); return _this; } _createClass(RawRangeInput, [{ key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props.canRefine && (prevProps.currentRefinement.min !== this.props.currentRefinement.min || prevProps.currentRefinement.max !== this.props.currentRefinement.max)) { this.setState(this.normalizeStateForRendering(this.props)); } } }, { key: "normalizeStateForRendering", value: function normalizeStateForRendering(props) { var canRefine = props.canRefine, rangeMin = props.min, rangeMax = props.max; var _props$currentRefinem = props.currentRefinement, valueMin = _props$currentRefinem.min, valueMax = _props$currentRefinem.max; return { from: canRefine && valueMin !== undefined && valueMin !== rangeMin ? valueMin : '', to: canRefine && valueMax !== undefined && valueMax !== rangeMax ? valueMax : '' }; } }, { key: "normalizeRangeForRendering", value: function normalizeRangeForRendering(_ref) { var canRefine = _ref.canRefine, min = _ref.min, max = _ref.max; var hasMin = min !== undefined; var hasMax = max !== undefined; return { min: canRefine && hasMin && hasMax ? min : '', max: canRefine && hasMin && hasMax ? max : '' }; } }, { key: "render", value: function render() { var _this2 = this; var _this$state = this.state, from = _this$state.from, to = _this$state.to; var _this$props = this.props, precision = _this$props.precision, translate = _this$props.translate, canRefine = _this$props.canRefine, className = _this$props.className; var _this$normalizeRangeF = this.normalizeRangeForRendering(this.props), min = _this$normalizeRangeF.min, max = _this$normalizeRangeF.max; var step = 1 / Math.pow(10, precision); return React__default.createElement("div", { className: classnames(cx$f('', !canRefine && '-noRefinement'), className) }, React__default.createElement("form", { className: cx$f('form'), onSubmit: this.onSubmit }, React__default.createElement("input", { className: cx$f('input', 'input--min'), type: "number", min: min, max: max, value: from, step: step, placeholder: min, disabled: !canRefine, onChange: function onChange(e) { return _this2.setState({ from: e.currentTarget.value }); } }), React__default.createElement("span", { className: cx$f('separator') }, translate('separator')), React__default.createElement("input", { className: cx$f('input', 'input--max'), type: "number", min: min, max: max, value: to, step: step, placeholder: max, disabled: !canRefine, onChange: function onChange(e) { return _this2.setState({ to: e.currentTarget.value }); } }), React__default.createElement("button", { className: cx$f('submit'), type: "submit" }, translate('submit')))); } }]); return RawRangeInput; }(React.Component); _defineProperty(RawRangeInput, "propTypes", { canRefine: propTypes.bool.isRequired, precision: propTypes.number.isRequired, translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, min: propTypes.number, max: propTypes.number, currentRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }), className: propTypes.string }); _defineProperty(RawRangeInput, "defaultProps", { currentRefinement: {}, className: '' }); var RangeInput = translatable({ submit: 'ok', separator: 'to' })(RawRangeInput); /** * 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 `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 - 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. * @propType {number} [precision=0] - Number of digits after decimal point to use. * @themeKey ais-RangeInput - the root div of the widget * @themeKey ais-RangeInput-form - the wrapping form * @themeKey ais-RangeInput-label - the label wrapping inputs * @themeKey ais-RangeInput-input - the input (number) * @themeKey ais-RangeInput-input--min - the minimum input * @themeKey ais-RangeInput-input--max - the maximum input * @themeKey ais-RangeInput-separator - the separator word used between the two inputs * @themeKey ais-RangeInput-button - the submit button * @translationKey submit - Label value for the submit button * @translationKey separator - Label value for the input separator * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, RangeInput } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <RangeInput attribute="price" /> * </InstantSearch> * ); */ var RangeInputWidget = function RangeInputWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(RangeInput, props)); }; var RangeInput$1 = connectRange(RangeInputWidget); /** * 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. ⚠️ This example only works with the version 2.x of Rheostat. import React, {Component} from 'react'; import PropTypes from 'prop-types'; import Rheostat from 'rheostat'; import { connectRange } from 'react-instantsearch-dom'; 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 } }; componentDidUpdate(prevProps) { if ( this.props.canRefine && (prevProps.currentRefinement.min !== this.props.currentRefinement.min || prevProps.currentRefinement.max !== this.props.currentRefinement.max) ) { this.setState({ currentValues: { min: this.props.currentRefinement.min, max: this.props.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 className="ais-RangeSlider" 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); */ var RangeSlider = (function () { return React__default.createElement("div", null, "We do not provide any Slider, see the documentation to learn how to connect one easily:", React__default.createElement("a", { target: "_blank", rel: "noopener noreferrer", href: "https://www.algolia.com/doc/api-reference/widgets/range-slider/react/" }, "https://www.algolia.com/doc/api-reference/widgets/range-slider/react/")); }); var cx$g = createClassNames('RatingMenu'); var RatingMenu = /*#__PURE__*/ function (_Component) { _inherits(RatingMenu, _Component); function RatingMenu() { _classCallCheck(this, RatingMenu); return _possibleConstructorReturn(this, _getPrototypeOf(RatingMenu).apply(this, arguments)); } _createClass(RatingMenu, [{ 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, lowerBound = _ref.lowerBound, count = _ref.count, translate = _ref.translate, createURL = _ref.createURL, 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 = []; var rating = 0; for (var icon = 0; icon < max; icon++) { if (icon < lowerBound) { rating++; } icons.push([React__default.createElement("svg", { key: icon, className: cx$g('starIcon', icon >= lowerBound ? 'starIcon--empty' : 'starIcon--full'), "aria-hidden": "true", width: "24", height: "24" }, React__default.createElement("use", { xlinkHref: "#".concat(cx$g(icon >= lowerBound ? 'starEmptySymbol' : 'starSymbol')) })), ' ']); } // The last item of the list (the default item), should not // be clickable if it is selected. var isLastAndSelect = isLastSelectableItem && selected; var onClickHandler = disabled || isLastAndSelect ? {} : { href: createURL({ min: lowerBound, max: max }), onClick: this.onClick.bind(this, lowerBound, max) }; return React__default.createElement("li", { key: lowerBound, className: cx$g('item', selected && 'item--selected', disabled && 'item--disabled') }, React__default.createElement("a", _extends({ className: cx$g('link'), "aria-label": "".concat(rating).concat(translate('ratingLabel')) }, onClickHandler), icons, React__default.createElement("span", { className: cx$g('label'), "aria-hidden": "true" }, translate('ratingLabel')), ' ', React__default.createElement("span", { className: cx$g('count') }, count))); } }, { key: "render", value: function render() { var _this = this; var _this$props = this.props, min = _this$props.min, max = _this$props.max, translate = _this$props.translate, count = _this$props.count, createURL = _this$props.createURL, canRefine = _this$props.canRefine, className = _this$props.className; // min & max are always set when there is a results, otherwise it means // that we don't want to render anything since we don't have any values. var limitMin = min !== undefined && min >= 0 ? min : 1; var limitMax = max !== undefined && max >= 0 ? max : 0; var inclusiveLength = limitMax - limitMin + 1; var values = count.map(function (item) { return _objectSpread({}, item, { value: parseFloat(item.value) }); }).filter(function (item) { return item.value >= limitMin && item.value <= limitMax; }); var items = range({ start: 0, end: Math.max(inclusiveLength, 0) }).map(function (index) { var element = find$2(values, function (item) { return item.value === limitMax - index; }); var placeholder = { value: limitMax - index, count: 0, total: 0 }; return element || placeholder; }).reduce(function (acc, item, index) { return acc.concat(_objectSpread({}, item, { total: index === 0 ? item.count : acc[index - 1].total + item.count })); }, []).map(function (item, index, arr) { return _this.buildItem({ lowerBound: item.value, count: item.total, isLastSelectableItem: arr.length - 1 === index, max: limitMax, translate: translate, createURL: createURL }); }); return React__default.createElement("div", { className: classnames(cx$g('', !canRefine && '-noRefinement'), className) }, React__default.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", style: { display: 'none' } }, React__default.createElement("symbol", { id: cx$g('starSymbol'), viewBox: "0 0 24 24" }, React__default.createElement("path", { d: "M12 .288l2.833 8.718h9.167l-7.417 5.389 2.833 8.718-7.416-5.388-7.417 5.388 2.833-8.718-7.416-5.389h9.167z" })), React__default.createElement("symbol", { id: cx$g('starEmptySymbol'), viewBox: "0 0 24 24" }, React__default.createElement("path", { d: "M12 6.76l1.379 4.246h4.465l-3.612 2.625 1.379 4.246-3.611-2.625-3.612 2.625 1.379-4.246-3.612-2.625h4.465l1.38-4.246zm0-6.472l-2.833 8.718h-9.167l7.416 5.389-2.833 8.718 7.417-5.388 7.416 5.388-2.833-8.718 7.417-5.389h-9.167l-2.833-8.718z" }))), React__default.createElement("ul", { className: cx$g('list', !canRefine && 'list--noRefinement') }, items)); } }]); return RatingMenu; }(React.Component); _defineProperty(RatingMenu, "propTypes", { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, createURL: propTypes.func.isRequired, min: propTypes.number, max: propTypes.number, currentRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }), count: propTypes.arrayOf(propTypes.shape({ value: propTypes.string, count: propTypes.number })), canRefine: propTypes.bool.isRequired, className: propTypes.string }); _defineProperty(RatingMenu, "defaultProps", { className: '' }); var RatingMenu$1 = translatable({ ratingLabel: ' & Up' })(RatingMenu); /** * RatingMenu lets the user refine search results by clicking on stars. * * The stars are based on the selected `attribute`. * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @name RatingMenu * @kind widget * @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 - 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-RatingMenu - the root div of the widget * @themeKey ais-RatingMenu--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-RatingMenu-list - the list of ratings * @themeKey ais-RatingMenu-list--noRefinement - the list of ratings when there is no refinement * @themeKey ais-RatingMenu-item - the rating list item * @themeKey ais-RatingMenu-item--selected - the selected rating list item * @themeKey ais-RatingMenu-item--disabled - the disabled rating list item * @themeKey ais-RatingMenu-link - the rating clickable item * @themeKey ais-RatingMenu-starIcon - the star icon * @themeKey ais-RatingMenu-starIcon--full - the filled star icon * @themeKey ais-RatingMenu-starIcon--empty - the empty star icon * @themeKey ais-RatingMenu-label - the label used after the stars * @themeKey ais-RatingMenu-count - the count of ratings for a specific item * @translationKey ratingLabel - Label value for the rating link * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, RatingMenu } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <RatingMenu attribute="rating" /> * </InstantSearch> * ); */ var RatingMenuWidget = function RatingMenuWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(RatingMenu$1, props)); }; var RatingMenu$2 = connectRange(RatingMenuWidget); var cx$h = createClassNames('RefinementList'); var RefinementList$1 = /*#__PURE__*/ function (_Component) { _inherits(RefinementList, _Component); function RefinementList() { var _getPrototypeOf2; var _this; _classCallCheck(this, RefinementList); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(RefinementList)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "state", { query: '' }); _defineProperty(_assertThisInitialized(_this), "selectItem", function (item, resetQuery) { resetQuery(); _this.props.refine(item.value); }); _defineProperty(_assertThisInitialized(_this), "renderItem", function (item, resetQuery) { var label = _this.props.isFromSearch ? React__default.createElement(Highlight$2, { attribute: "label", hit: item }) : item.label; return React__default.createElement("label", { className: cx$h('label') }, React__default.createElement("input", { className: cx$h('checkbox'), type: "checkbox", checked: item.isRefined, onChange: function onChange() { return _this.selectItem(item, resetQuery); } }), React__default.createElement("span", { className: cx$h('labelText') }, label), ' ', React__default.createElement("span", { className: cx$h('count') }, item.count.toLocaleString())); }); return _this; } _createClass(RefinementList, [{ key: "render", value: function render() { var _this$props = this.props, translate = _this$props.translate, items = _this$props.items, showMore = _this$props.showMore, limit = _this$props.limit, showMoreLimit = _this$props.showMoreLimit, isFromSearch = _this$props.isFromSearch, searchForItems = _this$props.searchForItems, searchable = _this$props.searchable, canRefine = _this$props.canRefine, className = _this$props.className; return React__default.createElement(List, { renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$h, translate: translate, items: items, showMore: showMore, limit: limit, showMoreLimit: showMoreLimit, isFromSearch: isFromSearch, searchForItems: searchForItems, searchable: searchable, canRefine: canRefine, className: className, query: this.state.query }); } }]); return RefinementList; }(React.Component); _defineProperty(RefinementList$1, "propTypes", { translate: propTypes.func.isRequired, refine: propTypes.func.isRequired, searchForItems: propTypes.func.isRequired, searchable: propTypes.bool, createURL: propTypes.func.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string.isRequired, value: propTypes.arrayOf(propTypes.string).isRequired, count: propTypes.number.isRequired, isRefined: propTypes.bool.isRequired })), isFromSearch: propTypes.bool.isRequired, canRefine: propTypes.bool.isRequired, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func, className: propTypes.string }); _defineProperty(RefinementList$1, "defaultProps", { className: '' }); var RefinementList$2 = translatable({ 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$1); /** * The RefinementList component displays a list that let the end user choose multiple values for a specific facet. * @name RefinementList * @kind widget * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [searchable=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/). * @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 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 - the root div of the widget * @themeKey ais-RefinementList--noRefinement - the root div of the widget when there is no refinement * @themeKey ais-RefinementList-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox. * @themeKey ais-RefinementList-list - the list of refinement items * @themeKey ais-RefinementList-item - the refinement list item * @themeKey ais-RefinementList-item--selected - the refinement selected list item * @themeKey ais-RefinementList-label - the label of each refinement item * @themeKey ais-RefinementList-checkbox - the checkbox input of each refinement item * @themeKey ais-RefinementList-labelText - the label text of each refinement item * @themeKey ais-RefinementList-count - the count of values for each item * @themeKey ais-RefinementList-noResults - the div displayed when there are no results * @themeKey ais-RefinementList-showMore - the button used to display more categories * @themeKey ais-RefinementList-showMore--disabled - the disabled button used to display more categories * @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 `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. * * If you are using the `searchable` prop, you'll also need to make the attribute searchable using * the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values). * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, RefinementList } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <RefinementList attribute="brand" /> * </InstantSearch> * ); */ var RefinementListWidget = function RefinementListWidget(props) { return React__default.createElement(PanelWrapper, props, React__default.createElement(RefinementList$2, props)); }; var RefinementList$3 = connectRefinementList(RefinementListWidget); var cx$i = createClassNames('ScrollTo'); var ScrollTo = /*#__PURE__*/ function (_Component) { _inherits(ScrollTo, _Component); function ScrollTo() { _classCallCheck(this, ScrollTo); return _possibleConstructorReturn(this, _getPrototypeOf(ScrollTo).apply(this, arguments)); } _createClass(ScrollTo, [{ key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var _this$props = this.props, value = _this$props.value, hasNotChanged = _this$props.hasNotChanged; if (value !== prevProps.value && hasNotChanged) { this.el.scrollIntoView(); } } }, { key: "render", value: function render() { var _this = this; return React__default.createElement("div", { ref: function ref(_ref) { return _this.el = _ref; }, className: cx$i('') }, this.props.children); } }]); return ScrollTo; }(React.Component); _defineProperty(ScrollTo, "propTypes", { value: propTypes.any, children: propTypes.node, hasNotChanged: propTypes.bool }); /** * The ScrollTo component will make 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. * @themeKey ais-ScrollTo - the root div of the widget * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, ScrollTo, Hits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <ScrollTo> * <Hits /> * </ScrollTo> * </InstantSearch> * ); */ var ScrollTo$1 = connectScrollTo(ScrollTo); /** * 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 from the search input itself. * @propType {node} [submit] - Change the apparence of the default submit button (magnifying glass). * @propType {node} [reset] - Change the apparence of the default reset button (cross). * @propType {node} [loadingIndicator] - Change the apparence of the default loading indicator (spinning circle). * @propType {string} [defaultRefinement] - Provide default refinement value when component is mounted. * @propType {boolean} [showLoadingIndicator=false] - Display that the search is loading. This only happens after a certain amount of time to avoid a blinking effect. This timer can be configured with `stalledSearchDelay` props on <InstantSearch>. By default, the value is 200ms. * @themeKey ais-SearchBox - the root div of the widget * @themeKey ais-SearchBox-form - the wrapping form * @themeKey ais-SearchBox-input - the search input * @themeKey ais-SearchBox-submit - the submit button * @themeKey ais-SearchBox-submitIcon - the default magnifier icon used with the search input * @themeKey ais-SearchBox-reset - the reset button used to clear the content of the input * @themeKey ais-SearchBox-resetIcon - the default reset icon used inside the reset button * @themeKey ais-SearchBox-loadingIndicator - the loading indicator container * @themeKey ais-SearchBox-loadingIcon - the default loading icon * @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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox /> * </InstantSearch> * ); */ var SearchBox$2 = connectSearchBox(SearchBox$1); var cx$j = createClassNames('Snippet'); var Snippet = function Snippet(props) { return React__default.createElement(Highlighter, _extends({}, props, { highlightProperty: "_snippetResult", cx: cx$j })); }; /** * 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 * @requirements To use this widget, the attribute name passed to the `attribute` prop must be * present in "Attributes to snippet" on the Algolia dashboard or configured as `attributesToSnippet` * via a set settings call to the Algolia API. * @propType {string} attribute - location of the highlighted snippet attribute in the hit (the corresponding element can be either a string or an array of strings) * @propType {object} hit - hit object containing the highlighted snippet attribute * @propType {string} [tagName='em'] - tag to be used for highlighted parts of the attribute * @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted * @propType {node} [separator=',<space>'] - symbol used to separate the elements of the array in case the attribute points to an array of strings. * @themeKey ais-Snippet - the root span of the widget * @themeKey ais-Snippet-highlighted - the highlighted text * @themeKey ais-Snippet-nonHighlighted - the normal text * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox, Hits, Snippet } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const Hit = ({ hit }) => ( * <div> * <Snippet attribute="description" hit={hit} /> * </div> * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox defaultRefinement="adjustable" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var Snippet$1 = connectHighlight(Snippet); var cx$k = createClassNames('SortBy'); var SortBy = /*#__PURE__*/ function (_Component) { _inherits(SortBy, _Component); function SortBy() { _classCallCheck(this, SortBy); return _possibleConstructorReturn(this, _getPrototypeOf(SortBy).apply(this, arguments)); } _createClass(SortBy, [{ key: "render", value: function render() { var _this$props = this.props, items = _this$props.items, currentRefinement = _this$props.currentRefinement, refine = _this$props.refine, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$k(''), className) }, React__default.createElement(Select, { cx: cx$k, items: items, selectedItem: currentRefinement, onSelect: refine })); } }]); return SortBy; }(React.Component); _defineProperty(SortBy, "propTypes", { items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, currentRefinement: propTypes.string.isRequired, refine: propTypes.func.isRequired, className: propTypes.string }); _defineProperty(SortBy, "defaultProps", { className: '' }); /** * 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 - the root div of the widget * @themeKey ais-SortBy-select - the select * @themeKey ais-SortBy-option - the select option * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SortBy } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <SortBy * defaultRefinement="instant_search" * items={[ * { value: 'instant_search', label: 'Featured' }, * { value: 'instant_search_price_asc', label: 'Price asc.' }, * { value: 'instant_search_price_desc', label: 'Price desc.' }, * ]} * /> * </InstantSearch> * ); */ var SortBy$1 = connectSortBy(SortBy); var cx$l = createClassNames('Stats'); var Stats = /*#__PURE__*/ function (_Component) { _inherits(Stats, _Component); function Stats() { _classCallCheck(this, Stats); return _possibleConstructorReturn(this, _getPrototypeOf(Stats).apply(this, arguments)); } _createClass(Stats, [{ key: "render", value: function render() { var _this$props = this.props, translate = _this$props.translate, nbHits = _this$props.nbHits, processingTimeMS = _this$props.processingTimeMS, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$l(''), className) }, React__default.createElement("span", { className: cx$l('text') }, translate('stats', nbHits, processingTimeMS))); } }]); return Stats; }(React.Component); _defineProperty(Stats, "propTypes", { translate: propTypes.func.isRequired, nbHits: propTypes.number.isRequired, processingTimeMS: propTypes.number.isRequired, className: propTypes.string }); _defineProperty(Stats, "defaultProps", { className: '' }); var Stats$1 = translatable({ stats: function stats(n, ms) { return "".concat(n.toLocaleString(), " results found in ").concat(ms.toLocaleString(), "ms"); } })(Stats); /** * 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 - the root div of the widget * @themeKey ais-Stats-text - the text of the widget - the count of items for each item * @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 { InstantSearch, Stats, Hits } from 'react-instantsearch-dom'; * import algoliasearch from 'algoliasearch/lite'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <Stats /> * <Hits /> * </InstantSearch> * ); */ var Stats$2 = connectStats(Stats$1); var cx$m = createClassNames('ToggleRefinement'); var ToggleRefinement = function ToggleRefinement(_ref) { var currentRefinement = _ref.currentRefinement, label = _ref.label, canRefine = _ref.canRefine, refine = _ref.refine, className = _ref.className; return React__default.createElement("div", { className: classnames(cx$m('', !canRefine && '-noRefinement'), className) }, React__default.createElement("label", { className: cx$m('label') }, React__default.createElement("input", { className: cx$m('checkbox'), type: "checkbox", checked: currentRefinement, onChange: function onChange(event) { return refine(event.target.checked); } }), React__default.createElement("span", { className: cx$m('labelText') }, label))); }; ToggleRefinement.defaultProps = { className: '' }; /** * The ToggleRefinement provides an on/off filtering feature based on an attribute value. * @name ToggleRefinement * @kind widget * @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 {any} value - Value of the refinement to apply on `attribute` when checked. * @propType {boolean} [defaultRefinement=false] - Default state of the widget. Should the toggle be checked by default? * @themeKey ais-ToggleRefinement - the root div of the widget * @themeKey ais-ToggleRefinement-list - the list of toggles * @themeKey ais-ToggleRefinement-item - the toggle list item * @themeKey ais-ToggleRefinement-label - the label of each toggle item * @themeKey ais-ToggleRefinement-checkbox - the checkbox input of each toggle item * @themeKey ais-ToggleRefinement-labelText - the label text of each toggle item * @example * import React from 'react'; * import algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, ToggleRefinement } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <ToggleRefinement * attribute="free_shipping" * label="Free Shipping" * value={true} * /> * </InstantSearch> * ); */ var ToggleRefinement$1 = connectToggleRefinement(ToggleRefinement); exports.Breadcrumb = Breadcrumb$2; exports.ClearRefinements = ClearRefinements$2; exports.Configure = Configure; exports.CurrentRefinements = CurrentRefinements$2; exports.HierarchicalMenu = HierarchicalMenu$2; exports.Highlight = Highlight$2; exports.Hits = Hits$1; exports.HitsPerPage = HitsPerPage$1; exports.Index = IndexWrapper; exports.InfiniteHits = InfiniteHits$2; exports.InstantSearch = InstantSearch; exports.Menu = Menu$2; exports.MenuSelect = MenuSelect$2; exports.NumericMenu = NumericMenu$2; exports.Pagination = Pagination$2; exports.Panel = Panel; exports.PoweredBy = PoweredBy$2; exports.RangeInput = RangeInput$1; exports.RangeSlider = RangeSlider; exports.RatingMenu = RatingMenu$2; exports.RefinementList = RefinementList$3; exports.ScrollTo = ScrollTo$1; exports.SearchBox = SearchBox$2; exports.Snippet = Snippet$1; exports.SortBy = SortBy$1; exports.Stats = Stats$2; exports.ToggleRefinement = ToggleRefinement$1; Object.defineProperty(exports, '__esModule', { value: true }); })); //# sourceMappingURL=Dom.js.map
ajax/libs/primereact/6.6.0-rc.1/paginator/paginator.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames, Ripple, ObjectUtils } from 'primereact/core'; import { Dropdown } from 'primereact/dropdown'; import { InputNumber } from 'primereact/inputnumber'; function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _i = arr && (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 _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 _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 _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$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 FirstPageLink = /*#__PURE__*/function (_Component) { _inherits(FirstPageLink, _Component); var _super = _createSuper$8(FirstPageLink); function FirstPageLink() { _classCallCheck(this, FirstPageLink); return _super.apply(this, arguments); } _createClass(FirstPageLink, [{ key: "render", value: function render() { var className = classNames('p-paginator-first p-paginator-element p-link', { 'p-disabled': this.props.disabled }); var iconClassName = 'p-paginator-icon pi pi-angle-double-left'; var element = /*#__PURE__*/React.createElement("button", { type: "button", className: className, onClick: this.props.onClick, disabled: this.props.disabled }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (this.props.template) { var defaultOptions = { onClick: this.props.onClick, className: className, iconClassName: iconClassName, disabled: this.props.disabled, element: element, props: this.props }; return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return FirstPageLink; }(Component); _defineProperty(FirstPageLink, "defaultProps", { disabled: false, onClick: null, template: null }); 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 NextPageLink = /*#__PURE__*/function (_Component) { _inherits(NextPageLink, _Component); var _super = _createSuper$7(NextPageLink); function NextPageLink() { _classCallCheck(this, NextPageLink); return _super.apply(this, arguments); } _createClass(NextPageLink, [{ key: "render", value: function render() { var className = classNames('p-paginator-next p-paginator-element p-link', { 'p-disabled': this.props.disabled }); var iconClassName = 'p-paginator-icon pi pi-angle-right'; var element = /*#__PURE__*/React.createElement("button", { type: "button", className: className, onClick: this.props.onClick, disabled: this.props.disabled }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (this.props.template) { var defaultOptions = { onClick: this.props.onClick, className: className, iconClassName: iconClassName, disabled: this.props.disabled, element: element, props: this.props }; return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return NextPageLink; }(Component); _defineProperty(NextPageLink, "defaultProps", { disabled: false, onClick: null, template: null }); 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 PrevPageLink = /*#__PURE__*/function (_Component) { _inherits(PrevPageLink, _Component); var _super = _createSuper$6(PrevPageLink); function PrevPageLink() { _classCallCheck(this, PrevPageLink); return _super.apply(this, arguments); } _createClass(PrevPageLink, [{ key: "render", value: function render() { var className = classNames('p-paginator-prev p-paginator-element p-link', { 'p-disabled': this.props.disabled }); var iconClassName = 'p-paginator-icon pi pi-angle-left'; var element = /*#__PURE__*/React.createElement("button", { type: "button", className: className, onClick: this.props.onClick, disabled: this.props.disabled }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (this.props.template) { var defaultOptions = { onClick: this.props.onClick, className: className, iconClassName: iconClassName, disabled: this.props.disabled, element: element, props: this.props }; return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return PrevPageLink; }(Component); _defineProperty(PrevPageLink, "defaultProps", { disabled: false, onClick: null, template: null }); 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 LastPageLink = /*#__PURE__*/function (_Component) { _inherits(LastPageLink, _Component); var _super = _createSuper$5(LastPageLink); function LastPageLink() { _classCallCheck(this, LastPageLink); return _super.apply(this, arguments); } _createClass(LastPageLink, [{ key: "render", value: function render() { var className = classNames('p-paginator-last p-paginator-element p-link', { 'p-disabled': this.props.disabled }); var iconClassName = 'p-paginator-icon pi pi-angle-double-right'; var element = /*#__PURE__*/React.createElement("button", { type: "button", className: className, onClick: this.props.onClick, disabled: this.props.disabled }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (this.props.template) { var defaultOptions = { onClick: this.props.onClick, className: className, iconClassName: iconClassName, disabled: this.props.disabled, element: element, props: this.props }; return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return LastPageLink; }(Component); _defineProperty(LastPageLink, "defaultProps", { disabled: false, onClick: null, template: null }); 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 PageLinks = /*#__PURE__*/function (_Component) { _inherits(PageLinks, _Component); var _super = _createSuper$4(PageLinks); function PageLinks() { _classCallCheck(this, PageLinks); return _super.apply(this, arguments); } _createClass(PageLinks, [{ key: "onPageLinkClick", value: function onPageLinkClick(event, pageLink) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, value: pageLink }); } event.preventDefault(); } }, { key: "render", value: function render() { var _this = this; var elements; if (this.props.value) { var startPageInView = this.props.value[0]; var endPageInView = this.props.value[this.props.value.length - 1]; elements = this.props.value.map(function (pageLink, i) { var className = classNames('p-paginator-page p-paginator-element p-link', { 'p-paginator-page-start': pageLink === startPageInView, 'p-paginator-page-end': pageLink === endPageInView, 'p-highlight': pageLink - 1 === _this.props.page }); var element = /*#__PURE__*/React.createElement("button", { type: "button", className: className, onClick: function onClick(e) { return _this.onPageLinkClick(e, pageLink); } }, pageLink, /*#__PURE__*/React.createElement(Ripple, null)); if (_this.props.template) { var defaultOptions = { onClick: function onClick(e) { return _this.onPageLinkClick(e, pageLink); }, className: className, view: { startPage: startPageInView - 1, endPage: endPageInView - 1 }, page: pageLink - 1, currentPage: _this.props.page, totalPages: _this.props.pageCount, element: element, props: _this.props }; element = ObjectUtils.getJSXElement(_this.props.template, defaultOptions); } return /*#__PURE__*/React.createElement(React.Fragment, { key: pageLink }, element); }); } return /*#__PURE__*/React.createElement("span", { className: "p-paginator-pages" }, elements); } }]); return PageLinks; }(Component); _defineProperty(PageLinks, "defaultProps", { value: null, page: null, rows: null, pageCount: null, links: null, template: null }); 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 RowsPerPageDropdown = /*#__PURE__*/function (_Component) { _inherits(RowsPerPageDropdown, _Component); var _super = _createSuper$3(RowsPerPageDropdown); function RowsPerPageDropdown() { _classCallCheck(this, RowsPerPageDropdown); return _super.apply(this, arguments); } _createClass(RowsPerPageDropdown, [{ key: "hasOptions", value: function hasOptions() { return this.props.options && this.props.options.length > 0; } }, { key: "render", value: function render() { var hasOptions = this.hasOptions(); var options = hasOptions ? this.props.options.map(function (opt) { return { label: String(opt), value: opt }; }) : []; var element = hasOptions ? /*#__PURE__*/React.createElement(Dropdown, { value: this.props.value, options: options, onChange: this.props.onChange, appendTo: this.props.appendTo, disabled: this.props.disabled }) : null; if (this.props.template) { var defaultOptions = { value: this.props.value, options: options, onChange: this.props.onChange, appendTo: this.props.appendTo, currentPage: this.props.page, totalPages: this.props.pageCount, totalRecords: this.props.totalRecords, disabled: this.props.disabled, element: element, props: this.props }; return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return RowsPerPageDropdown; }(Component); _defineProperty(RowsPerPageDropdown, "defaultProps", { options: null, value: null, page: null, pageCount: null, totalRecords: 0, appendTo: null, onChange: null, template: null, disabled: false }); 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$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 CurrentPageReport = /*#__PURE__*/function (_Component) { _inherits(CurrentPageReport, _Component); var _super = _createSuper$2(CurrentPageReport); function CurrentPageReport() { _classCallCheck(this, CurrentPageReport); return _super.apply(this, arguments); } _createClass(CurrentPageReport, [{ key: "render", value: function render() { var report = { currentPage: this.props.page + 1, totalPages: this.props.pageCount, first: Math.min(this.props.first + 1, this.props.totalRecords), last: Math.min(this.props.first + this.props.rows, this.props.totalRecords), rows: this.props.rows, totalRecords: this.props.totalRecords }; var text = this.props.reportTemplate.replace("{currentPage}", report.currentPage).replace("{totalPages}", report.totalPages).replace("{first}", report.first).replace("{last}", report.last).replace("{rows}", report.rows).replace("{totalRecords}", report.totalRecords); var element = /*#__PURE__*/React.createElement("span", { className: "p-paginator-current" }, text); if (this.props.template) { var defaultOptions = _objectSpread(_objectSpread({}, report), { className: 'p-paginator-current', element: element, props: this.props }); return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return CurrentPageReport; }(Component); _defineProperty(CurrentPageReport, "defaultProps", { pageCount: null, page: null, first: null, rows: null, totalRecords: null, reportTemplate: '({currentPage} of {totalPages})', template: 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 JumpToPageInput = /*#__PURE__*/function (_Component) { _inherits(JumpToPageInput, _Component); var _super = _createSuper$1(JumpToPageInput); function JumpToPageInput(props) { var _this; _classCallCheck(this, JumpToPageInput); _this = _super.call(this, props); _this.onChange = _this.onChange.bind(_assertThisInitialized(_this)); return _this; } _createClass(JumpToPageInput, [{ key: "onChange", value: function onChange(event) { if (this.props.onChange) { this.props.onChange(this.props.rows * (event.value - 1), this.props.rows); } } }, { key: "render", value: function render() { var value = this.props.pageCount > 0 ? this.props.page + 1 : 0; var element = /*#__PURE__*/React.createElement(InputNumber, { value: value, onChange: this.onChange, className: "p-paginator-page-input", disabled: this.props.disabled }); if (this.props.template) { var defaultOptions = { value: value, onChange: this.onChange, disabled: this.props.disabled, className: 'p-paginator-page-input', element: element, props: this.props }; return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return JumpToPageInput; }(Component); _defineProperty(JumpToPageInput, "defaultProps", { page: null, rows: null, pageCount: null, disabled: false, template: null, onChange: null }); 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 Paginator = /*#__PURE__*/function (_Component) { _inherits(Paginator, _Component); var _super = _createSuper(Paginator); function Paginator(props) { var _this; _classCallCheck(this, Paginator); _this = _super.call(this, props); _this.changePageToFirst = _this.changePageToFirst.bind(_assertThisInitialized(_this)); _this.changePageToPrev = _this.changePageToPrev.bind(_assertThisInitialized(_this)); _this.changePageToNext = _this.changePageToNext.bind(_assertThisInitialized(_this)); _this.changePageToLast = _this.changePageToLast.bind(_assertThisInitialized(_this)); _this.onRowsChange = _this.onRowsChange.bind(_assertThisInitialized(_this)); _this.changePage = _this.changePage.bind(_assertThisInitialized(_this)); _this.onPageLinkClick = _this.onPageLinkClick.bind(_assertThisInitialized(_this)); return _this; } _createClass(Paginator, [{ key: "isFirstPage", value: function isFirstPage() { return this.getPage() === 0; } }, { key: "isLastPage", value: function isLastPage() { return this.getPage() === this.getPageCount() - 1; } }, { key: "getPageCount", value: function getPageCount() { return Math.ceil(this.props.totalRecords / this.props.rows); } }, { key: "calculatePageLinkBoundaries", value: function calculatePageLinkBoundaries() { var numberOfPages = this.getPageCount(); var visiblePages = Math.min(this.props.pageLinkSize, numberOfPages); //calculate range, keep current in middle if necessary var start = Math.max(0, Math.ceil(this.getPage() - visiblePages / 2)); var end = Math.min(numberOfPages - 1, start + visiblePages - 1); //check when approaching to last page var delta = this.props.pageLinkSize - (end - start + 1); start = Math.max(0, start - delta); return [start, end]; } }, { key: "updatePageLinks", value: function updatePageLinks() { var pageLinks = []; var boundaries = this.calculatePageLinkBoundaries(); var start = boundaries[0]; var end = boundaries[1]; for (var i = start; i <= end; i++) { pageLinks.push(i + 1); } return pageLinks; } }, { key: "changePage", value: function changePage(first, rows) { var pc = this.getPageCount(); var p = Math.floor(first / rows); if (p >= 0 && p < pc) { var newPageState = { first: first, rows: rows, page: p, pageCount: pc }; if (this.props.onPageChange) { this.props.onPageChange(newPageState); } } } }, { key: "getPage", value: function getPage() { return Math.floor(this.props.first / this.props.rows); } }, { key: "empty", value: function empty() { var pageCount = this.getPageCount(); return pageCount === 0; } }, { key: "changePageToFirst", value: function changePageToFirst(event) { this.changePage(0, this.props.rows); event.preventDefault(); } }, { key: "changePageToPrev", value: function changePageToPrev(event) { this.changePage(this.props.first - this.props.rows, this.props.rows); event.preventDefault(); } }, { key: "onPageLinkClick", value: function onPageLinkClick(event) { this.changePage((event.value - 1) * this.props.rows, this.props.rows); } }, { key: "changePageToNext", value: function changePageToNext(event) { this.changePage(this.props.first + this.props.rows, this.props.rows); event.preventDefault(); } }, { key: "changePageToLast", value: function changePageToLast(event) { this.changePage((this.getPageCount() - 1) * this.props.rows, this.props.rows); event.preventDefault(); } }, { key: "onRowsChange", value: function onRowsChange(event) { var rows = event.value; this.isRowChanged = rows !== this.props.rows; this.changePage(0, rows); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.props.rows !== prevProps.rows && !this.isRowChanged) { this.changePage(0, this.props.rows); } else if (this.getPage() > 0 && prevProps.totalRecords !== this.props.totalRecords && this.props.first >= this.props.totalRecords) { this.changePage((this.getPageCount() - 1) * this.props.rows, this.props.rows); } this.isRowChanged = false; } }, { key: "renderElement", value: function renderElement(key, template) { var element; switch (key) { case 'FirstPageLink': element = /*#__PURE__*/React.createElement(FirstPageLink, { key: key, onClick: this.changePageToFirst, disabled: this.isFirstPage() || this.empty(), template: template }); break; case 'PrevPageLink': element = /*#__PURE__*/React.createElement(PrevPageLink, { key: key, onClick: this.changePageToPrev, disabled: this.isFirstPage() || this.empty(), template: template }); break; case 'NextPageLink': element = /*#__PURE__*/React.createElement(NextPageLink, { key: key, onClick: this.changePageToNext, disabled: this.isLastPage() || this.empty(), template: template }); break; case 'LastPageLink': element = /*#__PURE__*/React.createElement(LastPageLink, { key: key, onClick: this.changePageToLast, disabled: this.isLastPage() || this.empty(), template: template }); break; case 'PageLinks': element = /*#__PURE__*/React.createElement(PageLinks, { key: key, value: this.updatePageLinks(), page: this.getPage(), rows: this.props.rows, pageCount: this.getPageCount(), onClick: this.onPageLinkClick, template: template }); break; case 'RowsPerPageDropdown': element = /*#__PURE__*/React.createElement(RowsPerPageDropdown, { key: key, value: this.props.rows, page: this.getPage(), pageCount: this.getPageCount(), totalRecords: this.props.totalRecords, options: this.props.rowsPerPageOptions, onChange: this.onRowsChange, appendTo: this.props.dropdownAppendTo, template: template, disabled: this.empty() }); break; case 'CurrentPageReport': element = /*#__PURE__*/React.createElement(CurrentPageReport, { reportTemplate: this.props.currentPageReportTemplate, key: key, page: this.getPage(), pageCount: this.getPageCount(), first: this.props.first, rows: this.props.rows, totalRecords: this.props.totalRecords, template: template }); break; case 'JumpToPageInput': element = /*#__PURE__*/React.createElement(JumpToPageInput, { key: key, rows: this.props.rows, page: this.getPage(), pageCount: this.getPageCount(), onChange: this.changePage, disabled: this.empty(), template: template }); break; default: element = null; break; } return element; } }, { key: "renderElements", value: function renderElements() { var _this2 = this; var template = this.props.template; if (template) { if (_typeof(template) === 'object') { return template.layout ? template.layout.split(' ').map(function (value) { var key = value.trim(); return _this2.renderElement(key, template[key]); }) : Object.entries(template).map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], _template = _ref2[1]; return _this2.renderElement(key, _template); }); } return template.split(' ').map(function (value) { return _this2.renderElement(value.trim()); }); } return null; } }, { key: "render", value: function render() { if (!this.props.alwaysShow && this.getPageCount() === 1) { return null; } else { var className = classNames('p-paginator p-component', this.props.className); var leftContent = ObjectUtils.getJSXElement(this.props.leftContent, this.props); var rightContent = ObjectUtils.getJSXElement(this.props.rightContent, this.props); var elements = this.renderElements(); var leftElement = leftContent && /*#__PURE__*/React.createElement("div", { className: "p-paginator-left-content" }, leftContent); var rightElement = rightContent && /*#__PURE__*/React.createElement("div", { className: "p-paginator-right-content" }, rightContent); return /*#__PURE__*/React.createElement("div", { className: className, style: this.props.style }, leftElement, elements, rightElement); } } }]); return Paginator; }(Component); _defineProperty(Paginator, "defaultProps", { totalRecords: 0, rows: 0, first: 0, pageLinkSize: 5, rowsPerPageOptions: null, alwaysShow: true, style: null, className: null, template: 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown', onPageChange: null, leftContent: null, rightContent: null, dropdownAppendTo: null, currentPageReportTemplate: '({currentPage} of {totalPages})' }); export { Paginator };
ajax/libs/material-ui/5.0.0-alpha.13/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.11.5/vendor/react-native/ListView/cloneReferencedElement.js
cdnjs/cdnjs
'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; } import React from 'react'; var __DEV__ = process.env.NODE_ENV !== 'production'; function cloneReferencedElement(element, config) { var cloneRef = config.ref; var originalRef = element.ref; for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } if (originalRef == null || cloneRef == null) { return React.cloneElement.apply(React, [element, config].concat(children)); } if (typeof originalRef !== 'function') { if (__DEV__) { console.warn('Cloning an element with a ref that will be overwritten because it ' + 'is not a function. Use a composable callback-style ref instead. ' + 'Ignoring ref: ' + originalRef); } return React.cloneElement.apply(React, [element, config].concat(children)); } return React.cloneElement.apply(React, [element, _objectSpread({}, config, { ref: function ref(component) { cloneRef(component); originalRef(component); } })].concat(children)); } export default cloneReferencedElement;
ajax/libs/primereact/7.0.1/csstransition/csstransition.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { CSSTransition as CSSTransition$1 } from 'react-transition-group'; 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 _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 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 CSSTransition = /*#__PURE__*/function (_Component) { _inherits(CSSTransition, _Component); var _super = _createSuper(CSSTransition); function CSSTransition(props) { var _this; _classCallCheck(this, CSSTransition); _this = _super.call(this, props); _this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this)); _this.onEntering = _this.onEntering.bind(_assertThisInitialized(_this)); _this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this)); _this.onExit = _this.onExit.bind(_assertThisInitialized(_this)); _this.onExiting = _this.onExiting.bind(_assertThisInitialized(_this)); _this.onExited = _this.onExited.bind(_assertThisInitialized(_this)); return _this; } _createClass(CSSTransition, [{ key: "onEnter", value: function onEnter(node, isAppearing) { this.props.onEnter && this.props.onEnter(node, isAppearing); // component this.props.options && this.props.options.onEnter && this.props.options.onEnter(node, isAppearing); // user option } }, { key: "onEntering", value: function onEntering(node, isAppearing) { this.props.onEntering && this.props.onEntering(node, isAppearing); // component this.props.options && this.props.options.onEntering && this.props.options.onEntering(node, isAppearing); // user option } }, { key: "onEntered", value: function onEntered(node, isAppearing) { this.props.onEntered && this.props.onEntered(node, isAppearing); // component this.props.options && this.props.options.onEntered && this.props.options.onEntered(node, isAppearing); // user option } }, { key: "onExit", value: function onExit(node) { this.props.onExit && this.props.onExit(node); // component this.props.options && this.props.options.onExit && this.props.options.onExit(node); // user option } }, { key: "onExiting", value: function onExiting(node) { this.props.onExiting && this.props.onExiting(node); // component this.props.options && this.props.options.onExiting && this.props.options.onExiting(node); // user option } }, { key: "onExited", value: function onExited(node) { this.props.onExited && this.props.onExited(node); // component this.props.options && this.props.options.onExited && this.props.options.onExited(node); // user option } }, { key: "render", value: function render() { var immutableProps = { nodeRef: this.props.nodeRef, in: this.props.in, onEnter: this.onEnter, onEntering: this.onEntering, onEntered: this.onEntered, onExit: this.onExit, onExiting: this.onExiting, onExited: this.onExited }; var mutableProps = { classNames: this.props.classNames, timeout: this.props.timeout, unmountOnExit: this.props.unmountOnExit }; var props = _objectSpread(_objectSpread(_objectSpread({}, mutableProps), this.props.options || {}), immutableProps); return /*#__PURE__*/React.createElement(CSSTransition$1, props, this.props.children); } }]); return CSSTransition; }(Component); export { CSSTransition };
ajax/libs/material-ui/4.10.1/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 React.memo(React.forwardRef(Component)); }
ajax/libs/primereact/7.0.0-rc.2/picklist/picklist.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames, Ripple, ObjectUtils, DomHandler } from 'primereact/core'; import { Button } from 'primereact/button'; 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 _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 _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 _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 PickListItem = /*#__PURE__*/function (_Component) { _inherits(PickListItem, _Component); var _super = _createSuper$4(PickListItem); function PickListItem(props) { var _this; _classCallCheck(this, PickListItem); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(PickListItem, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, value: this.props.value }); } } }, { key: "onKeyDown", value: function onKeyDown(event) { if (this.props.onKeyDown) { this.props.onKeyDown({ originalEvent: event, value: this.props.value }); } } }, { key: "render", value: function render() { var content = this.props.template ? this.props.template(this.props.value) : this.props.value; var className = classNames('p-picklist-item', { 'p-highlight': this.props.selected }, this.props.className); return /*#__PURE__*/React.createElement("li", { className: className, onClick: this.onClick, onKeyDown: this.onKeyDown, tabIndex: this.props.tabIndex, role: "option", "aria-selected": this.props.selected }, content, /*#__PURE__*/React.createElement(Ripple, null)); } }]); return PickListItem; }(Component); _defineProperty(PickListItem, "defaultProps", { value: null, className: null, template: null, selected: false, tabIndex: null, onClick: null, onKeyDown: null }); 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 PickListSubListComponent = /*#__PURE__*/function (_Component) { _inherits(PickListSubListComponent, _Component); var _super = _createSuper$3(PickListSubListComponent); function PickListSubListComponent(props) { var _this; _classCallCheck(this, PickListSubListComponent); _this = _super.call(this, props); _this.onItemClick = _this.onItemClick.bind(_assertThisInitialized(_this)); _this.onItemKeyDown = _this.onItemKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(PickListSubListComponent, [{ key: "onItemClick", value: function onItemClick(event) { var originalEvent = event.originalEvent; var item = event.value; var selection = _toConsumableArray(this.props.selection); var index = ObjectUtils.findIndexInList(item, selection, this.props.dataKey); var selected = index !== -1; var metaSelection = this.props.metaKeySelection; if (metaSelection) { var metaKey = originalEvent.metaKey || originalEvent.ctrlKey; if (selected && metaKey) { selection.splice(index, 1); } else { if (!metaKey) { selection.length = 0; } selection.push(item); } } else { if (selected) selection.splice(index, 1);else selection.push(item); } if (this.props.onSelectionChange) { this.props.onSelectionChange({ event: originalEvent, value: 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-picklist-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-picklist-item') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "isSelected", value: function isSelected(item) { return ObjectUtils.findIndexInList(item, this.props.selection, this.props.dataKey) !== -1; } }, { key: "render", value: function render() { var _this2 = this; var header = null; var items = null; var wrapperClassName = classNames('p-picklist-list-wrapper', this.props.className); var listClassName = classNames('p-picklist-list', this.props.listClassName); if (this.props.header) { header = /*#__PURE__*/React.createElement("div", { className: "p-picklist-header" }, ObjectUtils.getJSXElement(this.props.header, this.props)); } if (this.props.list) { items = this.props.list.map(function (item, i) { return /*#__PURE__*/React.createElement(PickListItem, { key: JSON.stringify(item), value: item, template: _this2.props.itemTemplate, selected: _this2.isSelected(item), onClick: _this2.onItemClick, onKeyDown: _this2.onItemKeyDown, tabIndex: _this2.props.tabIndex }); }); } return /*#__PURE__*/React.createElement("div", { ref: this.props.forwardRef, className: wrapperClassName }, header, /*#__PURE__*/React.createElement("ul", { className: listClassName, style: this.props.style, role: "listbox", "aria-multiselectable": true }, items)); } }]); return PickListSubListComponent; }(Component); var PickListSubList = /*#__PURE__*/React.forwardRef(function (props, ref) { return /*#__PURE__*/React.createElement(PickListSubListComponent, _extends({ forwardRef: ref }, props)); }); 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 PickListControls = /*#__PURE__*/function (_Component) { _inherits(PickListControls, _Component); var _super = _createSuper$2(PickListControls); function PickListControls(props) { var _this; _classCallCheck(this, PickListControls); _this = _super.call(this, props); _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(PickListControls, [{ key: "moveUp", value: function moveUp(event) { var selectedItems = this.props.selection; if (selectedItems && selectedItems.length) { var list = _toConsumableArray(this.props.list); for (var i = 0; i < selectedItems.length; i++) { var selectedItem = selectedItems[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list, this.props.dataKey); if (selectedItemIndex !== 0) { var movedItem = list[selectedItemIndex]; var temp = list[selectedItemIndex - 1]; list[selectedItemIndex - 1] = movedItem; list[selectedItemIndex] = temp; } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: list, direction: 'up' }); } } } }, { key: "moveTop", value: function moveTop(event) { var selectedItems = this.props.selection; if (selectedItems && selectedItems.length) { var list = _toConsumableArray(this.props.list); for (var i = 0; i < selectedItems.length; i++) { var selectedItem = selectedItems[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list, this.props.dataKey); if (selectedItemIndex !== 0) { var movedItem = list.splice(selectedItemIndex, 1)[0]; list.unshift(movedItem); } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: list, direction: 'top' }); } } } }, { key: "moveDown", value: function moveDown(event) { var selectedItems = this.props.selection; if (selectedItems && selectedItems.length) { var list = _toConsumableArray(this.props.list); for (var i = selectedItems.length - 1; i >= 0; i--) { var selectedItem = selectedItems[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list, this.props.dataKey); if (selectedItemIndex !== list.length - 1) { var movedItem = list[selectedItemIndex]; var temp = list[selectedItemIndex + 1]; list[selectedItemIndex + 1] = movedItem; list[selectedItemIndex] = temp; } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: list, direction: 'down' }); } this.movedDown = true; } } }, { key: "moveBottom", value: function moveBottom(event) { var selectedItems = this.props.selection; if (selectedItems && selectedItems.length) { var list = _toConsumableArray(this.props.list); for (var i = selectedItems.length - 1; i >= 0; i--) { var selectedItem = selectedItems[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list, this.props.dataKey); if (selectedItemIndex !== list.length - 1) { var movedItem = list.splice(selectedItemIndex, 1)[0]; list.push(movedItem); } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: list, direction: 'bottom' }); } } } }, { key: "render", value: function render() { var moveDisabled = !this.props.selection.length; var className = classNames('p-picklist-buttons', this.props.className); return /*#__PURE__*/React.createElement("div", { className: className }, /*#__PURE__*/React.createElement(Button, { disabled: moveDisabled, type: "button", icon: "pi pi-angle-up", onClick: this.moveUp }), /*#__PURE__*/React.createElement(Button, { disabled: moveDisabled, type: "button", icon: "pi pi-angle-double-up", onClick: this.moveTop }), /*#__PURE__*/React.createElement(Button, { disabled: moveDisabled, type: "button", icon: "pi pi-angle-down", onClick: this.moveDown }), /*#__PURE__*/React.createElement(Button, { disabled: moveDisabled, type: "button", icon: "pi pi-angle-double-down", onClick: this.moveBottom })); } }]); return PickListControls; }(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 PickListTransferControls = /*#__PURE__*/function (_Component) { _inherits(PickListTransferControls, _Component); var _super = _createSuper$1(PickListTransferControls); function PickListTransferControls(props) { var _this; _classCallCheck(this, PickListTransferControls); _this = _super.call(this, props); _this.moveRight = _this.moveRight.bind(_assertThisInitialized(_this)); _this.moveAllRight = _this.moveAllRight.bind(_assertThisInitialized(_this)); _this.moveLeft = _this.moveLeft.bind(_assertThisInitialized(_this)); _this.moveAllLeft = _this.moveAllLeft.bind(_assertThisInitialized(_this)); return _this; } _createClass(PickListTransferControls, [{ key: "moveRight", value: function moveRight(event) { var selection = this.props.sourceSelection; if (selection && selection.length) { var targetList = _toConsumableArray(this.props.target); var sourceList = _toConsumableArray(this.props.source); for (var i = 0; i < selection.length; i++) { var selectedItem = selection[i]; if (ObjectUtils.findIndexInList(selectedItem, targetList, this.props.dataKey) === -1) { targetList.push(sourceList.splice(ObjectUtils.findIndexInList(selectedItem, sourceList, this.props.dataKey), 1)[0]); } } if (this.props.onTransfer) { this.props.onTransfer({ originalEvent: event, source: sourceList, target: targetList, direction: 'toTarget' }); } } } }, { key: "moveAllRight", value: function moveAllRight(event) { if (this.props.source) { var targetList = [].concat(_toConsumableArray(this.props.target), _toConsumableArray(this.props.source)); var sourceList = []; if (this.props.onTransfer) { this.props.onTransfer({ originalEvent: event, source: sourceList, target: targetList, direction: 'allToTarget' }); } } } }, { key: "moveLeft", value: function moveLeft(event) { var selection = this.props.targetSelection; if (selection && selection.length) { var targetList = _toConsumableArray(this.props.target); var sourceList = _toConsumableArray(this.props.source); for (var i = 0; i < selection.length; i++) { var selectedItem = selection[i]; if (ObjectUtils.findIndexInList(selectedItem, sourceList, this.props.dataKey) === -1) { sourceList.push(targetList.splice(ObjectUtils.findIndexInList(selectedItem, targetList, this.props.dataKey), 1)[0]); } } if (this.props.onTransfer) { this.props.onTransfer({ originalEvent: event, source: sourceList, target: targetList, direction: 'toSource' }); } } } }, { key: "moveAllLeft", value: function moveAllLeft(event) { if (this.props.source) { var sourceList = [].concat(_toConsumableArray(this.props.source), _toConsumableArray(this.props.target)); var targetList = []; if (this.props.onTransfer) { this.props.onTransfer({ originalEvent: event, source: sourceList, target: targetList, direction: 'allToSource' }); } } } }, { key: "render", value: function render() { var moveRightDisabled = !this.props.sourceSelection.length; var moveLeftDisabled = !this.props.targetSelection.length; var moveAllRightDisabled = !this.props.source.length; var moveAllLeftDisabled = !this.props.target.length; var className = classNames('p-picklist-buttons p-picklist-transfer-buttons', this.props.className); return /*#__PURE__*/React.createElement("div", { className: className }, /*#__PURE__*/React.createElement(Button, { disabled: moveRightDisabled, type: "button", icon: "pi pi-angle-right", onClick: this.moveRight }), /*#__PURE__*/React.createElement(Button, { disabled: moveAllRightDisabled, type: "button", icon: "pi pi-angle-double-right", onClick: this.moveAllRight }), /*#__PURE__*/React.createElement(Button, { disabled: moveLeftDisabled, type: "button", icon: "pi pi-angle-left", onClick: this.moveLeft }), /*#__PURE__*/React.createElement(Button, { disabled: moveAllLeftDisabled, type: "button", icon: "pi pi-angle-double-left", onClick: this.moveAllLeft })); } }]); return PickListTransferControls; }(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 PickList = /*#__PURE__*/function (_Component) { _inherits(PickList, _Component); var _super = _createSuper(PickList); function PickList(props) { var _this; _classCallCheck(this, PickList); _this = _super.call(this, props); _this.state = {}; if (!_this.props.onSourceSelectionChange) { _this.state.sourceSelection = []; } if (!_this.props.onTargetSelectionChange) { _this.state.targetSelection = []; } _this.onSourceReorder = _this.onSourceReorder.bind(_assertThisInitialized(_this)); _this.onTargetReorder = _this.onTargetReorder.bind(_assertThisInitialized(_this)); _this.onTransfer = _this.onTransfer.bind(_assertThisInitialized(_this)); return _this; } _createClass(PickList, [{ key: "getSourceSelection", value: function getSourceSelection() { return this.props.onSourceSelectionChange ? this.props.sourceSelection : this.state.sourceSelection; } }, { key: "getTargetSelection", value: function getTargetSelection() { return this.props.onTargetSelectionChange ? this.props.targetSelection : this.state.targetSelection; } }, { key: "onSourceReorder", value: function onSourceReorder(event) { this.handleChange(event, event.value, this.props.target); this.reorderedListElement = this.sourceListElement; this.reorderDirection = event.direction; } }, { key: "onTargetReorder", value: function onTargetReorder(event) { this.handleChange(event, this.props.source, event.value); this.reorderedListElement = this.targetListElement; this.reorderDirection = event.direction; } }, { key: "handleScrollPosition", value: function handleScrollPosition(listElement, direction) { if (listElement) { var listContainer = DomHandler.findSingle(listElement, '.p-picklist-list'); switch (direction) { case 'up': this.scrollInView(listContainer, -1); break; case 'top': listContainer.scrollTop = 0; break; case 'down': this.scrollInView(listContainer, 1); break; case 'bottom': listContainer.scrollTop = listContainer.scrollHeight; break; } } } }, { key: "handleChange", value: function handleChange(event, source, target) { if (this.props.onChange) { this.props.onChange({ originalEvent: event.originalEvent, source: source, target: target }); } } }, { key: "onTransfer", value: function onTransfer(event) { var originalEvent = event.originalEvent, source = event.source, target = event.target, direction = event.direction; switch (direction) { case 'toTarget': if (this.props.onMoveToTarget) { this.props.onMoveToTarget({ originalEvent: originalEvent, value: this.getSourceSelection() }); } break; case 'allToTarget': if (this.props.onMoveAllToTarget) { this.props.onMoveAllToTarget({ originalEvent: originalEvent, value: this.props.source }); } break; case 'toSource': if (this.props.onMoveToSource) { this.props.onMoveToSource({ originalEvent: originalEvent, value: this.getTargetSelection() }); } break; case 'allToSource': if (this.props.onMoveAllToSource) { this.props.onMoveAllToSource({ originalEvent: originalEvent, value: this.props.target }); } break; } this.onSelectionChange({ originalEvent: originalEvent, value: [] }, 'sourceSelection', this.props.onSourceSelectionChange); this.onSelectionChange({ originalEvent: originalEvent, value: [] }, 'targetSelection', this.props.onTargetSelectionChange); this.handleChange(event, source, target); } }, { key: "scrollInView", value: function scrollInView(listContainer) { var direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var selectedItems = listContainer.getElementsByClassName('p-highlight'); DomHandler.scrollInView(listContainer, direction === -1 ? selectedItems[0] : selectedItems[selectedItems.length - 1]); } }, { key: "onSelectionChange", value: function onSelectionChange(e, stateKey, callback) { if (callback) { callback(e); } else { this.setState(_defineProperty({}, stateKey, e.value)); } if (this.state.sourceSelection && this.state.sourceSelection.length && stateKey === 'targetSelection') { this.setState({ sourceSelection: [] }); } else if (this.state.targetSelection && this.state.targetSelection.length && stateKey === 'sourceSelection') { this.setState({ targetSelection: [] }); } } }, { key: "componentDidUpdate", value: function componentDidUpdate() { if (this.reorderedListElement) { this.handleScrollPosition(this.reorderedListElement, this.reorderDirection); this.reorderedListElement = null; this.reorderDirection = null; } } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-picklist p-component', this.props.className); var sourceSelection = this.getSourceSelection(); var targetSelection = this.getTargetSelection(); return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: className, style: this.props.style }, this.props.showSourceControls && /*#__PURE__*/React.createElement(PickListControls, { list: this.props.source, selection: sourceSelection, onReorder: this.onSourceReorder, className: "p-picklist-source-controls", dataKey: this.props.dataKey }), /*#__PURE__*/React.createElement(PickListSubList, { ref: function ref(el) { return _this2.sourceListElement = el; }, list: this.props.source, selection: sourceSelection, onSelectionChange: function onSelectionChange(e) { return _this2.onSelectionChange(e, 'sourceSelection', _this2.props.onSourceSelectionChange); }, itemTemplate: this.props.itemTemplate, header: this.props.sourceHeader, style: this.props.sourceStyle, className: "p-picklist-source-wrapper", listClassName: "p-picklist-source", metaKeySelection: this.props.metaKeySelection, tabIndex: this.props.tabIndex, dataKey: this.props.dataKey }), /*#__PURE__*/React.createElement(PickListTransferControls, { onTransfer: this.onTransfer, source: this.props.source, target: this.props.target, sourceSelection: sourceSelection, targetSelection: targetSelection, dataKey: this.props.dataKey }), /*#__PURE__*/React.createElement(PickListSubList, { ref: function ref(el) { return _this2.targetListElement = el; }, list: this.props.target, selection: targetSelection, onSelectionChange: function onSelectionChange(e) { return _this2.onSelectionChange(e, 'targetSelection', _this2.props.onTargetSelectionChange); }, itemTemplate: this.props.itemTemplate, header: this.props.targetHeader, style: this.props.targetStyle, className: "p-picklist-target-wrapper", listClassName: "p-picklist-target", metaKeySelection: this.props.metaKeySelection, tabIndex: this.props.tabIndex, dataKey: this.props.dataKey }), this.props.showTargetControls && /*#__PURE__*/React.createElement(PickListControls, { list: this.props.target, selection: targetSelection, onReorder: this.onTargetReorder, className: "p-picklist-target-controls", dataKey: this.props.dataKey })); } }]); return PickList; }(Component); _defineProperty(PickList, "defaultProps", { id: null, source: null, target: null, sourceHeader: null, targetHeader: null, style: null, className: null, sourceStyle: null, targetStyle: null, sourceSelection: null, targetSelection: null, showSourceControls: true, showTargetControls: true, metaKeySelection: true, tabIndex: 0, dataKey: null, itemTemplate: null, onChange: null, onMoveToSource: null, onMoveAllToSource: null, onMoveToTarget: null, onMoveAllToTarget: null, onSourceSelectionChange: null, onTargetSelectionChange: null }); export { PickList };
ajax/libs/primereact/7.0.1/progressbar/progressbar.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); 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 ProgressBar = /*#__PURE__*/function (_Component) { _inherits(ProgressBar, _Component); var _super = _createSuper(ProgressBar); function ProgressBar() { _classCallCheck(this, ProgressBar); return _super.apply(this, arguments); } _createClass(ProgressBar, [{ key: "renderLabel", value: function renderLabel() { if (this.props.showValue && this.props.value != null) { var label = this.props.displayValueTemplate ? this.props.displayValueTemplate(this.props.value) : this.props.value + this.props.unit; return /*#__PURE__*/React.createElement("div", { className: "p-progressbar-label" }, label); } return null; } }, { key: "renderDeterminate", value: function renderDeterminate() { var className = classNames('p-progressbar p-component p-progressbar-determinate', this.props.className); var label = this.renderLabel(); return /*#__PURE__*/React.createElement("div", { role: "progressbar", id: this.props.id, className: className, style: this.props.style, "aria-valuemin": "0", "aria-valuenow": this.props.value, "aria-valuemax": "100", "aria-label": this.props.value }, /*#__PURE__*/React.createElement("div", { className: "p-progressbar-value p-progressbar-value-animate", style: { width: this.props.value + '%', display: 'block', backgroundColor: this.props.color } }), label); } }, { key: "renderIndeterminate", value: function renderIndeterminate() { var className = classNames('p-progressbar p-component p-progressbar-indeterminate', this.props.className); return /*#__PURE__*/React.createElement("div", { role: "progressbar", id: this.props.id, className: className, style: this.props.style }, /*#__PURE__*/React.createElement("div", { className: "p-progressbar-indeterminate-container" }, /*#__PURE__*/React.createElement("div", { className: "p-progressbar-value p-progressbar-value-animate", style: { backgroundColor: this.props.color } }))); } }, { key: "render", value: function render() { if (this.props.mode === 'determinate') return this.renderDeterminate();else if (this.props.mode === 'indeterminate') return this.renderIndeterminate();else throw new Error(this.props.mode + " is not a valid mode for the ProgressBar. Valid values are 'determinate' and 'indeterminate'"); } }]); return ProgressBar; }(Component); _defineProperty(ProgressBar, "defaultProps", { id: null, value: null, showValue: true, unit: '%', style: null, className: null, mode: 'determinate', displayValueTemplate: null, color: null }); export { ProgressBar };
ajax/libs/primereact/6.5.0/messages/messages.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { Ripple, classNames, CSSTransition } from 'primereact/core'; import { TransitionGroup } from 'react-transition-group'; 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 _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$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 UIMessageComponent = /*#__PURE__*/function (_Component) { _inherits(UIMessageComponent, _Component); var _super = _createSuper$1(UIMessageComponent); function UIMessageComponent(props) { var _this; _classCallCheck(this, UIMessageComponent); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onClose = _this.onClose.bind(_assertThisInitialized(_this)); return _this; } _createClass(UIMessageComponent, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; if (!this.props.message.sticky) { this.timeout = setTimeout(function () { _this2.onClose(null); }, this.props.message.life || 3000); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.timeout) { clearTimeout(this.timeout); } } }, { key: "onClose", value: function onClose(event) { if (this.timeout) { clearTimeout(this.timeout); } if (this.props.onClose) { this.props.onClose(this.props.message); } if (event) { event.preventDefault(); event.stopPropagation(); } } }, { key: "onClick", value: function onClick() { if (this.props.onClick) { this.props.onClick(this.props.message); } } }, { key: "renderCloseIcon", value: function renderCloseIcon() { if (this.props.message.closable !== false) { return /*#__PURE__*/React.createElement("button", { type: "button", className: "p-message-close p-link", onClick: this.onClose }, /*#__PURE__*/React.createElement("i", { className: "p-message-close-icon pi pi-times" }), /*#__PURE__*/React.createElement(Ripple, null)); } return null; } }, { key: "renderMessage", value: function renderMessage() { if (this.props.message) { var _this$props$message = this.props.message, severity = _this$props$message.severity, content = _this$props$message.content, summary = _this$props$message.summary, detail = _this$props$message.detail; var icon = classNames('p-message-icon pi ', { 'pi-info-circle': severity === 'info', 'pi-check': severity === 'success', 'pi-exclamation-triangle': severity === 'warn', 'pi-times-circle': severity === 'error' }); return content || /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", { className: icon }), /*#__PURE__*/React.createElement("span", { className: "p-message-summary" }, summary), /*#__PURE__*/React.createElement("span", { className: "p-message-detail" }, detail)); } return null; } }, { key: "render", value: function render() { var severity = this.props.message.severity; var className = 'p-message p-component p-message-' + severity; var closeIcon = this.renderCloseIcon(); var message = this.renderMessage(); return /*#__PURE__*/React.createElement("div", { ref: this.props.forwardRef, className: className, onClick: this.onClick }, /*#__PURE__*/React.createElement("div", { className: "p-message-wrapper" }, message, closeIcon)); } }]); return UIMessageComponent; }(Component); _defineProperty(UIMessageComponent, "defaultProps", { message: null, onClose: null, onClick: null }); var UIMessage = /*#__PURE__*/React.forwardRef(function (props, ref) { return /*#__PURE__*/React.createElement(UIMessageComponent, _extends({ forwardRef: ref }, props)); }); 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 messageIdx = 0; var Messages = /*#__PURE__*/function (_Component) { _inherits(Messages, _Component); var _super = _createSuper(Messages); function Messages(props) { var _this; _classCallCheck(this, Messages); _this = _super.call(this, props); _this.state = { messages: [] }; _this.onClose = _this.onClose.bind(_assertThisInitialized(_this)); return _this; } _createClass(Messages, [{ key: "show", value: function show(value) { if (value) { var newMessages = []; if (Array.isArray(value)) { for (var i = 0; i < value.length; i++) { value[i].id = messageIdx++; newMessages = [].concat(_toConsumableArray(this.state.messages), _toConsumableArray(value)); } } else { value.id = messageIdx++; newMessages = this.state.messages ? [].concat(_toConsumableArray(this.state.messages), [value]) : [value]; } this.setState({ messages: newMessages }); } } }, { key: "clear", value: function clear() { this.setState({ messages: [] }); } }, { key: "replace", value: function replace(value) { var _this2 = this; this.setState({ messages: [] }, function () { return _this2.show(value); }); } }, { key: "onClose", value: function onClose(message) { var newMessages = this.state.messages.filter(function (msg) { return msg.id !== message.id; }); this.setState({ messages: newMessages }); if (this.props.onRemove) { this.props.onRemove(message); } } }, { key: "render", value: function render() { var _this3 = this; return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: this.props.className, style: this.props.style }, /*#__PURE__*/React.createElement(TransitionGroup, null, this.state.messages.map(function (message) { var messageRef = /*#__PURE__*/React.createRef(); return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: messageRef, key: message.id, classNames: "p-message", unmountOnExit: true, timeout: { enter: 300, exit: 300 }, options: _this3.props.transitionOptions }, /*#__PURE__*/React.createElement(UIMessage, { ref: messageRef, message: message, onClick: _this3.props.onClick, onClose: _this3.onClose })); }))); } }]); return Messages; }(Component); _defineProperty(Messages, "defaultProps", { id: null, className: null, style: null, transitionOptions: null, onRemove: null, onClick: null }); export { Messages };
ajax/libs/react-native-web/0.14.10/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/ExpansionPanel/ExpansionPanelContext.js
cdnjs/cdnjs
import React from 'react'; /** * @ignore - internal component. * @type {React.Context<{} | {expanded: boolean, disabled: boolean, toggle: () => void}>} */ var ExpansionPanelContext = React.createContext({}); if (process.env.NODE_ENV !== 'production') { ExpansionPanelContext.displayName = 'ExpansionPanelContext'; } export default ExpansionPanelContext;
ajax/libs/react-instantsearch/6.1.0/Connectors.js
cdnjs/cdnjs
/*! React InstantSearch 6.1.0 | © Algolia, inc. | https://github.com/algolia/react-instantsearch */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (global = global || self, 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; 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 _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 _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 _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 _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 _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); } function _typeof(obj) { if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") { _typeof = function _typeof(obj) { return _typeof2(obj); }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(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 _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); } var isArray = Array.isArray; var keyList = Object.keys; var hasProp = Object.prototype.hasOwnProperty; var fastDeepEqual = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { var arrA = isArray(a) , arrB = isArray(b) , i , length , key; if (arrA && arrB) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!equal(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 = keyList(a); length = keys.length; if (length !== keyList(b).length) return false; for (i = length; i-- !== 0;) if (!hasProp.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { key = keys[i]; if (!equal(a[key], b[key])) return false; } return true; } return a!==a && b!==b; }; 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 isPlainObject = function isPlainObject(value) { return _typeof(value) === 'object' && value !== null && !Array.isArray(value); }; var removeEmptyKey = function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (!isPlainObject(value)) { return; } if (!objectHasKeys(value)) { delete obj[key]; } else { removeEmptyKey(value); } }); return obj; }; function addAbsolutePositions(hits, hitsPerPage, page) { return hits.map(function (hit, index) { return _objectSpread({}, hit, { __position: hitsPerPage * page + index + 1 }); }); } function addQueryID(hits, queryID) { if (!queryID) { return hits; } return hits.map(function (hit) { return _objectSpread({}, hit, { __queryID: queryID }); }); } function find(array, comparator) { if (!Array.isArray(array)) { return undefined; } for (var i = 0; i < array.length; i++) { if (comparator(array[i])) { return array[i]; } } return undefined; } function objectHasKeys(object) { return object && Object.keys(object).length > 0; } // https://github.com/babel/babel/blob/3aaafae053fa75febb3aa45d45b6f00646e30ba4/packages/babel-helpers/src/helpers.js#L604-L620 function omit(source, excluded) { if (source === null || source === undefined) { return {}; } var target = {}; var sourceKeys = Object.keys(source); for (var i = 0; i < sourceKeys.length; i++) { var _key = sourceKeys[i]; if (excluded.indexOf(_key) >= 0) { // eslint-disable-next-line no-continue continue; } target[_key] = source[_key]; } return target; } /** * Retrieve the value at a path of the object: * * @example * getPropertyByPath( * { test: { this: { function: [{ now: { everyone: true } }] } } }, * 'test.this.function[0].now.everyone' * ); // true * * getPropertyByPath( * { test: { this: { function: [{ now: { everyone: true } }] } } }, * ['test', 'this', 'function', 0, 'now', 'everyone'] * ); // true * * @param object Source object to query * @param path either an array of properties, or a string form of the properties, separated by . */ var getPropertyByPath = function getPropertyByPath(object, path) { return (Array.isArray(path) ? path : path.replace(/\[(\d+)]/g, '.$1').split('.')).reduce(function (current, key) { return current ? current[key] : undefined; }, object); }; var _createContext = React.createContext({ onInternalStateUpdate: function onInternalStateUpdate() { return undefined; }, createHrefForState: function createHrefForState() { return '#'; }, onSearchForFacetValues: function onSearchForFacetValues() { return undefined; }, onSearchStateChange: function onSearchStateChange() { return undefined; }, onSearchParameters: function onSearchParameters() { return undefined; }, store: {}, widgetsManager: {}, mainTargetedIndex: '' }), InstantSearchConsumer = _createContext.Consumer, InstantSearchProvider = _createContext.Provider; var _createContext2 = React.createContext(undefined), IndexConsumer = _createContext2.Consumer, IndexProvider = _createContext2.Provider; /** * 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 createConnectorWithoutContext(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var isWidget = typeof connectorDesc.getSearchParameters === 'function' || typeof connectorDesc.getMetadata === 'function' || typeof connectorDesc.transitionState === 'function'; return function (Composed) { var Connector = /*#__PURE__*/ function (_Component) { _inherits(Connector, _Component); function Connector(props) { var _this; _classCallCheck(this, Connector); _this = _possibleConstructorReturn(this, _getPrototypeOf(Connector).call(this, props)); _defineProperty(_assertThisInitialized(_this), "unsubscribe", void 0); _defineProperty(_assertThisInitialized(_this), "unregisterWidget", void 0); _defineProperty(_assertThisInitialized(_this), "isUnmounting", false); _defineProperty(_assertThisInitialized(_this), "state", { providedProps: _this.getProvidedProps(_this.props) }); _defineProperty(_assertThisInitialized(_this), "refine", function () { var _ref; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this.props.contextValue.onInternalStateUpdate( // refine will always be defined here because the prop is only given conditionally (_ref = connectorDesc.refine).call.apply(_ref, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args))); }); _defineProperty(_assertThisInitialized(_this), "createURL", function () { var _ref2; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return _this.props.contextValue.createHrefForState( // refine will always be defined here because the prop is only given conditionally (_ref2 = connectorDesc.refine).call.apply(_ref2, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args))); }); _defineProperty(_assertThisInitialized(_this), "searchForFacetValues", function () { var _ref3; for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } _this.props.contextValue.onSearchForFacetValues( // searchForFacetValues will always be defined here because the prop is only given conditionally (_ref3 = connectorDesc.searchForFacetValues).call.apply(_ref3, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args))); }); if (connectorDesc.getSearchParameters) { _this.props.contextValue.onSearchParameters(connectorDesc.getSearchParameters.bind(_assertThisInitialized(_this)), { ais: _this.props.contextValue, multiIndexContext: _this.props.indexContextValue }, _this.props); } return _this; } _createClass(Connector, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; this.unsubscribe = this.props.contextValue.store.subscribe(function () { if (!_this2.isUnmounting) { _this2.setState({ providedProps: _this2.getProvidedProps(_this2.props) }); } }); if (isWidget) { this.unregisterWidget = this.props.contextValue.widgetsManager.registerWidget(this); } } }, { key: "shouldComponentUpdate", value: function shouldComponentUpdate(nextProps, nextState) { if (typeof connectorDesc.shouldComponentUpdate === 'function') { return connectorDesc.shouldComponentUpdate.call(this, this.props, nextProps, this.state, nextState); } var propsEqual = shallowEqual(this.props, nextProps); if (this.state.providedProps === null || nextState.providedProps === null) { if (this.state.providedProps === nextState.providedProps) { return !propsEqual; } return true; } return !propsEqual || !shallowEqual(this.state.providedProps, nextState.providedProps); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (!fastDeepEqual(prevProps, this.props)) { this.setState({ providedProps: this.getProvidedProps(this.props) }); if (isWidget) { this.props.contextValue.widgetsManager.update(); if (typeof connectorDesc.transitionState === 'function') { this.props.contextValue.onSearchStateChange(connectorDesc.transitionState.call(this, this.props, this.props.contextValue.store.getState().widgets, this.props.contextValue.store.getState().widgets)); } } } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.isUnmounting = true; if (this.unsubscribe) { this.unsubscribe(); } if (this.unregisterWidget) { this.unregisterWidget(); if (typeof connectorDesc.cleanUp === 'function') { var nextState = connectorDesc.cleanUp.call(this, this.props, this.props.contextValue.store.getState().widgets); this.props.contextValue.store.setState(_objectSpread({}, this.props.contextValue.store.getState(), { widgets: nextState })); this.props.contextValue.onSearchStateChange(removeEmptyKey(nextState)); } } } }, { key: "getProvidedProps", value: function getProvidedProps(props) { var _this$props$contextVa = this.props.contextValue.store.getState(), widgets = _this$props$contextVa.widgets, results = _this$props$contextVa.results, resultsFacetValues = _this$props$contextVa.resultsFacetValues, searching = _this$props$contextVa.searching, searchingForFacetValues = _this$props$contextVa.searchingForFacetValues, isSearchStalled = _this$props$contextVa.isSearchStalled, metadata = _this$props$contextVa.metadata, error = _this$props$contextVa.error; var searchResults = { results: results, searching: searching, searchingForFacetValues: searchingForFacetValues, isSearchStalled: isSearchStalled, error: error }; return connectorDesc.getProvidedProps.call(this, props, widgets, searchResults, metadata, // @MAJOR: move this attribute on the `searchResults` it doesn't // makes sense to have it into a separate argument. The search // flags are on the object why not the results? resultsFacetValues); } }, { key: "getSearchParameters", value: function getSearchParameters(searchParameters) { if (typeof connectorDesc.getSearchParameters === 'function') { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.props.contextValue.store.getState().widgets); } return null; } }, { key: "getMetadata", value: function getMetadata(nextWidgetsState) { if (typeof connectorDesc.getMetadata === 'function') { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: "transitionState", value: function transitionState(prevWidgetsState, nextWidgetsState) { if (typeof connectorDesc.transitionState === 'function') { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { key: "render", value: function render() { var _this$props = this.props, contextValue = _this$props.contextValue, props = _objectWithoutProperties(_this$props, ["contextValue"]); var providedProps = this.state.providedProps; if (providedProps === null) { return null; } var refineProps = typeof connectorDesc.refine === 'function' ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = typeof connectorDesc.searchForFacetValues === 'function' ? { searchForItems: this.searchForFacetValues } : {}; return React__default.createElement(Composed, _extends({}, props, providedProps, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component); _defineProperty(Connector, "displayName", "".concat(connectorDesc.displayName, "(").concat(getDisplayName(Composed), ")")); _defineProperty(Connector, "propTypes", connectorDesc.propTypes); _defineProperty(Connector, "defaultProps", connectorDesc.defaultProps); return Connector; }; } var createConnectorWithContext = function createConnectorWithContext(connectorDesc) { return function (Composed) { var Connector = createConnectorWithoutContext(connectorDesc)(Composed); var ConnectorWrapper = function ConnectorWrapper(props) { return React__default.createElement(InstantSearchConsumer, null, function (contextValue) { return React__default.createElement(IndexConsumer, null, function (indexContextValue) { return React__default.createElement(Connector, _extends({ contextValue: contextValue, indexContextValue: indexContextValue }, props)); }); }); }; return ConnectorWrapper; }; }; 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, isHighlighted: boolean}. */ function parseHighlightedAttribute(_ref) { var preTag = _ref.preTag, postTag = _ref.postTag, _ref$highlightedValue = _ref.highlightedValue, highlightedValue = _ref$highlightedValue === void 0 ? '' : _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 * highlightPostTag 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 === void 0 ? '<em>' : _ref2$preTag, _ref2$postTag = _ref2.postTag, postTag = _ref2$postTag === void 0 ? '</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 = getPropertyByPath(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 }); } function getIndexId(context) { return hasMultipleIndices(context) ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (searchResults.results) { if (searchResults.results.hits) { return searchResults.results; } var indexId = getIndexId(context); if (searchResults.results[indexId]) { return searchResults.results[indexId]; } } return null; } function hasMultipleIndices(context) { return context && context.multiIndexContext; } // eslint-disable-next-line max-params function refineValue(searchState, nextRefinement, context, resetPage, namespace) { if (hasMultipleIndices(context)) { var indexId = getIndexId(context); return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, indexId, 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, indexId, resetPage) { var page = resetPage ? { page: 1 } : undefined; var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], nextRefinement, page))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, nextRefinement, page))); return _objectSpread({}, searchState, { indices: state }); } function refineSingleIndex(searchState, nextRefinement, resetPage) { var page = resetPage ? { page: 1 } : undefined; return _objectSpread({}, searchState, nextRefinement, page); } // eslint-disable-next-line max-params function refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) { var _objectSpread4; var page = resetPage ? { page: 1 } : undefined; var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], (_objectSpread4 = {}, _defineProperty(_objectSpread4, namespace, _objectSpread({}, searchState.indices[indexId][namespace], nextRefinement)), _defineProperty(_objectSpread4, "page", 1), _objectSpread4)))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread(_defineProperty({}, namespace, nextRefinement), page))); return _objectSpread({}, searchState, { indices: state }); } function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) { var page = resetPage ? { page: 1 } : undefined; return _objectSpread({}, searchState, _defineProperty({}, namespace, _objectSpread({}, 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 }; } function hasRefinements(_ref) { var multiIndex = _ref.multiIndex, indexId = _ref.indexId, namespace = _ref.namespace, attributeName = _ref.attributeName, id = _ref.id, searchState = _ref.searchState; if (multiIndex && namespace) { return searchState.indices && searchState.indices[indexId] && searchState.indices[indexId][namespace] && Object.hasOwnProperty.call(searchState.indices[indexId][namespace], attributeName); } if (multiIndex) { return searchState.indices && searchState.indices[indexId] && Object.hasOwnProperty.call(searchState.indices[indexId], id); } if (namespace) { return searchState[namespace] && Object.hasOwnProperty.call(searchState[namespace], attributeName); } return Object.hasOwnProperty.call(searchState, id); } function getRefinements(_ref2) { var multiIndex = _ref2.multiIndex, indexId = _ref2.indexId, namespace = _ref2.namespace, attributeName = _ref2.attributeName, id = _ref2.id, searchState = _ref2.searchState; if (multiIndex && namespace) { return searchState.indices[indexId][namespace][attributeName]; } if (multiIndex) { return searchState.indices[indexId][id]; } if (namespace) { return searchState[namespace][attributeName]; } return searchState[id]; } function getCurrentRefinementValue(props, searchState, context, id, defaultValue) { var indexId = getIndexId(context); var _getNamespaceAndAttri = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri.namespace, attributeName = _getNamespaceAndAttri.attributeName; var multiIndex = hasMultipleIndices(context); var args = { multiIndex: multiIndex, indexId: indexId, namespace: namespace, attributeName: attributeName, id: id, searchState: searchState }; var hasRefinementsValue = hasRefinements(args); if (hasRefinementsValue) { return getRefinements(args); } if (props.defaultRefinement) { return props.defaultRefinement; } return defaultValue; } function cleanUpValue(searchState, context, id) { var indexId = getIndexId(context); var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri2.namespace, attributeName = _getNamespaceAndAttri2.attributeName; if (hasMultipleIndices(context) && Boolean(searchState.indices)) { return cleanUpValueWithMultiIndex({ attribute: attributeName, searchState: searchState, indexId: indexId, id: id, namespace: namespace }); } return cleanUpValueWithSingleIndex({ attribute: attributeName, searchState: searchState, id: id, namespace: namespace }); } function cleanUpValueWithSingleIndex(_ref3) { var searchState = _ref3.searchState, id = _ref3.id, namespace = _ref3.namespace, attribute = _ref3.attribute; if (namespace) { return _objectSpread({}, searchState, _defineProperty({}, namespace, omit(searchState[namespace], [attribute]))); } return omit(searchState, [id]); } function cleanUpValueWithMultiIndex(_ref4) { var searchState = _ref4.searchState, indexId = _ref4.indexId, id = _ref4.id, namespace = _ref4.namespace, attribute = _ref4.attribute; var indexSearchState = searchState.indices[indexId]; if (namespace && indexSearchState) { return _objectSpread({}, searchState, { indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, indexSearchState, _defineProperty({}, namespace, omit(indexSearchState[namespace], [attribute]))))) }); } if (indexSearchState) { return _objectSpread({}, searchState, { indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, omit(indexSearchState, [id]))) }); } return searchState; } function getId() { return 'configure'; } var connectConfigure = createConnectorWithContext({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var children = props.children, contextValue = props.contextValue, indexContextValue = props.indexContextValue, items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var children = props.children, contextValue = props.contextValue, indexContextValue = props.indexContextValue, items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]); var propKeys = Object.keys(props); var nonPresentKeys = this._props ? Object.keys(this._props).filter(function (prop) { return propKeys.indexOf(prop) === -1; }) : []; this._props = props; var nextValue = _defineProperty({}, id, _objectSpread({}, omit(nextSearchState[id], nonPresentKeys), items)); return refineValue(nextSearchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var indexId = getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }); var subState = hasMultipleIndices({ ais: props.contextValue, multiIndexContext: props.indexContextValue }) && searchState.indices ? searchState.indices[indexId] : 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({}, id, configureState); return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); if (typeof global$1.setTimeout === 'function') ; if (typeof global$1.clearTimeout === 'function') ; // 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() }; function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /* 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; function emptyFunction() {} var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret_1) { // 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, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim }; ReactPropTypes.checkPropTypes = emptyFunction; 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(); } }); function clone(value) { if (typeof value === 'object' && value !== null) { return _merge(Array.isArray(value) ? [] : {}, value); } return value; } function isObjectOrArrayOrFunction(value) { return ( typeof value === 'function' || Array.isArray(value) || Object.prototype.toString.call(value) === '[object Object]' ); } function _merge(target, source) { if (target === source) { return target; } for (var key in source) { if (!Object.prototype.hasOwnProperty.call(source, key)) { continue; } var sourceVal = source[key]; var targetVal = target[key]; if (typeof targetVal !== 'undefined' && typeof sourceVal === 'undefined') { continue; } if (isObjectOrArrayOrFunction(targetVal) && isObjectOrArrayOrFunction(sourceVal)) { target[key] = _merge(targetVal, sourceVal); } else { target[key] = clone(sourceVal); } } return target; } /** * This method is like Object.assign, but recursively merges own and inherited * enumerable keyed properties of source objects into the destination object. * * NOTE: this behaves like lodash/merge, but: * - does mutate functions if they are a source * - treats non-plain objects as plain * - does not work for circular objects * - treats sparse arrays as sparse * - does not convert Array-like objects (Arguments, NodeLists, etc.) to arrays * * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. */ function merge(target) { if (!isObjectOrArrayOrFunction(target)) { target = {}; } for (var i = 1, l = arguments.length; i < l; i++) { var source = arguments[i]; if (isObjectOrArrayOrFunction(source)) { _merge(target, source); } } return target; } var merge_1 = merge; // NOTE: this behaves like lodash/defaults, but doesn't mutate the target var defaultsPure = function defaultsPure() { var sources = Array.prototype.slice.call(arguments); return sources.reduceRight(function(acc, source) { Object.keys(Object(source)).forEach(function(key) { if (source[key] !== undefined) { acc[key] = source[key]; } }); return acc; }, {}); }; function intersection(arr1, arr2) { return arr1.filter(function(value, index) { return ( arr2.indexOf(value) > -1 && arr1.indexOf(value) === index /* skips duplicates */ ); }); } var intersection_1 = intersection; // @MAJOR can be replaced by native Array#find when we change support var find$1 = function find(array, comparator) { if (!Array.isArray(array)) { return undefined; } for (var i = 0; i < array.length; i++) { if (comparator(array[i])) { return array[i]; } } }; function valToNumber(v) { if (typeof v === 'number') { return v; } else if (typeof v === 'string') { return parseFloat(v); } else if (Array.isArray(v)) { return v.map(valToNumber); } throw new Error('The value should be a number, a parsable string or an array of those.'); } var valToNumber_1 = valToNumber; // https://github.com/babel/babel/blob/3aaafae053fa75febb3aa45d45b6f00646e30ba4/packages/babel-helpers/src/helpers.js#L604-L620 function _objectWithoutPropertiesLoose$1(source, excluded) { if (source === null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key; var i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } var omit$1 = _objectWithoutPropertiesLoose$1; function objectHasKeys$1(obj) { return obj && Object.keys(obj).length > 0; } var objectHasKeys_1 = objectHasKeys$1; /** * 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 defaultsPure({}, 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 (value === undefined) { // we use the "filter" form of clearRefinement, since it leaves empty values as-is // the form with a string will remove the attribute completely return lib.clearRefinement(refinementList, function(v, f) { return attribute === f; }); } 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 (value === undefined) 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 (attribute === undefined) { if (!objectHasKeys_1(refinementList)) { return refinementList; } return {}; } else if (typeof attribute === 'string') { return omit$1(refinementList, attribute); } else if (typeof attribute === 'function') { var hasChanged = false; var newRefinementList = Object.keys(refinementList).reduce(function(memo, key) { var values = refinementList[key] || []; var facetList = values.filter(function(value) { return !attribute(value, key, refinementType); }); if (facetList.length !== values.length) { hasChanged = true; } memo[key] = facetList; 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 containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (refinementValue === undefined || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return refinementList[attribute].indexOf(refinementValueAsString) !== -1; } }; var RefinementList = lib; /** * isEqual, but only for numeric refinement values, possible values: * - 5 * - [5] * - [[5]] * - [[5,5],[4]] */ function isEqualNumericRefinement(a, b) { if (Array.isArray(a) && Array.isArray(b)) { return ( a.length === b.length && a.every(function(el, i) { return isEqualNumericRefinement(b[i], el); }) ); } return a === b; } /** * like _.find but using deep equality to be able to use it * to find arrays. * @private * @param {any[]} array array to search into (elements are base or array of base) * @param {any} searchedValue the value we're looking for (base or array of base) * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find$1(array, function(currentValue) { return isEqualNumericRefinement(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) : {}; /** * 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 || {}; var self = this; Object.keys(params).forEach(function(paramName) { var isKeyKnown = SearchParameters.PARAMETERS.indexOf(paramName) !== -1; var isValueDefined = params[paramName] !== undefined; if (!isKeyKnown && isValueDefined) { self[paramName] = params[paramName]; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = Object.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' ]; numberKeys.forEach(function(k) { var value = partialState[k]; if (typeof value === 'string') { var parsedValue = parseFloat(value); // global isNaN is ok to use here, value is only number or NaN 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 = {}; Object.keys(partialState.numericRefinements).forEach(function(attribute) { var operators = partialState.numericRefinements[attribute] || {}; numericRefinements[attribute] = {}; Object.keys(operators).forEach(function(operator) { var values = operators[operator]; var parsedValues = values.map(function(v) { if (Array.isArray(v)) { return v.map(function(vPrime) { if (typeof vPrime === 'string') { return parseFloat(vPrime); } return vPrime; }); } else if (typeof v === 'string') { 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); var hierarchicalFacets = newParameters.hierarchicalFacets || []; hierarchicalFacets.forEach(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 && objectHasKeys_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 (objectHasKeys_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 patch = { numericRefinements: this._clearNumericRefinements(attribute), facetsRefinements: RefinementList.clearRefinement( this.facetsRefinements, attribute, 'conjunctiveFacet' ), facetsExcludes: RefinementList.clearRefinement( this.facetsExcludes, attribute, 'exclude' ), disjunctiveFacetsRefinements: RefinementList.clearRefinement( this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet' ), hierarchicalFacetsRefinements: RefinementList.clearRefinement( 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)) { return []; } 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)) { return []; } 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)) { return []; } 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) { if (!this.isNumericRefined(attribute, operator, paramValue)) { return this; } return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return ( key === attribute && value.op === operator && isEqualNumericRefinement(value.val, valToNumber_1(paramValue)) ); }) }); } 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 (attribute === undefined) { if (!objectHasKeys_1(this.numericRefinements)) { return this.numericRefinements; } return {}; } else if (typeof attribute === 'string') { if (!objectHasKeys_1(this.numericRefinements[attribute])) { return this.numericRefinements; } return omit$1(this.numericRefinements, attribute); } else if (typeof attribute === 'function') { var hasChanged = false; var numericRefinements = this.numericRefinements; var newNumericRefinements = Object.keys(numericRefinements).reduce(function(memo, key) { var operators = numericRefinements[key]; var operatorList = {}; operators = operators || {}; Object.keys(operators).forEach(function(operator) { var values = operators[operator] || []; var outValues = []; values.forEach(function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (outValues.length !== values.length) { hasChanged = true; } operatorList[operator] = outValues; }); 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: this.facets.filter(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: this.disjunctiveFacets.filter(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: this.hierarchicalFacets.filter(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: this.tagRefinements.filter(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: defaultsPure({}, 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.'); } if (!this.isHierarchicalFacet(facet)) { throw new Error(facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaultsPure({}, 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)) { return this; } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaultsPure({}, 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 this.disjunctiveFacets.indexOf(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 this.facets.indexOf(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)) { return false; } 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)) { return false; } 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)) { return false; } 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)) { return false; } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return refinements.indexOf(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 (value === undefined && operator === undefined) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && this.numericRefinements[attribute][operator] !== undefined; if (value === undefined || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber_1(value); var isAttributeValueDefined = findArray(this.numericRefinements[attribute][operator], parsedValue) !== undefined; 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 this.tagRefinements.indexOf(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() { var self = this; // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection_1( Object.keys(this.numericRefinements).filter(function(facet) { return Object.keys(self.numericRefinements[facet]).length > 0; }), this.disjunctiveFacets ); return Object.keys(this.disjunctiveFacetsRefinements).filter(function(facet) { return self.disjunctiveFacetsRefinements[facet].length > 0; }) .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() { var self = this; return intersection_1( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index this.hierarchicalFacets.map(function(facet) { return facet.name; }), Object.keys(this.hierarchicalFacetsRefinements).filter(function(facet) { return self.hierarchicalFacetsRefinements[facet].length > 0; }) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return this.disjunctiveFacets.filter(function(f) { return refinedFacets.indexOf(f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; var self = this; Object.keys(this).forEach(function(paramName) { var paramValue = self[paramName]; if (managedParameters.indexOf(paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * 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 self = this; var nextWithNumbers = SearchParameters._parseNumbers(params); var previousPlainObject = Object.keys(this).reduce(function(acc, key) { acc[key] = self[key]; return acc; }, {}); var nextPlainObject = Object.keys(nextWithNumbers).reduce( function(previous, key) { var isPreviousValueDefined = previous[key] !== undefined; var isNextValueDefined = nextWithNumbers[key] !== undefined; if (isPreviousValueDefined && !isNextValueDefined) { return omit$1(previous, [key]); } if (isNextValueDefined) { previous[key] = nextWithNumbers[key]; } return previous; }, previousPlainObject ); return new this.constructor(nextPlainObject); }, /** * Returns a new instance with the page reset. Two scenarios possible: * the page is omitted -> return the given instance * the page is set -> return a new instance with a page of 0 * @return {SearchParameters} a new updated instance */ resetPage: function() { if (this.page === undefined) { return this; } return this.setPage(0); }, /** * 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, function(f) { return f.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)) { return []; } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return path.map(function(part) { return part.trim(); }); }, 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; function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined; var valIsNull = value === null; var othIsDefined = other !== undefined; var othIsNull = other === null; if ( (!othIsNull && value > other) || (valIsNull && othIsDefined) || !valIsDefined ) { return 1; } if ( (!valIsNull && value < other) || (othIsNull && valIsDefined) || !othIsDefined ) { return -1; } } return 0; } /** * @param {Array<object>} collection object with keys in attributes * @param {Array<string>} iteratees attributes * @param {Array<string>} orders asc | desc */ function orderBy(collection, iteratees, orders) { if (!Array.isArray(collection)) { return []; } if (!Array.isArray(orders)) { orders = []; } var result = collection.map(function(value, index) { return { criteria: iteratees.map(function(iteratee) { return value[iteratee]; }), index: index, value: value }; }); result.sort(function comparer(object, other) { var index = -1; while (++index < object.criteria.length) { var res = compareAscending(object.criteria[index], other.criteria[index]); if (res) { if (index >= orders.length) { return res; } if (orders[index] === 'desc') { return -res; } return res; } } // This 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; }); return result.map(function(res) { return res.value; }); } var orderBy_1 = orderBy; var compact = function compact(array) { if (!Array.isArray(array)) { return []; } return array.filter(Boolean); }; // @MAJOR can be replaced by native Array#findIndex when we change support var findIndex = function find(array, comparator) { if (!Array.isArray(array)) { return -1; } for (var i = 0; i < array.length; i++) { if (comparator(array[i])) { return i; } } return -1; }; /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @param {string[]} [defaults] array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ var formatSort = function formatSort(sortBy, defaults) { var defaultInstructions = (defaults || []).map(function(sort) { return sort.split(':'); }); return sortBy.reduce( function preparePredicate(out, sort) { var sortInstruction = sort.split(':'); var matchingDefault = find$1(defaultInstructions, function( defaultInstruction ) { return defaultInstruction[0] === sortInstruction[0]; }); if (sortInstruction.length > 1 || !matchingDefault) { out[0].push(sortInstruction[0]); out[1].push(sortInstruction[1]); return out; } out[0].push(matchingDefault[0]); out[1].push(matchingDefault[1]); return out; }, [[], []] ); }; 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 rootExhaustive = hierarchicalFacetResult.every(function(facetResult) { return facetResult.exhaustive; }); var generateTreeFn = generateHierarchicalTree( sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement ); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice( hierarchicalRootPath.split(hierarchicalSeparator).length ); } return results.reduce(generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path exhaustive: rootExhaustive, 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) { /** * @type {object[]]} hierarchical data */ var data = parent && Array.isArray(parent.data) ? parent.data : []; parent = find$1(data, function(subtree) { return subtree.isRefined; }); 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 picked = Object.keys(hierarchicalFacetResult.data) .map(function(facetValue) { return [facetValue, hierarchicalFacetResult.data[facetValue]]; }) .filter(function(tuple) { var facetValue = tuple[0]; return onlyMatchingTree( facetValue, parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel ); }); parent.data = orderBy_1( picked.map(function(tuple) { var facetValue = tuple[0]; var facetCount = tuple[1]; return format( facetCount, facetValue, hierarchicalSeparator, currentRefinement, hierarchicalFacetResult.exhaustive ); }), sortBy[0], sortBy[1] ); } return hierarchicalTree; }; } function onlyMatchingTree( facetValue, parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel ) { // 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 format( facetCount, facetValue, hierarchicalSeparator, currentRefinement, exhaustive ) { var parts = facetValue.split(hierarchicalSeparator); return { name: parts[parts.length - 1].trim(), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, exhaustive: exhaustive, 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 */ /** * @param {string[]} attributes */ function getIndices(attributes) { var indices = {}; attributes.forEach(function(val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } /** * @typedef {Object} HierarchicalFacet * @property {string} name * @property {string[]} attributes */ /** * @param {HierarchicalFacet[]} hierarchicalFacets * @param {string} hierarchicalAttributeName */ function findMatchingHierarchicalFacetFromAttributeName( hierarchicalFacets, hierarchicalAttributeName ) { return find$1(hierarchicalFacets, function facetKeyMatchesAttribute( hierarchicalFacet ) { var facetNames = hierarchicalFacet.attributes || []; return facetNames.indexOf(hierarchicalAttributeName) > -1; }); } /*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 = results.reduce(function(sum, result) { return result.processingTimeMS === undefined ? sum : sum + result.processingTimeMS; }, 0); /** * 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. * * getRankingInfo needs to be set to `true` for this to be returned * * @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 = state.hierarchicalFacets.map(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 information from the first, general, response. var mainFacets = mainSubResponse.facets || {}; Object.keys(mainFacets).forEach(function(facetKey) { var facetValueObject = mainFacets[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, function(f) { return f.name === hierarchicalFacet.name; }); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = state.disjunctiveFacets.indexOf(facetKey) !== -1; var isFacetConjunctive = state.facets.indexOf(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 disjunctiveFacets.forEach(function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var facets = result && result.facets ? result.facets : {}; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. Object.keys(facets).forEach(function(dfacet) { var facetResults = facets[dfacet]; var position; if (hierarchicalFacet) { position = findIndex(state.hierarchicalFacets, function(f) { return f.name === hierarchicalFacet.name; }); var attributeIndex = findIndex(self.hierarchicalFacets[position], function(f) { return f.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: defaultsPure({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { state.disjunctiveFacetsRefinements[dfacet].forEach(function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && state.disjunctiveFacetsRefinements[dfacet].indexOf(refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them state.getRefinedHierarchicalFacets().forEach(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]; var facets = result && result.facets ? result.facets : {}; Object.keys(facets).forEach(function(dfacet) { var facetResults = facets[dfacet]; var position = findIndex(state.hierarchicalFacets, function(f) { return f.name === hierarchicalFacet.name; }); var attributeIndex = findIndex(self.hierarchicalFacets[position], function(f) { return f.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 = defaultsPure( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes Object.keys(state.facetsExcludes).forEach(function(facetName) { var excludes = state.facetsExcludes[facetName]; var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; excludes.forEach(function(facetValue) { self.facets[position] = self.facets[position] || {name: facetName}; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); /** * @type {Array} */ this.hierarchicalFacets = this.hierarchicalFacets.map(generateHierarchicalTree_1(state)); /** * @type {Array} */ this.facets = compact(this.facets); /** * @type {Array} */ this.disjunctiveFacets = compact(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) { function predicate(facet) { return facet.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) { function predicate(facet) { return facet.name === attribute; } if (results._state.isConjunctiveFacet(attribute)) { var facet = find$1(results.facets, predicate); if (!facet) return []; return Object.keys(facet.data).map(function(name) { return { name: name, count: facet.data[name], isRefined: results._state.isFacetRefined(attribute, name), isExcluded: results._state.isExcludeRefined(attribute, name) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find$1(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return Object.keys(disjunctiveFacet.data).map(function(name) { return { name: name, count: disjunctiveFacet.data[name], isRefined: results._state.isDisjunctiveFacetRefined(attribute, name) }; }); } 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 = node.data.map(function(childNode) { return recSort(sortFn, childNode); }); 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|undefined} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('result', function(event){ * //get values ordered only by name ascending using the string predicate * event.results.getFacetValues('city', {sortBy: ['name:asc']}); * //get values ordered only by count ascending using a function * event.results.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) { return undefined; } var options = defaultsPure({}, 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(function(hierarchicalFacetValues) { return orderBy_1(hierarchicalFacetValues, order[0], order[1]); }, facetValues); } else if (typeof options.sortBy === 'function') { 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(function(data) { return vanillaSortFn(options.sortBy, data); }, 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); } return undefined; }; /** * @typedef {Object} FacetListItem * @property {string} name */ /** * @param {FacetListItem[]} facetList (has more items, but enough for here) * @param {string} facetName */ function getFacetStatsIfAvailable(facetList, facetName) { var data = find$1(facetList, function(facet) { return facet.name === facetName; }); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhaustiveness for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * Note that for a numeric refinement, results are grouped per operator, this * means that it will return responses for operators which are empty. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function() { var state = this._state; var results = this; var res = []; Object.keys(state.facetsRefinements).forEach(function(attributeName) { state.facetsRefinements[attributeName].forEach(function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); Object.keys(state.facetsExcludes).forEach(function(attributeName) { state.facetsExcludes[attributeName].forEach(function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); Object.keys(state.disjunctiveFacetsRefinements).forEach(function(attributeName) { state.disjunctiveFacetsRefinements[attributeName].forEach(function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); Object.keys(state.hierarchicalFacetsRefinements).forEach(function(attributeName) { state.hierarchicalFacetsRefinements[attributeName].forEach(function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); Object.keys(state.numericRefinements).forEach(function(attributeName) { var operators = state.numericRefinements[attributeName]; Object.keys(operators).forEach(function(operator) { operators[operator].forEach(function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); state.tagRefinements.forEach(function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; /** * @typedef {Object} Facet * @property {string} name * @property {Object} data * @property {boolean} exhaustive */ /** * @param {*} state * @param {*} type * @param {string} attributeName * @param {*} name * @param {Facet[]} resultsFacets */ function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find$1(resultsFacets, function(f) { return f.name === attributeName; }); var count = facet && facet.data && facet.data[name] ? facet.data[name] : 0; var exhaustive = (facet && facet.exhaustive) || false; return { type: type, attributeName: attributeName, name: name, count: count, exhaustive: exhaustive }; } /** * @param {*} state * @param {string} attributeName * @param {*} name * @param {Facet[]} resultsFacets */ function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var separator = state._getHierarchicalFacetSeparator(facetDeclaration); var split = name.split(separator); var rootFacet = find$1(resultsFacets, function(facet) { return facet.name === attributeName; }); var facet = split.reduce(function(intermediateFacet, part) { var newFacet = intermediateFacet && find$1(intermediateFacet.data, function(f) { return f.name === part; }); return newFacet !== undefined ? newFacet : intermediateFacet; }, rootFacet); var count = (facet && facet.count) || 0; var exhaustive = (facet && facet.exhaustive) || false; var path = (facet && facet.path) || ''; return { type: 'hierarchical', attributeName: attributeName, name: path, count: count, exhaustive: exhaustive }; } var SearchResults_1 = SearchResults; // 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(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; } function inherits(ctor, superCtor) { ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } var inherits_1 = inherits; /** * 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; } inherits_1(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 state.getRefinedDisjunctiveFacets().forEach(function(refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated state.getRefinedHierarchicalFacets().forEach(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 = []; Object.keys(state.numericRefinements).forEach(function(attribute) { var operators = state.numericRefinements[attribute] || {}; Object.keys(operators).forEach(function(operator) { var values = operators[operator] || []; if (facetName !== attribute) { values.forEach(function(value) { if (Array.isArray(value)) { var vs = value.map(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 = []; var facetsRefinements = state.facetsRefinements || {}; Object.keys(facetsRefinements).forEach(function(facetName) { var facetValues = facetsRefinements[facetName] || []; facetValues.forEach(function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); var facetsExcludes = state.facetsExcludes || {}; Object.keys(facetsExcludes).forEach(function(facetName) { var facetValues = facetsExcludes[facetName] || []; facetValues.forEach(function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); var disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements || {}; Object.keys(disjunctiveFacetsRefinements).forEach(function(facetName) { var facetValues = disjunctiveFacetsRefinements[facetName] || []; if (facetName === facet || !facetValues || facetValues.length === 0) { return; } var orFilters = []; facetValues.forEach(function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); var hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements || {}; Object.keys(hierarchicalFacetsRefinements).forEach(function(facetName) { var facetValues = hierarchicalFacetsRefinements[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 state.hierarchicalFacets.reduce( // 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; } return merge_1( {}, requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters ); } }; var requestBuilder_1 = requestBuilder; var version = '3.0.0'; /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {object} event * @property {SearchParameters} event.state the current parameters with the latest changes applied * @property {SearchResults} event.results the previous results received from Algolia. `null` before the first request * @example * helper.on('change', function(event) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when a main search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {object} event * @property {SearchParameters} event.state the parameters used for this search * @property {SearchResults} event.results the results from the previous search. `null` if it is the first search. * @example * helper.on('search', function(event) { * console.log('Search sent'); * }); */ /** * Event triggered when a search using `searchForFacetValues` is sent to Algolia * @event AlgoliaSearchHelper#event:searchForFacetValues * @property {object} event * @property {SearchParameters} event.state the parameters used for this search it is the first search. * @property {string} event.facet the facet searched into * @property {string} event.query the query used to search in the facets * @example * helper.on('searchForFacetValues', function(event) { * console.log('searchForFacetValues sent'); * }); */ /** * Event triggered when a search using `searchOnce` is sent to Algolia * @event AlgoliaSearchHelper#event:searchOnce * @property {object} event * @property {SearchParameters} event.state the parameters used for this search it is the first search. * @example * helper.on('searchOnce', function(event) { * console.log('searchOnce sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {object} event * @property {SearchResults} event.results the results received from Algolia * @property {SearchParameters} event.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(event) { * 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 {object} event * @property {Error} event.error the error returned by the Algolia. * @example * helper.on('error', function(event) { * 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 (typeof client.addAlgoliaAgent === 'function') { client.addAlgoliaAgent('JS Helper (' + version + ')'); } 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; } inherits_1(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({onlyWithDerivedHelpers: false}); return this; }; AlgoliaSearchHelper.prototype.searchOnlyWithDerivedHelpers = function() { this._search({onlyWithDerivedHelpers: true}); 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', { state: 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 clientHasSFFV = typeof this.client.searchForFacetValues === 'function'; if ( !clientHasSFFV && typeof this.client.initIndex !== 'function' ) { throw new Error( 'search for facet values (searchable) was called, but this client does not have a function client.searchForFacetValues or client.initIndex(index).searchForFacetValues' ); } 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: state, facet: facet, query: query }); var searchForFacetValuesPromise = clientHasSFFV ? 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(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({ state: this.state.resetPage().setQuery(q), isPageReset: true }); 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({ state: this.state.resetPage().clearRefinements(name), isPageReset: true }); 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({ state: this.state.resetPage().clearTags(), isPageReset: true }); 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({ state: this.state.resetPage().addDisjunctiveFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addHierarchicalFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addNumericRefinement(attribute, operator, value), isPageReset: true }); 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({ state: this.state.resetPage().addFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addExcludeRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().addTagRefinement(tag), isPageReset: true }); 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({ state: this.state.resetPage().removeNumericRefinement(attribute, operator, value), isPageReset: true }); 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({ state: this.state.resetPage().removeDisjunctiveFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().removeHierarchicalFacetRefinement(facet), isPageReset: true }); 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({ state: this.state.resetPage().removeFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().removeExcludeRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().removeTagRefinement(tag), isPageReset: true }); 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({ state: this.state.resetPage().toggleExcludeFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().toggleFacetRefinement(facet, value), isPageReset: true }); 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({ state: this.state.resetPage().toggleTagRefinement(tag), isPageReset: true }); 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() { var page = this.state.page || 0; return this.setPage(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() { var page = this.state.page || 0; return this.setPage(page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this._change({ state: this.state.setPage(page), isPageReset: false }); 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({ state: this.state.resetPage().setIndex(name), isPageReset: true }); 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({ state: this.state.resetPage().setQueryParameter(parameter, value), isPageReset: true }); 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({ state: SearchParameters_1.make(newState), isPageReset: false }); return this; }; /** * 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; }; /** * 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 (objectHasKeys_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 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); conjRefinements.forEach(function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); excludeRefinements.forEach(function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); disjRefinements.forEach(function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); Object.keys(numericRefinements).forEach(function(operator) { var value = numericRefinements[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(options) { var state = this.state; var states = []; var mainQueries = []; if (!options.onlyWithDerivedHelpers) { mainQueries = requestBuilder_1._getQueries(state.index, state); states.push({ state: state, queriesCount: mainQueries.length, helper: this }); this.emit('search', { state: state, results: this.lastResults }); } var derivedQueries = this.derivedHelpers.map(function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var derivedStateQueries = requestBuilder_1._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: derivedStateQueries.length, helper: derivedHelper }); derivedHelper.emit('search', { state: derivedState, results: derivedHelper.lastResults }); return derivedStateQueries; }); var queries = Array.prototype.concat.apply(mainQueries, 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 (error) { // If we reach this part, we're in an internal error state this.emit('error', { error: error }); } }; /** * 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.slice(); states.forEach(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', { results: formattedResponse, state: state }); }); }; AlgoliaSearchHelper.prototype._dispatchAlgoliaError = function(queryId, error) { if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= queryId - this._lastQueryIdReceived; this._lastQueryIdReceived = queryId; this.emit('error', { error: error }); 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(event) { var state = event.state; var isPageReset = event.isPageReset; if (state !== this.state) { this.state = state; this.emit('change', { state: this.state, results: this.lastResults, isPageReset: isPageReset }); } }; /** * 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 (typeof newClient.addAlgoliaAgent === 'function') { 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_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' */ 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(event) { * console.log(event.results); * }); * helper * .toggleFacetRefinement('category', 'Movies & TV Shows') * .toggleFacetRefinement('shipping', '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; /** * 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; var algoliasearchHelper_1 = algoliasearchHelper; var getId$1 = function getId() { return 'query'; }; function getCurrentRefinement(props, searchState, context) { var id = getId$1(); var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, ''); if (currentRefinement) { return currentRefinement; } return ''; } function getHits(searchResults) { if (searchResults.results) { if (searchResults.results.hits && Array.isArray(searchResults.results.hits)) { return addAbsolutePositions(addQueryID(searchResults.results.hits, searchResults.results.queryID), searchResults.results.hitsPerPage, searchResults.results.page); } else { return Object.keys(searchResults.results).reduce(function (hits, index) { return [].concat(_toConsumableArray(hits), [{ index: index, hits: addAbsolutePositions(addQueryID(searchResults.results[index].hits, searchResults.results[index].queryID), searchResults.results[index].hitsPerPage, searchResults.results[index].page) }]); }, []); } } else { return []; } } function _refine(props, searchState, nextRefinement, context) { var id = getId$1(); var nextValue = _defineProperty({}, 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 * @propType {string} [defaultRefinement] - Provide a default value for the query * @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 = createConnectorWithContext({ displayName: 'AlgoliaAutoComplete', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { hits: getHits(searchResults), currentRefinement: getCurrentRefinement(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, /** * AutoComplete needs to be considered as a widget to trigger a search, * even if no other widgets are used. * * To be considered as a widget you need either: * - getSearchParameters * - getMetadata * - transitionState * * See: createConnector.tsx */ getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue })); } }); 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({}, 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)); } } 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 = createConnectorWithContext({ 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 ".concat(propName, " supplied to ").concat(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, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); /** * 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 = createConnectorWithContext({ 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 _objectSpread({}, item, { id: meta.id, index: meta.index }); })); } } return res; }, []); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems, canRefine: transformedItems.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); } }); /** * The GeoSearch connector provides the logic to build a widget that will display the results on a map. * It also provides a way to search for results based on their position. The connector provides function to manage the search experience (search on map interaction). * @name connectGeoSearch * @kind connector * @requirements Note that the GeoSearch connector uses the [geosearch](https://www.algolia.com/doc/guides/searching/geo-search) capabilities of Algolia. * Your hits **must** have a `_geoloc` attribute in order to be passed to the rendering function. Currently, the feature is not compatible with multiple values in the `_geoloc` attribute * (e.g. a restaurant with multiple locations). In that case you can duplicate your records and use the [distinct](https://www.algolia.com/doc/guides/ranking/distinct) feature of Algolia to only retrieve unique results. * @propType {{ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } }} [defaultRefinement] - Default search state of the widget containing the bounds for the map * @providedPropType {function({ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } })} refine - a function to toggle the refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {array.<object>} hits - the records that matched the search * @providedPropType {boolean} isRefinedWithMap - true if the current refinement is set with the map bounds * @providedPropType {{ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } }} [currentRefinement] - the refinement currently applied * @providedPropType {{ lat: number, lng: number }} [position] - the position of the search */ // To control the map with an external widget the other widget // **must** write the value in the attribute `aroundLatLng` var getBoundingBoxId = function getBoundingBoxId() { return 'boundingBox'; }; var getAroundLatLngId = function getAroundLatLngId() { return 'aroundLatLng'; }; var getConfigureAroundLatLngId = function getConfigureAroundLatLngId() { return 'configure.aroundLatLng'; }; var currentRefinementToString = function currentRefinementToString(currentRefinement) { return [currentRefinement.northEast.lat, currentRefinement.northEast.lng, currentRefinement.southWest.lat, currentRefinement.southWest.lng].join(); }; var stringToCurrentRefinement = function stringToCurrentRefinement(value) { var values = value.split(','); return { northEast: { lat: parseFloat(values[0]), lng: parseFloat(values[1]) }, southWest: { lat: parseFloat(values[2]), lng: parseFloat(values[3]) } }; }; var latLngRegExp = /^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/; var stringToPosition = function stringToPosition(value) { var pattern = value.match(latLngRegExp); return { lat: parseFloat(pattern[1]), lng: parseFloat(pattern[2]) }; }; var getCurrentRefinement$1 = function getCurrentRefinement(props, searchState, context) { var refinement = getCurrentRefinementValue(props, searchState, context, getBoundingBoxId(), {}); if (!objectHasKeys(refinement)) { return; } // eslint-disable-next-line consistent-return return { northEast: { lat: parseFloat(refinement.northEast.lat), lng: parseFloat(refinement.northEast.lng) }, southWest: { lat: parseFloat(refinement.southWest.lat), lng: parseFloat(refinement.southWest.lng) } }; }; var getCurrentPosition = function getCurrentPosition(props, searchState, context) { var defaultRefinement = props.defaultRefinement, propsWithoutDefaultRefinement = _objectWithoutProperties(props, ["defaultRefinement"]); var aroundLatLng = getCurrentRefinementValue(propsWithoutDefaultRefinement, searchState, context, getAroundLatLngId()); if (!aroundLatLng) { // Fallback on `configure.aroundLatLng` var configureAroundLatLng = getCurrentRefinementValue(propsWithoutDefaultRefinement, searchState, context, getConfigureAroundLatLngId()); return configureAroundLatLng && stringToPosition(configureAroundLatLng); } return aroundLatLng; }; var _refine$2 = function refine(searchState, nextValue, context) { var resetPage = true; var nextRefinement = _defineProperty({}, getBoundingBoxId(), nextValue); return refineValue(searchState, nextRefinement, context, resetPage); }; var connectGeoSearch = createConnectorWithContext({ displayName: 'AlgoliaGeoSearch', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var context = { ais: props.contextValue, multiIndexContext: props.indexContextValue }; var results = getResults(searchResults, context); // We read it from both because the SearchParameters & the searchState are not always // in sync. When we set the refinement the searchState is used but when we clear the refinement // the SearchParameters is used. In the first case when we render, the results are not there // so we can't find the value from the results. The most up to date value is the searchState. // But when we clear the refinement the searchState is immediately cleared even when the items // retrieved are still the one from the previous query with the bounding box. It leads to some // issue with the position of the map. We should rely on 1 source of truth or at least always // be sync. var currentRefinementFromSearchState = getCurrentRefinement$1(props, searchState, context); var currentRefinementFromSearchParameters = results && results._state.insideBoundingBox && stringToCurrentRefinement(results._state.insideBoundingBox) || undefined; var currentPositionFromSearchState = getCurrentPosition(props, searchState, context); var currentPositionFromSearchParameters = results && results._state.aroundLatLng && stringToPosition(results._state.aroundLatLng) || undefined; var currentRefinement = currentRefinementFromSearchState || currentRefinementFromSearchParameters; var position = currentPositionFromSearchState || currentPositionFromSearchParameters; return { hits: !results ? [] : results.hits.filter(function (_) { return Boolean(_._geoloc); }), isRefinedWithMap: Boolean(currentRefinement), currentRefinement: currentRefinement, position: position }; }, refine: function refine(props, searchState, nextValue) { return _refine$2(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var currentRefinement = getCurrentRefinement$1(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (!currentRefinement) { return searchParameters; } return searchParameters.setQueryParameter('insideBoundingBox', currentRefinementToString(currentRefinement)); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, getBoundingBoxId()); }, getMetadata: function getMetadata(props, searchState) { var items = []; var id = getBoundingBoxId(); var context = { ais: props.contextValue, multiIndexContext: props.indexContextValue }; var index = getIndexId(context); var nextRefinement = {}; var currentRefinement = getCurrentRefinement$1(props, searchState, context); if (currentRefinement) { items.push({ label: "".concat(id, ": ").concat(currentRefinementToString(currentRefinement)), value: function value(nextState) { return _refine$2(nextState, nextRefinement, context); }, currentRefinement: currentRefinement }); } return { id: id, index: index, items: items }; }, shouldComponentUpdate: function shouldComponentUpdate() { return true; } }); var getId$3 = function getId(props) { return props.attributes[0]; }; var namespace$1 = 'hierarchicalMenu'; function getCurrentRefinement$2(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$1, ".").concat(getId$3(props)), null); if (currentRefinement === '') { return null; } return currentRefinement; } function getValue(path, props, searchState, context) { var id = props.id, attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel; var currentRefinement = getCurrentRefinement$2(props, searchState, context); var nextRefinement; if (currentRefinement === null) { nextRefinement = path; } else { var tmpSearchParameters = new algoliasearchHelper_1.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$1(value, props, searchState, context) { return value.map(function (v) { return { label: v.name, value: getValue(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) ? _objectSpread({}, item, { items: truncate(item.items, limit) }) : item; }); }; function _refine$3(props, searchState, nextRefinement, context) { var id = getId$3(props); var nextValue = _defineProperty({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$1); } function _cleanUp$1(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$1, ".").concat(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 path to use if the first level is not the root level. * @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 = createConnectorWithContext({ 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 ".concat(propName, " supplied to ").concat(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, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement$2(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: false }; } var itemsLimit = showMore ? showMoreLimit : limit; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue$1(value.data, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: truncate(transformedItems, itemsLimit), currentRefinement: getCurrentRefinement$2(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$3(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$1(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, 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, contextValue = props.contextValue; 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$2(props, searchState, { ais: contextValue, multiIndexContext: props.indexContextValue }); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var rootAttribute = props.attributes[0]; var id = getId$3(props); var currentRefinement = getCurrentRefinement$2(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = !currentRefinement ? [] : [{ label: "".concat(rootAttribute, ": ").concat(currentRefinement), attribute: rootAttribute, value: function value(nextState) { return _refine$3(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: currentRefinement }]; return { id: id, index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: items }; } }); var highlight = function highlight(_ref) { var attribute = _ref.attribute, hit = _ref.hit, highlightProperty = _ref.highlightProperty, _ref$preTag = _ref.preTag, preTag = _ref$preTag === void 0 ? HIGHLIGHT_TAGS.highlightPreTag : _ref$preTag, _ref$postTag = _ref.postTag, postTag = _ref$postTag === void 0 ? 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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox, Hits, connectHighlight } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * 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 * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox defaultRefinement="pho" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var connectHighlight = createConnectorWithContext({ 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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, Highlight, connectHits } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * const CustomHits = connectHits(({ hits }) => ( * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attribute="name" hit={hit} /> * </p> * )} * </div> * )); * * const App = () => ( * <InstantSearch * searchClient={searchClient} * indexName="instant_search" * > * <CustomHits /> * </InstantSearch> * ); */ var connectHits = createConnectorWithContext({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (!results) { return { hits: [] }; } var hitsWithPositions = addAbsolutePositions(results.hits, results.hitsPerPage, results.page); var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID); return { hits: hitsWithPositionsAndQueryID }; }, /** * Hits needs to be considered as a widget to trigger a search, * even if no other widgets are used. * * To be considered as a widget you need either: * - getSearchParameters * - getMetadata * - transitionState * * See: createConnector.tsx */ getSearchParameters: function getSearchParameters(searchParameters) { return searchParameters; } }); function getId$4() { return 'hitsPerPage'; } function getCurrentRefinement$3(props, searchState, context) { var id = getId$4(); var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null); 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 = createConnectorWithContext({ 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$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = props.items.map(function (item) { return item.value === currentRefinement ? _objectSpread({}, item, { isRefined: true }) : _objectSpread({}, 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({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, getId$4()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue })); }, getMetadata: function getMetadata() { return { id: getId$4() }; } }); function getId$5() { return 'page'; } function getCurrentRefinement$4(props, searchState, context) { var id = getId$5(); var page = 1; var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page); if (typeof currentRefinement === 'string') { return 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 = createConnectorWithContext({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var _this = this; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); this._allResults = this._allResults || []; this._prevState = this._prevState || {}; if (!results) { return { hits: [], hasPrevious: false, hasMore: false, refine: function refine() {}, refinePrevious: function refinePrevious() {}, refineNext: function refineNext() {} }; } var page = results.page, hits = results.hits, hitsPerPage = results.hitsPerPage, nbPages = results.nbPages, _results$_state = results._state; _results$_state = _results$_state === void 0 ? {} : _results$_state; var p = _results$_state.page, currentState = _objectWithoutProperties(_results$_state, ["page"]); var hitsWithPositions = addAbsolutePositions(hits, hitsPerPage, page); var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID); if (this._firstReceivedPage === undefined || !fastDeepEqual(currentState, this._prevState)) { this._allResults = _toConsumableArray(hitsWithPositionsAndQueryID); this._firstReceivedPage = page; this._lastReceivedPage = page; } else if (this._lastReceivedPage < page) { this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hitsWithPositionsAndQueryID)); this._lastReceivedPage = page; } else if (this._firstReceivedPage > page) { this._allResults = [].concat(_toConsumableArray(hitsWithPositionsAndQueryID), _toConsumableArray(this._allResults)); this._firstReceivedPage = page; } this._prevState = currentState; var hasPrevious = this._firstReceivedPage > 0; var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; var refinePrevious = function refinePrevious(event) { return _this.refine(event, _this._firstReceivedPage - 1); }; var refineNext = function refineNext(event) { return _this.refine(event, _this._lastReceivedPage + 1); }; return { hits: this._allResults, hasPrevious: hasPrevious, hasMore: hasMore, refinePrevious: refinePrevious, refineNext: refineNext }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQueryParameters({ page: getCurrentRefinement$4(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }) - 1 }); }, refine: function refine(props, searchState, event, index) { if (index === undefined && this._lastReceivedPage !== undefined) { index = this._lastReceivedPage + 1; } else if (index === undefined) { index = getCurrentRefinement$4(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } var id = getId$5(); var nextValue = _defineProperty({}, id, index + 1); var resetPage = false; return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, resetPage); } }); var namespace$2 = 'menu'; function getId$6(props) { return props.attribute; } function getCurrentRefinement$5(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$2, ".").concat(getId$6(props)), null); if (currentRefinement === '') { return null; } return currentRefinement; } function getValue$1(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$5(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$4(props, searchState, nextRefinement, context) { var id = getId$6(props); var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$2); } function _cleanUp$2(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$2, ".").concat(getId$6(props))); } var defaultSortBy = ['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 = createConnectorWithContext({ 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 attribute = props.attribute, searchable = props.searchable, indexContextValue = props.indexContextValue; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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 && indexContextValue) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$5(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isFromSearch: isFromSearch, searchable: searchable, canRefine: canRefine }; } var items; if (isFromSearch) { items = searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$1(v.value, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }); } else { items = results.getFacetValues(attribute, { sortBy: searchable ? undefined : defaultSortBy }).map(function (v) { return { label: v.name, value: getValue$1(v.name, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), count: v.count, isRefined: v.isRefined }; }); } var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit(props)), currentRefinement: getCurrentRefinement$5(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isFromSearch: isFromSearch, searchable: searchable, canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$4(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, 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, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, 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$5(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId$6(props); var currentRefinement = getCurrentRefinement$5(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); return { id: id, index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: currentRefinement === null ? [] : [{ label: "".concat(props.attribute, ": ").concat(currentRefinement), attribute: props.attribute, value: function value(nextState) { return _refine$4(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: currentRefinement }] }; } }); function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(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"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function stringifyItem(item) { if (typeof item.start === 'undefined' && typeof item.end === 'undefined') { return ''; } var start = typeof item.start !== 'undefined' ? item.start : ''; var end = typeof item.end !== 'undefined' ? item.end : ''; return "".concat(start, ":").concat(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$6(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, "".concat(namespace$3, ".").concat(getId$7(props)), ''); } 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$5(props, searchState, nextRefinement, context) { var nextValue = _defineProperty({}, getId$7(props), nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$3); } function _cleanUp$3(props, searchState, context) { return cleanUpValue(searchState, context, "".concat(namespace$3, ".").concat(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 = createConnectorWithContext({ 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$6(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: refinedItem === undefined, noRefinement: !stats, label: 'All' }); } var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems, currentRefinement: currentRefinement, canRefine: transformedItems.length > 0 && transformedItems.some(function (item) { return item.noRefinement === false; }) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$5(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$3(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; var _parseItem = parseItem(getCurrentRefinement$6(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue })), start = _parseItem.start, end = _parseItem.end; searchParameters = searchParameters.addDisjunctiveFacet(attribute); if (typeof start === 'number') { searchParameters = searchParameters.addNumericRefinement(attribute, '>=', start); } if (typeof end === 'number') { searchParameters = searchParameters.addNumericRefinement(attribute, '<=', end); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId$7(props); var value = getCurrentRefinement$6(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = []; var index = getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (value !== '') { var _find = find(props.items, function (item) { return stringifyItem(item) === value; }), label = _find.label; items.push({ label: "".concat(props.attribute, ": ").concat(label), attribute: props.attribute, currentRefinement: label, value: function value(nextState) { return _refine$5(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); } return { id: id, index: index, items: items }; } }); function getId$8() { return 'page'; } function getCurrentRefinement$7(props, searchState, context) { var id = getId$8(); var page = 1; var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page); if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; } function _refine$6(props, searchState, nextPage, context) { var id = getId$8(); var nextValue = _defineProperty({}, 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 = createConnectorWithContext({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement$7(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine$6(props, searchState, nextPage, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, getId$8()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement$7(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }) - 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 = createConnectorWithContext({ displayName: 'AlgoliaPoweredBy', getProvidedProps: function getProvidedProps() { var hostname = typeof window === 'undefined' ? '' : window.location.hostname; var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + "utm_content=".concat(hostname, "&") + 'utm_campaign=poweredby'; return { url: url }; } }); /** * 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; if (typeof boundaries.min === 'number' && isFinite(boundaries.min)) { min = boundaries.min; } else if (typeof stats.min === 'number' && isFinite(stats.min)) { min = stats.min; } else { min = undefined; } var max; if (typeof boundaries.max === 'number' && isFinite(boundaries.max)) { max = boundaries.max; } else if (typeof stats.max === 'number' && 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$8(props, searchState, currentRange, context) { var _getCurrentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$4, ".").concat(getId$9(props)), {}), min = _getCurrentRefinement.min, max = _getCurrentRefinement.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); } var refinement = { 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; if (!hasBound && range === value) { next = undefined; } else if (hasBound && isReset) { next = range; } else { next = value; } return next; } function _refine$7(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({}, 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, "".concat(namespace$4, ".").concat(getId$9(props))); } var connectRange = createConnectorWithContext({ 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, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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 behavior 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$8(props, searchState, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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$7(props, searchState, nextRefinement, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$4(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attribute = props.attribute; var _getCurrentRefinement2 = getCurrentRefinement$8(props, searchState, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), min = _getCurrentRefinement2.min, max = _getCurrentRefinement2.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 _this$_currentRange = this._currentRange, minRange = _this$_currentRange.min, maxRange = _this$_currentRange.max; var _getCurrentRefinement3 = getCurrentRefinement$8(props, searchState, this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), 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 ? "".concat(minValue, " <= ") : '', props.attribute, hasMax ? " <= ".concat(maxValue) : '']; items.push({ label: fragments.join(''), attribute: props.attribute, value: function value(nextState) { return _refine$7(props, nextState, {}, _this._currentRange, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: getCurrentRefinementWithRange({ min: minValue, max: maxValue }, { min: minRange, max: maxRange }) }); } return { id: getId$9(props), index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: items }; } }); var namespace$5 = 'refinementList'; function getId$a(props) { return props.attribute; } function getCurrentRefinement$9(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$5, ".").concat(getId$a(props)), []); if (typeof currentRefinement !== 'string') { return currentRefinement; } if (currentRefinement) { return [currentRefinement]; } return []; } function getValue$2(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$9(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$8(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({}, 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, "".concat(namespace$5, ".").concat(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. * @providedPropType {boolean} canRefine - a boolean that says whether you can refine */ var sortBy$1 = ['isRefined', 'count:desc', 'name:asc']; var connectRefinementList = createConnectorWithContext({ 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 attribute = props.attribute, searchable = props.searchable, indexContextValue = props.indexContextValue; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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 && indexContextValue) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$9(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), canRefine: canRefine, isFromSearch: isFromSearch, searchable: searchable }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$2(v.value, props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), _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, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit$1(props)), currentRefinement: getCurrentRefinement$9(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isFromSearch: isFromSearch, searchable: searchable, canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$8(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, 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, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, operator = props.operator; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = "".concat(addKey, "Refinement"); searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props)) }); searchParameters = searchParameters[addKey](attribute); return getCurrentRefinement$9(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }).reduce(function (res, val) { return res[addRefinementKey](attribute, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId$a(props); var context = { ais: props.contextValue, multiIndexContext: props.indexContextValue }; return { id: id, index: getIndexId(context), items: getCurrentRefinement$9(props, searchState, context).length > 0 ? [{ attribute: props.attribute, label: "".concat(props.attribute, ": "), currentRefinement: getCurrentRefinement$9(props, searchState, context), value: function value(nextState) { return _refine$8(props, nextState, [], context); }, items: getCurrentRefinement$9(props, searchState, context).map(function (item) { return { label: "".concat(item), value: function value(nextState) { var nextSelectedItems = getCurrentRefinement$9(props, nextState, context).filter(function (other) { return other !== item; }); return _refine$8(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 = createConnectorWithContext({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: propTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = getCurrentRefinementValue(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, id, null); if (!this._prevSearchState) { this._prevSearchState = {}; } // Get the subpart of the state that interest us if (hasMultipleIndices({ ais: props.contextValue, multiIndexContext: props.indexContextValue })) { searchState = searchState.indices ? searchState.indices[getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue })] : {}; } // 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 comparison 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(searchState, ['configure', id]); var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState); this._prevSearchState = cleanedSearchState; return { value: value, hasNotChanged: hasNotChanged }; } }); function getId$b() { return 'query'; } function getCurrentRefinement$a(props, searchState, context) { var id = getId$b(); var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, ''); if (currentRefinement) { return currentRefinement; } return ''; } function _refine$9(props, searchState, nextRefinement, context) { var id = getId$b(); var nextValue = _defineProperty({}, 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 * @propType {string} [defaultRefinement] - Provide a default value for the query * @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 = createConnectorWithContext({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: propTypes.string }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { currentRefinement: getCurrentRefinement$a(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }), isSearchStalled: searchResults.isSearchStalled }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$9(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$6(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$a(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue })); }, getMetadata: function getMetadata(props, searchState) { var id = getId$b(); var currentRefinement = getCurrentRefinement$a(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); return { id: id, index: getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }), items: currentRefinement === null ? [] : [{ label: "".concat(id, ": ").concat(currentRefinement), value: function value(nextState) { return _refine$9(props, nextState, '', { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, currentRefinement: currentRefinement }] }; } }); function getId$c() { return 'sortBy'; } function getCurrentRefinement$b(props, searchState, context) { var id = getId$c(); var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null); 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 = createConnectorWithContext({ 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$b(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = props.items.map(function (item) { return item.value === currentRefinement ? _objectSpread({}, item, { isRefined: true }) : _objectSpread({}, 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({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }, getId$c()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement$b(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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 algoliasearch from 'algoliasearch/lite'; * import { InstantSearch, SearchBox, Hits, connectStateResults } from 'react-instantsearch-dom'; * * const searchClient = algoliasearch( * 'latency', * '6be0576ff61c053d5f9a3225e2a90f76' * ); * * 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 * searchClient={searchClient} * indexName="instant_search" * > * <SearchBox /> * <Content /> * </InstantSearch> * ); */ var connectStateResults = createConnectorWithContext({ displayName: 'AlgoliaStateResults', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); 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 = createConnectorWithContext({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); function getId$d(props) { return props.attribute; } var namespace$6 = 'toggle'; var falsyStrings = ['0', 'false', 'null', 'undefined']; function getCurrentRefinement$c(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$6, ".").concat(getId$d(props)), false); if (falsyStrings.indexOf(currentRefinement) !== -1) { return false; } return Boolean(currentRefinement); } function _refine$a(props, searchState, nextRefinement, context) { var id = getId$d(props); var nextValue = _defineProperty({}, 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, "".concat(namespace$6, ".").concat(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 {boolean} currentRefinement - `true` when the refinement is applied, `false` otherwise * @providedPropType {object} count - an object that contains the count for `checked` and `unchecked` state * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state */ var connectToggleRefinement = createConnectorWithContext({ displayName: 'AlgoliaToggle', propTypes: { label: propTypes.string.isRequired, attribute: propTypes.string.isRequired, value: propTypes.any.isRequired, filter: propTypes.func, defaultRefinement: propTypes.bool }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute, value = props.value; var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var currentRefinement = getCurrentRefinement$c(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var allFacetValues = results && results.getFacetByName(attribute) ? results.getFacetValues(attribute) : null; var facetValue = // Use null to always be consistent with type of the value // count: number | null allFacetValues && allFacetValues.length ? find(allFacetValues, function (item) { return item.name === value.toString(); }) : null; var facetValueCount = facetValue && facetValue.count; var allFacetValuesCount = // Use null to always be consistent with type of the value // count: number | null allFacetValues && allFacetValues.length ? allFacetValues.reduce(function (acc, item) { return acc + item.count; }, 0) : null; var canRefine = currentRefinement ? allFacetValuesCount !== null && allFacetValuesCount > 0 : facetValueCount !== null && facetValueCount > 0; var count = { checked: allFacetValuesCount, unchecked: facetValueCount }; return { currentRefinement: currentRefinement, canRefine: canRefine, count: count }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$a(props, searchState, nextRefinement, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$7(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, value = props.value, filter = props.filter; var checked = getCurrentRefinement$c(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var nextSearchParameters = searchParameters.addDisjunctiveFacet(attribute); if (checked) { nextSearchParameters = nextSearchParameters.addDisjunctiveFacetRefinement(attribute, value); if (filter) { nextSearchParameters = filter(nextSearchParameters); } } return nextSearchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId$d(props); var checked = getCurrentRefinement$c(props, searchState, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var items = []; var index = getIndexId({ ais: props.contextValue, multiIndexContext: props.indexContextValue }); if (checked) { items.push({ label: props.label, currentRefinement: checked, attribute: props.attribute, value: function value(nextState) { return _refine$a(props, nextState, false, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); } }); } return { id: id, index: index, items: items }; } }); function inferPayload(_ref) { var method = _ref.method, results = _ref.results, currentHit = _ref.currentHit; var index = results.index; var queryID = currentHit.__queryID; var objectIDs = [currentHit.objectID]; if (!queryID) { throw new Error("Could not infer `queryID`. Ensure `clickAnalytics: true` was added with the Configure widget.\nSee: https://alg.li/VpPpLt"); } switch (method) { case 'clickedObjectIDsAfterSearch': { var positions = [currentHit.__position]; return { index: index, queryID: queryID, objectIDs: objectIDs, positions: positions }; } case 'convertedObjectIDsAfterSearch': return { index: index, queryID: queryID, objectIDs: objectIDs }; default: throw new Error("Unsupported method \"".concat(method, "\" passed to the insights function. The supported methods are: \"clickedObjectIDsAfterSearch\", \"convertedObjectIDsAfterSearch\".")); } } var wrapInsightsClient = function wrapInsightsClient(aa, results, currentHit) { return function (method, payload) { if (typeof aa !== 'function') { throw new TypeError("Expected insightsClient to be a Function"); } var inferredPayload = inferPayload({ method: method, results: results, currentHit: currentHit }); aa(method, _objectSpread({}, inferredPayload, payload)); }; }; var connectHitInsights = (function (insightsClient) { return createConnectorWithContext({ displayName: 'AlgoliaInsights', getProvidedProps: function getProvidedProps(props, _, searchResults) { var results = getResults(searchResults, { ais: props.contextValue, multiIndexContext: props.indexContextValue }); var insights = wrapInsightsClient(insightsClient, results, props.hit); return { insights: insights }; } }); }); exports.connectAutoComplete = connectAutoComplete; exports.connectBreadcrumb = connectBreadcrumb; exports.connectConfigure = connectConfigure; exports.connectCurrentRefinements = connectCurrentRefinements; exports.connectGeoSearch = connectGeoSearch; exports.connectHierarchicalMenu = connectHierarchicalMenu; exports.connectHighlight = connectHighlight; exports.connectHitInsights = connectHitInsights; 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.0.0-3553c0b23/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 /*#__PURE__*/React.createElement(View, rest); } export default RefreshControl;
ajax/libs/zingchart-react/3.1.0/zingchart-react.es.js
cdnjs/cdnjs
import React, { Component } from 'react'; var EVENT_NAMES = [ 'about_hide', 'about_show', 'animation_end', 'animation_start', 'animation_step', 'beforedestroy', 'bugreport_hide', 'bugreport_show', 'click', 'complete', 'data_export', 'dataexport', 'dataload', 'dataparse', 'dataready', 'destroy', 'dimension_change', 'error', 'feed_clear', 'feed_interval_modify', 'feed_start', 'feed_stop', 'gcomplete', 'gload', 'gparse', 'guide_mousemove', 'guide_mouseout', 'guide_mouseout', 'heatmap.mousemove', 'history_back', 'history_forward', 'image_save', 'label_click', 'label_mousedown', 'label_mouseout', 'label_mouseover', 'label_mouseup', 'legend_hide', 'legend_item_click', 'legend_item_mousemove', 'legend_item_mouseout', 'legend_item_mouseout', 'legend_item_mouseover', 'legend_marker_click', 'legend_marker_click', 'legend_maximize', 'legend_minimize', 'legend_minimize_click', 'legend_pagination_click', 'legend_show', 'legend-drag_mousedown', 'lens_hide', 'lens_show', 'load', 'maps.zoom', 'menu_item_click', 'modify', 'modulesready', 'mousewheel', 'node_add', 'node_click', 'node_deselect', 'node_doubleclick', 'node_mousedown', 'node_mouseout', 'node_mouseover', 'node_mouseup', 'node_remove', 'node_select', 'node_set', 'objectsinit', 'objectsready', 'overscroll', 'plot_add', 'plot_click', 'plot_deselect', 'plot_doubleclick', 'plot_hide', 'plot_modify', 'plot_mouseout', 'plot_mouseover', 'plot_remove', 'plot_select', 'plot_show', 'postzoom', 'print', 'reload', 'render', 'resize', 'setdata', 'shape_click', 'shape_mousedown', 'shape_mouseout', 'shape_mouseover', 'shape_mouseup', 'source_hide', 'source_show', 'swipe', 'touchemove', 'touchend', 'touchstart', 'zingchart.plugins.selection-tool.mouseup', 'zingchart.plugins.selection-tool.selection', 'zoom' ]; var METHOD_NAMES = [ 'addgraph', 'addmenuitem', 'addnode', 'addnote', 'addobject', 'addplot', 'addrule', 'addscalevalue', 'appendseriesdata', 'appendseriesvalues', 'clearfeed', 'clearscroll', 'clearselection', 'clicknode', 'clicknode', 'closemodal', 'closemodal', 'destroy/zcdestroy', 'disable', 'downloadCSV', 'downloadRAW', 'downloadXLS', 'exitfullscreen', 'exportdata', 'exportimage', 'fullscreen', 'get3dview', 'getbubblesize', 'getcharttype', 'getdata', 'getgraphlength', 'getimagedata', 'getinterval', 'getnodelength', 'getnodevalue', 'getobjectinfo', 'getoriginaljson', 'getpage', 'getplotlength', 'getplotvalues', 'getrender', 'getrules', 'getscaleinfo', 'getscales', 'getselection', 'getseriesdata', 'getseriesdata', 'getseriesvalues', 'getversion', 'getxyinfo', 'goback', 'goforward', 'hideguide', 'hidemenu', 'hideplot/plothide', 'hidetooltip', 'legendmaximize', 'legendminimize', 'legendscroll', 'load', 'loadstorage', 'locktooltip', 'mapdata', 'mapdata', 'modify', 'modifyplot', 'openmodal', 'print', 'reload', 'removegraph', 'removenode', 'removenote', 'removeobject', 'removeplot', 'removerule', 'removescalevalue', 'repaintobjects', 'resize', 'saveasimage', 'set3dview', 'setcharttype', 'setdata', 'setguide', 'setinterval', 'setmode', 'setnodevalue', 'setpage', 'setscalevalues', 'setselection', 'setseriesdata', 'setseriesvalues', 'showhoverstate', 'showmenu', 'showplot/plotshow', 'showtooltip', 'startfeed', 'stopfeed', 'togglebugreport', 'toggledimension', 'togglelegend', 'toggleplot', 'togglesource', 'unbinddocument', 'unlocktooltip', 'update', 'updatenote', 'updateobject', 'updaterule', 'viewDataTable', 'zoomin', 'zoomout', 'zoomto', 'zoomtovalues' ]; var MARKER_NAMES = [ 'square', 'parallelogram', 'trapezoid', 'circle', 'diamond', 'triangle', 'ellipse', 'star5', 'star6', 'star7', 'star8', 'rpoly5', 'rpoly6', 'rpoly7', 'rpoly8', 'gear5', 'gear6', 'gear7', 'gear8', 'pie', ]; var MISC = { DEFAULT_WIDTH: '100%', DEFAULT_HEIGHT: 480, DEFAULT_OUTPUT: 'svg', }; const {DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_OUTPUT} = MISC; var constants = { EVENT_NAMES, METHOD_NAMES, MARKER_NAMES, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_OUTPUT, }; 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 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 DEFAULT_WIDTH$1 = constants.DEFAULT_WIDTH, DEFAULT_HEIGHT$1 = constants.DEFAULT_HEIGHT, DEFAULT_OUTPUT$1 = constants.DEFAULT_OUTPUT, EVENT_NAMES$1 = constants.EVENT_NAMES, METHOD_NAMES$1 = constants.METHOD_NAMES; // One time setup globally to handle all zingchart-react objects in the app space. if (!window.ZCReact) { window.ZCReact = { instances: {}, count: 0 }; } var ZingChart = function (_Component) { inherits(ZingChart, _Component); function ZingChart(props) { classCallCheck(this, ZingChart); var _this = possibleConstructorReturn(this, (ZingChart.__proto__ || Object.getPrototypeOf(ZingChart)).call(this, props)); _this.id = _this.props.id || 'zingchart-react-' + window.ZCReact.count++; console.log(props); // Bind all methods available to zingchart to be accessed via Refs. METHOD_NAMES$1.forEach(function (name) { _this[name] = function (args) { return window.zingchart.exec(_this.id, name, args); }; }); _this.state = { style: { height: _this.props.height || DEFAULT_HEIGHT$1, width: _this.props.width || DEFAULT_WIDTH$1 } }; return _this; } createClass(ZingChart, [{ key: 'render', value: function render() { return React.createElement('div', { id: this.id, style: this.state.style }); } }, { key: 'componentDidMount', value: function componentDidMount() { var _this2 = this; // Bind all events registered. Object.keys(this.props).forEach(function (eventName) { if (EVENT_NAMES$1.includes(eventName)) { // Filter through the provided events list, then register it to zingchart. window.zingchart.bind(_this2.id, eventName, function (result) { _this2.props[eventName](result); }); } }); this.renderChart(); } // Used to check the values being passed in to avoid unnecessary changes. }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps) { // Data change if (JSON.stringify(nextProps.data) !== JSON.stringify(this.props.data)) { zingchart.exec(this.id, 'setdata', { data: nextProps.data }); // Series change } else if (JSON.stringify(nextProps.series) !== JSON.stringify(this.props.series)) { zingchart.exec(this.id, 'setseriesdata', { graphid: 0, plotindex: 0, data: nextProps.series }); // Resize } else if (nextProps.width !== this.props.width || nextProps.height !== this.props.height) { this.setState({ style: { width: nextProps.width || DEFAULT_WIDTH$1, height: nextProps.height || DEFAULT_HEIGHT$1 } }); zingchart.exec(this.id, 'resize', { width: nextProps.width || DEFAULT_WIDTH$1, height: nextProps.height || DEFAULT_HEIGHT$1 }); } // React should never re-render since ZingChart controls this component. return false; } }, { key: 'renderChart', value: function renderChart() { var _this3 = this; var renderObject = {}; Object.keys(this.props).forEach(function (prop) { renderObject[prop] = _this3.props[prop]; }); // Overwrite some existing props. renderObject.id = this.id; renderObject.width = this.props.width || DEFAULT_WIDTH$1; renderObject.height = this.props.height || DEFAULT_HEIGHT$1; renderObject.data = this.props.data; renderObject.output = this.props.output || DEFAULT_OUTPUT$1; if (this.props.series) { renderObject.data.series = this.props.series; } if (this.props.theme) { renderObject.defaults = this.props.theme; } zingchart.render(renderObject); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { zingchart.exec(this.id, 'destroy'); } }]); return ZingChart; }(Component); export default ZingChart; //# sourceMappingURL=zingchart-react.es.js.map
ajax/libs/material-ui/4.11.3-deprecations.0/es/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() { const 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.3/es/Modal/SimpleBackdrop.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'; export const styles = { /* Styles applied to the root element. */ root: { zIndex: -1, position: 'fixed', 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' } }; /** * @ignore - internal component. */ const SimpleBackdrop = React.forwardRef(function SimpleBackdrop(props, ref) { const { invisible = false, open } = props, other = _objectWithoutPropertiesLoose(props, ["invisible", "open"]); return open ? React.createElement("div", _extends({ "aria-hidden": true, ref: ref }, other, { style: _extends({}, styles.root, {}, invisible ? styles.invisible : {}, {}, other.style) })) : null; }); process.env.NODE_ENV !== "production" ? SimpleBackdrop.propTypes = { /** * 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 } : void 0; export default SimpleBackdrop;
ajax/libs/material-ui/4.9.9/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/primereact/6.5.0-rc.2/accordion/accordion.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 _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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 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 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 AccordionTab = /*#__PURE__*/function (_Component) { _inherits(AccordionTab, _Component); var _super = _createSuper(AccordionTab); function AccordionTab() { _classCallCheck(this, AccordionTab); return _super.apply(this, arguments); } return AccordionTab; }(Component); _defineProperty(AccordionTab, "defaultProps", { header: null, disabled: false, headerStyle: null, headerClassName: null, headerTemplate: null, contentStyle: null, contentClassName: null }); _defineProperty(AccordionTab, "propTypes", { header: PropTypes.any, disabled: PropTypes.bool, headerStyle: PropTypes.object, headerClassName: PropTypes.string, headerTemplate: PropTypes.any, contentStyle: PropTypes.object, contentClassName: PropTypes.string }); var Accordion = /*#__PURE__*/function (_Component2) { _inherits(Accordion, _Component2); var _super2 = _createSuper(Accordion); function Accordion(props) { var _this; _classCallCheck(this, Accordion); _this = _super2.call(this, props); var state = { id: _this.props.id }; if (!_this.props.onTabChange) { state = _objectSpread(_objectSpread({}, state), {}, { activeIndex: props.activeIndex }); } _this.state = state; _this.contentWrappers = []; return _this; } _createClass(Accordion, [{ key: "onTabHeaderClick", value: function onTabHeaderClick(event, tab, index) { if (!tab.props.disabled) { var selected = this.isSelected(index); var newActiveIndex = null; if (this.props.multiple) { var indexes = (this.props.onTabChange ? this.props.activeIndex : this.state.activeIndex) || []; if (selected) indexes = indexes.filter(function (i) { return i !== index; });else indexes = [].concat(_toConsumableArray(indexes), [index]); newActiveIndex = indexes; } else { newActiveIndex = selected ? null : index; } var callback = selected ? this.props.onTabClose : this.props.onTabOpen; if (callback) { callback({ originalEvent: event, index: index }); } if (this.props.onTabChange) { this.props.onTabChange({ originalEvent: event, index: newActiveIndex }); } else { this.setState({ activeIndex: newActiveIndex }); } } event.preventDefault(); } }, { key: "isSelected", value: function isSelected(index) { var activeIndex = this.props.onTabChange ? this.props.activeIndex : this.state.activeIndex; return this.props.multiple ? activeIndex && activeIndex.indexOf(index) >= 0 : activeIndex === index; } }, { key: "componentDidMount", value: function componentDidMount() { if (!this.state.id) { this.setState({ id: UniqueComponentId() }); } } }, { key: "renderTabHeader", value: function renderTabHeader(tab, selected, index) { var _classNames, _this2 = this; var tabHeaderClass = classNames('p-accordion-header', { 'p-highlight': selected, 'p-disabled': tab.props.disabled }, tab.props.headerClassName); var iconClassName = classNames('p-accordion-toggle-icon', (_classNames = {}, _defineProperty(_classNames, "".concat(this.props.expandIcon), !selected), _defineProperty(_classNames, "".concat(this.props.collapseIcon), selected), _classNames)); var id = this.state.id + '_header_' + index; var ariaControls = this.state.id + '_content_' + index; var tabIndex = tab.props.disabled ? -1 : null; var header = tab.props.headerTemplate ? ObjectUtils.getJSXElement(tab.props.headerTemplate, tab.props) : /*#__PURE__*/React.createElement("span", { className: "p-accordion-header-text" }, tab.props.header); return /*#__PURE__*/React.createElement("div", { className: tabHeaderClass, style: tab.props.headerStyle }, /*#__PURE__*/React.createElement("a", { href: '#' + ariaControls, id: id, className: "p-accordion-header-link", "aria-controls": ariaControls, role: "tab", "aria-expanded": selected, onClick: function onClick(event) { return _this2.onTabHeaderClick(event, tab, index); }, tabIndex: tabIndex }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), header)); } }, { key: "renderTabContent", value: function renderTabContent(tab, selected, index) { var className = classNames('p-toggleable-content', tab.props.contentClassName); var id = this.state.id + '_content_' + index; var toggleableContentRef = /*#__PURE__*/React.createRef(); return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: toggleableContentRef, classNames: "p-toggleable-content", timeout: { enter: 1000, exit: 450 }, in: selected, unmountOnExit: true, options: this.props.transitionOptions }, /*#__PURE__*/React.createElement("div", { ref: toggleableContentRef, id: id, className: className, style: tab.props.contentStyle, role: "region", "aria-labelledby": this.state.id + '_header_' + index }, /*#__PURE__*/React.createElement("div", { className: "p-accordion-content" }, tab.props.children))); } }, { key: "renderTab", value: function renderTab(tab, index) { var selected = this.isSelected(index); var tabHeader = this.renderTabHeader(tab, selected, index); var tabContent = this.renderTabContent(tab, selected, index); var tabClassName = classNames('p-accordion-tab', { 'p-accordion-tab-active': selected }); return /*#__PURE__*/React.createElement("div", { key: tab.props.header, className: tabClassName }, tabHeader, tabContent); } }, { key: "renderTabs", value: function renderTabs() { var _this3 = this; return React.Children.map(this.props.children, function (tab, index) { if (tab && tab.type === AccordionTab) { return _this3.renderTab(tab, index); } }); } }, { key: "render", value: function render() { var _this4 = this; var className = classNames('p-accordion p-component', this.props.className); var tabs = this.renderTabs(); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this4.container = el; }, id: this.state.id, className: className, style: this.props.style }, tabs); } }]); return Accordion; }(Component); _defineProperty(Accordion, "defaultProps", { id: null, activeIndex: null, className: null, style: null, multiple: false, expandIcon: 'pi pi-chevron-right', collapseIcon: 'pi pi-chevron-down', transitionOptions: null, onTabOpen: null, onTabClose: null, onTabChange: null }); _defineProperty(Accordion, "propTypes", { id: PropTypes.string, activeIndex: PropTypes.any, className: PropTypes.string, style: PropTypes.object, multiple: PropTypes.bool, expandIcon: PropTypes.string, collapseIcon: PropTypes.string, transitionOptions: PropTypes.object, onTabOpen: PropTypes.func, onTabClose: PropTypes.func, onTabChange: PropTypes.func }); export { Accordion, AccordionTab };
ajax/libs/material-ui/4.10.2/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/primereact/7.2.1/treetable/treetable.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import PrimeReact, { 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); 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 _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: "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$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 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; }(); 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); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : 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'); DomHandler$1.addClass(this.checkboxRef, 'p-checkbox-focused'); } }, { key: "onCheckboxBlur", value: function onCheckboxBlur() { DomHandler$1.removeClass(this.checkboxBox, 'p-focus'); DomHandler$1.removeClass(this.checkboxRef, 'p-checkbox-focused'); } }, { 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", ref: function ref(el) { return _this2.checkboxRef = el; }, 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); 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 _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); 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 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); return ObjectUtils.sort(value1, value2, _this2.getSortOrder(), PrimeReact.locale); }); 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, PrimeReact.locale, { 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.props.rowHover, 'p-treetable-selectable': 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, rowHover: false, 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/react-native-web/0.15.6/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.3/es/Snackbar/Snackbar.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 withStyles from '../styles/withStyles'; import { duration } from '../styles/transitions'; import ClickAwayListener from '../ClickAwayListener'; import useEventCallback from '../utils/useEventCallback'; import capitalize from '../utils/capitalize'; import createChainedFunction from '../utils/createChainedFunction'; import Grow from '../Grow'; import SnackbarContent from '../SnackbarContent'; export const styles = theme => { const top1 = { top: 8 }; const bottom1 = { bottom: 8 }; const right = { justifyContent: 'flex-end' }; const left = { justifyContent: 'flex-start' }; const top3 = { top: 24 }; const bottom3 = { bottom: 24 }; const right3 = { right: 24 }; const left3 = { left: 24 }; const center = { left: '50%', right: 'auto', transform: 'translateX(-50%)' }; return { /* Styles applied to the root element. */ root: { zIndex: theme.zIndex.snackbar, position: 'fixed', display: 'flex', left: 8, right: 8, justifyContent: 'center', alignItems: 'center' }, /* Styles applied to the root element if `anchorOrigin={{ 'top', 'center' }}`. */ anchorOriginTopCenter: _extends({}, top1, { [theme.breakpoints.up('sm')]: _extends({}, top3, {}, center) }), /* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'center' }}`. */ anchorOriginBottomCenter: _extends({}, bottom1, { [theme.breakpoints.up('sm')]: _extends({}, bottom3, {}, center) }), /* Styles applied to the root element if `anchorOrigin={{ 'top', 'right' }}`. */ anchorOriginTopRight: _extends({}, top1, {}, right, { [theme.breakpoints.up('sm')]: _extends({ left: 'auto' }, top3, {}, right3) }), /* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'right' }}`. */ anchorOriginBottomRight: _extends({}, bottom1, {}, right, { [theme.breakpoints.up('sm')]: _extends({ left: 'auto' }, bottom3, {}, right3) }), /* Styles applied to the root element if `anchorOrigin={{ 'top', 'left' }}`. */ anchorOriginTopLeft: _extends({}, top1, {}, left, { [theme.breakpoints.up('sm')]: _extends({ right: 'auto' }, top3, {}, left3) }), /* Styles applied to the root element if `anchorOrigin={{ 'bottom', 'left' }}`. */ anchorOriginBottomLeft: _extends({}, bottom1, {}, left, { [theme.breakpoints.up('sm')]: _extends({ right: 'auto' }, bottom3, {}, left3) }) }; }; const Snackbar = React.forwardRef(function Snackbar(props, ref) { const { action, anchorOrigin: { vertical, horizontal } = { vertical: 'bottom', horizontal: 'center' }, autoHideDuration = null, children, classes, className, ClickAwayListenerProps, ContentProps, disableWindowBlurListener = false, message, onClose, onEnter, onEntered, onEntering, onExit, onExited, onExiting, onMouseEnter, onMouseLeave, open, resumeHideDuration, TransitionComponent = Grow, transitionDuration = { enter: duration.enteringScreen, exit: duration.leavingScreen }, TransitionProps } = props, other = _objectWithoutPropertiesLoose(props, ["action", "anchorOrigin", "autoHideDuration", "children", "classes", "className", "ClickAwayListenerProps", "ContentProps", "disableWindowBlurListener", "message", "onClose", "onEnter", "onEntered", "onEntering", "onExit", "onExited", "onExiting", "onMouseEnter", "onMouseLeave", "open", "resumeHideDuration", "TransitionComponent", "transitionDuration", "TransitionProps"]); const timerAutoHide = React.useRef(); const [exited, setExited] = React.useState(true); const handleClose = useEventCallback((...args) => { if (onClose) { onClose(...args); } }); const setAutoHideTimer = useEventCallback(autoHideDurationParam => { if (!onClose || autoHideDurationParam == null) { return; } clearTimeout(timerAutoHide.current); timerAutoHide.current = setTimeout(() => { handleClose(null, 'timeout'); }, autoHideDurationParam); }); React.useEffect(() => { if (open) { setAutoHideTimer(autoHideDuration); } return () => { clearTimeout(timerAutoHide.current); }; }, [open, autoHideDuration, setAutoHideTimer]); // Pause the timer when the user is interacting with the Snackbar // or when the user hide the window. const handlePause = () => { clearTimeout(timerAutoHide.current); }; // Restart the timer when the user is no longer interacting with the Snackbar // or when the window is shown back. const handleResume = React.useCallback(() => { if (autoHideDuration != null) { setAutoHideTimer(resumeHideDuration != null ? resumeHideDuration : autoHideDuration * 0.5); } }, [autoHideDuration, resumeHideDuration, setAutoHideTimer]); const handleMouseEnter = event => { if (onMouseEnter) { onMouseEnter(event); } handlePause(); }; const handleMouseLeave = event => { if (onMouseLeave) { onMouseLeave(event); } handleResume(); }; const handleClickAway = event => { if (onClose) { onClose(event, 'clickaway'); } }; const handleExited = () => { setExited(true); }; const handleEnter = () => { setExited(false); }; React.useEffect(() => { if (!disableWindowBlurListener && open) { window.addEventListener('focus', handleResume); window.addEventListener('blur', handlePause); return () => { window.removeEventListener('focus', handleResume); window.removeEventListener('blur', handlePause); }; } return undefined; }, [disableWindowBlurListener, handleResume, open]); // So we only render active snackbars. if (!open && exited) { return null; } return React.createElement(ClickAwayListener, _extends({ onClickAway: handleClickAway }, ClickAwayListenerProps), React.createElement("div", _extends({ className: clsx(classes.root, classes[`anchorOrigin${capitalize(vertical)}${capitalize(horizontal)}`], className), onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, ref: ref }, other), React.createElement(TransitionComponent, _extends({ appear: true, in: open, onEnter: createChainedFunction(handleEnter, onEnter), onEntered: onEntered, onEntering: onEntering, onExit: onExit, onExited: createChainedFunction(handleExited, onExited), onExiting: onExiting, timeout: transitionDuration, direction: vertical === 'top' ? 'down' : 'up' }, TransitionProps), children || React.createElement(SnackbarContent, _extends({ message: message, action: action }, ContentProps))))); }); process.env.NODE_ENV !== "production" ? Snackbar.propTypes = { /** * The action to display. It renders after the message, at the end of the snackbar. */ action: PropTypes.node, /** * The anchor of the `Snackbar`. */ anchorOrigin: PropTypes.shape({ horizontal: PropTypes.oneOf(['left', 'center', 'right']).isRequired, vertical: PropTypes.oneOf(['top', 'bottom']).isRequired }), /** * The number of milliseconds to wait before automatically calling the * `onClose` function. `onClose` should then set the state of the `open` * prop to hide the Snackbar. This behavior is disabled by default with * the `null` value. */ autoHideDuration: PropTypes.number, /** * Replace the `SnackbarContent` component. */ children: PropTypes.element, /** * 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, /** * Props applied to the `ClickAwayListener` element. */ ClickAwayListenerProps: PropTypes.object, /** * Props applied to the [`SnackbarContent`](/api/snackbar-content/) element. */ ContentProps: PropTypes.object, /** * If `true`, the `autoHideDuration` timer will expire even if the window is not focused. */ disableWindowBlurListener: PropTypes.bool, /** * When displaying multiple consecutive Snackbars from a parent rendering a single * <Snackbar/>, add the key prop to ensure independent treatment of each message. * e.g. <Snackbar key={message} />, otherwise, the message may update-in-place and * features such as autoHideDuration may be canceled. */ key: PropTypes.any, /** * The message to display. */ message: PropTypes.node, /** * Callback fired when the component requests to be closed. * Typically `onClose` is used to set state in the parent component, * which is used to control the `Snackbar` `open` prop. * The `reason` parameter can optionally be used to control the response to `onClose`, * for example ignoring `clickaway`. * * @param {object} event The event source of the callback. * @param {string} reason Can be: `"timeout"` (`autoHideDuration` expired), `"clickaway"`. */ onClose: PropTypes.func, /** * Callback fired before the transition is entering. */ onEnter: PropTypes.func, /** * Callback fired when the transition has entered. */ onEntered: PropTypes.func, /** * Callback fired when the transition is entering. */ onEntering: PropTypes.func, /** * Callback fired before the transition is exiting. */ onExit: PropTypes.func, /** * Callback fired when the transition has exited. */ onExited: PropTypes.func, /** * Callback fired when the transition is exiting. */ onExiting: PropTypes.func, /** * @ignore */ onMouseEnter: PropTypes.func, /** * @ignore */ onMouseLeave: PropTypes.func, /** * If `true`, `Snackbar` is open. */ open: PropTypes.bool, /** * The number of milliseconds to wait before dismissing after user interaction. * If `autoHideDuration` prop isn't specified, it does nothing. * If `autoHideDuration` prop is specified but `resumeHideDuration` isn't, * we default to `autoHideDuration / 2` ms. */ resumeHideDuration: PropTypes.number, /** * The component used for the transition. * [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component. */ TransitionComponent: PropTypes.elementType, /** * 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({ enter: PropTypes.number, exit: PropTypes.number })]), /** * Props applied to the [`Transition`](http://reactcommunity.org/react-transition-group/transition#Transition-props) element. */ TransitionProps: PropTypes.object } : void 0; export default withStyles(styles, { flip: false, name: 'MuiSnackbar' })(Snackbar);
ajax/libs/material-ui/4.9.3/es/utils/isMuiElement.js
cdnjs/cdnjs
import React from 'react'; export default function isMuiElement(element, muiNames) { return React.isValidElement(element) && muiNames.indexOf(element.type.muiName) !== -1; }
ajax/libs/react-instantsearch/3.2.0/Dom.js
cdnjs/cdnjs
/*! ReactInstantSearch 3.2.0 | © Algolia, inc. | https://community.algolia.com/instantsearch.js/react/ */ (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_105__, __WEBPACK_EXTERNAL_MODULE_373__) { 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] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = 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; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ 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.InstantSearch = undefined; var _Configure = __webpack_require__(107); Object.defineProperty(exports, 'Configure', { enumerable: true, get: function get() { return _interopRequireDefault(_Configure).default; } }); var _CurrentRefinements = __webpack_require__(172); Object.defineProperty(exports, 'CurrentRefinements', { enumerable: true, get: function get() { return _interopRequireDefault(_CurrentRefinements).default; } }); var _HierarchicalMenu = __webpack_require__(179); Object.defineProperty(exports, 'HierarchicalMenu', { enumerable: true, get: function get() { return _interopRequireDefault(_HierarchicalMenu).default; } }); var _Highlight = __webpack_require__(325); Object.defineProperty(exports, 'Highlight', { enumerable: true, get: function get() { return _interopRequireDefault(_Highlight).default; } }); var _Snippet = __webpack_require__(331); Object.defineProperty(exports, 'Snippet', { enumerable: true, get: function get() { return _interopRequireDefault(_Snippet).default; } }); var _Hits = __webpack_require__(333); Object.defineProperty(exports, 'Hits', { enumerable: true, get: function get() { return _interopRequireDefault(_Hits).default; } }); var _HitsPerPage = __webpack_require__(336); Object.defineProperty(exports, 'HitsPerPage', { enumerable: true, get: function get() { return _interopRequireDefault(_HitsPerPage).default; } }); var _InfiniteHits = __webpack_require__(340); Object.defineProperty(exports, 'InfiniteHits', { enumerable: true, get: function get() { return _interopRequireDefault(_InfiniteHits).default; } }); var _Menu = __webpack_require__(343); Object.defineProperty(exports, 'Menu', { enumerable: true, get: function get() { return _interopRequireDefault(_Menu).default; } }); var _MultiRange = __webpack_require__(346); Object.defineProperty(exports, 'MultiRange', { enumerable: true, get: function get() { return _interopRequireDefault(_MultiRange).default; } }); var _Pagination = __webpack_require__(349); Object.defineProperty(exports, 'Pagination', { enumerable: true, get: function get() { return _interopRequireDefault(_Pagination).default; } }); var _PoweredBy = __webpack_require__(356); Object.defineProperty(exports, 'PoweredBy', { enumerable: true, get: function get() { return _interopRequireDefault(_PoweredBy).default; } }); var _RangeInput = __webpack_require__(359); Object.defineProperty(exports, 'RangeInput', { enumerable: true, get: function get() { return _interopRequireDefault(_RangeInput).default; } }); var _RangeSlider = __webpack_require__(362); Object.defineProperty(exports, 'RangeSlider', { enumerable: true, get: function get() { return _interopRequireDefault(_RangeSlider).default; } }); var _StarRating = __webpack_require__(363); Object.defineProperty(exports, 'StarRating', { enumerable: true, get: function get() { return _interopRequireDefault(_StarRating).default; } }); var _RefinementList = __webpack_require__(365); Object.defineProperty(exports, 'RefinementList', { enumerable: true, get: function get() { return _interopRequireDefault(_RefinementList).default; } }); var _ClearAll = __webpack_require__(368); Object.defineProperty(exports, 'ClearAll', { enumerable: true, get: function get() { return _interopRequireDefault(_ClearAll).default; } }); var _ScrollTo = __webpack_require__(370); Object.defineProperty(exports, 'ScrollTo', { enumerable: true, get: function get() { return _interopRequireDefault(_ScrollTo).default; } }); var _SearchBox = __webpack_require__(374); Object.defineProperty(exports, 'SearchBox', { enumerable: true, get: function get() { return _interopRequireDefault(_SearchBox).default; } }); var _SortBy = __webpack_require__(376); Object.defineProperty(exports, 'SortBy', { enumerable: true, get: function get() { return _interopRequireDefault(_SortBy).default; } }); var _Stats = __webpack_require__(379); Object.defineProperty(exports, 'Stats', { enumerable: true, get: function get() { return _interopRequireDefault(_Stats).default; } }); var _Toggle = __webpack_require__(382); Object.defineProperty(exports, 'Toggle', { enumerable: true, get: function get() { return _interopRequireDefault(_Toggle).default; } }); var _Panel = __webpack_require__(385); Object.defineProperty(exports, 'Panel', { enumerable: true, get: function get() { return _interopRequireDefault(_Panel).default; } }); var _createInstantSearch = __webpack_require__(387); var _createInstantSearch2 = _interopRequireDefault(_createInstantSearch); var _algoliasearch = __webpack_require__(392); var _algoliasearch2 = _interopRequireDefault(_algoliasearch); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var InstantSearch = (0, _createInstantSearch2.default)(_algoliasearch2.default, { Root: 'div', props: { className: 'ais-InstantSearch__root' } }); exports.InstantSearch = InstantSearch; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEqual2 = __webpack_require__(2); var _isEqual3 = _interopRequireDefault(_isEqual2); var _has2 = __webpack_require__(92); 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(106); 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, store = _context$ais.store, widgetsManager = _context$ais.widgetsManager; _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(searchParameters, _this.props, store.getState().widgets); } : null; var getMetadata = hasMetadata ? function (nextWidgetsState) { return connectorDesc.getMetadata(_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 }); } 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(); if (hasCleanUp) { var newState = connectorDesc.cleanUp(this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), { widgets: newState })); this.context.ais.onInternalStateUpdate(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: _react.PropTypes.object.isRequired }, _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; var searchState = { results: results, searching: searching, error: error }; return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchState, metadata, resultsFacetValues); }; this.refine = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this3.context.ais.onInternalStateUpdate(connectorDesc.refine.apply(connectorDesc, [_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 () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this3.context.ais.createHrefForState(connectorDesc.refine.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args))); }; this.cleanUp = function () { return connectorDesc.cleanUp.apply(connectorDesc, arguments); }; }, _temp; }; } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(3); /** * 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; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(4), isObjectLike = __webpack_require__(72); /** * 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; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(5), equalArrays = __webpack_require__(49), equalByTag = __webpack_require__(55), equalObjects = __webpack_require__(59), getTag = __webpack_require__(87), isArray = __webpack_require__(63), isBuffer = __webpack_require__(73), isTypedArray = __webpack_require__(77); /** 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; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(6), stackClear = __webpack_require__(14), stackDelete = __webpack_require__(15), stackGet = __webpack_require__(16), stackHas = __webpack_require__(17), stackSet = __webpack_require__(18); /** * 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; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(7), listCacheDelete = __webpack_require__(8), listCacheGet = __webpack_require__(11), listCacheHas = __webpack_require__(12), listCacheSet = __webpack_require__(13); /** * 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; /***/ }, /* 7 */ /***/ 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; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(9); /** 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; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(10); /** * 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; /***/ }, /* 10 */ /***/ 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; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(9); /** * 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; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(9); /** * 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; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(9); /** * 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; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(6); /** * 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; /***/ }, /* 15 */ /***/ 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; /***/ }, /* 16 */ /***/ 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; /***/ }, /* 17 */ /***/ 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; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(6), Map = __webpack_require__(19), MapCache = __webpack_require__(34); /** 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; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20), root = __webpack_require__(25); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var baseIsNative = __webpack_require__(21), getValue = __webpack_require__(33); /** * 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; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(22), isMasked = __webpack_require__(30), isObject = __webpack_require__(29), toSource = __webpack_require__(32); /** * 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; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), isObject = __webpack_require__(29); /** `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; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24), getRawTag = __webpack_require__(27), objectToString = __webpack_require__(28); /** `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; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(25); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(26); /** 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; /***/ }, /* 26 */ /***/ function(module, exports) { /* 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, (function() { return this; }()))) /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24); /** 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; /***/ }, /* 28 */ /***/ 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; /***/ }, /* 29 */ /***/ 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; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var coreJsData = __webpack_require__(31); /** 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; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(25); /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; module.exports = coreJsData; /***/ }, /* 32 */ /***/ 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; /***/ }, /* 33 */ /***/ 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; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var mapCacheClear = __webpack_require__(35), mapCacheDelete = __webpack_require__(43), mapCacheGet = __webpack_require__(46), mapCacheHas = __webpack_require__(47), mapCacheSet = __webpack_require__(48); /** * 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; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var Hash = __webpack_require__(36), ListCache = __webpack_require__(6), Map = __webpack_require__(19); /** * 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; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var hashClear = __webpack_require__(37), hashDelete = __webpack_require__(39), hashGet = __webpack_require__(40), hashHas = __webpack_require__(41), hashSet = __webpack_require__(42); /** * 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; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(38); /** * 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; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }, /* 39 */ /***/ 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; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(38); /** 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; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(38); /** 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; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(38); /** 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; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(44); /** * 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; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(45); /** * 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; /***/ }, /* 45 */ /***/ 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; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(44); /** * 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; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(44); /** * 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; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(44); /** * 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; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(50), arraySome = __webpack_require__(53), cacheHas = __webpack_require__(54); /** 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; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(34), setCacheAdd = __webpack_require__(51), setCacheHas = __webpack_require__(52); /** * * 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; /***/ }, /* 51 */ /***/ 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; /***/ }, /* 52 */ /***/ 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; /***/ }, /* 53 */ /***/ 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; /***/ }, /* 54 */ /***/ 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; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24), Uint8Array = __webpack_require__(56), eq = __webpack_require__(10), equalArrays = __webpack_require__(49), mapToArray = __webpack_require__(57), setToArray = __webpack_require__(58); /** 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; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(25); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }, /* 57 */ /***/ 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; /***/ }, /* 58 */ /***/ 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; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var getAllKeys = __webpack_require__(60); /** 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; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(61), getSymbols = __webpack_require__(64), keys = __webpack_require__(67); /** * 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; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(62), isArray = __webpack_require__(63); /** * 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; /***/ }, /* 62 */ /***/ 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; /***/ }, /* 63 */ /***/ 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; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(65), stubArray = __webpack_require__(66); /** 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; /***/ }, /* 65 */ /***/ 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; /***/ }, /* 66 */ /***/ 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; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(68), baseKeys = __webpack_require__(82), isArrayLike = __webpack_require__(86); /** * 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; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(69), isArguments = __webpack_require__(70), isArray = __webpack_require__(63), isBuffer = __webpack_require__(73), isIndex = __webpack_require__(76), isTypedArray = __webpack_require__(77); /** 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; /***/ }, /* 69 */ /***/ 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; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { var baseIsArguments = __webpack_require__(71), isObjectLike = __webpack_require__(72); /** 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; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), isObjectLike = __webpack_require__(72); /** `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; /***/ }, /* 72 */ /***/ 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; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(25), stubFalse = __webpack_require__(75); /** 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__(74)(module))) /***/ }, /* 74 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 75 */ /***/ 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; /***/ }, /* 76 */ /***/ 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; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(78), baseUnary = __webpack_require__(80), nodeUtil = __webpack_require__(81); /* 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; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), isLength = __webpack_require__(79), isObjectLike = __webpack_require__(72); /** `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; /***/ }, /* 79 */ /***/ 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; /***/ }, /* 80 */ /***/ 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; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(26); /** 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__(74)(module))) /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { var isPrototype = __webpack_require__(83), nativeKeys = __webpack_require__(84); /** 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; /***/ }, /* 83 */ /***/ 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; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(85); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }, /* 85 */ /***/ 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; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(22), isLength = __webpack_require__(79); /** * 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; /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { var DataView = __webpack_require__(88), Map = __webpack_require__(19), Promise = __webpack_require__(89), Set = __webpack_require__(90), WeakMap = __webpack_require__(91), baseGetTag = __webpack_require__(23), toSource = __webpack_require__(32); /** `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; /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20), root = __webpack_require__(25); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20), root = __webpack_require__(25); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20), root = __webpack_require__(25); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20), root = __webpack_require__(25); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { var baseHas = __webpack_require__(93), hasPath = __webpack_require__(94); /** * 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; /***/ }, /* 93 */ /***/ 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; /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(95), isArguments = __webpack_require__(70), isArray = __webpack_require__(63), isIndex = __webpack_require__(76), isLength = __webpack_require__(79), toKey = __webpack_require__(104); /** * 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; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(63), isKey = __webpack_require__(96), stringToPath = __webpack_require__(98), toString = __webpack_require__(101); /** * 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; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(63), isSymbol = __webpack_require__(97); /** 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; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), isObjectLike = __webpack_require__(72); /** `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; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { var memoizeCapped = __webpack_require__(99); /** 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; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { var memoize = __webpack_require__(100); /** 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; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(34); /** 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; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(102); /** * 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; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24), arrayMap = __webpack_require__(103), isArray = __webpack_require__(63), isSymbol = __webpack_require__(97); /** 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; /***/ }, /* 103 */ /***/ 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; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(97); /** 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; /***/ }, /* 105 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_105__; /***/ }, /* 106 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.shallowEqual = shallowEqual; exports.isSpecialClick = isSpecialClick; exports.capitalize = capitalize; exports.assertFacetDefined = assertFacetDefined; exports.getDisplayName = getDisplayName; // 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); }; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectConfigure = __webpack_require__(108); var _connectConfigure2 = _interopRequireDefault(_connectConfigure); var _Configure = __webpack_require__(171); 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); /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _keys2 = __webpack_require__(67); var _keys3 = _interopRequireDefault(_keys2); var _difference2 = __webpack_require__(109); var _difference3 = _interopRequireDefault(_difference2); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); 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__(1); 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 = '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 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; return _extends({}, nextSearchState, _defineProperty({}, namespace, _extends({}, (0, _omit3.default)(nextSearchState[namespace], nonPresentKeys), items))); }, cleanUp: function cleanUp(props, searchState) { var configureKeys = searchState[namespace] ? Object.keys(searchState[namespace]) : []; var configureState = configureKeys.reduce(function (acc, item) { if (!props[item]) { acc[item] = searchState[namespace][item]; } return acc; }, {}); return (0, _isEmpty3.default)(configureState) ? (0, _omit3.default)(searchState, namespace) : _extends({}, searchState, _defineProperty({}, namespace, configureState)); } }); /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { var baseDifference = __webpack_require__(110), baseFlatten = __webpack_require__(117), baseRest = __webpack_require__(119), isArrayLikeObject = __webpack_require__(128); /** * 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; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(50), arrayIncludes = __webpack_require__(111), arrayIncludesWith = __webpack_require__(116), arrayMap = __webpack_require__(103), baseUnary = __webpack_require__(80), cacheHas = __webpack_require__(54); /** 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; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(112); /** * 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; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(113), baseIsNaN = __webpack_require__(114), strictIndexOf = __webpack_require__(115); /** * 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; /***/ }, /* 113 */ /***/ 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; /***/ }, /* 114 */ /***/ 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; /***/ }, /* 115 */ /***/ 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; /***/ }, /* 116 */ /***/ 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; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(62), isFlattenable = __webpack_require__(118); /** * 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; /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24), isArguments = __webpack_require__(70), isArray = __webpack_require__(63); /** 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; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(120), overRest = __webpack_require__(121), setToString = __webpack_require__(123); /** * 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; /***/ }, /* 120 */ /***/ 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; /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(122); /* 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; /***/ }, /* 122 */ /***/ 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; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { var baseSetToString = __webpack_require__(124), shortOut = __webpack_require__(127); /** * 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; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { var constant = __webpack_require__(125), defineProperty = __webpack_require__(126), identity = __webpack_require__(120); /** * 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; /***/ }, /* 125 */ /***/ 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; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(20); var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); module.exports = defineProperty; /***/ }, /* 127 */ /***/ 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; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(86), isObjectLike = __webpack_require__(72); /** * 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; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { var baseKeys = __webpack_require__(82), getTag = __webpack_require__(87), isArguments = __webpack_require__(70), isArray = __webpack_require__(63), isArrayLike = __webpack_require__(86), isBuffer = __webpack_require__(73), isPrototype = __webpack_require__(83), isTypedArray = __webpack_require__(77); /** `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; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103), baseClone = __webpack_require__(131), baseUnset = __webpack_require__(162), castPath = __webpack_require__(95), copyObject = __webpack_require__(136), customOmitClone = __webpack_require__(167), flatRest = __webpack_require__(169), getAllKeysIn = __webpack_require__(147); /** 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; /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(5), arrayEach = __webpack_require__(132), assignValue = __webpack_require__(133), baseAssign = __webpack_require__(135), baseAssignIn = __webpack_require__(137), cloneBuffer = __webpack_require__(141), copyArray = __webpack_require__(142), copySymbols = __webpack_require__(143), copySymbolsIn = __webpack_require__(144), getAllKeys = __webpack_require__(60), getAllKeysIn = __webpack_require__(147), getTag = __webpack_require__(87), initCloneArray = __webpack_require__(148), initCloneByTag = __webpack_require__(149), initCloneObject = __webpack_require__(160), isArray = __webpack_require__(63), isBuffer = __webpack_require__(73), isObject = __webpack_require__(29), keys = __webpack_require__(67); /** 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; /***/ }, /* 132 */ /***/ 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; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(134), eq = __webpack_require__(10); /** 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; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { var defineProperty = __webpack_require__(126); /** * 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; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), keys = __webpack_require__(67); /** * 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; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(133), baseAssignValue = __webpack_require__(134); /** * 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; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), keysIn = __webpack_require__(138); /** * 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; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(68), baseKeysIn = __webpack_require__(139), isArrayLike = __webpack_require__(86); /** * 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; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(29), isPrototype = __webpack_require__(83), nativeKeysIn = __webpack_require__(140); /** 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; /***/ }, /* 140 */ /***/ 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; /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(25); /** 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__(74)(module))) /***/ }, /* 142 */ /***/ 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; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), getSymbols = __webpack_require__(64); /** * 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; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), getSymbolsIn = __webpack_require__(145); /** * 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; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(62), getPrototype = __webpack_require__(146), getSymbols = __webpack_require__(64), stubArray = __webpack_require__(66); /* 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; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(85); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(61), getSymbolsIn = __webpack_require__(145), keysIn = __webpack_require__(138); /** * 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; /***/ }, /* 148 */ /***/ 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; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(150), cloneDataView = __webpack_require__(151), cloneMap = __webpack_require__(152), cloneRegExp = __webpack_require__(155), cloneSet = __webpack_require__(156), cloneSymbol = __webpack_require__(158), cloneTypedArray = __webpack_require__(159); /** `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; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { var Uint8Array = __webpack_require__(56); /** * 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; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(150); /** * 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; /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { var addMapEntry = __webpack_require__(153), arrayReduce = __webpack_require__(154), mapToArray = __webpack_require__(57); /** 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; /***/ }, /* 153 */ /***/ 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; /***/ }, /* 154 */ /***/ 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; /***/ }, /* 155 */ /***/ 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; /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { var addSetEntry = __webpack_require__(157), arrayReduce = __webpack_require__(154), setToArray = __webpack_require__(58); /** 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; /***/ }, /* 157 */ /***/ 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; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(24); /** 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; /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(150); /** * 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; /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(161), getPrototype = __webpack_require__(146), isPrototype = __webpack_require__(83); /** * 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; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(29); /** 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; /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(95), last = __webpack_require__(163), parent = __webpack_require__(164), toKey = __webpack_require__(104); /** * 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; /***/ }, /* 163 */ /***/ 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; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(165), baseSlice = __webpack_require__(166); /** * 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; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(95), toKey = __webpack_require__(104); /** * 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; /***/ }, /* 166 */ /***/ 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; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { var isPlainObject = __webpack_require__(168); /** * 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; /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), getPrototype = __webpack_require__(146), isObjectLike = __webpack_require__(72); /** `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; /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { var flatten = __webpack_require__(170), overRest = __webpack_require__(121), setToString = __webpack_require__(123); /** * 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; /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(117); /** * 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; /***/ }, /* 171 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { return null; }; /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectCurrentRefinements = __webpack_require__(173); var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements); var _CurrentRefinements = __webpack_require__(174); 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); /***/ }, /* 173 */ /***/ 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 _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); var _react = __webpack_require__(105); 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 {function} query - the search query */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: _react.PropTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) { var items = metadata.reduce(function (res, meta) { return typeof meta.items !== 'undefined' ? res.concat(meta.items) : res; }, []); var query = props.clearsQuery && searchResults.results ? searchResults.results.query : undefined; return { items: props.transformItems ? props.transformItems(items) : items, canRefine: items.length > 0, query: query }; }, 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]; searchState = props.clearsQuery && searchState.query ? _extends({}, searchState, { query: '' }) : searchState; return refinementsToClear.reduce(function (res, clear) { return clear(res); }, searchState); } }); /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); 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, translate = _props.translate, items = _props.items, refine = _props.refine, 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: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string })).isRequired, refine: _react.PropTypes.func.isRequired, canRefine: _react.PropTypes.bool.isRequired, transformItems: _react.PropTypes.func }; CurrentRefinements.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ clearFilter: '✕' })(CurrentRefinements); /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(92); 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__(105); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(106); var _propTypes = __webpack_require__(176); 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, 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; }; } /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.withKeysPropType = exports.stateManagerPropType = exports.configManagerPropType = undefined; var _react = __webpack_require__(105); var configManagerPropType = exports.configManagerPropType = _react.PropTypes.shape({ register: _react.PropTypes.func.isRequired, swap: _react.PropTypes.func.isRequired, unregister: _react.PropTypes.func.isRequired }); var stateManagerPropType = exports.stateManagerPropType = _react.PropTypes.shape({ createURL: _react.PropTypes.func.isRequired, setState: _react.PropTypes.func.isRequired, getState: _react.PropTypes.func.isRequired, unlisten: _react.PropTypes.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; }; }; /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = classNames; var _classnames = __webpack_require__(178); 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; })) }; }; } /***/ }, /* 178 */ /***/ 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; } }()); /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHierarchicalMenu = __webpack_require__(180); var _connectHierarchicalMenu2 = _interopRequireDefault(_connectHierarchicalMenu); var _HierarchicalMenu = __webpack_require__(321); 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); /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getId = undefined; var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); 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 _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); var _algoliasearchHelper = __webpack_require__(181); 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) { var id = getId(props); if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') { var subState = searchState[namespace]; if (subState[id] === '') { return null; } return subState[id]; } if (props.defaultRefinement) { return props.defaultRefinement; } return null; } function getValue(path, props, searchState) { var id = props.id, attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel; var currentRefinement = getCurrentRefinement(props, searchState); 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) { return value.slice(0, limit).map(function (v) { return { label: v.name, value: getValue(v.path, props, searchState), count: v.count, isRefined: v.isRefined, items: v.data && transformValue(v.data, limit, props, searchState) }; }); } 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: _react.PropTypes.string, rootPath: _react.PropTypes.string, showParentLevel: _react.PropTypes.bool, defaultRefinement: _react.PropTypes.string, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, transformItems: _react.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(props); var results = searchResults.results; var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState), canRefine: false }; } var limit = showMore ? limitMax : limitMin; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue(value.data, limit, props, searchState) : []; return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: getCurrentRefinement(props, searchState), canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId(props); return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, id, nextRefinement || '')))); }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, 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(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); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var rootAttribute = props.attributes[0]; var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState); return { id: id, items: !currentRefinement ? [] : [{ label: rootAttribute + ': ' + currentRefinement, attributeName: rootAttribute, value: function value(nextState) { return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, '')))); }, currentRefinement: currentRefinement }] }; } }); /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var AlgoliaSearchHelper = __webpack_require__(182); var SearchParameters = __webpack_require__(183); var SearchResults = __webpack_require__(246); /** * 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__(320); /** * 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__(305); module.exports = algoliasearchHelper; /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var SearchParameters = __webpack_require__(183); var SearchResults = __webpack_require__(246); var DerivedHelper = __webpack_require__(298); var requestBuilder = __webpack_require__(304); var util = __webpack_require__(299); var events = __webpack_require__(303); var flatten = __webpack_require__(170); var forEach = __webpack_require__(192); var isEmpty = __webpack_require__(129); var map = __webpack_require__(210); var url = __webpack_require__(305); var version = __webpack_require__(320); /** * 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 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 */ AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) { this.state = this.state.setPage(0).toggleRefinement(facet, value); this._change(); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleRefinement} */ AlgoliaSearchHelper.prototype.toggleRefine = function() { return this.toggleRefinement.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.toggleRefinement('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) 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`, `results` 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' */ module.exports = AlgoliaSearchHelper; /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var keys = __webpack_require__(67); var intersection = __webpack_require__(184); var forOwn = __webpack_require__(187); var forEach = __webpack_require__(192); var filter = __webpack_require__(195); var map = __webpack_require__(210); var reduce = __webpack_require__(212); var omit = __webpack_require__(130); var indexOf = __webpack_require__(214); var isNaN = __webpack_require__(218); var isArray = __webpack_require__(63); var isEmpty = __webpack_require__(129); var isEqual = __webpack_require__(2); var isUndefined = __webpack_require__(220); var isString = __webpack_require__(221); var isFunction = __webpack_require__(22); var find = __webpack_require__(222); var trim = __webpack_require__(225); var defaults = __webpack_require__(233); var merge = __webpack_require__(238); var valToNumber = __webpack_require__(243); var filterState = __webpack_require__(244); var RefinementList = __webpack_require__(245); /** * 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 */ toggleRefinement: function toggleRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleFacetRefinement(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} */ toggleFacetRefinement: function toggleFacetRefinement(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; /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103), baseIntersection = __webpack_require__(185), baseRest = __webpack_require__(119), castArrayLikeObject = __webpack_require__(186); /** * 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; /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(50), arrayIncludes = __webpack_require__(111), arrayIncludesWith = __webpack_require__(116), arrayMap = __webpack_require__(103), baseUnary = __webpack_require__(80), cacheHas = __webpack_require__(54); /* 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; /***/ }, /* 186 */ /***/ function(module, exports, __webpack_require__) { var isArrayLikeObject = __webpack_require__(128); /** * 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; /***/ }, /* 187 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(188), castFunction = __webpack_require__(191); /** * 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; /***/ }, /* 188 */ /***/ function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(189), keys = __webpack_require__(67); /** * 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; /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(190); /** * 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; /***/ }, /* 190 */ /***/ 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; /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(120); /** * 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; /***/ }, /* 192 */ /***/ function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(132), baseEach = __webpack_require__(193), castFunction = __webpack_require__(191), isArray = __webpack_require__(63); /** * 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; /***/ }, /* 193 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(188), createBaseEach = __webpack_require__(194); /** * 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; /***/ }, /* 194 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(86); /** * 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; /***/ }, /* 195 */ /***/ function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(65), baseFilter = __webpack_require__(196), baseIteratee = __webpack_require__(197), isArray = __webpack_require__(63); /** * 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; /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(193); /** * 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; /***/ }, /* 197 */ /***/ function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(198), baseMatchesProperty = __webpack_require__(203), identity = __webpack_require__(120), isArray = __webpack_require__(63), property = __webpack_require__(207); /** * 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; /***/ }, /* 198 */ /***/ function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(199), getMatchData = __webpack_require__(200), matchesStrictComparable = __webpack_require__(202); /** * 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; /***/ }, /* 199 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(5), baseIsEqual = __webpack_require__(3); /** 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; /***/ }, /* 200 */ /***/ function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(201), keys = __webpack_require__(67); /** * 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; /***/ }, /* 201 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(29); /** * 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; /***/ }, /* 202 */ /***/ 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; /***/ }, /* 203 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(3), get = __webpack_require__(204), hasIn = __webpack_require__(205), isKey = __webpack_require__(96), isStrictComparable = __webpack_require__(201), matchesStrictComparable = __webpack_require__(202), toKey = __webpack_require__(104); /** 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; /***/ }, /* 204 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(165); /** * 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; /***/ }, /* 205 */ /***/ function(module, exports, __webpack_require__) { var baseHasIn = __webpack_require__(206), hasPath = __webpack_require__(94); /** * 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; /***/ }, /* 206 */ /***/ 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; /***/ }, /* 207 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(208), basePropertyDeep = __webpack_require__(209), isKey = __webpack_require__(96), toKey = __webpack_require__(104); /** * 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; /***/ }, /* 208 */ /***/ 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; /***/ }, /* 209 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(165); /** * 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; /***/ }, /* 210 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103), baseIteratee = __webpack_require__(197), baseMap = __webpack_require__(211), isArray = __webpack_require__(63); /** * 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; /***/ }, /* 211 */ /***/ function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(193), isArrayLike = __webpack_require__(86); /** * 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; /***/ }, /* 212 */ /***/ function(module, exports, __webpack_require__) { var arrayReduce = __webpack_require__(154), baseEach = __webpack_require__(193), baseIteratee = __webpack_require__(197), baseReduce = __webpack_require__(213), isArray = __webpack_require__(63); /** * 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; /***/ }, /* 213 */ /***/ 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; /***/ }, /* 214 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(112), toInteger = __webpack_require__(215); /* 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; /***/ }, /* 215 */ /***/ function(module, exports, __webpack_require__) { var toFinite = __webpack_require__(216); /** * 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; /***/ }, /* 216 */ /***/ function(module, exports, __webpack_require__) { var toNumber = __webpack_require__(217); /** 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; /***/ }, /* 217 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(29), isSymbol = __webpack_require__(97); /** 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; /***/ }, /* 218 */ /***/ function(module, exports, __webpack_require__) { var isNumber = __webpack_require__(219); /** * 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 baseGetTag = __webpack_require__(23), isObjectLike = __webpack_require__(72); /** `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; /***/ }, /* 220 */ /***/ 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; /***/ }, /* 221 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(23), isArray = __webpack_require__(63), isObjectLike = __webpack_require__(72); /** `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; /***/ }, /* 222 */ /***/ function(module, exports, __webpack_require__) { var createFind = __webpack_require__(223), findIndex = __webpack_require__(224); /** * 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; /***/ }, /* 223 */ /***/ function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(197), isArrayLike = __webpack_require__(86), keys = __webpack_require__(67); /** * 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; /***/ }, /* 224 */ /***/ function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(113), baseIteratee = __webpack_require__(197), toInteger = __webpack_require__(215); /* 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; /***/ }, /* 225 */ /***/ function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(102), castSlice = __webpack_require__(226), charsEndIndex = __webpack_require__(227), charsStartIndex = __webpack_require__(228), stringToArray = __webpack_require__(229), toString = __webpack_require__(101); /** 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; /***/ }, /* 226 */ /***/ function(module, exports, __webpack_require__) { var baseSlice = __webpack_require__(166); /** * 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; /***/ }, /* 227 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(112); /** * 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; /***/ }, /* 228 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(112); /** * 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; /***/ }, /* 229 */ /***/ function(module, exports, __webpack_require__) { var asciiToArray = __webpack_require__(230), hasUnicode = __webpack_require__(231), unicodeToArray = __webpack_require__(232); /** * 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; /***/ }, /* 230 */ /***/ 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; /***/ }, /* 231 */ /***/ 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; /***/ }, /* 232 */ /***/ 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; /***/ }, /* 233 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(122), assignInWith = __webpack_require__(234), baseRest = __webpack_require__(119), customDefaultsAssignIn = __webpack_require__(237); /** * 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; /***/ }, /* 234 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), createAssigner = __webpack_require__(235), keysIn = __webpack_require__(138); /** * 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; /***/ }, /* 235 */ /***/ function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(119), isIterateeCall = __webpack_require__(236); /** * 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; /***/ }, /* 236 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(10), isArrayLike = __webpack_require__(86), isIndex = __webpack_require__(76), isObject = __webpack_require__(29); /** * 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; /***/ }, /* 237 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(10); /** 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; /***/ }, /* 238 */ /***/ function(module, exports, __webpack_require__) { var baseMerge = __webpack_require__(239), createAssigner = __webpack_require__(235); /** * 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; /***/ }, /* 239 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(5), assignMergeValue = __webpack_require__(240), baseFor = __webpack_require__(189), baseMergeDeep = __webpack_require__(241), isObject = __webpack_require__(29), keysIn = __webpack_require__(138); /** * 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; /***/ }, /* 240 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(134), eq = __webpack_require__(10); /** * 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; /***/ }, /* 241 */ /***/ function(module, exports, __webpack_require__) { var assignMergeValue = __webpack_require__(240), cloneBuffer = __webpack_require__(141), cloneTypedArray = __webpack_require__(159), copyArray = __webpack_require__(142), initCloneObject = __webpack_require__(160), isArguments = __webpack_require__(70), isArray = __webpack_require__(63), isArrayLikeObject = __webpack_require__(128), isBuffer = __webpack_require__(73), isFunction = __webpack_require__(22), isObject = __webpack_require__(29), isPlainObject = __webpack_require__(168), isTypedArray = __webpack_require__(77), toPlainObject = __webpack_require__(242); /** * 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; /***/ }, /* 242 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(136), keysIn = __webpack_require__(138); /** * 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; /***/ }, /* 243 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var map = __webpack_require__(210); var isArray = __webpack_require__(63); var isNumber = __webpack_require__(219); var isString = __webpack_require__(221); 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; /***/ }, /* 244 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var forEach = __webpack_require__(192); var filter = __webpack_require__(195); var map = __webpack_require__(210); var isEmpty = __webpack_require__(129); var indexOf = __webpack_require__(214); 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; /***/ }, /* 245 */ /***/ 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__(220); var isString = __webpack_require__(221); var isFunction = __webpack_require__(22); var isEmpty = __webpack_require__(129); var defaults = __webpack_require__(233); var reduce = __webpack_require__(212); var filter = __webpack_require__(195); var omit = __webpack_require__(130); 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__(214); 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; /***/ }, /* 246 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var forEach = __webpack_require__(192); var compact = __webpack_require__(247); var indexOf = __webpack_require__(214); var findIndex = __webpack_require__(224); var get = __webpack_require__(204); var sumBy = __webpack_require__(248); var find = __webpack_require__(222); var includes = __webpack_require__(250); var map = __webpack_require__(210); var orderBy = __webpack_require__(253); var defaults = __webpack_require__(233); var merge = __webpack_require__(238); var isArray = __webpack_require__(63); var isFunction = __webpack_require__(22); var partial = __webpack_require__(258); var partialRight = __webpack_require__(290); var formatSort = __webpack_require__(291); var generateHierarchicalTree = __webpack_require__(294); /** * @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]; /** * 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; /***/ }, /* 247 */ /***/ 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; /***/ }, /* 248 */ /***/ function(module, exports, __webpack_require__) { var baseIteratee = __webpack_require__(197), baseSum = __webpack_require__(249); /** * 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; /***/ }, /* 249 */ /***/ 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; /***/ }, /* 250 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(112), isArrayLike = __webpack_require__(86), isString = __webpack_require__(221), toInteger = __webpack_require__(215), values = __webpack_require__(251); /* 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; /***/ }, /* 251 */ /***/ function(module, exports, __webpack_require__) { var baseValues = __webpack_require__(252), keys = __webpack_require__(67); /** * 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; /***/ }, /* 252 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103); /** * 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; /***/ }, /* 253 */ /***/ function(module, exports, __webpack_require__) { var baseOrderBy = __webpack_require__(254), isArray = __webpack_require__(63); /** * 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; /***/ }, /* 254 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103), baseIteratee = __webpack_require__(197), baseMap = __webpack_require__(211), baseSortBy = __webpack_require__(255), baseUnary = __webpack_require__(80), compareMultiple = __webpack_require__(256), identity = __webpack_require__(120); /** * 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; /***/ }, /* 255 */ /***/ 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; /***/ }, /* 256 */ /***/ function(module, exports, __webpack_require__) { var compareAscending = __webpack_require__(257); /** * 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; /***/ }, /* 257 */ /***/ function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(97); /** * 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; /***/ }, /* 258 */ /***/ function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(119), createWrap = __webpack_require__(259), getHolder = __webpack_require__(285), replaceHolders = __webpack_require__(287); /** 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; /***/ }, /* 259 */ /***/ function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(260), createBind = __webpack_require__(262), createCurry = __webpack_require__(264), createHybrid = __webpack_require__(265), createPartial = __webpack_require__(288), getData = __webpack_require__(273), mergeData = __webpack_require__(289), setData = __webpack_require__(280), setWrapToString = __webpack_require__(281), toInteger = __webpack_require__(215); /** 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; /***/ }, /* 260 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(120), metaMap = __webpack_require__(261); /** * 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; /***/ }, /* 261 */ /***/ function(module, exports, __webpack_require__) { var WeakMap = __webpack_require__(91); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; module.exports = metaMap; /***/ }, /* 262 */ /***/ function(module, exports, __webpack_require__) { var createCtor = __webpack_require__(263), root = __webpack_require__(25); /** 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; /***/ }, /* 263 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(161), isObject = __webpack_require__(29); /** * 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; /***/ }, /* 264 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(122), createCtor = __webpack_require__(263), createHybrid = __webpack_require__(265), createRecurry = __webpack_require__(269), getHolder = __webpack_require__(285), replaceHolders = __webpack_require__(287), root = __webpack_require__(25); /** * 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; /***/ }, /* 265 */ /***/ function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(266), composeArgsRight = __webpack_require__(267), countHolders = __webpack_require__(268), createCtor = __webpack_require__(263), createRecurry = __webpack_require__(269), getHolder = __webpack_require__(285), reorder = __webpack_require__(286), replaceHolders = __webpack_require__(287), root = __webpack_require__(25); /** 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; /***/ }, /* 266 */ /***/ 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; /***/ }, /* 267 */ /***/ 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; /***/ }, /* 268 */ /***/ 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; /***/ }, /* 269 */ /***/ function(module, exports, __webpack_require__) { var isLaziable = __webpack_require__(270), setData = __webpack_require__(280), setWrapToString = __webpack_require__(281); /** 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; /***/ }, /* 270 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(271), getData = __webpack_require__(273), getFuncName = __webpack_require__(275), lodash = __webpack_require__(277); /** * 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; /***/ }, /* 271 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(161), baseLodash = __webpack_require__(272); /** 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; /***/ }, /* 272 */ /***/ function(module, exports) { /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } module.exports = baseLodash; /***/ }, /* 273 */ /***/ function(module, exports, __webpack_require__) { var metaMap = __webpack_require__(261), noop = __webpack_require__(274); /** * 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; /***/ }, /* 274 */ /***/ 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; /***/ }, /* 275 */ /***/ function(module, exports, __webpack_require__) { var realNames = __webpack_require__(276); /** 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; /***/ }, /* 276 */ /***/ function(module, exports) { /** Used to lookup unminified function names. */ var realNames = {}; module.exports = realNames; /***/ }, /* 277 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(271), LodashWrapper = __webpack_require__(278), baseLodash = __webpack_require__(272), isArray = __webpack_require__(63), isObjectLike = __webpack_require__(72), wrapperClone = __webpack_require__(279); /** 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; /***/ }, /* 278 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(161), baseLodash = __webpack_require__(272); /** * 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; /***/ }, /* 279 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(271), LodashWrapper = __webpack_require__(278), copyArray = __webpack_require__(142); /** * 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; /***/ }, /* 280 */ /***/ function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(260), shortOut = __webpack_require__(127); /** * 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; /***/ }, /* 281 */ /***/ function(module, exports, __webpack_require__) { var getWrapDetails = __webpack_require__(282), insertWrapDetails = __webpack_require__(283), setToString = __webpack_require__(123), updateWrapDetails = __webpack_require__(284); /** * 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; /***/ }, /* 282 */ /***/ 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; /***/ }, /* 283 */ /***/ 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; /***/ }, /* 284 */ /***/ function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(132), arrayIncludes = __webpack_require__(111); /** 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; /***/ }, /* 285 */ /***/ 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; /***/ }, /* 286 */ /***/ function(module, exports, __webpack_require__) { var copyArray = __webpack_require__(142), isIndex = __webpack_require__(76); /* 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; /***/ }, /* 287 */ /***/ 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; /***/ }, /* 288 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(122), createCtor = __webpack_require__(263), root = __webpack_require__(25); /** 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; /***/ }, /* 289 */ /***/ function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(266), composeArgsRight = __webpack_require__(267), replaceHolders = __webpack_require__(287); /** 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; /***/ }, /* 290 */ /***/ function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(119), createWrap = __webpack_require__(259), getHolder = __webpack_require__(285), replaceHolders = __webpack_require__(287); /** 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; /***/ }, /* 291 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var reduce = __webpack_require__(212); var find = __webpack_require__(222); var startsWith = __webpack_require__(292); /** * 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; }, [[], []]); }; /***/ }, /* 292 */ /***/ function(module, exports, __webpack_require__) { var baseClamp = __webpack_require__(293), baseToString = __webpack_require__(102), toInteger = __webpack_require__(215), toString = __webpack_require__(101); /** * 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; /***/ }, /* 293 */ /***/ 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; /***/ }, /* 294 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = generateTrees; var last = __webpack_require__(163); var map = __webpack_require__(210); var reduce = __webpack_require__(212); var orderBy = __webpack_require__(253); var trim = __webpack_require__(225); var find = __webpack_require__(222); var pickBy = __webpack_require__(295); var prepareHierarchicalFacetSortBy = __webpack_require__(291); 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 }; }; } /***/ }, /* 295 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(103), baseIteratee = __webpack_require__(197), basePickBy = __webpack_require__(296), getAllKeysIn = __webpack_require__(147); /** * 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; /***/ }, /* 296 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(165), baseSet = __webpack_require__(297), castPath = __webpack_require__(95); /** * 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; /***/ }, /* 297 */ /***/ function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(133), castPath = __webpack_require__(95), isIndex = __webpack_require__(76), isObject = __webpack_require__(29), toKey = __webpack_require__(104); /** * 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; /***/ }, /* 298 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var util = __webpack_require__(299); var events = __webpack_require__(303); /** * 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; /***/ }, /* 299 */ /***/ 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 = ({"NODE_ENV":"production"}).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__(301); 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__(302); 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, (function() { return this; }()), __webpack_require__(300))) /***/ }, /* 300 */ /***/ 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; }; /***/ }, /* 301 */ /***/ 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'; } /***/ }, /* 302 */ /***/ 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 } } /***/ }, /* 303 */ /***/ 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; } /***/ }, /* 304 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var forEach = __webpack_require__(192); var map = __webpack_require__(210); var reduce = __webpack_require__(212); var merge = __webpack_require__(238); var isArray = __webpack_require__(63); 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; /***/ }, /* 305 */ /***/ 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__(306); var SearchParameters = __webpack_require__(183); var qs = __webpack_require__(310); var bind = __webpack_require__(315); var forEach = __webpack_require__(192); var pick = __webpack_require__(316); var map = __webpack_require__(210); var mapKeys = __webpack_require__(318); var mapValues = __webpack_require__(319); var isString = __webpack_require__(221); var isPlainObject = __webpack_require__(168); var isArray = __webpack_require__(63); var invert = __webpack_require__(307); var encode = __webpack_require__(312).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}); }; /***/ }, /* 306 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var invert = __webpack_require__(307); var keys = __webpack_require__(67); 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]; } }; /***/ }, /* 307 */ /***/ function(module, exports, __webpack_require__) { var constant = __webpack_require__(125), createInverter = __webpack_require__(308), identity = __webpack_require__(120); /** * 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; /***/ }, /* 308 */ /***/ function(module, exports, __webpack_require__) { var baseInverter = __webpack_require__(309); /** * 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; /***/ }, /* 309 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(188); /** * 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; /***/ }, /* 310 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var stringify = __webpack_require__(311); var parse = __webpack_require__(314); var formats = __webpack_require__(313); module.exports = { formats: formats, parse: parse, stringify: stringify }; /***/ }, /* 311 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(312); var formats = __webpack_require__(313); 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); }; /***/ }, /* 312 */ /***/ function(module, exports) { '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)); }; /***/ }, /* 313 */ /***/ function(module, exports) { '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' }; /***/ }, /* 314 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(312); 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); }; /***/ }, /* 315 */ /***/ function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(119), createWrap = __webpack_require__(259), getHolder = __webpack_require__(285), replaceHolders = __webpack_require__(287); /** 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; /***/ }, /* 316 */ /***/ function(module, exports, __webpack_require__) { var basePick = __webpack_require__(317), flatRest = __webpack_require__(169); /** * 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; /***/ }, /* 317 */ /***/ function(module, exports, __webpack_require__) { var basePickBy = __webpack_require__(296), hasIn = __webpack_require__(205); /** * 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; /***/ }, /* 318 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(134), baseForOwn = __webpack_require__(188), baseIteratee = __webpack_require__(197); /** * 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; /***/ }, /* 319 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(134), baseForOwn = __webpack_require__(188), baseIteratee = __webpack_require__(197); /** * 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; /***/ }, /* 320 */ /***/ function(module, exports) { 'use strict'; module.exports = '2.18.0'; /***/ }, /* 321 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(316); 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(322); var _List2 = _interopRequireDefault(_List); var _Link = __webpack_require__(324); var _Link2 = _interopRequireDefault(_Link); var _classNames = __webpack_require__(177); 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 = _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string.isRequired, value: _react.PropTypes.string, count: _react.PropTypes.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, createURL = _this$props.createURL, 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: _react.PropTypes.func.isRequired, refine: _react.PropTypes.func.isRequired, createURL: _react.PropTypes.func.isRequired, canRefine: _react.PropTypes.bool.isRequired, items: itemsPropType, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, transformItems: _react.PropTypes.func }; HierarchicalMenu.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ showMore: function showMore(extended) { return extended ? 'Show less' : 'Show more'; } })(HierarchicalMenu); /***/ }, /* 322 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _SearchBox = __webpack_require__(323); 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 = _react.PropTypes.arrayOf(_react.PropTypes.shape({ value: _react.PropTypes.any, label: _react.PropTypes.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, limitMin = _this$props.limitMin, limitMax = _this$props.limitMax; var extended = _this.state.extended; return extended ? limitMax : limitMin; }; _this.renderItem = function (item) { 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), items ); }; _this.state = { extended: false, query: '' }; return _this; } _createClass(List, [{ key: 'renderShowMore', value: function renderShowMore() { var _props = this.props, showMore = _props.showMore, translate = _props.translate, 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, cx = _props2.cx, searchForItems = _props2.searchForItems, isFromSearch = _props2.isFromSearch, translate = _props2.translate, items = _props2.items, 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: isFromSearch ? 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]); } } }), noResults ); } }, { key: 'render', value: function render() { var _this3 = this; var _props3 = this.props, cx = _props3.cx, items = _props3.items, withSearchBox = _props3.withSearchBox, 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); }) ), this.renderShowMore() ); } }]); return List; }(_react.Component); List.propTypes = { cx: _react.PropTypes.func.isRequired, // Only required with showMore. translate: _react.PropTypes.func, items: itemsPropType, renderItem: _react.PropTypes.func.isRequired, selectItem: _react.PropTypes.func, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, limit: _react.PropTypes.number, show: _react.PropTypes.func, searchForItems: _react.PropTypes.func, withSearchBox: _react.PropTypes.bool, isFromSearch: _react.PropTypes.bool, canRefine: _react.PropTypes.bool }; exports.default = List; /***/ }, /* 323 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); 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)('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, refine = _this$props.refine, 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(); var _this$props2 = _this.props, refine = _this$props2.refine, searchAsYouType = _this$props2.searchAsYouType; if (!searchAsYouType) { refine(_this.getQuery()); } return false; }; _this.onChange = function (e) { _this.setQuery(e.target.value); }; _this.onReset = function () { _this.setQuery(''); _this.input.focus(); }; _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 _props = this.props, translate = _props.translate, autoFocus = _props.autoFocus; var query = this.getQuery(); /* 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')), _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', required: true, value: query, onChange: this.onChange }, cx('input'))), _react2.default.createElement( 'button', _extends({ type: 'submit', title: translate('submitTitle') }, cx('submit')), _react2.default.createElement( 'svg', { role: 'img' }, _react2.default.createElement('use', { xlinkHref: '#sbx-icon-search-13' }) ) ), _react2.default.createElement( 'button', _extends({ type: 'reset', title: translate('resetTitle') }, cx('reset'), { onClick: this.onReset }), _react2.default.createElement( 'svg', { role: 'img' }, _react2.default.createElement('use', { xlinkHref: '#sbx-icon-clear-3' }) ) ) ) ); /* eslint-enable */ } }]); return SearchBox; }(_react.Component); SearchBox.propTypes = { currentRefinement: _react.PropTypes.string, refine: _react.PropTypes.func.isRequired, translate: _react.PropTypes.func.isRequired, focusShortcuts: _react.PropTypes.arrayOf(_react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number])), autoFocus: _react.PropTypes.bool, searchAsYouType: _react.PropTypes.bool, onSubmit: _react.PropTypes.func, // For testing purposes __inputRef: _react.PropTypes.func }; SearchBox.defaultProps = { currentRefinement: '', focusShortcuts: ['s', '/'], autoFocus: false, searchAsYouType: true }; exports.default = (0, _translatable2.default)({ submit: null, reset: null, resetTitle: 'Clear the search query.', submitTitle: 'Submit your search query.', placeholder: 'Search here…' })(SearchBox); /***/ }, /* 324 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(106); 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: _react.PropTypes.func.isRequired }; exports.default = Link; /***/ }, /* 325 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHighlight = __webpack_require__(326); var _connectHighlight2 = _interopRequireDefault(_connectHighlight); var _Highlight = __webpack_require__(329); 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 * @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); /***/ }, /* 326 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); var _highlight = __webpack_require__(327); var _highlight2 = _interopRequireDefault(_highlight); var _highlightTags = __webpack_require__(328); var _highlightTags2 = _interopRequireDefault(_highlightTags); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var highlight = function highlight(_ref) { var attributeName = _ref.attributeName, hit = _ref.hit, 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 }; } }); /***/ }, /* 327 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _get2 = __webpack_require__(204); 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, 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 = (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, 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) { (function () { 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; } /***/ }, /* 328 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var timestamp = Date.now().toString(); exports.default = { highlightPreTag: "<ais-highlight-" + timestamp + ">", highlightPostTag: "</ais-highlight-" + timestamp + ">" }; /***/ }, /* 329 */ /***/ 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _Highlighter = __webpack_require__(330); 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: _react2.default.PropTypes.object.isRequired, attributeName: _react2.default.PropTypes.string.isRequired, highlight: _react2.default.PropTypes.func.isRequired }; /***/ }, /* 330 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Highlighter; var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Highlighter(_ref) { var hit = _ref.hit, attributeName = _ref.attributeName, highlight = _ref.highlight, highlightProperty = _ref.highlightProperty; 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 ); } return _react2.default.createElement( "em", { key: key, className: "ais-Highlight__highlighted" }, v.value ); }); return _react2.default.createElement( "span", { className: "ais-Highlight" }, reactHighlighted ); } Highlighter.propTypes = { hit: _react2.default.PropTypes.object.isRequired, attributeName: _react2.default.PropTypes.string.isRequired, highlight: _react2.default.PropTypes.func.isRequired, highlightProperty: _react2.default.PropTypes.string.isRequired }; /***/ }, /* 331 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHighlight = __webpack_require__(326); var _connectHighlight2 = _interopRequireDefault(_connectHighlight); var _Snippet = __webpack_require__(332); 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 * @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); /***/ }, /* 332 */ /***/ 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _Highlighter = __webpack_require__(330); 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: _react2.default.PropTypes.object.isRequired, attributeName: _react2.default.PropTypes.string.isRequired, highlight: _react2.default.PropTypes.func.isRequired }; /***/ }, /* 333 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHits = __webpack_require__(334); var _connectHits2 = _interopRequireDefault(_connectHits); var _Hits = __webpack_require__(335); 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); /***/ }, /* 334 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); 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 * parameter to the [searchParameters](guide/Search_parameters.html) prop on `<InstantSearch/>`. * @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 hits = searchResults.results ? searchResults.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; } }); /***/ }, /* 335 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(177); 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, ItemComponent = _props.hitComponent, 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: _react.PropTypes.array, hitComponent: _react.PropTypes.func.isRequired }; 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), '...' ); } }; exports.default = Hits; /***/ }, /* 336 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectHitsPerPage = __webpack_require__(337); var _connectHitsPerPage2 = _interopRequireDefault(_connectHitsPerPage); var _HitsPerPage = __webpack_require__(338); 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. * * @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}/> * </InstantSearch> * ); * } */ exports.default = (0, _connectHitsPerPage2.default)(_HitsPerPage2.default); /***/ }, /* 337 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); 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 _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); 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 'hitsPerPage'; } function getCurrentRefinement(props, searchState) { var id = getId(); if (typeof searchState[id] !== 'undefined') { if (typeof searchState[id] === 'string') { return parseInt(searchState[id], 10); } return searchState[id]; } return props.defaultRefinement; } /** * 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: _react.PropTypes.number.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string, value: _react.PropTypes.number.isRequired })).isRequired, transformItems: _react.PropTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState); 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, nextHitsPerPage) { var id = getId(); return _extends({}, searchState, _defineProperty({}, id, nextHitsPerPage)); }, cleanUp: function cleanUp(props, searchState) { return (0, _omit3.default)(searchState, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement(props, searchState)); }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }, /* 338 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(339); var _Select2 = _interopRequireDefault(_Select); var _classNames = __webpack_require__(177); 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, currentRefinement = _props.currentRefinement, refine = _props.refine, items = _props.items; return _react2.default.createElement(_Select2.default, { onSelect: refine, selectedItem: currentRefinement, items: items, cx: cx }); } }]); return HitsPerPage; }(_react.Component); HitsPerPage.propTypes = { refine: _react.PropTypes.func.isRequired, currentRefinement: _react.PropTypes.number.isRequired, transformItems: _react.PropTypes.func, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ /** * Number of hits to display. */ value: _react.PropTypes.number.isRequired, /** * Label to display on the option. */ label: _react.PropTypes.string })) }; exports.default = HitsPerPage; /***/ }, /* 339 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(92); 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 _react = __webpack_require__(105); 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, cx = _props.cx, items = _props.items, 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: _react.PropTypes.func.isRequired, onSelect: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ value: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]).isRequired, key: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]), label: _react.PropTypes.string, disabled: _react.PropTypes.bool })).isRequired, selectedItem: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]).isRequired }; exports.default = Select; /***/ }, /* 340 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectInfiniteHits = __webpack_require__(341); var _connectInfiniteHits2 = _interopRequireDefault(_connectInfiniteHits); var _InfiniteHits = __webpack_require__(342); 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 * @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); /***/ }, /* 341 */ /***/ 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 _createConnector = __webpack_require__(1); 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 _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'; } /** * 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 */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { if (!searchResults.results) { this._allResults = []; return { hits: this._allResults, hasMore: false }; } var _searchResults$result = searchResults.results, hits = _searchResults$result.hits, page = _searchResults$result.page, nbPages = _searchResults$result.nbPages, hitsPerPage = _searchResults$result.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) { var id = getId(); var currentPage = searchState[id] ? searchState[id] : 0; return searchParameters.setQueryParameters({ page: currentPage }); }, refine: function refine(props, searchState) { var id = getId(); var nextPage = searchState[id] ? Number(searchState[id]) + 1 : 1; return _extends({}, searchState, _defineProperty({}, id, nextPage)); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); if (prevSearchState[id] === nextSearchState[id]) { return _extends({}, nextSearchState, _defineProperty({}, id, 0)); } return nextSearchState; } }); /***/ }, /* 342 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(177); 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)('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, ItemComponent = _props.hitComponent, hits = _props.hits, hasMore = _props.hasMore, refine = _props.refine; 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(); } }), 'Load more' ) : _react2.default.createElement( 'button', _extends({}, cx('loadMore'), { disabled: true }), 'Load more' ); return _react2.default.createElement( 'div', cx('root'), renderedHits, loadMoreButton ); } }]); return InfiniteHits; }(_react.Component); InfiniteHits.propTypes = { hits: _react.PropTypes.array, hitComponent: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.func]).isRequired, hasMore: _react.PropTypes.bool.isRequired, refine: _react.PropTypes.func.isRequired }; 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), '...' ); } }; exports.default = InfiniteHits; /***/ }, /* 343 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectMenu = __webpack_require__(344); var _connectMenu2 = _interopRequireDefault(_connectMenu); var _Menu = __webpack_require__(345); 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); /***/ }, /* 344 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _orderBy2 = __webpack_require__(253); var _orderBy3 = _interopRequireDefault(_orderBy2); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); 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 _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); 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(props) { return props.attributeName; } var namespace = 'menu'; function getCurrentRefinement(props, searchState) { var id = getId(props); if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') { if (searchState[namespace][id] === '') { return null; } return searchState[namespace][id]; } if (props.defaultRefinement) { return props.defaultRefinement; } return null; } function getValue(name, props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState); return name === currentRefinement ? '' : name; } 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: _react.PropTypes.string.isRequired, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, defaultRefinement: _react.PropTypes.string, transformItems: _react.PropTypes.func, withSearchBox: _react.PropTypes.bool, searchForFacetValues: _react.PropTypes.bool }, defaultProps: { showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var results = searchResults.results; var attributeName = props.attributeName, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; 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.'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue(v.value, props, searchState), _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), 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), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId(props); return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, id, nextRefinement ? nextRefinement : '')))); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, 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(props, searchState); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attributeName, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState); return { id: id, items: currentRefinement === null ? [] : [{ label: props.attributeName + ': ' + currentRefinement, attributeName: props.attributeName, value: function value(nextState) { return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, '')))); }, currentRefinement: currentRefinement }] }; } }); /***/ }, /* 345 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(316); 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(322); var _List2 = _interopRequireDefault(_List); var _Link = __webpack_require__(324); var _Link2 = _interopRequireDefault(_Link); var _Highlight = __webpack_require__(325); var _Highlight2 = _interopRequireDefault(_Highlight); var _classNames = __webpack_require__(177); 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) { var _this$props = _this.props, refine = _this$props.refine, 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 refine(item.value); }, 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) { _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: _react.PropTypes.func.isRequired, refine: _react.PropTypes.func.isRequired, searchForItems: _react.PropTypes.func.isRequired, withSearchBox: _react.PropTypes.bool, createURL: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string.isRequired, value: _react.PropTypes.string.isRequired, count: _react.PropTypes.number.isRequired, isRefined: _react.PropTypes.bool.isRequired })), isFromSearch: _react.PropTypes.bool.isRequired, canRefine: _react.PropTypes.bool.isRequired, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, transformItems: _react.PropTypes.func }; Menu.contextTypes = { canRefine: _react.PropTypes.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); /***/ }, /* 346 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectMultiRange = __webpack_require__(347); var _connectMultiRange2 = _interopRequireDefault(_connectMultiRange); var _MultiRange = __webpack_require__(348); 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); /***/ }, /* 347 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); var _omit3 = _interopRequireDefault(_omit2); var _find3 = __webpack_require__(222); var _find4 = _interopRequireDefault(_find3); 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 _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 _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); 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(':'), _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 = 'multiRange'; function getId(props) { return props.attributeName; } function getCurrentRefinement(props, searchState) { var id = getId(props); if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') { return searchState[namespace][id]; } if (props.defaultRefinement) { return props.defaultRefinement; } return ''; } 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))); } /** * 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: _react.PropTypes.string, attributeName: _react.PropTypes.string.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.node, start: _react.PropTypes.number, end: _react.PropTypes.number })).isRequired, transformItems: _react.PropTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName; var currentRefinement = getCurrentRefinement(props, searchState); var items = props.items.map(function (item) { var value = stringifyItem(item); return { label: item.label, value: value, isRefined: value === currentRefinement, noRefinement: searchResults && searchResults.results ? itemHasRefinement(getId(props), searchResults.results, value) : false }; }); var stats = searchResults.results && searchResults.results.getFacetByName(attributeName) ? searchResults.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 _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, getId(props, searchState), nextRefinement)))); }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName; var _parseItem = parseItem(getCurrentRefinement(props, searchState)), 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 id = getId(props); var value = getCurrentRefinement(props, searchState); var items = []; if (value !== '') { var _find2 = (0, _find4.default)(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 _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, '')))); } }); } return { id: id, items: items }; } }); /***/ }, /* 348 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _List = __webpack_require__(322); var _List2 = _interopRequireDefault(_List); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); var _translatable = __webpack_require__(175); 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, refine = _this$props.refine, 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, items = _props.items, 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: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.node.isRequired, value: _react.PropTypes.string.isRequired, isRefined: _react.PropTypes.bool.isRequired, noRefinement: _react.PropTypes.bool.isRequired })).isRequired, refine: _react.PropTypes.func.isRequired, transformItems: _react.PropTypes.func, canRefine: _react.PropTypes.bool.isRequired, translate: _react.PropTypes.func.isRequired }; MultiRange.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ all: 'All' })(MultiRange); /***/ }, /* 349 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectPagination = __webpack_require__(350); var _connectPagination2 = _interopRequireDefault(_connectPagination); var _Pagination = __webpack_require__(351); 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); /***/ }, /* 350 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); 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__(1); 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) { var id = getId(); var page = searchState[id]; if (typeof page === 'undefined') { page = 1; } else if (typeof page === 'string') { page = parseInt(page, 10); } if (props.defaultRefinement) { return props.defaultRefinement; } return page; } /** * 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) { if (!searchResults.results) { return null; } var nbPages = searchResults.results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement(props, searchState), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { var id = getId(); return _extends({}, searchState, _defineProperty({}, id, nextPage)); }, cleanUp: function cleanUp(props, searchState) { return (0, _omit3.default)(searchState, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement(props, searchState) - 1); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); if (nextSearchState[id] && nextSearchState[id].isSamePage) { return _extends({}, nextSearchState, _defineProperty({}, id, prevSearchState[id])); } else if (prevSearchState[id] === nextSearchState[id]) { return (0, _omit3.default)(nextSearchState, id); } return nextSearchState; }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }, /* 351 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _range2 = __webpack_require__(352); 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _utils = __webpack_require__(106); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _LinkList = __webpack_require__(355); var _LinkList2 = _interopRequireDefault(_LinkList); var _classNames = __webpack_require__(177); 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, nbPages = _props.nbPages, maxPages = _props.maxPages, 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, nbPages = _props2.nbPages, maxPages = _props2.maxPages, currentRefinement = _props2.currentRefinement, pagesPadding = _props2.pagesPadding, showFirst = _props2.showFirst, showPrevious = _props2.showPrevious, showNext = _props2.showNext, showLast = _props2.showLast, refine = _props2.refine, createURL = _props2.createURL, translate = _props2.translate, ListComponent = _props2.listComponent, 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') }); } var samePage = { valueOf: function valueOf() { return currentRefinement; }, isSamePage: true }; items = items.concat(getPages(currentRefinement, totalPages, pagesPadding).map(function (value) { return { key: value, modifier: 'itemPage', label: translate('page', value), value: value === currentRefinement ? samePage : value, 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, selectedItem: currentRefinement, onSelect: refine, createURL: createURL })); } }]); return Pagination; }(_react.Component); Pagination.propTypes = { nbPages: _react.PropTypes.number.isRequired, currentRefinement: _react.PropTypes.number.isRequired, refine: _react.PropTypes.func.isRequired, createURL: _react.PropTypes.func.isRequired, canRefine: _react.PropTypes.bool.isRequired, translate: _react.PropTypes.func.isRequired, listComponent: _react.PropTypes.func, showFirst: _react.PropTypes.bool, showPrevious: _react.PropTypes.bool, showNext: _react.PropTypes.bool, showLast: _react.PropTypes.bool, pagesPadding: _react.PropTypes.number, maxPages: _react.PropTypes.number }; Pagination.defaultProps = { listComponent: _LinkList2.default, showFirst: true, showPrevious: true, showNext: true, showLast: false, pagesPadding: 3, maxPages: Infinity }; Pagination.contextTypes = { canRefine: _react.PropTypes.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); /***/ }, /* 352 */ /***/ function(module, exports, __webpack_require__) { var createRange = __webpack_require__(353); /** * 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; /***/ }, /* 353 */ /***/ function(module, exports, __webpack_require__) { var baseRange = __webpack_require__(354), isIterateeCall = __webpack_require__(236), toFinite = __webpack_require__(216); /** * 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; /***/ }, /* 354 */ /***/ 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; /***/ }, /* 355 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _has2 = __webpack_require__(92); 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _Link = __webpack_require__(324); 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, cx = _props.cx, createURL = _props.createURL, items = _props.items, selectedItem = _props.selectedItem, onSelect = _props.onSelect, 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', // on purpose == following, see // https://github.com/algolia/instantsearch.js/commit/bfed1f3512e40fb1e9989453582b4a2c2d90e3f2 // eslint-disable-next-line item.value == selectedItem && !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.value === selectedItem && '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: _react.PropTypes.func.isRequired, createURL: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ value: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number, _react.PropTypes.object]).isRequired, key: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]), label: _react.PropTypes.node, modifier: _react.PropTypes.string, ariaLabel: _react.PropTypes.string, disabled: _react.PropTypes.bool })), selectedItem: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number, _react.PropTypes.object]), onSelect: _react.PropTypes.func.isRequired, canRefine: _react.PropTypes.bool.isRequired }; exports.default = LinkList; /***/ }, /* 356 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectPoweredBy = __webpack_require__(357); var _connectPoweredBy2 = _interopRequireDefault(_connectPoweredBy); var _PoweredBy = __webpack_require__(358); 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); /***/ }, /* 357 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(1); 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=instantsearch.js&' + 'utm_medium=website&' + ('utm_content=' + location.hostname + '&') + 'utm_campaign=poweredby'; return { url: url }; } }); /***/ }, /* 358 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); 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, translate = _props.translate, 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: _react.PropTypes.string.isRequired, translate: _react.PropTypes.func.isRequired }; exports.default = (0, _translatable2.default)({ searchBy: 'Search by' })(PoweredBy); /***/ }, /* 359 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(360); var _connectRange2 = _interopRequireDefault(_connectRange); var _RangeInput = __webpack_require__(361); 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); /***/ }, /* 360 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); 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 _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); 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) { var id = getId(props); if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') { var _searchState$namespac = searchState[namespace][id], min = _searchState$namespac.min, max = _searchState$namespac.max; if (typeof min === 'string') { min = parseInt(min, 10); } if (typeof max === 'string') { max = parseInt(max, 10); } return { min: min, max: max }; } if (typeof props.defaultRefinement !== 'undefined') { return props.defaultRefinement; } return {}; } exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaRange', propTypes: { id: _react.PropTypes.string, attributeName: _react.PropTypes.string.isRequired, defaultRefinement: _react.PropTypes.shape({ min: _react.PropTypes.number.isRequired, max: _react.PropTypes.number.isRequired }), min: _react.PropTypes.number, max: _react.PropTypes.number }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attributeName = props.attributeName; var min = props.min, max = props.max; var hasMin = typeof min !== 'undefined'; var hasMax = typeof max !== 'undefined'; if (!hasMin || !hasMax) { if (!searchResults.results) { return { canRefine: false }; } var stats = searchResults.results.getFacetByName(attributeName) ? searchResults.results.getFacetStats(attributeName) : null; if (!stats) { return { canRefine: false }; } if (!hasMin) { min = stats.min; } if (!hasMax) { max = stats.max; } } var count = searchResults.results ? searchResults.results.getFacetValues(attributeName).map(function (v) { return { value: v.name, count: v.count }; }) : []; var _getCurrentRefinement = getCurrentRefinement(props, searchState), _getCurrentRefinement2 = _getCurrentRefinement.min, valueMin = _getCurrentRefinement2 === undefined ? min : _getCurrentRefinement2, _getCurrentRefinement3 = _getCurrentRefinement.max, 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) { if (!isFinite(nextRefinement.min) || !isFinite(nextRefinement.max)) { throw new Error('You can\'t provide non finite values to the range connector'); } return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, getId(props), nextRefinement)))); }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attributeName = props.attributeName; var currentRefinement = getCurrentRefinement(props, searchState); params = params.addDisjunctiveFacet(attributeName); var min = currentRefinement.min, 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 id = getId(props); var currentRefinement = getCurrentRefinement(props, searchState); 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 _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, {})))); } }; } return { id: id, items: item ? [item] : [] }; } }); /***/ }, /* 361 */ /***/ 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); 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, translate = _props.translate, 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: _react.PropTypes.func.isRequired, refine: _react.PropTypes.func.isRequired, min: _react.PropTypes.number, max: _react.PropTypes.number, currentRefinement: _react.PropTypes.shape({ min: _react.PropTypes.number, max: _react.PropTypes.number }), canRefine: _react.PropTypes.bool.isRequired }; RangeInput.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ submit: 'ok', separator: 'to' })(RangeInput); /***/ }, /* 362 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(360); var _connectRange2 = _interopRequireDefault(_connectRange); var _react = __webpack_require__(105); 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 React, {PropTypes} from 'react'; * import {connectRange} from 'react-instantsearch/connectors'; * import Rheostat from 'rheostat'; * * const Range = React.createClass({ propTypes: { min: React.PropTypes.number.isRequired, max: React.PropTypes.number.isRequired, currentRefinement: React.PropTypes.object.isRequired, refine: React.PropTypes.func.isRequired, }, getInitialState() { return {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 ( <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> ); }, }); 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/instantsearch.js/react/widgets/RangeSlider.html' }, 'https://community.algolia.com/instantsearch.js/react/widgets/RangeSlider.html' ) ); }); /***/ }, /* 363 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRange = __webpack_require__(360); var _connectRange2 = _interopRequireDefault(_connectRange); var _StarRating = __webpack_require__(364); 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); /***/ }, /* 364 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(129); 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); 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, lowerBound = _ref.lowerBound, count = _ref.count, translate = _ref.translate, createURL = _ref.createURL, 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, translate = _props.translate, refine = _props.refine, min = _props.min, max = _props.max, count = _props.count, createURL = _props.createURL, 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: _react.PropTypes.func.isRequired, refine: _react.PropTypes.func.isRequired, createURL: _react.PropTypes.func.isRequired, min: _react.PropTypes.number, max: _react.PropTypes.number, currentRefinement: _react.PropTypes.shape({ min: _react.PropTypes.number, max: _react.PropTypes.number }), count: _react.PropTypes.arrayOf(_react.PropTypes.shape({ value: _react.PropTypes.string, count: _react.PropTypes.number })), canRefine: _react.PropTypes.bool.isRequired }; StarRating.contextTypes = { canRefine: _react.PropTypes.func }; exports.default = (0, _translatable2.default)({ ratingLabel: ' & Up' })(StarRating); /***/ }, /* 365 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectRefinementList = __webpack_require__(366); var _connectRefinementList2 = _interopRequireDefault(_connectRefinementList); var _RefinementList = __webpack_require__(367); 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); /***/ }, /* 366 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); 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 _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); 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) { var id = getId(props); if (searchState[namespace] && typeof searchState[namespace][id] !== 'undefined') { var subState = searchState[namespace]; if (typeof subState[id] === 'string') { // All items were unselected if (subState[id] === '') { return []; } // Only one item was in the searchState but we know it should be an array return [subState[id]]; } return subState[id]; } if (props.defaultRefinement) { return props.defaultRefinement; } return []; } function getValue(name, props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState); 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; } /** * connectRefinementList connector provides the logic to build a widget that will * give the user tha 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: _react.PropTypes.string, attributeName: _react.PropTypes.string.isRequired, operator: _react.PropTypes.oneOf(['and', 'or']), showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, defaultRefinement: _react.PropTypes.arrayOf(_react.PropTypes.string), withSearchBox: _react.PropTypes.bool, searchForFacetValues: _react.PropTypes.bool, // @deprecated transformItems: _react.PropTypes.func }, defaultProps: { operator: 'or', showMore: false, limitMin: 10, limitMax: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) { var results = searchResults.results; var attributeName = props.attributeName, showMore = props.showMore, limitMin = props.limitMin, limitMax = props.limitMax; var limit = showMore ? limitMax : limitMin; 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.'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState), canRefine: canRefine, isFromSearch: isFromSearch, withSearchBox: withSearchBox }; } var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) { return { label: v.value, value: getValue(v.value, props, searchState), _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), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, limit), currentRefinement: getCurrentRefinement(props, searchState), isFromSearch: isFromSearch, withSearchBox: withSearchBox, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId(props); return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, id, nextRefinement.length > 0 ? nextRefinement : '')))); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attributeName, query: nextRefinement }; }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, 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(props, searchState).reduce(function (res, val) { return res[addRefinementKey](attributeName, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId(props); return { id: id, items: getCurrentRefinement(props, searchState).length > 0 ? [{ attributeName: props.attributeName, label: props.attributeName + ': ', currentRefinement: getCurrentRefinement(props, searchState), value: function value(nextState) { return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, '')))); }, items: getCurrentRefinement(props, searchState).map(function (item) { return { label: '' + item, value: function value(nextState) { var nextSelectedItems = getCurrentRefinement(props, nextState).filter(function (other) { return other !== item; }); return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, nextSelectedItems.length > 0 ? nextSelectedItems : '')))); } }; }) }] : [] }; } }); /***/ }, /* 367 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _pick2 = __webpack_require__(316); 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _List = __webpack_require__(322); var _List2 = _interopRequireDefault(_List); var _classNames = __webpack_require__(177); var _classNames2 = _interopRequireDefault(_classNames); var _Highlight = __webpack_require__(325); 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) { _this.props.refine(item.value); }; _this.renderItem = function (item) { 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); } })), _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']))) ); } }]); return RefinementList; }(_react.Component); RefinementList.propTypes = { translate: _react.PropTypes.func.isRequired, refine: _react.PropTypes.func.isRequired, searchForItems: _react.PropTypes.func.isRequired, withSearchBox: _react.PropTypes.bool, createURL: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string.isRequired, value: _react.PropTypes.arrayOf(_react.PropTypes.string).isRequired, count: _react.PropTypes.number.isRequired, isRefined: _react.PropTypes.bool.isRequired })), isFromSearch: _react.PropTypes.bool.isRequired, canRefine: _react.PropTypes.bool.isRequired, showMore: _react.PropTypes.bool, limitMin: _react.PropTypes.number, limitMax: _react.PropTypes.number, transformItems: _react.PropTypes.func }; RefinementList.contextTypes = { canRefine: _react.PropTypes.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); /***/ }, /* 368 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectCurrentRefinements = __webpack_require__(173); var _connectCurrentRefinements2 = _interopRequireDefault(_connectCurrentRefinements); var _ClearAll = __webpack_require__(369); 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); /***/ }, /* 369 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); 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, translate = _props.translate, items = _props.items, refine = _props.refine, query = _props.query; var isDisabled = items.length === 0 && (!query || query === ''); 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: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.object).isRequired, refine: _react.PropTypes.func.isRequired, query: _react.PropTypes.string }; exports.default = (0, _translatable2.default)({ reset: 'Clear all filters' })(ClearAll); /***/ }, /* 370 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectScrollTo = __webpack_require__(371); var _connectScrollTo2 = _interopRequireDefault(_connectScrollTo); var _ScrollTo = __webpack_require__(372); 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); /***/ }, /* 371 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); 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: _react.PropTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var value = searchState[props.scrollOn]; return { value: value }; } }); /***/ }, /* 372 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _reactDom = __webpack_require__(373); 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: _react.PropTypes.any, children: _react.PropTypes.node }; exports.default = ScrollTo; /***/ }, /* 373 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_373__; /***/ }, /* 374 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectSearchBox = __webpack_require__(375); var _connectSearchBox2 = _interopRequireDefault(_connectSearchBox); var _SearchBox = __webpack_require__(323); 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. * @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 submit - The submit button label * @translationkey reset - The reset button label * @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); /***/ }, /* 375 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); 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__(1); var _createConnector2 = _interopRequireDefault(_createConnector); var _react = __webpack_require__(105); 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) { var id = getId(); if (typeof searchState[id] !== 'undefined') { return searchState[id]; } if (typeof props.defaultRefinement !== 'undefined') { return props.defaultRefinement; } return ''; } /** * 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: _react.PropTypes.string }, getProvidedProps: function getProvidedProps(props, searchState) { return { currentRefinement: getCurrentRefinement(props, searchState) }; }, refine: function refine(props, searchState, nextQuery) { var id = getId(); return _extends({}, searchState, _defineProperty({}, id, nextQuery)); }, cleanUp: function cleanUp(props, searchState) { return (0, _omit3.default)(searchState, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement(props, searchState)); } }); /***/ }, /* 376 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectSortBy = __webpack_require__(377); var _connectSortBy2 = _interopRequireDefault(_connectSortBy); var _SortBy = __webpack_require__(378); 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); /***/ }, /* 377 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); 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 _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); 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) { var id = getId(); if (searchState[id]) { return searchState[id]; } if (props.defaultRefinement) { return props.defaultRefinement; } 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: _react.PropTypes.string, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string, value: _react.PropTypes.string.isRequired })).isRequired, transformItems: _react.PropTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState); 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(); return _extends({}, searchState, _defineProperty({}, id, nextRefinement)); }, cleanUp: function cleanUp(props, searchState) { return (0, _omit3.default)(searchState, getId()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement(props, searchState); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId() }; } }); /***/ }, /* 378 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(339); var _Select2 = _interopRequireDefault(_Select); var _classNames = __webpack_require__(177); 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, refine = _props.refine, items = _props.items, currentRefinement = _props.currentRefinement; return _react2.default.createElement(_Select2.default, { cx: cx, selectedItem: currentRefinement, onSelect: refine, items: items }); } }]); return SortBy; }(_react.Component); SortBy.propTypes = { refine: _react.PropTypes.func.isRequired, items: _react.PropTypes.arrayOf(_react.PropTypes.shape({ label: _react.PropTypes.string, value: _react.PropTypes.string.isRequired })).isRequired, currentRefinement: _react.PropTypes.string.isRequired, transformItems: _react.PropTypes.func }; exports.default = SortBy; /***/ }, /* 379 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectStats = __webpack_require__(380); var _connectStats2 = _interopRequireDefault(_connectStats); var _Stats = __webpack_require__(381); 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); /***/ }, /* 380 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createConnector = __webpack_require__(1); var _createConnector2 = _interopRequireDefault(_createConnector); 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) { if (!searchResults.results) { return null; } return { nbHits: searchResults.results.nbHits, processingTimeMS: searchResults.results.processingTimeMS }; } }); /***/ }, /* 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _translatable = __webpack_require__(175); var _translatable2 = _interopRequireDefault(_translatable); var _classNames = __webpack_require__(177); 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, translate = _props.translate, nbHits = _props.nbHits, processingTimeMS = _props.processingTimeMS; return _react2.default.createElement( 'span', cx('root'), translate('stats', nbHits, processingTimeMS) ); } }]); return Stats; }(_react.Component); Stats.propTypes = { translate: _react.PropTypes.func.isRequired, nbHits: _react.PropTypes.number.isRequired, processingTimeMS: _react.PropTypes.number.isRequired }; exports.default = (0, _translatable2.default)({ stats: function stats(n, ms) { return n.toLocaleString() + ' results found in ' + ms.toLocaleString() + 'ms'; } })(Stats); /***/ }, /* 382 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _connectToggle = __webpack_require__(383); var _connectToggle2 = _interopRequireDefault(_connectToggle); var _Toggle = __webpack_require__(384); 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); /***/ }, /* 383 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _isEmpty2 = __webpack_require__(129); var _isEmpty3 = _interopRequireDefault(_isEmpty2); var _omit2 = __webpack_require__(130); 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 _react = __webpack_require__(105); var _createConnector = __webpack_require__(1); 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(props) { return props.attributeName; } var namespace = 'toggle'; function getCurrentRefinement(props, searchState) { var id = getId(props); if (searchState[namespace] && searchState[namespace][id]) { return searchState[namespace][id]; } if (props.defaultRefinement) { return props.defaultRefinement; } return false; } /** * 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 */ exports.default = (0, _createConnector2.default)({ displayName: 'AlgoliaToggle', propTypes: { label: _react.PropTypes.string, filter: _react.PropTypes.func, attributeName: _react.PropTypes.string, value: _react.PropTypes.any, defaultRefinement: _react.PropTypes.bool }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement(props, searchState); return { currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextChecked) { return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], _defineProperty({}, getId(props, searchState), nextChecked)))); }, cleanUp: function cleanUp(props, searchState) { var cleanState = (0, _omit3.default)(searchState, namespace + '.' + getId(props)); if ((0, _isEmpty3.default)(cleanState[namespace])) { return (0, _omit3.default)(cleanState, namespace); } return cleanState; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributeName = props.attributeName, value = props.value, filter = props.filter; var checked = getCurrentRefinement(props, searchState); if (checked) { if (attributeName) { searchParameters = searchParameters.addFacet(attributeName).addFacetRefinement(attributeName, value); } if (filter) { searchParameters = filter(searchParameters); } } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var id = getId(props); var checked = getCurrentRefinement(props, searchState); var items = []; if (checked) { items.push({ label: props.label, currentRefinement: props.label, attributeName: props.attributeName, value: function value(nextState) { return _extends({}, nextState, _defineProperty({}, namespace, _extends({}, nextState[namespace], _defineProperty({}, id, false)))); } }); } return { id: id, items: items }; } }); /***/ }, /* 384 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(177); 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, currentRefinement = _props.currentRefinement, 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: _react.PropTypes.bool.isRequired, refine: _react.PropTypes.func.isRequired, label: _react.PropTypes.string.isRequired }; exports.default = Toggle; /***/ }, /* 385 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Panel = __webpack_require__(386); 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; /***/ }, /* 386 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _classNames = __webpack_require__(177); 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: _react.PropTypes.string.isRequired, children: _react.PropTypes.node }; Panel.childContextTypes = { canRefine: _react.PropTypes.func }; exports.default = Panel; /***/ }, /* 387 */ /***/ 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 _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _InstantSearch = __webpack_require__(388); 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: '3.2.0', scripts: { build: './scripts/build.sh', 'build-and-publish': './scripts/build-and-publish.sh' }, homepage: 'https://community.algolia.com/instantsearch.js/react/', repository: { type: 'git', url: 'https://github.com/algolia/instantsearch.js/' }, dependencies: { algoliasearch: '^3.20.3', 'algoliasearch-helper': '^2.18.0', classnames: '^2.2.5', lodash: '^4.17.4' }, license: 'MIT', devDependencies: { enzyme: '^2.7.1', react: '^15.4.2', 'react-dom': '^15.4.2', 'react-native': '^0.41.2', 'react-test-renderer': '^15.4.2' } }; 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: _react.PropTypes.object, appId: _react.PropTypes.string, apiKey: _react.PropTypes.string, children: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.arrayOf(_react2.default.PropTypes.node), _react2.default.PropTypes.node]), indexName: _react.PropTypes.string.isRequired, searchParameters: _react.PropTypes.object, createURL: _react.PropTypes.func, searchState: _react.PropTypes.object, onSearchStateChange: _react.PropTypes.func }, _temp; } /***/ }, /* 388 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = __webpack_require__(105); var _react2 = _interopRequireDefault(_react); var _createInstantSearchManager = __webpack_require__(389); 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 {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.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: '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 }) }; } }, { 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.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, Root = _props$root.Root, 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: _react.PropTypes.string.isRequired, algoliaClient: _react.PropTypes.object.isRequired, searchParameters: _react.PropTypes.object, createURL: _react.PropTypes.func, searchState: _react.PropTypes.object, onSearchStateChange: _react.PropTypes.func, children: _react.PropTypes.node, root: _react.PropTypes.shape({ Root: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.func]), props: _react.PropTypes.object }).isRequired }; InstantSearch.childContextTypes = { // @TODO: more precise widgets manager propType ais: _react.PropTypes.object.isRequired }; exports.default = InstantSearch; /***/ }, /* 389 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _omit2 = __webpack_require__(130); 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__(181); var _algoliasearchHelper2 = _interopRequireDefault(_algoliasearchHelper); var _createWidgetsManager = __webpack_require__(390); var _createWidgetsManager2 = _interopRequireDefault(_createWidgetsManager); var _createStore = __webpack_require__(391); var _createStore2 = _interopRequireDefault(_createStore); var _highlightTags = __webpack_require__(328); 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, _ref$initialState = _ref.initialState, initialState = _ref$initialState === undefined ? {} : _ref$initialState, algoliaClient = _ref.algoliaClient, _ref$searchParameters = _ref.searchParameters, 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 initialSearchParameters = helper.state; var widgetsManager = (0, _createWidgetsManager2.default)(onWidgetsUpdate); var store = (0, _createStore2.default)({ widgets: initialState, metadata: [], results: null, error: null, searching: false }); 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() { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, initialSearchParameters); } function search() { var widgetSearchParameters = getSearchParameters(helper.state); helper.setState(widgetSearchParameters).search(); } function handleSearchSuccess(content) { var nextState = (0, _omit3.default)(_extends({}, store.getState(), { results: content, 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 }; } /***/ }, /* 390 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createWidgetsManager; var _utils = __webpack_require__(106); 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; } }; } /***/ }, /* 391 */ /***/ function(module, exports) { "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); }; } }; } /***/ }, /* 392 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var AlgoliaSearch = __webpack_require__(393); var createAlgoliasearch = __webpack_require__(416); module.exports = createAlgoliasearch(AlgoliaSearch); /***/ }, /* 393 */ /***/ function(module, exports, __webpack_require__) { module.exports = AlgoliaSearch; var Index = __webpack_require__(394); var deprecate = __webpack_require__(400); var deprecatedMessage = __webpack_require__(401); var AlgoliaSearchCore = __webpack_require__(411); var inherits = __webpack_require__(395); var errors = __webpack_require__(398); function AlgoliaSearch() { AlgoliaSearchCore.apply(this, arguments); } inherits(AlgoliaSearch, AlgoliaSearchCore); /* * Delete an index * * @param indexName the name of index to delete * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer that contains the task ID */ AlgoliaSearch.prototype.deleteIndex = function(indexName, callback) { return this._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexName), hostType: 'write', callback: callback }); }; /** * Move an existing index. * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy of * srcIndexName (destination will be overriten if it already exist). * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer that contains the task ID */ AlgoliaSearch.prototype.moveIndex = function(srcIndexName, dstIndexName, callback) { var postObj = { operation: 'move', destination: dstIndexName }; return this._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation', body: postObj, hostType: 'write', callback: callback }); }; /** * Copy an existing index. * @param srcIndexName the name of index to copy. * @param dstIndexName the new index name that will contains a copy * of srcIndexName (destination will be overriten if it already exist). * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer that contains the task ID */ AlgoliaSearch.prototype.copyIndex = function(srcIndexName, dstIndexName, callback) { var postObj = { operation: 'copy', destination: dstIndexName }; return this._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(srcIndexName) + '/operation', body: postObj, hostType: 'write', callback: callback }); }; /** * Return last log entries. * @param offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry). * @param length Specify the maximum number of entries to retrieve starting * at offset. Maximum allowed value: 1000. * @param type Specify the maximum number of entries to retrieve starting * at offset. Maximum allowed value: 1000. * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer that contains the task ID */ AlgoliaSearch.prototype.getLogs = function(offset, length, callback) { var clone = __webpack_require__(403); var params = {}; if (typeof offset === 'object') { // getLogs(params) params = clone(offset); callback = length; } else if (arguments.length === 0 || typeof offset === 'function') { // getLogs([cb]) callback = offset; } else if (arguments.length === 1 || typeof length === 'function') { // getLogs(1, [cb)] callback = length; params.offset = offset; } else { // getLogs(1, 2, [cb]) params.offset = offset; params.length = length; } if (params.offset === undefined) params.offset = 0; if (params.length === undefined) params.length = 10; return this._jsonRequest({ method: 'GET', url: '/1/logs?' + this._getSearchParams(params, ''), hostType: 'read', callback: callback }); }; /* * List all existing indexes (paginated) * * @param page The page to retrieve, starting at 0. * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with index list */ AlgoliaSearch.prototype.listIndexes = function(page, callback) { var params = ''; if (page === undefined || typeof page === 'function') { callback = page; } else { params = '?page=' + page; } return this._jsonRequest({ method: 'GET', url: '/1/indexes' + params, hostType: 'read', callback: callback }); }; /* * Get the index object initialized * * @param indexName the name of index * @param callback the result callback with one argument (the Index instance) */ AlgoliaSearch.prototype.initIndex = function(indexName) { return new Index(this, indexName); }; /* * List all existing user keys with their associated ACLs * * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ AlgoliaSearch.prototype.listUserKeys = function(callback) { return this._jsonRequest({ method: 'GET', url: '/1/keys', hostType: 'read', callback: callback }); }; /* * Get ACL of a user key * * @param key * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ AlgoliaSearch.prototype.getUserKeyACL = function(key, callback) { return this._jsonRequest({ method: 'GET', url: '/1/keys/' + key, hostType: 'read', callback: callback }); }; /* * Delete an existing user key * @param key * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ AlgoliaSearch.prototype.deleteUserKey = function(key, callback) { return this._jsonRequest({ method: 'DELETE', url: '/1/keys/' + key, hostType: 'write', callback: callback }); }; /* * Add a new global API key * * @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param {Object} [params] - Optionnal parameters to set for the key * @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key) * @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour * @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call * @param {string[]} params.indexes - Allowed targeted indexes for this key * @param {string} params.description - A description for your key * @param {string[]} params.referers - A list of authorized referers * @param {Object} params.queryParameters - Force the key to use specific query parameters * @param {Function} callback - The result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list * @return {Promise|undefined} Returns a promise if no callback given * @example * client.addUserKey(['search'], { * validity: 300, * maxQueriesPerIPPerHour: 2000, * maxHitsPerQuery: 3, * indexes: ['fruits'], * description: 'Eat three fruits', * referers: ['*.algolia.com'], * queryParameters: { * tagFilters: ['public'], * } * }) * @see {@link https://www.algolia.com/doc/rest_api#AddKey|Algolia REST API Documentation} */ AlgoliaSearch.prototype.addUserKey = function(acls, params, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: client.addUserKey(arrayOfAcls[, params, callback])'; if (!isArray(acls)) { throw new Error(usage); } if (arguments.length === 1 || typeof params === 'function') { callback = params; params = null; } var postObj = { acl: acls }; if (params) { postObj.validity = params.validity; postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour; postObj.maxHitsPerQuery = params.maxHitsPerQuery; postObj.indexes = params.indexes; postObj.description = params.description; if (params.queryParameters) { postObj.queryParameters = this._getSearchParams(params.queryParameters, ''); } postObj.referers = params.referers; } return this._jsonRequest({ method: 'POST', url: '/1/keys', body: postObj, hostType: 'write', callback: callback }); }; /** * Add a new global API key * @deprecated Please use client.addUserKey() */ AlgoliaSearch.prototype.addUserKeyWithValidity = deprecate(function(acls, params, callback) { return this.addUserKey(acls, params, callback); }, deprecatedMessage('client.addUserKeyWithValidity()', 'client.addUserKey()')); /** * Update an existing API key * @param {string} key - The key to update * @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param {Object} [params] - Optionnal parameters to set for the key * @param {number} params.validity - Number of seconds after which the key will be automatically removed (0 means no time limit for this key) * @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour * @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call * @param {string[]} params.indexes - Allowed targeted indexes for this key * @param {string} params.description - A description for your key * @param {string[]} params.referers - A list of authorized referers * @param {Object} params.queryParameters - Force the key to use specific query parameters * @param {Function} callback - The result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list * @return {Promise|undefined} Returns a promise if no callback given * @example * client.updateUserKey('APIKEY', ['search'], { * validity: 300, * maxQueriesPerIPPerHour: 2000, * maxHitsPerQuery: 3, * indexes: ['fruits'], * description: 'Eat three fruits', * referers: ['*.algolia.com'], * queryParameters: { * tagFilters: ['public'], * } * }) * @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation} */ AlgoliaSearch.prototype.updateUserKey = function(key, acls, params, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: client.updateUserKey(key, arrayOfAcls[, params, callback])'; if (!isArray(acls)) { throw new Error(usage); } if (arguments.length === 2 || typeof params === 'function') { callback = params; params = null; } var putObj = { acl: acls }; if (params) { putObj.validity = params.validity; putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour; putObj.maxHitsPerQuery = params.maxHitsPerQuery; putObj.indexes = params.indexes; putObj.description = params.description; if (params.queryParameters) { putObj.queryParameters = this._getSearchParams(params.queryParameters, ''); } putObj.referers = params.referers; } return this._jsonRequest({ method: 'PUT', url: '/1/keys/' + key, body: putObj, hostType: 'write', callback: callback }); }; /** * Initialize a new batch of search queries * @deprecated use client.search() */ AlgoliaSearch.prototype.startQueriesBatch = deprecate(function startQueriesBatchDeprecated() { this._batch = []; }, deprecatedMessage('client.startQueriesBatch()', 'client.search()')); /** * Add a search query in the batch * @deprecated use client.search() */ AlgoliaSearch.prototype.addQueryInBatch = deprecate(function addQueryInBatchDeprecated(indexName, query, args) { this._batch.push({ indexName: indexName, query: query, params: args }); }, deprecatedMessage('client.addQueryInBatch()', 'client.search()')); /** * Launch the batch of queries using XMLHttpRequest. * @deprecated use client.search() */ AlgoliaSearch.prototype.sendQueriesBatch = deprecate(function sendQueriesBatchDeprecated(callback) { return this.search(this._batch, callback); }, deprecatedMessage('client.sendQueriesBatch()', 'client.search()')); /** * Perform write operations accross multiple indexes. * * To reduce the amount of time spent on network round trips, * you can create, update, or delete several objects in one call, * using the batch endpoint (all operations are done in the given order). * * Available actions: * - addObject * - updateObject * - partialUpdateObject * - partialUpdateObjectNoCreate * - deleteObject * * https://www.algolia.com/doc/rest_api#Indexes * @param {Object[]} operations An array of operations to perform * @return {Promise|undefined} Returns a promise if no callback given * @example * client.batch([{ * action: 'addObject', * indexName: 'clients', * body: { * name: 'Bill' * } * }, { * action: 'udpateObject', * indexName: 'fruits', * body: { * objectID: '29138', * name: 'banana' * } * }], cb) */ AlgoliaSearch.prototype.batch = function(operations, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: client.batch(operations[, callback])'; if (!isArray(operations)) { throw new Error(usage); } return this._jsonRequest({ method: 'POST', url: '/1/indexes/*/batch', body: { requests: operations }, hostType: 'write', callback: callback }); }; // environment specific methods AlgoliaSearch.prototype.destroy = notImplemented; AlgoliaSearch.prototype.enableRateLimitForward = notImplemented; AlgoliaSearch.prototype.disableRateLimitForward = notImplemented; AlgoliaSearch.prototype.useSecuredAPIKey = notImplemented; AlgoliaSearch.prototype.disableSecuredAPIKey = notImplemented; AlgoliaSearch.prototype.generateSecuredApiKey = notImplemented; function notImplemented() { var message = 'Not implemented in this environment.\n' + 'If you feel this is a mistake, write to [email protected]'; throw new errors.AlgoliaSearchError(message); } /***/ }, /* 394 */ /***/ function(module, exports, __webpack_require__) { var inherits = __webpack_require__(395); var IndexCore = __webpack_require__(396); var deprecate = __webpack_require__(400); var deprecatedMessage = __webpack_require__(401); var exitPromise = __webpack_require__(409); var errors = __webpack_require__(398); var deprecateForwardToSlaves = deprecate( function() {}, deprecatedMessage('forwardToSlaves', 'forwardToReplicas') ); module.exports = Index; function Index() { IndexCore.apply(this, arguments); } inherits(Index, IndexCore); /* * Add an object in this index * * @param content contains the javascript object to add inside the index * @param objectID (optional) an objectID you want to attribute to this object * (if the attribute already exist the old object will be overwrite) * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that contains 3 elements: createAt, taskId and objectID */ Index.prototype.addObject = function(content, objectID, callback) { var indexObj = this; if (arguments.length === 1 || typeof objectID === 'function') { callback = objectID; objectID = undefined; } return this.as._jsonRequest({ method: objectID !== undefined ? 'PUT' : // update or create 'POST', // create (API generates an objectID) url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + // create (objectID !== undefined ? '/' + encodeURIComponent(objectID) : ''), // update or create body: content, hostType: 'write', callback: callback }); }; /* * Add several objects * * @param objects contains an array of objects to add * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that updateAt and taskID */ Index.prototype.addObjects = function(objects, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: index.addObjects(arrayOfObjects[, callback])'; if (!isArray(objects)) { throw new Error(usage); } var indexObj = this; var postObj = { requests: [] }; for (var i = 0; i < objects.length; ++i) { var request = { action: 'addObject', body: objects[i] }; postObj.requests.push(request); } return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, hostType: 'write', callback: callback }); }; /* * Update partially an object (only update attributes passed in argument) * * @param partialObject contains the javascript attributes to override, the * object must contains an objectID attribute * @param createIfNotExists (optional) if false, avoid an automatic creation of the object * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that contains 3 elements: createAt, taskId and objectID */ Index.prototype.partialUpdateObject = function(partialObject, createIfNotExists, callback) { if (arguments.length === 1 || typeof createIfNotExists === 'function') { callback = createIfNotExists; createIfNotExists = undefined; } var indexObj = this; var url = '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(partialObject.objectID) + '/partial'; if (createIfNotExists === false) { url += '?createIfNotExists=false'; } return this.as._jsonRequest({ method: 'POST', url: url, body: partialObject, hostType: 'write', callback: callback }); }; /* * Partially Override the content of several objects * * @param objects contains an array of objects to update (each object must contains a objectID attribute) * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that updateAt and taskID */ Index.prototype.partialUpdateObjects = function(objects, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: index.partialUpdateObjects(arrayOfObjects[, callback])'; if (!isArray(objects)) { throw new Error(usage); } var indexObj = this; var postObj = { requests: [] }; for (var i = 0; i < objects.length; ++i) { var request = { action: 'partialUpdateObject', objectID: objects[i].objectID, body: objects[i] }; postObj.requests.push(request); } return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, hostType: 'write', callback: callback }); }; /* * Override the content of object * * @param object contains the javascript object to save, the object must contains an objectID attribute * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that updateAt and taskID */ Index.prototype.saveObject = function(object, callback) { var indexObj = this; return this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(object.objectID), body: object, hostType: 'write', callback: callback }); }; /* * Override the content of several objects * * @param objects contains an array of objects to update (each object must contains a objectID attribute) * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that updateAt and taskID */ Index.prototype.saveObjects = function(objects, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: index.saveObjects(arrayOfObjects[, callback])'; if (!isArray(objects)) { throw new Error(usage); } var indexObj = this; var postObj = { requests: [] }; for (var i = 0; i < objects.length; ++i) { var request = { action: 'updateObject', objectID: objects[i].objectID, body: objects[i] }; postObj.requests.push(request); } return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, hostType: 'write', callback: callback }); }; /* * Delete an object from the index * * @param objectID the unique identifier of object to delete * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that contains 3 elements: createAt, taskId and objectID */ Index.prototype.deleteObject = function(objectID, callback) { if (typeof objectID === 'function' || typeof objectID !== 'string' && typeof objectID !== 'number') { var err = new errors.AlgoliaSearchError('Cannot delete an object without an objectID'); callback = objectID; if (typeof callback === 'function') { return callback(err); } return this.as._promise.reject(err); } var indexObj = this; return this.as._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID), hostType: 'write', callback: callback }); }; /* * Delete several objects from an index * * @param objectIDs contains an array of objectID to delete * @param callback (optional) the result callback called with two arguments: * error: null or Error('message') * content: the server answer that contains 3 elements: createAt, taskId and objectID */ Index.prototype.deleteObjects = function(objectIDs, callback) { var isArray = __webpack_require__(407); var map = __webpack_require__(408); var usage = 'Usage: index.deleteObjects(arrayOfObjectIDs[, callback])'; if (!isArray(objectIDs)) { throw new Error(usage); } var indexObj = this; var postObj = { requests: map(objectIDs, function prepareRequest(objectID) { return { action: 'deleteObject', objectID: objectID, body: { objectID: objectID } }; }) }; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/batch', body: postObj, hostType: 'write', callback: callback }); }; /* * Delete all objects matching a query * * @param query the query string * @param params the optional query parameters * @param callback (optional) the result callback called with one argument * error: null or Error('message') */ Index.prototype.deleteByQuery = function(query, params, callback) { var clone = __webpack_require__(403); var map = __webpack_require__(408); var indexObj = this; var client = indexObj.as; if (arguments.length === 1 || typeof params === 'function') { callback = params; params = {}; } else { params = clone(params); } params.attributesToRetrieve = 'objectID'; params.hitsPerPage = 1000; params.distinct = false; // when deleting, we should never use cache to get the // search results this.clearCache(); // there's a problem in how we use the promise chain, // see how waitTask is done var promise = this .search(query, params) .then(stopOrDelete); function stopOrDelete(searchContent) { // stop here if (searchContent.nbHits === 0) { // return indexObj.as._request.resolve(); return searchContent; } // continue and do a recursive call var objectIDs = map(searchContent.hits, function getObjectID(object) { return object.objectID; }); return indexObj .deleteObjects(objectIDs) .then(waitTask) .then(doDeleteByQuery); } function waitTask(deleteObjectsContent) { return indexObj.waitTask(deleteObjectsContent.taskID); } function doDeleteByQuery() { return indexObj.deleteByQuery(query, params); } if (!callback) { return promise; } promise.then(success, failure); function success() { exitPromise(function exit() { callback(null); }, client._setTimeout || setTimeout); } function failure(err) { exitPromise(function exit() { callback(err); }, client._setTimeout || setTimeout); } }; /* * Browse all content from an index using events. Basically this will do * .browse() -> .browseFrom -> .browseFrom -> .. until all the results are returned * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @return {EventEmitter} * @example * var browser = index.browseAll('cool songs', { * tagFilters: 'public,comments', * hitsPerPage: 500 * }); * * browser.on('result', function resultCallback(content) { * console.log(content.hits); * }); * * // if any error occurs, you get it * browser.on('error', function(err) { * throw err; * }); * * // when you have browsed the whole index, you get this event * browser.on('end', function() { * console.log('finished'); * }); * * // at any point if you want to stop the browsing process, you can stop it manually * // otherwise it will go on and on * browser.stop(); * * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ Index.prototype.browseAll = function(query, queryParameters) { if (typeof query === 'object') { queryParameters = query; query = undefined; } var merge = __webpack_require__(402); var IndexBrowser = __webpack_require__(410); var browser = new IndexBrowser(); var client = this.as; var index = this; var params = client._getSearchParams( merge({}, queryParameters || {}, { query: query }), '' ); // start browsing browseLoop(); function browseLoop(cursor) { if (browser._stopped) { return; } var queryString; if (cursor !== undefined) { queryString = 'cursor=' + encodeURIComponent(cursor); } else { queryString = params; } client._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(index.indexName) + '/browse?' + queryString, hostType: 'read', callback: browseCallback }); } function browseCallback(err, content) { if (browser._stopped) { return; } if (err) { browser._error(err); return; } browser._result(content); // no cursor means we are finished browsing if (content.cursor === undefined) { browser._end(); return; } browseLoop(content.cursor); } return browser; }; /* * Get a Typeahead.js adapter * @param searchParams contains an object with query parameters (see search for details) */ Index.prototype.ttAdapter = function(params) { var self = this; return function ttAdapter(query, syncCb, asyncCb) { var cb; if (typeof asyncCb === 'function') { // typeahead 0.11 cb = asyncCb; } else { // pre typeahead 0.11 cb = syncCb; } self.search(query, params, function searchDone(err, content) { if (err) { cb(err); return; } cb(content.hits); }); }; }; /* * Wait the publication of a task on the server. * All server task are asynchronous and you can check with this method that the task is published. * * @param taskID the id of the task returned by server * @param callback the result callback with with two arguments: * error: null or Error('message') * content: the server answer that contains the list of results */ Index.prototype.waitTask = function(taskID, callback) { // wait minimum 100ms before retrying var baseDelay = 100; // wait maximum 5s before retrying var maxDelay = 5000; var loop = 0; // waitTask() must be handled differently from other methods, // it's a recursive method using a timeout var indexObj = this; var client = indexObj.as; var promise = retryLoop(); function retryLoop() { return client._jsonRequest({ method: 'GET', hostType: 'read', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/task/' + taskID }).then(function success(content) { loop++; var delay = baseDelay * loop * loop; if (delay > maxDelay) { delay = maxDelay; } if (content.status !== 'published') { return client._promise.delay(delay).then(retryLoop); } return content; }); } if (!callback) { return promise; } promise.then(successCb, failureCb); function successCb(content) { exitPromise(function exit() { callback(null, content); }, client._setTimeout || setTimeout); } function failureCb(err) { exitPromise(function exit() { callback(err); }, client._setTimeout || setTimeout); } }; /* * This function deletes the index content. Settings and index specific API keys are kept untouched. * * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the settings object or the error message if a failure occured */ Index.prototype.clearIndex = function(callback) { var indexObj = this; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/clear', hostType: 'write', callback: callback }); }; /* * Get settings of this index * * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the settings object or the error message if a failure occured */ Index.prototype.getSettings = function(callback) { var indexObj = this; return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings?getVersion=2', hostType: 'read', callback: callback }); }; Index.prototype.searchSynonyms = function(params, callback) { if (typeof params === 'function') { callback = params; params = {}; } else if (params === undefined) { params = {}; } return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/search', body: params, hostType: 'read', callback: callback }); }; Index.prototype.saveSynonym = function(synonym, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves(); var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false'; return this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(synonym.objectID) + '?forwardToReplicas=' + forwardToReplicas, body: synonym, hostType: 'write', callback: callback }); }; Index.prototype.getSynonym = function(objectID, callback) { return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID), hostType: 'read', callback: callback }); }; Index.prototype.deleteSynonym = function(objectID, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves(); var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false'; return this.as._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/' + encodeURIComponent(objectID) + '?forwardToReplicas=' + forwardToReplicas, hostType: 'write', callback: callback }); }; Index.prototype.clearSynonyms = function(opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves(); var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false'; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/clear' + '?forwardToReplicas=' + forwardToReplicas, hostType: 'write', callback: callback }); }; Index.prototype.batchSynonyms = function(synonyms, opts, callback) { if (typeof opts === 'function') { callback = opts; opts = {}; } else if (opts === undefined) { opts = {}; } if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves(); var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false'; return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/synonyms/batch' + '?forwardToReplicas=' + forwardToReplicas + '&replaceExistingSynonyms=' + (opts.replaceExistingSynonyms ? 'true' : 'false'), hostType: 'write', body: synonyms, callback: callback }); }; /* * Set settings for this index * * @param settigns the settings object that can contains : * - minWordSizefor1Typo: (integer) the minimum number of characters to accept one typo (default = 3). * - minWordSizefor2Typos: (integer) the minimum number of characters to accept two typos (default = 7). * - hitsPerPage: (integer) the number of hits per page (default = 10). * - attributesToRetrieve: (array of strings) default list of attributes to retrieve in objects. * If set to null, all attributes are retrieved. * - attributesToHighlight: (array of strings) default list of attributes to highlight. * If set to null, all indexed attributes are highlighted. * - attributesToSnippet**: (array of strings) default list of attributes to snippet alongside the number * of words to return (syntax is attributeName:nbWords). * By default no snippet is computed. If set to null, no snippet is computed. * - attributesToIndex: (array of strings) the list of fields you want to index. * If set to null, all textual and numerical attributes of your objects are indexed, * but you should update it to get optimal results. * This parameter has two important uses: * - Limit the attributes to index: For example if you store a binary image in base64, * you want to store it and be able to * retrieve it but you don't want to search in the base64 string. * - Control part of the ranking*: (see the ranking parameter for full explanation) * Matches in attributes at the beginning of * the list will be considered more important than matches in attributes further down the list. * In one attribute, matching text at the beginning of the attribute will be * considered more important than text after, you can disable * this behavior if you add your attribute inside `unordered(AttributeName)`, * for example attributesToIndex: ["title", "unordered(text)"]. * - attributesForFaceting: (array of strings) The list of fields you want to use for faceting. * All strings in the attribute selected for faceting are extracted and added as a facet. * If set to null, no attribute is used for faceting. * - attributeForDistinct: (string) The attribute name used for the Distinct feature. * This feature is similar to the SQL "distinct" keyword: when enabled * in query with the distinct=1 parameter, all hits containing a duplicate * value for this 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. * - ranking: (array of strings) controls the way results are sorted. * We have six available criteria: * - typo: sort according to number of typos, * - geo: sort according to decreassing distance when performing a geo-location based search, * - proximity: sort according to the proximity of query words in hits, * - attribute: sort according to the order of attributes defined by attributesToIndex, * - exact: * - if the user query contains one word: sort objects having an attribute * that is exactly the query word before others. * For example if you search for the "V" TV show, you want to find it * with the "V" query and avoid to have all popular TV * show starting by the v letter before it. * - if the user query contains multiple words: sort according to the * number of words that matched exactly (and not as a prefix). * - custom: sort according to a user defined formula set in **customRanking** attribute. * The standard order is ["typo", "geo", "proximity", "attribute", "exact", "custom"] * - customRanking: (array of strings) lets you specify part of the ranking. * The syntax of this condition is an array of strings containing attributes * prefixed by asc (ascending order) or desc (descending order) operator. * For example `"customRanking" => ["desc(population)", "asc(name)"]` * - 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. * - highlightPreTag: (string) Specify the string that is inserted before * the highlighted parts in the query result (default to "<em>"). * - highlightPostTag: (string) Specify the string that is inserted after * the highlighted parts in the query result (default to "</em>"). * - optionalWords: (array of strings) Specify a list of words that should * be considered as optional when found in the query. * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the server answer or the error message if a failure occured */ Index.prototype.setSettings = function(settings, opts, callback) { if (arguments.length === 1 || typeof opts === 'function') { callback = opts; opts = {}; } if (opts.forwardToSlaves !== undefined) deprecateForwardToSlaves(); var forwardToReplicas = (opts.forwardToSlaves || opts.forwardToReplicas) ? 'true' : 'false'; var indexObj = this; return this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/settings?forwardToReplicas=' + forwardToReplicas, hostType: 'write', body: settings, callback: callback }); }; /* * List all existing user keys associated to this index * * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ Index.prototype.listUserKeys = function(callback) { var indexObj = this; return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys', hostType: 'read', callback: callback }); }; /* * Get ACL of a user key associated to this index * * @param key * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ Index.prototype.getUserKeyACL = function(key, callback) { var indexObj = this; return this.as._jsonRequest({ method: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key, hostType: 'read', callback: callback }); }; /* * Delete an existing user key associated to this index * * @param key * @param callback the result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list */ Index.prototype.deleteUserKey = function(key, callback) { var indexObj = this; return this.as._jsonRequest({ method: 'DELETE', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/keys/' + key, hostType: 'write', callback: callback }); }; /* * Add a new API key to this index * * @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param {Object} [params] - Optionnal parameters to set for the key * @param {number} params.validity - Number of seconds after which the key will * be automatically removed (0 means no time limit for this key) * @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour * @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call * @param {string} params.description - A description for your key * @param {string[]} params.referers - A list of authorized referers * @param {Object} params.queryParameters - Force the key to use specific query parameters * @param {Function} callback - The result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list * @return {Promise|undefined} Returns a promise if no callback given * @example * index.addUserKey(['search'], { * validity: 300, * maxQueriesPerIPPerHour: 2000, * maxHitsPerQuery: 3, * description: 'Eat three fruits', * referers: ['*.algolia.com'], * queryParameters: { * tagFilters: ['public'], * } * }) * @see {@link https://www.algolia.com/doc/rest_api#AddIndexKey|Algolia REST API Documentation} */ Index.prototype.addUserKey = function(acls, params, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: index.addUserKey(arrayOfAcls[, params, callback])'; if (!isArray(acls)) { throw new Error(usage); } if (arguments.length === 1 || typeof params === 'function') { callback = params; params = null; } var postObj = { acl: acls }; if (params) { postObj.validity = params.validity; postObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour; postObj.maxHitsPerQuery = params.maxHitsPerQuery; postObj.description = params.description; if (params.queryParameters) { postObj.queryParameters = this.as._getSearchParams(params.queryParameters, ''); } postObj.referers = params.referers; } return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys', body: postObj, hostType: 'write', callback: callback }); }; /** * Add an existing user key associated to this index * @deprecated use index.addUserKey() */ Index.prototype.addUserKeyWithValidity = deprecate(function deprecatedAddUserKeyWithValidity(acls, params, callback) { return this.addUserKey(acls, params, callback); }, deprecatedMessage('index.addUserKeyWithValidity()', 'index.addUserKey()')); /** * Update an existing API key of this index * @param {string} key - The key to update * @param {string[]} acls - The list of ACL for this key. Defined by an array of strings that * can contains the following values: * - search: allow to search (https and http) * - addObject: allows to add/update an object in the index (https only) * - deleteObject : allows to delete an existing object (https only) * - deleteIndex : allows to delete index content (https only) * - settings : allows to get index settings (https only) * - editSettings : allows to change index settings (https only) * @param {Object} [params] - Optionnal parameters to set for the key * @param {number} params.validity - Number of seconds after which the key will * be automatically removed (0 means no time limit for this key) * @param {number} params.maxQueriesPerIPPerHour - Number of API calls allowed from an IP address per hour * @param {number} params.maxHitsPerQuery - Number of hits this API key can retrieve in one call * @param {string} params.description - A description for your key * @param {string[]} params.referers - A list of authorized referers * @param {Object} params.queryParameters - Force the key to use specific query parameters * @param {Function} callback - The result callback called with two arguments * error: null or Error('message') * content: the server answer with user keys list * @return {Promise|undefined} Returns a promise if no callback given * @example * index.updateUserKey('APIKEY', ['search'], { * validity: 300, * maxQueriesPerIPPerHour: 2000, * maxHitsPerQuery: 3, * description: 'Eat three fruits', * referers: ['*.algolia.com'], * queryParameters: { * tagFilters: ['public'], * } * }) * @see {@link https://www.algolia.com/doc/rest_api#UpdateIndexKey|Algolia REST API Documentation} */ Index.prototype.updateUserKey = function(key, acls, params, callback) { var isArray = __webpack_require__(407); var usage = 'Usage: index.updateUserKey(key, arrayOfAcls[, params, callback])'; if (!isArray(acls)) { throw new Error(usage); } if (arguments.length === 2 || typeof params === 'function') { callback = params; params = null; } var putObj = { acl: acls }; if (params) { putObj.validity = params.validity; putObj.maxQueriesPerIPPerHour = params.maxQueriesPerIPPerHour; putObj.maxHitsPerQuery = params.maxHitsPerQuery; putObj.description = params.description; if (params.queryParameters) { putObj.queryParameters = this.as._getSearchParams(params.queryParameters, ''); } putObj.referers = params.referers; } return this.as._jsonRequest({ method: 'PUT', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/keys/' + key, body: putObj, hostType: 'write', callback: callback }); }; /***/ }, /* 395 */ /***/ 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 } } /***/ }, /* 396 */ /***/ function(module, exports, __webpack_require__) { var buildSearchMethod = __webpack_require__(397); var deprecate = __webpack_require__(400); var deprecatedMessage = __webpack_require__(401); 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 query the full text query * @param 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 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 query the similar query * @param 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__(402); 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: 'GET', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse?' + 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: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse?cursor=' + encodeURIComponent(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__(403); var omit = __webpack_require__(404); 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) { 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 }); }; /* * 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__(407); var map = __webpack_require__(408); 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; /***/ }, /* 397 */ /***/ function(module, exports, __webpack_require__) { module.exports = buildSearchMethod; var errors = __webpack_require__(398); function buildSearchMethod(queryParam, url) { 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)'); } if (arguments.length === 0 || typeof query === 'function') { // .search(), .search(cb) callback = query; query = ''; } else if (arguments.length === 1 || typeof args === 'function') { // .search(query/args), .search(query, cb) callback = args; args = undefined; } // .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); } if (args !== undefined) { // `_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); }; } /***/ }, /* 398 */ /***/ 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__(395); function AlgoliaSearchError(message, extraProperties) { var forEach = __webpack_require__(399); 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' ) }; /***/ }, /* 399 */ /***/ 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); } } } }; /***/ }, /* 400 */ /***/ 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; }; /***/ }, /* 401 */ /***/ 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; }; /***/ }, /* 402 */ /***/ function(module, exports, __webpack_require__) { var foreach = __webpack_require__(399); 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; }; /***/ }, /* 403 */ /***/ function(module, exports) { module.exports = function clone(obj) { return JSON.parse(JSON.stringify(obj)); }; /***/ }, /* 404 */ /***/ function(module, exports, __webpack_require__) { module.exports = function omit(obj, test) { var keys = __webpack_require__(405); var foreach = __webpack_require__(399); var filtered = {}; foreach(keys(obj), function doFilter(keyName) { if (test(keyName) !== true) { filtered[keyName] = obj[keyName]; } }); return filtered; }; /***/ }, /* 405 */ /***/ 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__(406); 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; /***/ }, /* 406 */ /***/ function(module, exports) { '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; }; /***/ }, /* 407 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }, /* 408 */ /***/ function(module, exports, __webpack_require__) { var foreach = __webpack_require__(399); module.exports = function map(arr, fn) { var newArr = []; foreach(arr, function(item, itemIndex) { newArr.push(fn(item, itemIndex, arr)); }); return newArr; }; /***/ }, /* 409 */ /***/ 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); }; /***/ }, /* 410 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // This is the object returned by the `index.browseAll()` method module.exports = IndexBrowser; var inherits = __webpack_require__(395); var EventEmitter = __webpack_require__(303).EventEmitter; function IndexBrowser() { } inherits(IndexBrowser, EventEmitter); IndexBrowser.prototype.stop = function() { this._stopped = true; this._clean(); }; IndexBrowser.prototype._end = function() { this.emit('end'); this._clean(); }; IndexBrowser.prototype._error = function(err) { this.emit('error', err); this._clean(); }; IndexBrowser.prototype._result = function(content) { this.emit('result', content); }; IndexBrowser.prototype._clean = function() { this.removeAllListeners('stop'); this.removeAllListeners('end'); this.removeAllListeners('error'); this.removeAllListeners('result'); }; /***/ }, /* 411 */ /***/ function(module, exports, __webpack_require__) { module.exports = AlgoliaSearchCore; var errors = __webpack_require__(398); var exitPromise = __webpack_require__(409); var IndexCore = __webpack_require__(396); var store = __webpack_require__(412); // 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 = ({"NODE_ENV":"production"}).RESET_APP_DATA_TIMER && parseInt(({"NODE_ENV":"production"}).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__(413)('algoliasearch'); var clone = __webpack_require__(403); var isArray = __webpack_require__(407); var map = __webpack_require__(408); 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__(413)('algoliasearch:' + initialOpts.url); var body; 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(false); } else { headers = this._computeRequestHeaders(); } 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(); 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 */ 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(withAPIKey) { var forEach = __webpack_require__(399); var requestHeaders = { 'x-algolia-agent': this._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__(407); var map = __webpack_require__(408); 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__(399); 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__(403); 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; } /***/ }, /* 412 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var debug = __webpack_require__(413)('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, (function() { return this; }()))) /***/ }, /* 413 */ /***/ 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__(414); 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() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window && typeof window.process !== 'undefined' && window.process.type === 'renderer') { return true; } // 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' && document && 'WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * 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(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit') // 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-zA-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); } /** * 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() { 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 ({"NODE_ENV":"production"}).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__(300))) /***/ }, /* 414 */ /***/ 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 = createDebug.debug = createDebug.default = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = __webpack_require__(415); /** * 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, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array 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.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-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 (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } return debug; } /** * 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, '.*?'); 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; } /***/ }, /* 415 */ /***/ 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' } /***/ }, /* 416 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var global = __webpack_require__(417); var Promise = global.Promise || __webpack_require__(418).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__(395); var errors = __webpack_require__(398); var inlineHeaders = __webpack_require__(420); var jsonpRequest = __webpack_require__(422); var places = __webpack_require__(423); uaSuffix = uaSuffix || ''; if (false) { require('debug').enable('algoliasearch*'); } function algoliasearch(applicationID, apiKey, opts) { var cloneDeep = __webpack_require__(403); var getDocumentProtocol = __webpack_require__(424); 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__(425); 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__(413), 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; }; /***/ }, /* 417 */ /***/ function(module, exports) { /* 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, (function() { return this; }()))) /***/ }, /* 418 */ /***/ function(module, exports, __webpack_require__) { var require;/* WEBPACK VAR INJECTION */(function(process, global) {/*! * @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__(419); 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__(300), (function() { return this; }()))) /***/ }, /* 419 */ /***/ function(module, exports) { /* (ignored) */ /***/ }, /* 420 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = inlineHeaders; var encode = __webpack_require__(421); function inlineHeaders(url, headers) { if (/\?/.test(url)) { url += '&'; } else { url += '?'; } return url + encode(headers); } /***/ }, /* 421 */ /***/ 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. 'use strict'; 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; }; /***/ }, /* 422 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = jsonpRequest; var errors = __webpack_require__(398); 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()); } } /***/ }, /* 423 */ /***/ function(module, exports, __webpack_require__) { module.exports = createPlacesClient; var buildSearchMethod = __webpack_require__(397); function createPlacesClient(algoliasearch) { return function places(appID, apiKey, opts) { var cloneDeep = __webpack_require__(403); 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; }; } /***/ }, /* 424 */ /***/ function(module, exports) { '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; } /***/ }, /* 425 */ /***/ function(module, exports) { 'use strict'; module.exports = '3.20.4'; /***/ } /******/ ]) }); ; //# sourceMappingURL=Dom.js.map
ajax/libs/material-ui/4.9.4/es/Tabs/TabIndicator.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'; export const styles = theme => ({ root: { position: 'absolute', height: 2, bottom: 0, width: '100%', transition: theme.transitions.create() }, colorPrimary: { backgroundColor: theme.palette.primary.main }, colorSecondary: { backgroundColor: theme.palette.secondary.main }, vertical: { height: '100%', width: 2, right: 0 } }); /** * @ignore - internal component. */ const TabIndicator = React.forwardRef(function TabIndicator(props, ref) { const { classes, className, color, orientation } = props, other = _objectWithoutPropertiesLoose(props, ["classes", "className", "color", "orientation"]); return React.createElement("span", _extends({ className: clsx(classes.root, classes[`color${capitalize(color)}`], className, orientation === 'vertical' && classes.vertical), ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? TabIndicator.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, /** * @ignore * The color of the tab indicator. */ color: PropTypes.oneOf(['primary', 'secondary']).isRequired, /** * The tabs orientation (layout flow direction). */ orientation: PropTypes.oneOf(['horizontal', 'vertical']).isRequired } : void 0; export default withStyles(styles, { name: 'PrivateTabIndicator' })(TabIndicator);
ajax/libs/material-ui/4.12.3/es/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() { const 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/primereact/6.5.0-rc.2/divider/divider.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); 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 Divider = /*#__PURE__*/function (_Component) { _inherits(Divider, _Component); var _super = _createSuper(Divider); function Divider() { _classCallCheck(this, Divider); return _super.apply(this, arguments); } _createClass(Divider, [{ key: "isHorizontal", get: function get() { return this.props.layout === 'horizontal'; } }, { key: "isVertical", get: function get() { return this.props.layout === 'vertical'; } }, { key: "render", value: function render() { var dividerClassName = classNames("p-divider p-component p-divider-".concat(this.props.layout, " p-divider-").concat(this.props.type), { 'p-divider-left': this.isHorizontal && (!this.props.align || this.props.align === 'left'), 'p-divider-right': this.isHorizontal && this.props.align === 'right', 'p-divider-center': this.isHorizontal && this.props.align === 'center' || this.isVertical && (!this.props.align || this.props.align === 'center'), 'p-divider-top': this.isVertical && this.props.align === 'top', 'p-divider-bottom': this.isVertical && this.props.align === 'bottom' }, this.props.className); return /*#__PURE__*/React.createElement("div", { className: dividerClassName, style: this.props.style, role: "separator" }, /*#__PURE__*/React.createElement("div", { className: "p-divider-content" }, this.props.children)); } }]); return Divider; }(Component); _defineProperty(Divider, "defaultProps", { align: null, layout: 'horizontal', type: 'solid', style: null, className: null }); _defineProperty(Divider, "propTypes", { align: PropTypes.string, layout: PropTypes.string, type: PropTypes.string, style: PropTypes.object, className: PropTypes.string }); export { Divider };
ajax/libs/react-native-web/0.12.0-rc.1/exports/ActivityIndicator/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 applyNativeMethods from '../../modules/applyNativeMethods'; import StyleSheet from '../StyleSheet'; import View from '../View'; import React from 'react'; var createSvgCircle = function createSvgCircle(style) { return React.createElement("circle", { cx: "16", cy: "16", fill: "none", r: "14", strokeWidth: "4", style: style }); }; var ActivityIndicator = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(ActivityIndicator, _React$Component); function ActivityIndicator() { return _React$Component.apply(this, arguments) || this; } var _proto = ActivityIndicator.prototype; _proto.render = function render() { var _this$props = this.props, _this$props$animating = _this$props.animating, animating = _this$props$animating === void 0 ? true : _this$props$animating, _this$props$color = _this$props.color, color = _this$props$color === void 0 ? '#1976D2' : _this$props$color, _this$props$hidesWhen = _this$props.hidesWhenStopped, hidesWhenStopped = _this$props$hidesWhen === void 0 ? true : _this$props$hidesWhen, _this$props$size = _this$props.size, size = _this$props$size === void 0 ? 'small' : _this$props$size, style = _this$props.style, other = _objectWithoutPropertiesLoose(_this$props, ["animating", "color", "hidesWhenStopped", "size", "style"]); var svg = React.createElement("svg", { height: "100%", viewBox: "0 0 32 32", width: "100%" }, createSvgCircle({ stroke: color, opacity: 0.2 }), createSvgCircle({ stroke: color, strokeDasharray: 80, strokeDashoffset: 60 })); return React.createElement(View, _extends({}, other, { accessibilityRole: "progressbar", "aria-valuemax": "1", "aria-valuemin": "0", style: [styles.container, style] }), React.createElement(View, { children: svg, style: [typeof size === 'number' ? { height: size, width: size } : indicatorSizes[size], styles.animation, !animating && styles.animationPause, !animating && hidesWhenStopped && styles.hidesWhenStopped] })); }; return ActivityIndicator; }(React.Component); ActivityIndicator.displayName = 'ActivityIndicator'; var styles = StyleSheet.create({ container: { alignItems: 'center', justifyContent: 'center' }, hidesWhenStopped: { visibility: 'hidden' }, animation: { animationDuration: '0.75s', animationKeyframes: [{ '0%': { transform: [{ rotate: '0deg' }] }, '100%': { transform: [{ rotate: '360deg' }] } }], animationTimingFunction: 'linear', animationIterationCount: 'infinite' }, animationPause: { animationPlayState: 'paused' } }); var indicatorSizes = StyleSheet.create({ small: { width: 20, height: 20 }, large: { width: 36, height: 36 } }); export default applyNativeMethods(ActivityIndicator);
ajax/libs/material-ui/4.9.4/es/Slider/ValueLabel.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; const styles = theme => ({ thumb: { '&$open': { '& $offset': { transform: 'scale(1) translateY(-10px)' } } }, open: {}, offset: _extends({ zIndex: 1 }, theme.typography.body2, { fontSize: theme.typography.pxToRem(12), lineHeight: 1.2, transition: theme.transitions.create(['transform'], { duration: theme.transitions.duration.shortest }), top: -34, transformOrigin: 'bottom center', transform: 'scale(0)', position: 'absolute' }), circle: { display: 'flex', alignItems: 'center', justifyContent: 'center', width: 32, height: 32, borderRadius: '50% 50% 50% 0', backgroundColor: 'currentColor', transform: 'rotate(-45deg)' }, label: { color: theme.palette.primary.contrastText, transform: 'rotate(45deg)' } }); /** * @ignore - internal component. */ function ValueLabel(props) { const { children, classes, className, open, value, valueLabelDisplay } = props; if (valueLabelDisplay === 'off') { return children; } return React.cloneElement(children, { className: clsx(children.props.className, (open || valueLabelDisplay === 'on') && classes.open, classes.thumb) }, React.createElement("span", { className: clsx(classes.offset, className) }, React.createElement("span", { className: classes.circle }, React.createElement("span", { className: classes.label }, value)))); } export default withStyles(styles, { name: 'PrivateValueLabel' })(ValueLabel);
ajax/libs/react-native-web/0.13.6/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/react-native-web/0.0.0-b2a3e86d/modules/UnimplementedView/index.js
cdnjs/cdnjs
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * Copyright (c) Meta Platforms, Inc. and 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 /*#__PURE__*/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/react-native-web/0.13.15/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.9.3/es/StepButton/StepButton.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 ButtonBase from '../ButtonBase'; import StepLabel from '../StepLabel'; import isMuiElement from '../utils/isMuiElement'; export const styles = { /* Styles applied to the root element. */ root: { width: '100%', padding: '24px 16px', margin: '-24px -16px', boxSizing: 'content-box' }, /* Styles applied to the root element if `orientation="horizontal"`. */ horizontal: {}, /* Styles applied to the root element if `orientation="vertical"`. */ vertical: { justifyContent: 'flex-start', padding: '8px', margin: '-8px' }, /* Styles applied to the `ButtonBase` touch-ripple. */ touchRipple: { color: 'rgba(0, 0, 0, 0.3)' } }; const StepButton = React.forwardRef(function StepButton(props, ref) { const { active, alternativeLabel, children, classes, className, completed, disabled, icon, optional, orientation } = props, other = _objectWithoutPropertiesLoose(props, ["active", "alternativeLabel", "children", "classes", "className", "completed", "disabled", "expanded", "icon", "last", "optional", "orientation"]); const childProps = { active, alternativeLabel, completed, disabled, icon, optional, orientation }; const child = isMuiElement(children, ['StepLabel']) ? React.cloneElement(children, childProps) : React.createElement(StepLabel, childProps, children); return React.createElement(ButtonBase, _extends({ disabled: disabled, TouchRippleProps: { className: classes.touchRipple }, className: clsx(classes.root, classes[orientation], className), ref: ref }, other), child); }); process.env.NODE_ENV !== "production" ? StepButton.propTypes = { /** * @ignore * Passed in via `Step` - passed through to `StepLabel`. */ active: PropTypes.bool, /** * @ignore * Set internally by Stepper when it's supplied with the alternativeLabel property. */ alternativeLabel: PropTypes.bool, /** * Can be a `StepLabel` or a node to place inside `StepLabel` as children. */ 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, /** * @ignore * Sets completed styling. Is passed to StepLabel. */ completed: PropTypes.bool, /** * @ignore * Disables the button and sets disabled styling. Is passed to StepLabel. */ disabled: PropTypes.bool, /** * @ignore * potentially passed from parent `Step` */ expanded: PropTypes.bool, /** * The icon displayed by the step label. */ icon: PropTypes.node, /** * @ignore */ last: PropTypes.bool, /** * The optional node to display. */ optional: PropTypes.node, /** * @ignore */ orientation: PropTypes.oneOf(['horizontal', 'vertical']) } : void 0; export default withStyles(styles, { name: 'MuiStepButton' })(StepButton);
ajax/libs/react-native-web/0.0.0-ec235e734/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(_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(_objectSpread({}, baseStatesConditions), {}, { RESPONDER_INACTIVE_PRESS_IN: true, RESPONDER_ACTIVE_PRESS_IN: true, RESPONDER_ACTIVE_LONG_PRESS_IN: true }); var IsLongPressingIn = _objectSpread(_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); // Clear DOM nodes this.pressInLocation = null; this.state.touchable.responderID = null; this._touchableNode = null; }, /** * 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 /*#__PURE__*/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.9.2/esm/CssBaseline/CssBaseline.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import PropTypes from 'prop-types'; import makeStyles from '../styles/makeStyles'; import { exactProp } from '@material-ui/utils'; var useStyles = makeStyles(function (theme) { return { '@global': { html: { WebkitFontSmoothing: 'antialiased', // Antialiasing. MozOsxFontSmoothing: 'grayscale', // Antialiasing. // Change from `box-sizing: content-box` so that `width` // is not affected by `padding` or `border`. boxSizing: 'border-box' }, '*, *::before, *::after': { boxSizing: 'inherit' }, 'strong, b': { fontWeight: 'bolder' }, body: _extends({ margin: 0, // Remove the margin in all browsers. color: theme.palette.text.primary }, theme.typography.body2, { backgroundColor: theme.palette.background.default, '@media print': { // Save printer ink. backgroundColor: theme.palette.common.white }, // Add support for document.body.requestFullScreen(). // Other elements, if background transparent, are not supported. '&::backdrop': { backgroundColor: theme.palette.background.default } }) } }; }, { name: 'MuiCssBaseline' }); /** * Kickstart an elegant, consistent, and simple baseline to build upon. */ function CssBaseline(props) { var _props$children = props.children, children = _props$children === void 0 ? null : _props$children; useStyles(); return React.createElement(React.Fragment, null, children); } process.env.NODE_ENV !== "production" ? CssBaseline.propTypes = { /** * You can wrap a node. */ children: PropTypes.node } : void 0; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line CssBaseline['propTypes' + ''] = exactProp(CssBaseline.propTypes); } export default CssBaseline;
ajax/libs/react-native-web/0.0.0-376ccc31b/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/material-ui/4.9.3/esm/CssBaseline/CssBaseline.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 { exactProp } from '@material-ui/utils'; export var html = { WebkitFontSmoothing: 'antialiased', // Antialiasing. MozOsxFontSmoothing: 'grayscale', // Antialiasing. // Change from `box-sizing: content-box` so that `width` // is not affected by `padding` or `border`. boxSizing: 'border-box' }; export var body = function body(theme) { return _extends({ color: theme.palette.text.primary }, theme.typography.body2, { backgroundColor: theme.palette.background.default, '@media print': { // Save printer ink. backgroundColor: theme.palette.common.white } }); }; export var styles = function styles(theme) { return { '@global': { html: html, '*, *::before, *::after': { boxSizing: 'inherit' }, 'strong, b': { fontWeight: theme.typography.fontWeightBold }, body: _extends({ margin: 0 }, body(theme), { // Add support for document.body.requestFullScreen(). // Other elements, if background transparent, are not supported. '&::backdrop': { backgroundColor: theme.palette.background.default } }) } }; }; /** * Kickstart an elegant, consistent, and simple baseline to build upon. */ function CssBaseline(props) { /* eslint-disable no-unused-vars */ var _props$children = props.children, children = _props$children === void 0 ? null : _props$children, classes = props.classes; /* eslint-enable no-unused-vars */ return React.createElement(React.Fragment, null, children); } process.env.NODE_ENV !== "production" ? CssBaseline.propTypes = { /** * You can wrap a node. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object } : void 0; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line CssBaseline['propTypes' + ''] = exactProp(CssBaseline.propTypes); } export default withStyles(styles, { name: 'MuiCssBaseline' })(CssBaseline);
ajax/libs/primereact/6.5.0/progressspinner/progressspinner.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 ProgressSpinner = /*#__PURE__*/function (_Component) { _inherits(ProgressSpinner, _Component); var _super = _createSuper(ProgressSpinner); function ProgressSpinner() { _classCallCheck(this, ProgressSpinner); return _super.apply(this, arguments); } _createClass(ProgressSpinner, [{ key: "render", value: function render() { var spinnerClass = classNames('p-progress-spinner', this.props.className); return /*#__PURE__*/React.createElement("div", { id: this.props.id, style: this.props.style, className: spinnerClass, role: "alert", "aria-busy": true }, /*#__PURE__*/React.createElement("svg", { className: "p-progress-spinner-svg", viewBox: "25 25 50 50", style: { animationDuration: this.props.animationDuration } }, /*#__PURE__*/React.createElement("circle", { className: "p-progress-spinner-circle", cx: "50", cy: "50", r: "20", fill: this.props.fill, strokeWidth: this.props.strokeWidth, strokeMiterlimit: "10" }))); } }]); return ProgressSpinner; }(Component); _defineProperty(ProgressSpinner, "defaultProps", { id: null, style: null, className: null, strokeWidth: "2", fill: "none", animationDuration: "2s" }); export { ProgressSpinner };
ajax/libs/material-ui/4.9.4/es/FormHelperText/FormHelperText.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 withStyles from '../styles/withStyles'; export const styles = theme => ({ /* Styles applied to the root element. */ root: _extends({ color: theme.palette.text.secondary }, theme.typography.caption, { textAlign: 'left', marginTop: 3, margin: 0, '&$disabled': { color: theme.palette.text.disabled }, '&$error': { color: theme.palette.error.main } }), /* Pseudo-class applied to the root element if `error={true}`. */ error: {}, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `margin="dense"`. */ marginDense: { marginTop: 4 }, /* Styles applied to the root element if `variant="filled"` or `variant="outlined"`. */ contained: { marginLeft: 14, marginRight: 14 }, /* Pseudo-class applied to the root element if `focused={true}`. */ focused: {}, /* Pseudo-class applied to the root element if `filled={true}`. */ filled: {}, /* Pseudo-class applied to the root element if `required={true}`. */ required: {} }); const FormHelperText = React.forwardRef(function FormHelperText(props, ref) { const { children, classes, className, component: Component = 'p' } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "component", "disabled", "error", "filled", "focused", "margin", "required", "variant"]); const muiFormControl = useFormControl(); const fcs = formControlState({ props, muiFormControl, states: ['variant', 'margin', 'disabled', 'error', 'filled', 'focused', 'required'] }); return React.createElement(Component, _extends({ className: clsx(classes.root, (fcs.variant === 'filled' || fcs.variant === 'outlined') && classes.contained, className, fcs.disabled && classes.disabled, fcs.error && classes.error, fcs.filled && classes.filled, fcs.focused && classes.focused, fcs.required && classes.required, fcs.margin === 'dense' && classes.marginDense), ref: ref }, other), children === ' ' ? // eslint-disable-next-line react/no-danger React.createElement("span", { dangerouslySetInnerHTML: { __html: '&#8203;' } }) : children); }); process.env.NODE_ENV !== "production" ? FormHelperText.propTypes = { /** * The content of the component. * * If `' '` is provided, the component reserves one line height for displaying a future message. */ 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 helper text should be displayed in a disabled state. */ disabled: PropTypes.bool, /** * If `true`, helper text should be displayed in an error state. */ error: PropTypes.bool, /** * If `true`, the helper text should use filled classes key. */ filled: PropTypes.bool, /** * If `true`, the helper text should use focused classes key. */ focused: PropTypes.bool, /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. */ margin: PropTypes.oneOf(['dense']), /** * If `true`, the helper text should use required classes key. */ required: PropTypes.bool, /** * The variant to use. */ variant: PropTypes.oneOf(['standard', 'outlined', 'filled']) } : void 0; export default withStyles(styles, { name: 'MuiFormHelperText' })(FormHelperText);
ajax/libs/material-ui/4.9.4/es/test-utils/getClasses.js
cdnjs/cdnjs
import React from 'react'; import createShallow from './createShallow'; const shallow = createShallow(); // Helper function to extract the classes from a styleSheet. export default function getClasses(element) { const { useStyles } = element.type; let classes; function Listener() { classes = useStyles(element.props); return null; } shallow(React.createElement(Listener, null)); return classes; }
ajax/libs/primereact/6.5.0/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; } 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/primereact/7.0.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); 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$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); 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 _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.6/exports/KeyboardAvoidingView/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. * 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 { number, oneOf } from 'prop-types'; import React, { Component } from 'react'; import ViewPropTypes from '../ViewPropTypes'; var KeyboardAvoidingView = /*#__PURE__*/ function (_Component) { _inheritsLoose(KeyboardAvoidingView, _Component); function KeyboardAvoidingView() { 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.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; 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; }(Component); KeyboardAvoidingView.defaultProps = { keyboardVerticalOffset: 0 }; KeyboardAvoidingView.propTypes = process.env.NODE_ENV !== "production" ? _objectSpread({}, ViewPropTypes, { behavior: oneOf(['height', 'padding', 'position']), contentContainerStyle: ViewPropTypes.style, keyboardVerticalOffset: number.isRequired }) : {}; export default KeyboardAvoidingView;
ajax/libs/react-native-web/0.0.0-aa93652b6/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/primereact/7.0.0/contextmenu/contextmenu.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, classNames, ObjectUtils, ZIndexUtils } from 'primereact/utils'; import { CSSTransition } from 'primereact/csstransition'; import { Ripple } from 'primereact/ripple'; 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 ContextMenuSub = /*#__PURE__*/function (_Component) { _inherits(ContextMenuSub, _Component); var _super = _createSuper(ContextMenuSub); function ContextMenuSub(props) { var _this; _classCallCheck(this, ContextMenuSub); _this = _super.call(this, props); _this.state = { activeItem: null }; _this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this)); _this.submenuRef = /*#__PURE__*/React.createRef(); return _this; } _createClass(ContextMenuSub, [{ key: "onItemMouseEnter", value: function onItemMouseEnter(event, item) { if (item.disabled) { event.preventDefault(); return; } this.setState({ activeItem: item }); } }, { 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 (!item.items) { this.props.onLeafClick(event); } } }, { key: "position", value: function position() { var parentItem = this.submenuRef.current.parentElement; var containerOffset = DomHandler.getOffset(this.submenuRef.current.parentElement); var viewport = DomHandler.getViewport(); var sublistWidth = this.submenuRef.current.offsetParent ? this.submenuRef.current.offsetWidth : DomHandler.getHiddenElementOuterWidth(this.submenuRef.current); var itemOuterWidth = DomHandler.getOuterWidth(parentItem.children[0]); this.submenuRef.current.style.top = '0px'; if (parseInt(containerOffset.left, 10) + itemOuterWidth + sublistWidth > viewport.width - DomHandler.calculateScrollbarWidth()) { this.submenuRef.current.style.left = -1 * sublistWidth + 'px'; } else { this.submenuRef.current.style.left = itemOuterWidth + 'px'; } } }, { key: "onEnter", value: function onEnter() { this.position(); } }, { key: "isActive", value: function isActive() { return this.props.root || !this.props.resetMenu; } }, { key: "componentDidUpdate", value: function componentDidUpdate() { if (this.isActive()) { this.position(); } } }, { key: "renderSeparator", value: function renderSeparator(index) { return /*#__PURE__*/React.createElement("li", { key: 'separator_' + index, className: "p-menu-separator", role: "separator" }); } }, { key: "renderSubmenu", value: function renderSubmenu(item) { if (item.items) { return /*#__PURE__*/React.createElement(ContextMenuSub, { model: item.items, resetMenu: item !== this.state.activeItem, onLeafClick: this.props.onLeafClick }); } return null; } }, { key: "renderMenuitem", value: function renderMenuitem(item, index) { var _this2 = this; var active = this.state.activeItem === item; var className = classNames('p-menuitem', { 'p-menuitem-active': active }, item.className); var linkClassName = classNames('p-menuitem-link', { 'p-disabled': item.disabled }); var iconClassName = classNames('p-menuitem-icon', item.icon); var submenuIconClassName = 'p-submenu-icon pi pi-angle-right'; 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); 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-haspopup": item.items != null, "aria-disabled": item.disabled }, icon, label, submenuIcon, /*#__PURE__*/React.createElement(Ripple, null)); 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, active: active }; content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions); } return /*#__PURE__*/React.createElement("li", { key: item.label + '_' + index, role: "none", className: className, style: item.style, onMouseEnter: function onMouseEnter(event) { return _this2.onItemMouseEnter(event, item); } }, 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.root }); var submenu = this.renderMenu(); var isActive = this.isActive(); return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.submenuRef, classNames: "p-contextmenusub", in: isActive, timeout: { enter: 0, exit: 0 }, unmountOnExit: true, onEnter: this.onEnter }, /*#__PURE__*/React.createElement("ul", { ref: this.submenuRef, className: className }, submenu)); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { if (nextProps.resetMenu === true) { return { activeItem: null }; } return null; } }]); return ContextMenuSub; }(Component); _defineProperty(ContextMenuSub, "defaultProps", { model: null, root: false, className: null, resetMenu: false, onLeafClick: null }); var ContextMenu = /*#__PURE__*/function (_Component2) { _inherits(ContextMenu, _Component2); var _super2 = _createSuper(ContextMenu); function ContextMenu(props) { var _this4; _classCallCheck(this, ContextMenu); _this4 = _super2.call(this, props); _this4.state = { visible: false, reshow: false, resetMenu: false }; _this4.onMenuClick = _this4.onMenuClick.bind(_assertThisInitialized(_this4)); _this4.onLeafClick = _this4.onLeafClick.bind(_assertThisInitialized(_this4)); _this4.onMenuMouseEnter = _this4.onMenuMouseEnter.bind(_assertThisInitialized(_this4)); _this4.onEnter = _this4.onEnter.bind(_assertThisInitialized(_this4)); _this4.onEntered = _this4.onEntered.bind(_assertThisInitialized(_this4)); _this4.onExit = _this4.onExit.bind(_assertThisInitialized(_this4)); _this4.onExited = _this4.onExited.bind(_assertThisInitialized(_this4)); _this4.menuRef = /*#__PURE__*/React.createRef(); return _this4; } _createClass(ContextMenu, [{ key: "onMenuClick", value: function onMenuClick() { this.setState({ resetMenu: false }); } }, { key: "onMenuMouseEnter", value: function onMenuMouseEnter() { this.setState({ resetMenu: false }); } }, { key: "show", value: function show(event) { var _this5 = this; if (!(event instanceof Event)) { event.persist(); } event.stopPropagation(); event.preventDefault(); this.currentEvent = event; if (this.state.visible) { this.setState({ reshow: true }); } else { this.setState({ visible: true }, function () { if (_this5.props.onShow) { _this5.props.onShow(_this5.currentEvent); } }); } } }, { key: "hide", value: function hide(event) { var _this6 = this; if (!(event instanceof Event)) { event.persist(); } this.currentEvent = event; this.setState({ visible: false, reshow: false }, function () { if (_this6.props.onHide) { _this6.props.onHide(_this6.currentEvent); } }); } }, { key: "onEnter", value: function onEnter() { if (this.props.autoZIndex) { ZIndexUtils.set('menu', this.menuRef.current, PrimeReact.autoZIndex, this.props.baseZIndex || PrimeReact.zIndex['menu']); } this.position(this.currentEvent); } }, { key: "onEntered", value: function onEntered() { this.bindDocumentListeners(); } }, { key: "onExit", value: function onExit() { this.currentEvent = null; this.unbindDocumentListeners(); } }, { key: "onExited", value: function onExited() { ZIndexUtils.clear(this.menuRef.current); } }, { key: "position", value: function position(event) { if (event) { var left = event.pageX + 1; var top = event.pageY + 1; var width = this.menuRef.current.offsetParent ? this.menuRef.current.offsetWidth : DomHandler.getHiddenElementOuterWidth(this.menuRef.current); var height = this.menuRef.current.offsetParent ? this.menuRef.current.offsetHeight : DomHandler.getHiddenElementOuterHeight(this.menuRef.current); var viewport = DomHandler.getViewport(); //flip if (left + width - document.body.scrollLeft > viewport.width) { left -= width; } //flip if (top + height - document.body.scrollTop > viewport.height) { top -= height; } //fit if (left < document.body.scrollLeft) { left = document.body.scrollLeft; } //fit if (top < document.body.scrollTop) { top = document.body.scrollTop; } this.menuRef.current.style.left = left + 'px'; this.menuRef.current.style.top = top + 'px'; } } }, { key: "onLeafClick", value: function onLeafClick(event) { this.setState({ resetMenu: true }); this.hide(event); event.stopPropagation(); } }, { 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: "bindDocumentListeners", value: function bindDocumentListeners() { this.bindDocumentResizeListener(); this.bindDocumentClickListener(); } }, { key: "unbindDocumentListeners", value: function unbindDocumentListeners() { this.unbindDocumentResizeListener(); this.unbindDocumentClickListener(); } }, { key: "bindDocumentClickListener", value: function bindDocumentClickListener() { var _this7 = this; if (!this.documentClickListener) { this.documentClickListener = function (event) { if (_this7.isOutsideClicked(event) && event.button !== 2) { _this7.hide(event); _this7.setState({ resetMenu: true }); } }; document.addEventListener('click', this.documentClickListener); } } }, { key: "bindDocumentContextMenuListener", value: function bindDocumentContextMenuListener() { var _this8 = this; if (!this.documentContextMenuListener) { this.documentContextMenuListener = function (event) { _this8.show(event); }; document.addEventListener('contextmenu', this.documentContextMenuListener); } } }, { key: "bindDocumentResizeListener", value: function bindDocumentResizeListener() { var _this9 = this; if (!this.documentResizeListener) { this.documentResizeListener = function (event) { if (_this9.state.visible && !DomHandler.isAndroid()) { _this9.hide(event); } }; window.addEventListener('resize', this.documentResizeListener); } } }, { key: "unbindDocumentClickListener", value: function unbindDocumentClickListener() { if (this.documentClickListener) { document.removeEventListener('click', this.documentClickListener); this.documentClickListener = null; } } }, { key: "unbindDocumentContextMenuListener", value: function unbindDocumentContextMenuListener() { if (this.documentContextMenuListener) { document.removeEventListener('contextmenu', this.documentContextMenuListener); this.documentContextMenuListener = null; } } }, { key: "unbindDocumentResizeListener", value: function unbindDocumentResizeListener() { if (this.documentResizeListener) { window.removeEventListener('resize', this.documentResizeListener); this.documentResizeListener = null; } } }, { key: "componentDidMount", value: function componentDidMount() { if (this.props.global) { this.bindDocumentContextMenuListener(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { var _this10 = this; if (this.state.visible && (prevState.reshow !== this.state.reshow || prevProps.model !== this.props.model)) { var event = this.currentEvent; this.setState({ visible: false, reshow: false, rePosition: false, resetMenu: true }, function () { return _this10.show(event); }); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindDocumentListeners(); this.unbindDocumentContextMenuListener(); ZIndexUtils.clear(this.menuRef.current); } }, { key: "renderContextMenu", value: function renderContextMenu() { var className = classNames('p-contextmenu p-component', this.props.className); return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.menuRef, classNames: "p-contextmenu", in: this.state.visible, timeout: { enter: 250, exit: 0 }, 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.onMenuClick, onMouseEnter: this.onMenuMouseEnter }, /*#__PURE__*/React.createElement(ContextMenuSub, { model: this.props.model, root: true, resetMenu: this.state.resetMenu, onLeafClick: this.onLeafClick }))); } }, { key: "render", value: function render() { var element = this.renderContextMenu(); return /*#__PURE__*/React.createElement(Portal, { element: element, appendTo: this.props.appendTo }); } }]); return ContextMenu; }(Component); _defineProperty(ContextMenu, "defaultProps", { id: null, model: null, style: null, className: null, global: false, autoZIndex: true, baseZIndex: 0, appendTo: null, transitionOptions: null, onShow: null, onHide: null }); export { ContextMenu };
ajax/libs/primereact/7.0.1/confirmdialog/confirmdialog.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { DomHandler, classNames, ObjectUtils, IconUtils } from 'primereact/utils'; import { Dialog } from 'primereact/dialog'; import { Button } from 'primereact/button'; import { localeOption } from 'primereact/api'; import { Portal } from 'primereact/portal'; 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 _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; } } 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 confirmDialog(props) { var appendTo = props.appendTo || document.body; var confirmDialogWrapper = document.createDocumentFragment(); DomHandler.appendChild(confirmDialogWrapper, appendTo); props = _objectSpread(_objectSpread({}, props), { visible: props.visible === undefined ? true : props.visible }); var confirmDialogEl = /*#__PURE__*/React.createElement(ConfirmDialog, props); ReactDOM.render(confirmDialogEl, confirmDialogWrapper); var updateConfirmDialog = function updateConfirmDialog(newProps) { props = _objectSpread(_objectSpread({}, props), newProps); ReactDOM.render( /*#__PURE__*/React.cloneElement(confirmDialogEl, props), confirmDialogWrapper); }; return { _destroy: function _destroy() { ReactDOM.unmountComponentAtNode(confirmDialogWrapper); }, show: function show() { updateConfirmDialog({ visible: true, onHide: function onHide() { updateConfirmDialog({ visible: false }); // reset } }); }, hide: function hide() { updateConfirmDialog({ visible: false }); }, update: function update(newProps) { updateConfirmDialog(newProps); } }; } var ConfirmDialog = /*#__PURE__*/function (_Component) { _inherits(ConfirmDialog, _Component); var _super = _createSuper(ConfirmDialog); function ConfirmDialog(props) { var _this; _classCallCheck(this, ConfirmDialog); _this = _super.call(this, props); _this.state = { visible: props.visible }; _this.reject = _this.reject.bind(_assertThisInitialized(_this)); _this.accept = _this.accept.bind(_assertThisInitialized(_this)); _this.hide = _this.hide.bind(_assertThisInitialized(_this)); return _this; } _createClass(ConfirmDialog, [{ key: "acceptLabel", value: function acceptLabel() { return this.props.acceptLabel || localeOption('accept'); } }, { key: "rejectLabel", value: function rejectLabel() { return this.props.rejectLabel || localeOption('reject'); } }, { 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() { this.setState({ visible: true }); } }, { key: "hide", value: function hide(result) { var _this2 = this; this.setState({ visible: false }, function () { if (_this2.props.onHide) { _this2.props.onHide(result); } }); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.visible !== this.props.visible) { this.setState({ visible: this.props.visible }); } } }, { key: "renderFooter", value: function renderFooter() { var acceptClassName = classNames('p-confirm-dialog-accept', this.props.acceptClassName); var rejectClassName = classNames('p-confirm-dialog-reject', { 'p-button-text': !this.props.rejectClassName }, this.props.rejectClassName); var content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, { label: this.rejectLabel(), icon: this.props.rejectIcon, className: rejectClassName, onClick: this.reject }), /*#__PURE__*/React.createElement(Button, { label: this.acceptLabel(), icon: this.props.acceptIcon, className: acceptClassName, onClick: this.accept, autoFocus: true })); if (this.props.footer) { var defaultContentOptions = { accept: this.accept, reject: this.reject, 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-dialog', this.props.className); var dialogProps = ObjectUtils.findDiffKeys(this.props, ConfirmDialog.defaultProps); var message = ObjectUtils.getJSXElement(this.props.message, this.props); var footer = this.renderFooter(); return /*#__PURE__*/React.createElement(Dialog, _extends({ visible: this.state.visible }, dialogProps, { className: className, footer: footer, onHide: this.hide, breakpoints: this.props.breakpoints }), IconUtils.getJSXIcon(this.props.icon, { className: 'p-confirm-dialog-icon' }, { props: this.props }), /*#__PURE__*/React.createElement("span", { className: "p-confirm-dialog-message" }, message)); } }, { key: "render", value: function render() { var element = this.renderElement(); return /*#__PURE__*/React.createElement(Portal, { element: element, appendTo: this.props.appendTo }); } }]); return ConfirmDialog; }(Component); _defineProperty(ConfirmDialog, "defaultProps", { visible: false, message: null, rejectLabel: null, acceptLabel: null, icon: null, rejectIcon: null, acceptIcon: null, rejectClassName: null, acceptClassName: null, className: null, appendTo: null, footer: null, breakpoints: null, onHide: null, accept: null, reject: null }); export { ConfirmDialog, confirmDialog };
ajax/libs/react-native-web/0.16.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/react-native-web/0.0.0-f6a9fbf6a/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/react-native-web/0.0.0-d48f63060/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/7.0.0-rc.2/csstransition/csstransition.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { CSSTransition as CSSTransition$1 } from 'react-transition-group'; 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 _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 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 CSSTransition = /*#__PURE__*/function (_Component) { _inherits(CSSTransition, _Component); var _super = _createSuper(CSSTransition); function CSSTransition(props) { var _this; _classCallCheck(this, CSSTransition); _this = _super.call(this, props); _this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this)); _this.onEntering = _this.onEntering.bind(_assertThisInitialized(_this)); _this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this)); _this.onExit = _this.onExit.bind(_assertThisInitialized(_this)); _this.onExiting = _this.onExiting.bind(_assertThisInitialized(_this)); _this.onExited = _this.onExited.bind(_assertThisInitialized(_this)); return _this; } _createClass(CSSTransition, [{ key: "onEnter", value: function onEnter(node, isAppearing) { this.props.onEnter && this.props.onEnter(node, isAppearing); // component this.props.options && this.props.options.onEnter && this.props.options.onEnter(node, isAppearing); // user option } }, { key: "onEntering", value: function onEntering(node, isAppearing) { this.props.onEntering && this.props.onEntering(node, isAppearing); // component this.props.options && this.props.options.onEntering && this.props.options.onEntering(node, isAppearing); // user option } }, { key: "onEntered", value: function onEntered(node, isAppearing) { this.props.onEntered && this.props.onEntered(node, isAppearing); // component this.props.options && this.props.options.onEntered && this.props.options.onEntered(node, isAppearing); // user option } }, { key: "onExit", value: function onExit(node) { this.props.onExit && this.props.onExit(node); // component this.props.options && this.props.options.onExit && this.props.options.onExit(node); // user option } }, { key: "onExiting", value: function onExiting(node) { this.props.onExiting && this.props.onExiting(node); // component this.props.options && this.props.options.onExiting && this.props.options.onExiting(node); // user option } }, { key: "onExited", value: function onExited(node) { this.props.onExited && this.props.onExited(node); // component this.props.options && this.props.options.onExited && this.props.options.onExited(node); // user option } }, { key: "render", value: function render() { var immutableProps = { nodeRef: this.props.nodeRef, in: this.props.in, onEnter: this.onEnter, onEntering: this.onEntering, onEntered: this.onEntered, onExit: this.onExit, onExiting: this.onExiting, onExited: this.onExited }; var mutableProps = { classNames: this.props.classNames, timeout: this.props.timeout, unmountOnExit: this.props.unmountOnExit }; var props = _objectSpread(_objectSpread(_objectSpread({}, mutableProps), this.props.options || {}), immutableProps); return /*#__PURE__*/React.createElement(CSSTransition$1, props, this.props.children); } }]); return CSSTransition; }(Component); export { CSSTransition };
ajax/libs/primereact/7.0.0-rc.1/togglebutton/togglebutton.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { tip, classNames, Ripple } 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 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 ToggleButton = /*#__PURE__*/function (_Component) { _inherits(ToggleButton, _Component); var _super = _createSuper(ToggleButton); function ToggleButton(props) { var _this; _classCallCheck(this, ToggleButton); _this = _super.call(this, props); _this.toggle = _this.toggle.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(ToggleButton, [{ key: "toggle", value: function toggle(e) { if (!this.props.disabled && this.props.onChange) { this.props.onChange({ originalEvent: e, value: !this.props.checked, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: !this.props.checked } }); } } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.key === 'Enter') { this.toggle(event); event.preventDefault(); } } }, { key: "hasLabel", value: function hasLabel() { return this.props.onLabel && this.props.onLabel.length > 0 && this.props.offLabel && this.props.offLabel.length > 0; } }, { key: "hasIcon", value: function hasIcon() { return this.props.onIcon && this.props.onIcon.length > 0 && this.props.offIcon && this.props.offIcon.length > 0; } }, { key: "getLabel", value: function getLabel() { return this.hasLabel() ? this.props.checked ? this.props.onLabel : this.props.offLabel : '&nbsp;'; } }, { 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.container, content: this.props.tooltip, options: this.props.tooltipOptions }); } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-button p-togglebutton p-component', { 'p-button-icon-only': this.hasIcon() && !this.hasLabel(), 'p-highlight': this.props.checked, 'p-disabled': this.props.disabled }, this.props.className), iconClassName = null; var hasIcon = this.hasIcon(); var label = this.getLabel(); if (hasIcon) { iconClassName = classNames('p-button-icon p-c', { 'p-button-icon-left': this.props.iconPos === 'left' && label, 'p-button-icon-right': this.props.iconPos === 'right' && label }, this.props.checked ? this.props.onIcon : this.props.offIcon); } return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this2.container = el; }, id: this.props.id, className: className, style: this.props.style, onClick: this.toggle, onFocus: this.props.onFocus, onBlur: this.props.onBlur, onKeyDown: this.onKeyDown, tabIndex: !this.props.disabled && this.props.tabIndex, "aria-labelledby": this.props.ariaLabelledBy }, hasIcon && /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement("span", { className: "p-button-label" }, label), /*#__PURE__*/React.createElement(Ripple, null)); } }]); return ToggleButton; }(Component); _defineProperty(ToggleButton, "defaultProps", { id: null, onIcon: null, offIcon: null, onLabel: 'Yes', offLabel: 'No', iconPos: 'left', style: null, className: null, checked: false, tabIndex: 0, tooltip: null, tooltipOptions: null, ariaLabelledBy: null, onChange: null, onFocus: null, onBlur: null }); export { ToggleButton };
ajax/libs/primereact/6.5.0/paginator/paginator.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames, Ripple, ObjectUtils } from 'primereact/core'; import { Dropdown } from 'primereact/dropdown'; function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _i = arr && (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 _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 _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 _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$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 FirstPageLink = /*#__PURE__*/function (_Component) { _inherits(FirstPageLink, _Component); var _super = _createSuper$7(FirstPageLink); function FirstPageLink() { _classCallCheck(this, FirstPageLink); return _super.apply(this, arguments); } _createClass(FirstPageLink, [{ key: "render", value: function render() { var className = classNames('p-paginator-first p-paginator-element p-link', { 'p-disabled': this.props.disabled }); var iconClassName = 'p-paginator-icon pi pi-angle-double-left'; var element = /*#__PURE__*/React.createElement("button", { type: "button", className: className, onClick: this.props.onClick, disabled: this.props.disabled }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (this.props.template) { var defaultOptions = { onClick: this.props.onClick, className: className, iconClassName: iconClassName, disabled: this.props.disabled, element: element, props: this.props }; return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return FirstPageLink; }(Component); _defineProperty(FirstPageLink, "defaultProps", { disabled: false, onClick: null, template: null }); 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 NextPageLink = /*#__PURE__*/function (_Component) { _inherits(NextPageLink, _Component); var _super = _createSuper$6(NextPageLink); function NextPageLink() { _classCallCheck(this, NextPageLink); return _super.apply(this, arguments); } _createClass(NextPageLink, [{ key: "render", value: function render() { var className = classNames('p-paginator-next p-paginator-element p-link', { 'p-disabled': this.props.disabled }); var iconClassName = 'p-paginator-icon pi pi-angle-right'; var element = /*#__PURE__*/React.createElement("button", { type: "button", className: className, onClick: this.props.onClick, disabled: this.props.disabled }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (this.props.template) { var defaultOptions = { onClick: this.props.onClick, className: className, iconClassName: iconClassName, disabled: this.props.disabled, element: element, props: this.props }; return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return NextPageLink; }(Component); _defineProperty(NextPageLink, "defaultProps", { disabled: false, onClick: null, template: null }); 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 PrevPageLink = /*#__PURE__*/function (_Component) { _inherits(PrevPageLink, _Component); var _super = _createSuper$5(PrevPageLink); function PrevPageLink() { _classCallCheck(this, PrevPageLink); return _super.apply(this, arguments); } _createClass(PrevPageLink, [{ key: "render", value: function render() { var className = classNames('p-paginator-prev p-paginator-element p-link', { 'p-disabled': this.props.disabled }); var iconClassName = 'p-paginator-icon pi pi-angle-left'; var element = /*#__PURE__*/React.createElement("button", { type: "button", className: className, onClick: this.props.onClick, disabled: this.props.disabled }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (this.props.template) { var defaultOptions = { onClick: this.props.onClick, className: className, iconClassName: iconClassName, disabled: this.props.disabled, element: element, props: this.props }; return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return PrevPageLink; }(Component); _defineProperty(PrevPageLink, "defaultProps", { disabled: false, onClick: null, template: null }); 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 LastPageLink = /*#__PURE__*/function (_Component) { _inherits(LastPageLink, _Component); var _super = _createSuper$4(LastPageLink); function LastPageLink() { _classCallCheck(this, LastPageLink); return _super.apply(this, arguments); } _createClass(LastPageLink, [{ key: "render", value: function render() { var className = classNames('p-paginator-last p-paginator-element p-link', { 'p-disabled': this.props.disabled }); var iconClassName = 'p-paginator-icon pi pi-angle-double-right'; var element = /*#__PURE__*/React.createElement("button", { type: "button", className: className, onClick: this.props.onClick, disabled: this.props.disabled }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (this.props.template) { var defaultOptions = { onClick: this.props.onClick, className: className, iconClassName: iconClassName, disabled: this.props.disabled, element: element, props: this.props }; return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return LastPageLink; }(Component); _defineProperty(LastPageLink, "defaultProps", { disabled: false, onClick: null, template: null }); 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 PageLinks = /*#__PURE__*/function (_Component) { _inherits(PageLinks, _Component); var _super = _createSuper$3(PageLinks); function PageLinks() { _classCallCheck(this, PageLinks); return _super.apply(this, arguments); } _createClass(PageLinks, [{ key: "onPageLinkClick", value: function onPageLinkClick(event, pageLink) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, value: pageLink }); } event.preventDefault(); } }, { key: "render", value: function render() { var _this = this; var elements; if (this.props.value) { var startPageInView = this.props.value[0]; var endPageInView = this.props.value[this.props.value.length - 1]; elements = this.props.value.map(function (pageLink, i) { var className = classNames('p-paginator-page p-paginator-element p-link', { 'p-paginator-page-start': pageLink === startPageInView, 'p-paginator-page-end': pageLink === endPageInView, 'p-highlight': pageLink - 1 === _this.props.page }); var element = /*#__PURE__*/React.createElement("button", { type: "button", className: className, onClick: function onClick(e) { return _this.onPageLinkClick(e, pageLink); } }, pageLink, /*#__PURE__*/React.createElement(Ripple, null)); if (_this.props.template) { var defaultOptions = { onClick: function onClick(e) { return _this.onPageLinkClick(e, pageLink); }, className: className, view: { startPage: startPageInView - 1, endPage: endPageInView - 1 }, page: pageLink - 1, currentPage: _this.props.page, totalPages: _this.props.pageCount, element: element, props: _this.props }; element = ObjectUtils.getJSXElement(_this.props.template, defaultOptions); } return /*#__PURE__*/React.createElement(React.Fragment, { key: pageLink }, element); }); } return /*#__PURE__*/React.createElement("span", { className: "p-paginator-pages" }, elements); } }]); return PageLinks; }(Component); _defineProperty(PageLinks, "defaultProps", { value: null, page: null, rows: null, pageCount: null, links: null, template: 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 RowsPerPageDropdown = /*#__PURE__*/function (_Component) { _inherits(RowsPerPageDropdown, _Component); var _super = _createSuper$2(RowsPerPageDropdown); function RowsPerPageDropdown() { _classCallCheck(this, RowsPerPageDropdown); return _super.apply(this, arguments); } _createClass(RowsPerPageDropdown, [{ key: "hasOptions", value: function hasOptions() { return this.props.options && this.props.options.length > 0; } }, { key: "render", value: function render() { var hasOptions = this.hasOptions(); var options = hasOptions ? this.props.options.map(function (opt) { return { label: String(opt), value: opt }; }) : []; var element = hasOptions ? /*#__PURE__*/React.createElement(Dropdown, { value: this.props.value, options: options, onChange: this.props.onChange, appendTo: this.props.appendTo }) : null; if (this.props.template) { var defaultOptions = { value: this.props.value, options: options, onChange: this.props.onChange, appendTo: this.props.appendTo, currentPage: this.props.page, totalPages: this.props.pageCount, totalRecords: this.props.totalRecords, element: element, props: this.props }; return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return RowsPerPageDropdown; }(Component); _defineProperty(RowsPerPageDropdown, "defaultProps", { options: null, value: null, page: null, pageCount: null, totalRecords: 0, appendTo: null, onChange: null, template: null }); 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$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 CurrentPageReport = /*#__PURE__*/function (_Component) { _inherits(CurrentPageReport, _Component); var _super = _createSuper$1(CurrentPageReport); function CurrentPageReport() { _classCallCheck(this, CurrentPageReport); return _super.apply(this, arguments); } _createClass(CurrentPageReport, [{ key: "render", value: function render() { var report = { currentPage: this.props.page + 1, totalPages: this.props.pageCount, first: Math.min(this.props.first + 1, this.props.totalRecords), last: Math.min(this.props.first + this.props.rows, this.props.totalRecords), rows: this.props.rows, totalRecords: this.props.totalRecords }; var text = this.props.reportTemplate.replace("{currentPage}", report.currentPage).replace("{totalPages}", report.totalPages).replace("{first}", report.first).replace("{last}", report.last).replace("{rows}", report.rows).replace("{totalRecords}", report.totalRecords); var element = /*#__PURE__*/React.createElement("span", { className: "p-paginator-current" }, text); if (this.props.template) { var defaultOptions = _objectSpread(_objectSpread({}, report), { className: 'p-paginator-current', element: element, props: this.props }); return ObjectUtils.getJSXElement(this.props.template, defaultOptions); } return element; } }]); return CurrentPageReport; }(Component); _defineProperty(CurrentPageReport, "defaultProps", { pageCount: null, page: null, first: null, rows: null, totalRecords: null, reportTemplate: '({currentPage} of {totalPages})', template: null }); 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 Paginator = /*#__PURE__*/function (_Component) { _inherits(Paginator, _Component); var _super = _createSuper(Paginator); function Paginator(props) { var _this; _classCallCheck(this, Paginator); _this = _super.call(this, props); _this.changePageToFirst = _this.changePageToFirst.bind(_assertThisInitialized(_this)); _this.changePageToPrev = _this.changePageToPrev.bind(_assertThisInitialized(_this)); _this.changePageToNext = _this.changePageToNext.bind(_assertThisInitialized(_this)); _this.changePageToLast = _this.changePageToLast.bind(_assertThisInitialized(_this)); _this.onRowsChange = _this.onRowsChange.bind(_assertThisInitialized(_this)); _this.onPageLinkClick = _this.onPageLinkClick.bind(_assertThisInitialized(_this)); return _this; } _createClass(Paginator, [{ key: "isFirstPage", value: function isFirstPage() { return this.getPage() === 0; } }, { key: "isLastPage", value: function isLastPage() { return this.getPage() === this.getPageCount() - 1; } }, { key: "getPageCount", value: function getPageCount() { return Math.ceil(this.props.totalRecords / this.props.rows) || 1; } }, { key: "calculatePageLinkBoundaries", value: function calculatePageLinkBoundaries() { var numberOfPages = this.getPageCount(); var visiblePages = Math.min(this.props.pageLinkSize, numberOfPages); //calculate range, keep current in middle if necessary var start = Math.max(0, Math.ceil(this.getPage() - visiblePages / 2)); var end = Math.min(numberOfPages - 1, start + visiblePages - 1); //check when approaching to last page var delta = this.props.pageLinkSize - (end - start + 1); start = Math.max(0, start - delta); return [start, end]; } }, { key: "updatePageLinks", value: function updatePageLinks() { var pageLinks = []; var boundaries = this.calculatePageLinkBoundaries(); var start = boundaries[0]; var end = boundaries[1]; for (var i = start; i <= end; i++) { pageLinks.push(i + 1); } return pageLinks; } }, { key: "changePage", value: function changePage(first, rows) { var pc = this.getPageCount(); var p = Math.floor(first / rows); if (p >= 0 && p < pc) { var newPageState = { first: first, rows: rows, page: p, pageCount: pc }; if (this.props.onPageChange) { this.props.onPageChange(newPageState); } } } }, { key: "getPage", value: function getPage() { return Math.floor(this.props.first / this.props.rows); } }, { key: "changePageToFirst", value: function changePageToFirst(event) { this.changePage(0, this.props.rows); event.preventDefault(); } }, { key: "changePageToPrev", value: function changePageToPrev(event) { this.changePage(this.props.first - this.props.rows, this.props.rows); event.preventDefault(); } }, { key: "onPageLinkClick", value: function onPageLinkClick(event) { this.changePage((event.value - 1) * this.props.rows, this.props.rows); } }, { key: "changePageToNext", value: function changePageToNext(event) { this.changePage(this.props.first + this.props.rows, this.props.rows); event.preventDefault(); } }, { key: "changePageToLast", value: function changePageToLast(event) { this.changePage((this.getPageCount() - 1) * this.props.rows, this.props.rows); event.preventDefault(); } }, { key: "onRowsChange", value: function onRowsChange(event) { var rows = event.value; this.isRowChanged = rows !== this.props.rows; this.changePage(0, rows); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.props.rows !== prevProps.rows && !this.isRowChanged) { this.changePage(0, this.props.rows); } else if (this.getPage() > 0 && prevProps.totalRecords !== this.props.totalRecords && this.props.first >= this.props.totalRecords) { this.changePage((this.getPageCount() - 1) * this.props.rows, this.props.rows); } this.isRowChanged = false; } }, { key: "renderElement", value: function renderElement(key, template) { var element; switch (key) { case 'FirstPageLink': element = /*#__PURE__*/React.createElement(FirstPageLink, { key: key, onClick: this.changePageToFirst, disabled: this.isFirstPage(), template: template }); break; case 'PrevPageLink': element = /*#__PURE__*/React.createElement(PrevPageLink, { key: key, onClick: this.changePageToPrev, disabled: this.isFirstPage(), template: template }); break; case 'NextPageLink': element = /*#__PURE__*/React.createElement(NextPageLink, { key: key, onClick: this.changePageToNext, disabled: this.isLastPage(), template: template }); break; case 'LastPageLink': element = /*#__PURE__*/React.createElement(LastPageLink, { key: key, onClick: this.changePageToLast, disabled: this.isLastPage(), template: template }); break; case 'PageLinks': element = /*#__PURE__*/React.createElement(PageLinks, { key: key, value: this.updatePageLinks(), page: this.getPage(), rows: this.props.rows, pageCount: this.getPageCount(), onClick: this.onPageLinkClick, template: template }); break; case 'RowsPerPageDropdown': element = /*#__PURE__*/React.createElement(RowsPerPageDropdown, { key: key, value: this.props.rows, page: this.getPage(), pageCount: this.getPageCount(), totalRecords: this.props.totalRecords, options: this.props.rowsPerPageOptions, onChange: this.onRowsChange, appendTo: this.props.dropdownAppendTo, template: template }); break; case 'CurrentPageReport': element = /*#__PURE__*/React.createElement(CurrentPageReport, { reportTemplate: this.props.currentPageReportTemplate, key: key, page: this.getPage(), pageCount: this.getPageCount(), first: this.props.first, rows: this.props.rows, totalRecords: this.props.totalRecords, template: template }); break; default: element = null; break; } return element; } }, { key: "renderElements", value: function renderElements() { var _this2 = this; var template = this.props.template; if (template) { if (_typeof(template) === 'object') { return template.layout ? template.layout.split(' ').map(function (value) { var key = value.trim(); return _this2.renderElement(key, template[key]); }) : Object.entries(template).map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], _template = _ref2[1]; return _this2.renderElement(key, _template); }); } return template.split(' ').map(function (value) { return _this2.renderElement(value.trim()); }); } return null; } }, { key: "render", value: function render() { if (!this.props.alwaysShow && this.getPageCount() === 1) { return null; } else { var className = classNames('p-paginator p-component', this.props.className); var leftContent = ObjectUtils.getJSXElement(this.props.leftContent, this.props); var rightContent = ObjectUtils.getJSXElement(this.props.rightContent, this.props); var elements = this.renderElements(); var leftElement = leftContent && /*#__PURE__*/React.createElement("div", { className: "p-paginator-left-content" }, leftContent); var rightElement = rightContent && /*#__PURE__*/React.createElement("div", { className: "p-paginator-right-content" }, rightContent); return /*#__PURE__*/React.createElement("div", { className: className, style: this.props.style }, leftElement, elements, rightElement); } } }]); return Paginator; }(Component); _defineProperty(Paginator, "defaultProps", { totalRecords: 0, rows: 0, first: 0, pageLinkSize: 5, rowsPerPageOptions: null, alwaysShow: true, style: null, className: null, template: 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown', onPageChange: null, leftContent: null, rightContent: null, dropdownAppendTo: null, currentPageReportTemplate: '({currentPage} of {totalPages})' }); export { Paginator };
ajax/libs/material-ui/5.0.0-alpha.7/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/primereact/7.0.0/slider/slider.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, classNames } from 'primereact/utils'; 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 Slider = /*#__PURE__*/function (_Component) { _inherits(Slider, _Component); var _super = _createSuper(Slider); function Slider(props) { var _this; _classCallCheck(this, Slider); _this = _super.call(this, props); _this.onBarClick = _this.onBarClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.handleIndex = 0; return _this; } _createClass(Slider, [{ key: "value", get: function get() { return this.props.range ? this.props.value || [0, 100] : this.props.value || 0; } }, { key: "spin", value: function spin(event, dir) { var value = this.props.range ? this.value[this.handleIndex] : this.value; var step = (this.props.step || 1) * dir; this.updateValue(event, value + step); event.preventDefault(); } }, { key: "onDragStart", value: function onDragStart(event, index) { if (this.props.disabled) { return; } this.dragging = true; this.updateDomData(); this.sliderHandleClick = true; this.handleIndex = index; //event.preventDefault(); } }, { key: "onMouseDown", value: function onMouseDown(event, index) { this.bindDragListeners(); this.onDragStart(event, index); } }, { key: "onTouchStart", value: function onTouchStart(event, index) { this.bindTouchListeners(); this.onDragStart(event, index); } }, { key: "onKeyDown", value: function onKeyDown(event, index) { if (this.props.disabled) { return; } this.handleIndex = index; var key = event.key; if (key === 'ArrowRight' || key === 'ArrowUp') { this.spin(event, 1); } else if (key === 'ArrowLeft' || key === 'ArrowDown') { this.spin(event, -1); } } }, { key: "onBarClick", value: function onBarClick(event) { if (this.props.disabled) { return; } if (!this.sliderHandleClick) { this.updateDomData(); var value = this.setValue(event); if (this.props.onSlideEnd) { this.props.onSlideEnd({ originalEvent: event, value: value }); } } this.sliderHandleClick = false; } }, { key: "onDrag", value: function onDrag(event) { if (this.dragging) { this.setValue(event); event.preventDefault(); } } }, { key: "onDragEnd", value: function onDragEnd(event) { if (this.dragging) { this.dragging = false; if (this.props.onSlideEnd) { this.props.onSlideEnd({ originalEvent: event, value: this.props.value }); } this.unbindDragListeners(); this.unbindTouchListeners(); } } }, { key: "bindDragListeners", value: function bindDragListeners() { if (!this.dragListener) { this.dragListener = this.onDrag.bind(this); document.addEventListener('mousemove', this.dragListener); } if (!this.dragEndListener) { this.dragEndListener = this.onDragEnd.bind(this); document.addEventListener('mouseup', this.dragEndListener); } } }, { key: "unbindDragListeners", value: function unbindDragListeners() { if (this.dragListener) { document.removeEventListener('mousemove', this.dragListener); this.dragListener = null; } if (this.dragEndListener) { document.removeEventListener('mouseup', this.dragEndListener); this.dragEndListener = null; } } }, { key: "bindTouchListeners", value: function bindTouchListeners() { if (!this.dragListener) { this.dragListener = this.onDrag.bind(this); document.addEventListener('touchmove', this.dragListener); } if (!this.dragEndListener) { this.dragEndListener = this.onDragEnd.bind(this); document.addEventListener('touchend', this.dragEndListener); } } }, { key: "unbindTouchListeners", value: function unbindTouchListeners() { if (this.dragListener) { document.removeEventListener('touchmove', this.dragListener); this.dragListener = null; } if (this.dragEndListener) { document.removeEventListener('touchend', this.dragEndListener); this.dragEndListener = null; } } }, { key: "updateDomData", value: function updateDomData() { var rect = this.el.getBoundingClientRect(); this.initX = rect.left + DomHandler.getWindowScrollLeft(); this.initY = rect.top + DomHandler.getWindowScrollTop(); this.barWidth = this.el.offsetWidth; this.barHeight = this.el.offsetHeight; } }, { key: "setValue", value: function setValue(event) { var handleValue; var pageX = event.touches ? event.touches[0].pageX : event.pageX; var pageY = event.touches ? event.touches[0].pageY : event.pageY; if (this.props.orientation === 'horizontal') handleValue = (pageX - this.initX) * 100 / this.barWidth;else handleValue = (this.initY + this.barHeight - pageY) * 100 / this.barHeight; var newValue = (this.props.max - this.props.min) * (handleValue / 100) + this.props.min; if (this.props.step) { var oldValue = this.props.range ? this.value[this.handleIndex] : this.value; var diff = newValue - oldValue; if (diff < 0) newValue = oldValue + Math.ceil(newValue / this.props.step - oldValue / this.props.step) * this.props.step;else if (diff > 0) newValue = oldValue + Math.floor(newValue / this.props.step - oldValue / this.props.step) * this.props.step; } else { newValue = Math.floor(newValue); } return this.updateValue(event, newValue); } }, { key: "updateValue", value: function updateValue(event, value) { var parsedValue = parseFloat(value.toFixed(10)); var newValue = parsedValue; if (this.props.range) { if (this.handleIndex === 0) { if (parsedValue < this.props.min) parsedValue = this.props.min;else if (parsedValue > this.value[1]) parsedValue = this.value[1]; } else { if (parsedValue > this.props.max) parsedValue = this.props.max;else if (parsedValue < this.value[0]) parsedValue = this.value[0]; } newValue = _toConsumableArray(this.value); newValue[this.handleIndex] = parsedValue; if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: newValue }); } } else { if (parsedValue < this.props.min) parsedValue = this.props.min;else if (parsedValue > this.props.max) parsedValue = this.props.max; newValue = parsedValue; if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: newValue }); } } return newValue; } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindDragListeners(); this.unbindTouchListeners(); } }, { key: "renderHandle", value: function renderHandle(leftValue, bottomValue, index) { var _this2 = this; var handleClassName = classNames('p-slider-handle', { 'p-slider-handle-start': index === 0, 'p-slider-handle-end': index === 1, 'p-slider-handle-active': this.handleIndex === index }); return /*#__PURE__*/React.createElement("span", { onMouseDown: function onMouseDown(event) { return _this2.onMouseDown(event, index); }, onTouchStart: function onTouchStart(event) { return _this2.onTouchStart(event, index); }, onKeyDown: function onKeyDown(event) { return _this2.onKeyDown(event, index); }, tabIndex: this.props.tabIndex, className: handleClassName, style: { transition: this.dragging ? 'none' : null, left: leftValue !== null && leftValue + '%', bottom: bottomValue && bottomValue + '%' }, role: "slider", "aria-valuemin": this.props.min, "aria-valuemax": this.props.max, "aria-valuenow": leftValue || bottomValue, "aria-labelledby": this.props.ariaLabelledBy }); } }, { key: "renderRangeSlider", value: function renderRangeSlider() { var values = this.value; var horizontal = this.props.orientation === 'horizontal'; var handleValueStart = (values[0] < this.props.min ? 0 : values[0] - this.props.min) * 100 / (this.props.max - this.props.min); var handleValueEnd = (values[1] > this.props.max ? 100 : values[1] - this.props.min) * 100 / (this.props.max - this.props.min); var rangeStartHandle = horizontal ? this.renderHandle(handleValueStart, null, 0) : this.renderHandle(null, handleValueStart, 0); var rangeEndHandle = horizontal ? this.renderHandle(handleValueEnd, null, 1) : this.renderHandle(null, handleValueEnd, 1); var rangeStyle = horizontal ? { left: handleValueStart + '%', width: handleValueEnd - handleValueStart + '%' } : { bottom: handleValueStart + '%', height: handleValueEnd - handleValueStart + '%' }; return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", { className: "p-slider-range", style: rangeStyle }), rangeStartHandle, rangeEndHandle); } }, { key: "renderSingleSlider", value: function renderSingleSlider() { var value = this.value; var handleValue; if (value < this.props.min) handleValue = 0;else if (value > this.props.max) handleValue = 100;else handleValue = (value - this.props.min) * 100 / (this.props.max - this.props.min); var rangeStyle = this.props.orientation === 'horizontal' ? { width: handleValue + '%' } : { height: handleValue + '%' }; var handle = this.props.orientation === 'horizontal' ? this.renderHandle(handleValue, null, null) : this.renderHandle(null, handleValue, null); return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", { className: "p-slider-range", style: rangeStyle }), handle); } }, { key: "render", value: function render() { var _this3 = this; var className = classNames('p-slider p-component', this.props.className, { 'p-disabled': this.props.disabled, 'p-slider-horizontal': this.props.orientation === 'horizontal', 'p-slider-vertical': this.props.orientation === 'vertical' }); var content = this.props.range ? this.renderRangeSlider() : this.renderSingleSlider(); return /*#__PURE__*/React.createElement("div", { id: this.props.id, ref: function ref(el) { return _this3.el = el; }, style: this.props.style, className: className, onClick: this.onBarClick }, content); } }]); return Slider; }(Component); _defineProperty(Slider, "defaultProps", { id: null, value: null, min: 0, max: 100, orientation: 'horizontal', step: null, range: false, style: null, className: null, disabled: false, tabIndex: 0, ariaLabelledBy: null, onChange: null, onSlideEnd: null }); export { Slider };
ajax/libs/react-native-web/0.12.1/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; } 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 RefreshControl = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(RefreshControl, _React$Component); function RefreshControl() { return _React$Component.apply(this, arguments) || this; } var _proto = RefreshControl.prototype; _proto.render = function render() { var _this$props = this.props, colors = _this$props.colors, enabled = _this$props.enabled, onRefresh = _this$props.onRefresh, progressBackgroundColor = _this$props.progressBackgroundColor, progressViewOffset = _this$props.progressViewOffset, refreshing = _this$props.refreshing, size = _this$props.size, tintColor = _this$props.tintColor, title = _this$props.title, titleColor = _this$props.titleColor, rest = _objectWithoutPropertiesLoose(_this$props, ["colors", "enabled", "onRefresh", "progressBackgroundColor", "progressViewOffset", "refreshing", "size", "tintColor", "title", "titleColor"]); return React.createElement(View, rest); }; return RefreshControl; }(React.Component); export default RefreshControl;
ajax/libs/primereact/6.6.0-rc.1/confirmdialog/confirmdialog.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { DomHandler, classNames, ObjectUtils, Portal } from 'primereact/core'; import { Dialog } from 'primereact/dialog'; import { Button } from 'primereact/button'; import { localeOption } from 'primereact/api'; 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 _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; } } 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 confirmDialog(props) { var appendTo = props.appendTo || document.body; var confirmDialogWrapper = document.createDocumentFragment(); DomHandler.appendChild(confirmDialogWrapper, appendTo); props = _objectSpread(_objectSpread({}, props), { visible: props.visible === undefined ? true : props.visible }); var confirmDialogEl = /*#__PURE__*/React.createElement(ConfirmDialog, props); ReactDOM.render(confirmDialogEl, confirmDialogWrapper); var updateConfirmDialog = function updateConfirmDialog(newProps) { props = _objectSpread(_objectSpread({}, props), newProps); ReactDOM.render( /*#__PURE__*/React.cloneElement(confirmDialogEl, props), confirmDialogWrapper); }; return { _destroy: function _destroy() { ReactDOM.unmountComponentAtNode(confirmDialogWrapper); }, show: function show() { updateConfirmDialog({ visible: true, onHide: function onHide() { updateConfirmDialog({ visible: false }); // reset } }); }, hide: function hide() { updateConfirmDialog({ visible: false }); }, update: function update(newProps) { updateConfirmDialog(newProps); } }; } var ConfirmDialog = /*#__PURE__*/function (_Component) { _inherits(ConfirmDialog, _Component); var _super = _createSuper(ConfirmDialog); function ConfirmDialog(props) { var _this; _classCallCheck(this, ConfirmDialog); _this = _super.call(this, props); _this.state = { visible: props.visible }; _this.reject = _this.reject.bind(_assertThisInitialized(_this)); _this.accept = _this.accept.bind(_assertThisInitialized(_this)); _this.hide = _this.hide.bind(_assertThisInitialized(_this)); return _this; } _createClass(ConfirmDialog, [{ key: "acceptLabel", value: function acceptLabel() { return this.props.acceptLabel || localeOption('accept'); } }, { key: "rejectLabel", value: function rejectLabel() { return this.props.rejectLabel || localeOption('reject'); } }, { 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() { this.setState({ visible: true }); } }, { key: "hide", value: function hide(result) { var _this2 = this; this.setState({ visible: false }, function () { if (_this2.props.onHide) { _this2.props.onHide(result); } }); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.visible !== this.props.visible) { this.setState({ visible: this.props.visible }); } } }, { key: "renderFooter", value: function renderFooter() { var acceptClassName = classNames('p-confirm-dialog-accept', this.props.acceptClassName); var rejectClassName = classNames('p-confirm-dialog-reject', { 'p-button-text': !this.props.rejectClassName }, this.props.rejectClassName); var content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, { label: this.rejectLabel(), icon: this.props.rejectIcon, className: rejectClassName, onClick: this.reject }), /*#__PURE__*/React.createElement(Button, { label: this.acceptLabel(), icon: this.props.acceptIcon, className: acceptClassName, onClick: this.accept, autoFocus: true })); if (this.props.footer) { var defaultContentOptions = { accept: this.accept, reject: this.reject, 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-dialog', this.props.className); var iconClassName = classNames('p-confirm-dialog-icon', this.props.icon); var dialogProps = ObjectUtils.findDiffKeys(this.props, ConfirmDialog.defaultProps); var message = ObjectUtils.getJSXElement(this.props.message, this.props); var footer = this.renderFooter(); return /*#__PURE__*/React.createElement(Dialog, _extends({ visible: this.state.visible }, dialogProps, { className: className, footer: footer, onHide: this.hide, breakpoints: this.props.breakpoints }), /*#__PURE__*/React.createElement("i", { className: iconClassName }), /*#__PURE__*/React.createElement("span", { className: "p-confirm-dialog-message" }, message)); } }, { key: "render", value: function render() { var element = this.renderElement(); return /*#__PURE__*/React.createElement(Portal, { element: element, appendTo: this.props.appendTo }); } }]); return ConfirmDialog; }(Component); _defineProperty(ConfirmDialog, "defaultProps", { visible: false, message: null, rejectLabel: null, acceptLabel: null, icon: null, rejectIcon: null, acceptIcon: null, rejectClassName: null, acceptClassName: null, className: null, appendTo: null, footer: null, breakpoints: null, onHide: null, accept: null, reject: null }); export { ConfirmDialog, confirmDialog };
ajax/libs/react-native-web/0.12.1/exports/Picker/PickerItem.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 React from 'react'; import createElement from '../createElement'; var PickerItem = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(PickerItem, _React$Component); function PickerItem() { return _React$Component.apply(this, arguments) || this; } var _proto = PickerItem.prototype; _proto.render = function render() { var _this$props = this.props, color = _this$props.color, label = _this$props.label, testID = _this$props.testID, value = _this$props.value; var style = { color: color }; return createElement('option', { style: style, testID: testID, value: value }, label); }; return PickerItem; }(React.Component); export { PickerItem as default };
ajax/libs/material-ui/4.9.2/esm/FormControl/FormControl.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 { isFilled, isAdornedStart } from '../InputBase/utils'; import withStyles from '../styles/withStyles'; import capitalize from '../utils/capitalize'; import isMuiElement from '../utils/isMuiElement'; import FormControlContext from './FormControlContext'; export var styles = { /* Styles applied to the root element. */ root: { display: 'inline-flex', flexDirection: 'column', position: 'relative', // Reset fieldset default style. minWidth: 0, padding: 0, margin: 0, border: 0, zIndex: 0, // Fix blur label text issue verticalAlign: 'top' // Fix alignment issue on Safari. }, /* Styles applied to the root element if `margin="normal"`. */ marginNormal: { marginTop: 16, marginBottom: 8 }, /* Styles applied to the root element if `margin="dense"`. */ marginDense: { marginTop: 8, marginBottom: 4 }, /* Styles applied to the root element if `fullWidth={true}`. */ fullWidth: { width: '100%' } }; /** * Provides context such as filled/focused/error/required for form inputs. * Relying on the context provides high flexibility and ensures that the state always stays * consistent across the children of the `FormControl`. * This context is used by the following components: * * - FormLabel * - FormHelperText * - Input * - InputLabel * * You can find one composition example below and more going to [the demos](/components/text-fields/#components). * * ```jsx * <FormControl> * <InputLabel htmlFor="my-input">Email address</InputLabel> * <Input id="my-input" aria-describedby="my-helper-text" /> * <FormHelperText id="my-helper-text">We'll never share your email.</FormHelperText> * </FormControl> * ``` * * ⚠️Only one input can be used within a FormControl. */ var FormControl = React.forwardRef(function FormControl(props, ref) { var children = props.children, classes = props.classes, className = props.className, _props$color = props.color, color = _props$color === void 0 ? 'primary' : _props$color, _props$component = props.component, Component = _props$component === void 0 ? 'div' : _props$component, _props$disabled = props.disabled, disabled = _props$disabled === void 0 ? false : _props$disabled, _props$error = props.error, error = _props$error === void 0 ? false : _props$error, _props$fullWidth = props.fullWidth, fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth, _props$hiddenLabel = props.hiddenLabel, hiddenLabel = _props$hiddenLabel === void 0 ? false : _props$hiddenLabel, _props$margin = props.margin, margin = _props$margin === void 0 ? 'none' : _props$margin, _props$required = props.required, required = _props$required === void 0 ? false : _props$required, size = props.size, _props$variant = props.variant, variant = _props$variant === void 0 ? 'standard' : _props$variant, other = _objectWithoutProperties(props, ["children", "classes", "className", "color", "component", "disabled", "error", "fullWidth", "hiddenLabel", "margin", "required", "size", "variant"]); var _React$useState = React.useState(function () { // We need to iterate through the children and find the Input in order // to fully support server-side rendering. var initialAdornedStart = false; if (children) { React.Children.forEach(children, function (child) { if (!isMuiElement(child, ['Input', 'Select'])) { return; } var input = isMuiElement(child, ['Select']) ? child.props.input : child; if (input && isAdornedStart(input.props)) { initialAdornedStart = true; } }); } return initialAdornedStart; }), adornedStart = _React$useState[0], setAdornedStart = _React$useState[1]; var _React$useState2 = React.useState(function () { // We need to iterate through the children and find the Input in order // to fully support server-side rendering. var initialFilled = false; if (children) { React.Children.forEach(children, function (child) { if (!isMuiElement(child, ['Input', 'Select'])) { return; } if (isFilled(child.props, true)) { initialFilled = true; } }); } return initialFilled; }), filled = _React$useState2[0], setFilled = _React$useState2[1]; var _React$useState3 = React.useState(false), focused = _React$useState3[0], setFocused = _React$useState3[1]; if (disabled && focused) { setFocused(false); } var registerEffect; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks var registeredInput = React.useRef(false); registerEffect = function registerEffect() { if (registeredInput.current) { console.error(['Material-UI: there are multiple InputBase components inside a FormControl.', 'This is not supported. It might cause infinite rendering loops.', 'Only use one InputBase.'].join('\n')); } registeredInput.current = true; return function () { registeredInput.current = false; }; }; } var onFilled = React.useCallback(function () { setFilled(true); }, []); var onEmpty = React.useCallback(function () { setFilled(false); }, []); var childContext = { adornedStart: adornedStart, setAdornedStart: setAdornedStart, color: color, disabled: disabled, error: error, filled: filled, focused: focused, fullWidth: fullWidth, hiddenLabel: hiddenLabel, margin: (size === 'small' ? 'dense' : undefined) || margin, onBlur: function onBlur() { setFocused(false); }, onEmpty: onEmpty, onFilled: onFilled, onFocus: function onFocus() { setFocused(true); }, registerEffect: registerEffect, required: required, variant: variant }; return React.createElement(FormControlContext.Provider, { value: childContext }, React.createElement(Component, _extends({ className: clsx(classes.root, className, margin !== 'none' && classes["margin".concat(capitalize(margin))], fullWidth && classes.fullWidth), ref: ref }, other), children)); }); process.env.NODE_ENV !== "production" ? FormControl.propTypes = { /** * The contents of the form control. */ 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, input and helper text 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 component will take up the full width of its container. */ fullWidth: PropTypes.bool, /** * If `true`, the label will be hidden. * This is used to increase density for a `FilledInput`. * Be sure to add `aria-label` to the `input` element. */ hiddenLabel: PropTypes.bool, /** * If `dense` or `normal`, will adjust vertical spacing of this and contained components. */ margin: PropTypes.oneOf(['none', 'dense', 'normal']), /** * If `true`, the label will indicate that the input is required. */ required: PropTypes.bool, /** * The size of the text field. */ size: PropTypes.oneOf(['small', 'medium']), /** * The variant to use. */ variant: PropTypes.oneOf(['standard', 'outlined', 'filled']) } : void 0; export default withStyles(styles, { name: 'MuiFormControl' })(FormControl);
ajax/libs/boardgame-io/0.49.7/boardgameio.es.js
cdnjs/cdnjs
import { nanoid } from 'nanoid/non-secure'; import { applyMiddleware, compose, createStore } from 'redux'; import produce from 'immer'; import isPlainObject from 'lodash.isplainobject'; import { applyPatch, createPatch } from 'rfc6902'; import { stringify, parse } from 'flatted'; import 'setimmediate'; 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 is_empty(obj) { return Object.keys(obj).length === 0; } 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_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_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 get_all_dirty_from_scope($$scope) { if ($$scope.ctx.length > 32) { const dirty = []; const length = $$scope.ctx.length / 32; for (let i = 0; i < length; i++) { dirty[i] = -1; } return dirty; } return -1; } 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 append_styles(target, style_sheet_id, styles) { const append_styles_to = get_root_for_style(target); if (!append_styles_to.getElementById(style_sheet_id)) { const style = element('style'); style.id = style_sheet_id; style.textContent = styles; append_stylesheet(append_styles_to, style); } } function get_root_for_style(node) { if (!node) return document; const root = node.getRootNode ? node.getRootNode() : node.ownerDocument; if (root.host) { return root; } return document; } function append_empty_stylesheet(node) { const style_element = element('style'); append_stylesheet(get_root_for_style(node), style_element); return style_element; } function append_stylesheet(node, style) { append(node.head || node, style); } 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 === '' ? null : +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, bubbles = false) { const e = document.createEvent('CustomEvent'); e.initCustomEvent(type, bubbles, 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 = get_root_for_style(node); active_docs.add(doc); const stylesheet = doc.__svelte_stylesheet || (doc.__svelte_stylesheet = append_empty_stylesheet(node).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) { // @ts-ignore callbacks.slice().forEach(fn => fn.call(this, 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.$$); } set_current_component(null); 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_in_transition(node, fn, params) { let config = fn(node, params); let running = false; let animation_name; let task; let uid = 0; function cleanup() { if (animation_name) delete_rule(node, animation_name); } function go() { const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition; if (css) animation_name = create_rule(node, 0, 1, duration, delay, easing, css, uid++); tick(0, 1); const start_time = now() + delay; const end_time = start_time + duration; if (task) task.abort(); running = true; add_render_callback(() => dispatch(node, true, 'start')); task = loop(now => { if (running) { if (now >= end_time) { tick(1, 0); dispatch(node, true, 'end'); cleanup(); return running = false; } if (now >= start_time) { const t = easing((now - start_time) / duration); tick(t, 1 - t); } } return running; }); } let started = false; return { start() { if (started) return; started = true; delete_rule(node); if (is_function(config)) { config = config(); wait().then(go); } else { go(); } }, invalidate() { started = false; }, end() { if (running) { cleanup(); running = false; } } }; } function create_out_transition(node, fn, params) { let config = fn(node, params); let running = true; let animation_name; const group = outros; group.r += 1; function go() { const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition; if (css) animation_name = create_rule(node, 1, 0, duration, delay, easing, css); const start_time = now() + delay; const end_time = start_time + duration; add_render_callback(() => dispatch(node, false, 'start')); loop(now => { if (running) { if (now >= end_time) { tick(0, 1); dispatch(node, false, 'end'); if (!--group.r) { // this will result in `end()` being called, // so we don't need to clean up here run_all(group.c); } return false; } if (now >= start_time) { const t = easing((now - start_time) / duration); tick(1 - t, t); } } return running; }); } if (is_function(config)) { wait().then(() => { // @ts-ignore config = config(); go(); }); } else { go(); } return { end(reset) { if (reset && config.tick) { config.tick(1, 0); } if (running) { if (animation_name) delete_rule(node, animation_name); running = false; } } }; } 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) { 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; } }; } 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, customElement) { const { fragment, on_mount, on_destroy, after_update } = component.$$; fragment && fragment.m(target, anchor); if (!customElement) { // 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, append_styles, dirty = [-1]) { const parent_component = current_component; set_current_component(component); const $$ = component.$$ = { fragment: null, ctx: null, // state props, update: noop, not_equal, bound: blank_object(), // lifecycle on_mount: [], on_destroy: [], on_disconnect: [], before_update: [], after_update: [], context: new Map(parent_component ? parent_component.$$.context : options.context || []), // everything else callbacks: blank_object(), dirty, skip_bound: false, root: options.target || parent_component.$$.root }; append_styles && append_styles($$.root); let ready = false; $$.ctx = instance ? instance(component, options.props || {}, (i, ret, ...rest) => { const value = rest.length ? rest[0] : ret; if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) { if (!$$.skip_bound && $$.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, options.customElement); flush(); } set_current_component(parent_component); } /** * Base class for Svelte components. Used when dev=false. */ 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($$props) { if (this.$$set && !is_empty($$props)) { this.$$.skip_bound = true; this.$$set($$props); this.$$.skip_bound = false; } } } /* * 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 PATCH = 'PATCH'; const PLUGIN = 'PLUGIN'; const STRIP_TRANSIENTS = 'STRIP_TRANSIENTS'; /* * 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 with patch in response to * an action coming from another player. * @param prevStateID previous stateID * @param stateID stateID after this patch * @param {Operation[]} patch - The patch to apply. * @param {LogEntry[]} deltalog - A log delta. */ const patch = (prevStateID, stateID, patch, deltalog) => ({ type: PATCH, prevStateID, stateID, patch, deltalog, 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 }, }); /** * Private action used to strip transient metadata (e.g. errors) from the game * state. */ const stripTransients = () => ({ type: STRIP_TRANSIENTS, }); var ActionCreators = /*#__PURE__*/Object.freeze({ __proto__: null, makeMove: makeMove, gameEvent: gameEvent, automaticGameEvent: automaticGameEvent, sync: sync, patch: patch, update: update$1, reset: reset, undo: undo, redo: redo, plugin: plugin, stripTransients: stripTransients }); /** * 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 : Array.from({ length: diceCount }).map(() => Math.floor(random() * spotvalue) + 1); }; } function Die(spotvalue = 6, diceCount) { return diceCount === undefined ? Math.floor(random() * spotvalue) + 1 : Array.from({ length: diceCount }).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]; let sourceIndex = deck.length; let destinationIndex = 0; const shuffled = Array.from({ length: sourceIndex }); while (sourceIndex) { const randomIndex = Math.trunc(sourceIndex * random()); shuffled[destinationIndex++] = clone[randomIndex]; clone[randomIndex] = clone[--sourceIndex]; } return shuffled; }, _private: 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._private.isUsed(); }, flush: ({ api }) => { return api._private.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, }; var GameMethod; (function (GameMethod) { GameMethod["MOVE"] = "MOVE"; GameMethod["GAME_ON_END"] = "GAME_ON_END"; GameMethod["PHASE_ON_BEGIN"] = "PHASE_ON_BEGIN"; GameMethod["PHASE_ON_END"] = "PHASE_ON_END"; GameMethod["TURN_ON_BEGIN"] = "TURN_ON_BEGIN"; GameMethod["TURN_ON_MOVE"] = "TURN_ON_MOVE"; GameMethod["TURN_ON_END"] = "TURN_ON_END"; })(GameMethod || (GameMethod = {})); /* * 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 Errors; (function (Errors) { Errors["CalledOutsideHook"] = "Events must be called from moves or the `onBegin`, `onEnd`, and `onMove` hooks.\nThis error probably means you called an event from other game code, like an `endIf` trigger or one of the `turn.order` methods."; Errors["EndTurnInOnEnd"] = "`endTurn` is disallowed in `onEnd` hooks \u2014 the turn is already ending."; Errors["MaxTurnEndings"] = "Maximum number of turn endings exceeded for this update.\nThis likely means game code is triggering an infinite loop."; Errors["PhaseEventInOnEnd"] = "`setPhase` & `endPhase` are disallowed in a phase\u2019s `onEnd` hook \u2014 the phase is already ending.\nIf you\u2019re trying to dynamically choose the next phase when a phase ends, use the phase\u2019s `next` trigger."; Errors["StageEventInOnEnd"] = "`setStage`, `endStage` & `setActivePlayers` are disallowed in `onEnd` hooks."; Errors["StageEventInPhaseBegin"] = "`setStage`, `endStage` & `setActivePlayers` are disallowed in a phase\u2019s `onBegin` hook.\nUse `setActivePlayers` in a `turn.onBegin` hook or declare stages with `turn.activePlayers` instead."; Errors["StageEventInTurnBegin"] = "`setStage` & `endStage` are disallowed in `turn.onBegin`.\nUse `setActivePlayers` or declare stages with `turn.activePlayers` instead."; })(Errors || (Errors = {})); /** * Events */ class Events { constructor(flow, ctx, playerID) { this.flow = flow; this.playerID = playerID; this.dispatch = []; this.initialTurn = ctx.turn; this.updateTurnContext(ctx, undefined); // This is an arbitrarily large upper threshold, which could be made // configurable via a game option if the need arises. this.maxEndedTurnsPerAction = ctx.numPlayers * 100; } api() { const events = { _private: this, }; for (const type of this.flow.eventNames) { events[type] = (...args) => { this.dispatch.push({ type, args, phase: this.currentPhase, turn: this.currentTurn, calledFrom: this.currentMethod, // Used to capture a stack trace in case it is needed later. error: new Error('Events Plugin Error'), }); }; } return events; } isUsed() { return this.dispatch.length > 0; } updateTurnContext(ctx, methodType) { this.currentPhase = ctx.phase; this.currentTurn = ctx.turn; this.currentMethod = methodType; } unsetCurrentMethod() { this.currentMethod = undefined; } /** * Updates ctx with the triggered events. * @param {object} state - The state object { G, ctx }. */ update(state) { const initialState = state; const stateWithError = ({ stack }, message) => ({ ...initialState, plugins: { ...initialState.plugins, events: { ...initialState.plugins.events, data: { error: message + '\n' + stack }, }, }, }); EventQueue: for (let i = 0; i < this.dispatch.length; i++) { const event = this.dispatch[i]; const turnHasEnded = event.turn !== state.ctx.turn; // This protects against potential infinite loops if specific events are called on hooks. // The moment we exceed the defined threshold, we just bail out of all phases. const endedTurns = this.currentTurn - this.initialTurn; if (endedTurns >= this.maxEndedTurnsPerAction) { return stateWithError(event.error, Errors.MaxTurnEndings); } if (event.calledFrom === undefined) { return stateWithError(event.error, Errors.CalledOutsideHook); } // Stop processing events once the game has finished. if (state.ctx.gameover) break EventQueue; switch (event.type) { case 'endStage': case 'setStage': case 'setActivePlayers': { switch (event.calledFrom) { // Disallow all stage events in onEnd and phase.onBegin hooks. case GameMethod.TURN_ON_END: case GameMethod.PHASE_ON_END: return stateWithError(event.error, Errors.StageEventInOnEnd); case GameMethod.PHASE_ON_BEGIN: return stateWithError(event.error, Errors.StageEventInPhaseBegin); // Disallow setStage & endStage in turn.onBegin hooks. case GameMethod.TURN_ON_BEGIN: if (event.type === 'setActivePlayers') break; return stateWithError(event.error, Errors.StageEventInTurnBegin); } // If the turn already ended, don't try to process stage events. if (turnHasEnded) continue EventQueue; break; } case 'endTurn': { if (event.calledFrom === GameMethod.TURN_ON_END || event.calledFrom === GameMethod.PHASE_ON_END) { return stateWithError(event.error, Errors.EndTurnInOnEnd); } // If the turn already ended some other way, // don't try to end the turn again. if (turnHasEnded) continue EventQueue; break; } case 'endPhase': case 'setPhase': { if (event.calledFrom === GameMethod.PHASE_ON_END) { return stateWithError(event.error, Errors.PhaseEventInOnEnd); } // If the phase already ended some other way, // don't try to end the phase again. if (event.phase !== state.ctx.phase) continue EventQueue; break; } } const action = automaticGameEvent(event.type, event.args, this.playerID); 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 }) => api._private.isUsed(), isInvalid: ({ data }) => data.error || false, // Update the events plugin’s internal turn context each time a move // or hook is called. This allows events called after turn or phase // endings to dispatch the current turn and phase correctly. fnWrap: (method, methodType) => (G, ctx, ...args) => { const api = ctx.events; if (api) api._private.updateTurnContext(ctx, methodType); G = method(G, ctx, ...args); if (api) api._private.unsetCurrentMethod(); return G; }, dangerouslyFlushRawState: ({ state, api }) => api._private.update(state), api: ({ game, ctx, playerID }) => new Events(game.flow, ctx, playerID).api(), }; /* * 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: () => ({}), }; /** * Check if a value can be serialized (e.g. using `JSON.stringify`). * Adapted from: https://stackoverflow.com/a/30712764/3829557 */ function isSerializable(value) { // Primitives are OK. if (value === undefined || value === null || typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') { return true; } // A non-primitive value that is neither a POJO or an array cannot be serialized. if (!isPlainObject(value) && !Array.isArray(value)) { return false; } // Recurse entries if the value is an object or array. for (const key in value) { if (!isSerializable(value[key])) return false; } return true; } /** * Plugin that checks whether state is serializable, in order to avoid * network serialization bugs. */ const SerializablePlugin = { name: 'plugin-serializable', fnWrap: (move) => (G, ctx, ...args) => { const result = move(G, ctx, ...args); // Check state in non-production environments. if (process.env.NODE_ENV !== 'production' && !isSerializable(result)) { throw new Error('Move state is not JSON-serialiazable.\n' + 'See https://boardgame.io/documentation/#/?id=state for more information.'); } return result; }, }; /* * 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 ? () => { } : (...msg) => console.log(...msg); const errorfn = (...msg) => console.error(...msg); function info(msg) { logfn(`INFO: ${msg}`); } function error(error) { errorfn('ERROR:', error); } /* * 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 CORE_PLUGINS = [ImmerPlugin, RandomPlugin, LogPlugin, SerializablePlugin]; const DEFAULT_PLUGINS = [...CORE_PLUGINS, EventsPlugin]; /** * Allow plugins to intercept actions and process them. */ const ProcessAction = (state, action, opts) => { // TODO(#723): Extend error handling to plugins. 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 methodToWrap - The move function or hook to apply the plugins to. * @param methodType - The type of the move or hook being wrapped. * @param plugins - The list of plugins. */ const FnWrap = (methodToWrap, methodType, plugins) => { return [...CORE_PLUGINS, ...plugins, EventsPlugin] .filter((plugin) => plugin.fnWrap !== undefined) .reduce((method, { fnWrap }) => fnWrap(method, methodType), methodToWrap); }; /** * 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) => { // We flush the events plugin first, then custom plugins and the core plugins. // This means custom plugins cannot use the events API but will be available in event hooks. // Note that plugins are flushed in reverse, to allow custom plugins calling each other. [...CORE_PLUGINS, ...opts.game.plugins, EventsPlugin] .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; }) .includes(true); }; /** * Allows plugins to indicate if the entire action should be thrown out * as invalid. This will cancel the entire state update. */ const IsInvalid = (state, opts) => { const firstInvalidReturn = [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter((plugin) => plugin.isInvalid !== undefined) .map((plugin) => { const { name } = plugin; const pluginState = state.plugins[name]; const message = plugin.isInvalid({ G: state.G, ctx: state.ctx, game: opts.game, data: pluginState && pluginState.data, }); return message ? { plugin: name, message } : false; }) .find((value) => value); return firstInvalidReturn || false; }; /** * Update plugin state after move/event & check if plugins consider the update to be valid. * @returns Tuple of `[updatedState]` or `[originalState, invalidError]`. */ const FlushAndValidate = (state, opts) => { const updatedState = Flush(state, opts); const isInvalid = IsInvalid(updatedState, opts); if (!isInvalid) return [updatedState]; const { plugin, message } = isInvalid; error(`${plugin} plugin declared action invalid:\n${message}`); return [state, isInvalid]; }; /** * 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; }; /** * Adjust the given options to use the new minMoves/maxMoves if a legacy moveLimit was given * @param options The options object to apply backwards compatibility to * @param enforceMinMoves Use moveLimit to set both minMoves and maxMoves */ function supportDeprecatedMoveLimit(options, enforceMinMoves = false) { if (options.moveLimit) { if (enforceMinMoves) { options.minMoves = options.moveLimit; } options.maxMoves = options.moveLimit; delete options.moveLimit; } } /* * 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 SetActivePlayers(ctx, arg) { let activePlayers = {}; let _prevActivePlayers = []; let _nextActivePlayers = null; let _activePlayersMinMoves = {}; let _activePlayersMaxMoves = {}; 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 // stages previously did not enforce minMoves, this behaviour is kept intentionally supportDeprecatedMoveLimit(arg); if (arg.next) { _nextActivePlayers = arg.next; } if (arg.revert) { _prevActivePlayers = [ ...ctx._prevActivePlayers, { activePlayers: ctx.activePlayers, _activePlayersMinMoves: ctx._activePlayersMinMoves, _activePlayersMaxMoves: ctx._activePlayersMaxMoves, _activePlayersNumMoves: ctx._activePlayersNumMoves, }, ]; } if (arg.currentPlayer !== undefined) { ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, 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, _activePlayersMinMoves, _activePlayersMaxMoves, id, arg.others); } } } if (arg.all !== undefined) { for (let i = 0; i < ctx.playOrder.length; i++) { const id = ctx.playOrder[i]; ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, id, arg.all); } } if (arg.value) { for (const id in arg.value) { ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, id, arg.value[id]); } } if (arg.minMoves) { for (const id in activePlayers) { if (_activePlayersMinMoves[id] === undefined) { _activePlayersMinMoves[id] = arg.minMoves; } } } if (arg.maxMoves) { for (const id in activePlayers) { if (_activePlayersMaxMoves[id] === undefined) { _activePlayersMaxMoves[id] = arg.maxMoves; } } } } if (Object.keys(activePlayers).length === 0) { activePlayers = null; } if (Object.keys(_activePlayersMinMoves).length === 0) { _activePlayersMinMoves = null; } if (Object.keys(_activePlayersMaxMoves).length === 0) { _activePlayersMaxMoves = null; } const _activePlayersNumMoves = {}; for (const id in activePlayers) { _activePlayersNumMoves[id] = 0; } return { ...ctx, activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, _activePlayersNumMoves, _prevActivePlayers, _nextActivePlayers, }; } /** * Update activePlayers, setting it to previous, next or null values * when it becomes empty. * @param ctx */ function UpdateActivePlayersOnceEmpty(ctx) { let { activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, _activePlayersNumMoves, _prevActivePlayers, _nextActivePlayers, } = ctx; if (activePlayers && Object.keys(activePlayers).length === 0) { if (_nextActivePlayers) { ctx = SetActivePlayers(ctx, _nextActivePlayers); ({ activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, _activePlayersNumMoves, _prevActivePlayers, } = ctx); } else if (_prevActivePlayers.length > 0) { const lastIndex = _prevActivePlayers.length - 1; ({ activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, _activePlayersNumMoves, } = _prevActivePlayers[lastIndex]); _prevActivePlayers = _prevActivePlayers.slice(0, lastIndex); } else { activePlayers = null; _activePlayersMinMoves = null; _activePlayersMaxMoves = null; } } return { ...ctx, activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, _activePlayersNumMoves, _prevActivePlayers, }; } /** * Apply an active player argument to the given player ID * @param {Object} activePlayers * @param {Object} _activePlayersMinMoves * @param {Object} _activePlayersMaxMoves * @param {String} playerID The player to apply the parameter to * @param {(String|Object)} arg An active player argument */ function ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, playerID, arg) { if (typeof arg !== 'object' || arg === Stage.NULL) { arg = { stage: arg }; } if (arg.stage !== undefined) { // stages previously did not enforce minMoves, this behaviour is kept intentionally supportDeprecatedMoveLimit(arg); activePlayers[playerID] = arg.stage; if (arg.minMoves) _activePlayersMinMoves[playerID] = arg.minMoves; if (arg.maxMoves) _activePlayersMaxMoves[playerID] = arg.maxMoves; } } /** * 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 { numPlayers } = ctx; const ctxWithAPI = EnhanceCtx(state); const order = turn.order; let playOrder = [...Array.from({ length: 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 = (hook, hookType) => { const withPlugins = FnWrap(hook, hookType, plugins); return (state) => { const ctxWithAPI = EnhanceCtx(state); return withPlugins(state.G, ctxWithAPI); }; }; const TriggerWrapper = (trigger) => { return (state) => { const ctxWithAPI = EnhanceCtx(state); return trigger(state.G, ctxWithAPI); }; }; const wrapped = { onEnd: HookWrapper(onEnd, GameMethod.GAME_ON_END), endIf: TriggerWrapper(endIf), }; for (const phase in phaseMap) { const phaseConfig = phaseMap[phase]; if (phaseConfig.start === true) { startingPhase = phase; } if (phaseConfig.moves !== undefined) { for (const move of Object.keys(phaseConfig.moves)) { moveMap[phase + '.' + move] = phaseConfig.moves[move]; moveNames.add(move); } } if (phaseConfig.endIf === undefined) { phaseConfig.endIf = () => undefined; } if (phaseConfig.onBegin === undefined) { phaseConfig.onBegin = (G) => G; } if (phaseConfig.onEnd === undefined) { phaseConfig.onEnd = (G) => G; } if (phaseConfig.turn === undefined) { phaseConfig.turn = turn; } if (phaseConfig.turn.order === undefined) { phaseConfig.turn.order = TurnOrder.DEFAULT; } if (phaseConfig.turn.onBegin === undefined) { phaseConfig.turn.onBegin = (G) => G; } if (phaseConfig.turn.onEnd === undefined) { phaseConfig.turn.onEnd = (G) => G; } if (phaseConfig.turn.endIf === undefined) { phaseConfig.turn.endIf = () => false; } if (phaseConfig.turn.onMove === undefined) { phaseConfig.turn.onMove = (G) => G; } if (phaseConfig.turn.stages === undefined) { phaseConfig.turn.stages = {}; } // turns previously treated moveLimit as both minMoves and maxMoves, this behaviour is kept intentionally supportDeprecatedMoveLimit(phaseConfig.turn, true); for (const stage in phaseConfig.turn.stages) { const stageConfig = phaseConfig.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); } } phaseConfig.wrapped = { onBegin: HookWrapper(phaseConfig.onBegin, GameMethod.PHASE_ON_BEGIN), onEnd: HookWrapper(phaseConfig.onEnd, GameMethod.PHASE_ON_END), endIf: TriggerWrapper(phaseConfig.endIf), }; phaseConfig.turn.wrapped = { onMove: HookWrapper(phaseConfig.turn.onMove, GameMethod.TURN_ON_MOVE), onBegin: HookWrapper(phaseConfig.turn.onBegin, GameMethod.TURN_ON_BEGIN), onEnd: HookWrapper(phaseConfig.turn.onEnd, GameMethod.TURN_ON_END), endIf: TriggerWrapper(phaseConfig.turn.endIf), }; if (typeof phaseConfig.next !== 'function') { const { next } = phaseConfig; phaseConfig.next = () => next || null; } phaseConfig.wrapped.next = TriggerWrapper(phaseConfig.next); } 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 ([OnMove, UpdateStage, UpdateActivePlayers].includes(fn)) { 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 phaseConfig = GetPhase(ctx); // Run any phase setup code provided by the user. G = phaseConfig.wrapped.onBegin(state); next.push({ fn: StartTurn }); return { ...state, G, ctx }; } function StartTurn(state, { currentPlayer }) { let { ctx } = state; const phaseConfig = GetPhase(ctx); // Initialize the turn order state. if (currentPlayer) { ctx = { ...ctx, currentPlayer }; if (phaseConfig.turn.activePlayers) { ctx = SetActivePlayers(ctx, phaseConfig.turn.activePlayers); } } else { // This is only called at the beginning of the phase // when there is no currentPlayer yet. ctx = InitTurnOrderState(state, phaseConfig.turn); } const turn = ctx.turn + 1; ctx = { ...ctx, turn, numMoves: 0, _prevActivePlayers: [] }; const G = phaseConfig.turn.wrapped.onBegin({ ...state, ctx }); return { ...state, G, ctx, _undo: [], _redo: [] }; } //////////// // Update // //////////// function UpdatePhase(state, { arg, next, phase }) { const phaseConfig = 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 { ctx = { ...ctx, phase: phaseConfig.wrapped.next(state) || 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 phaseConfig = GetPhase(ctx); // Update turn order state. const { endPhase, ctx: newCtx } = UpdateTurnOrderState(state, currentPlayer, phaseConfig.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 }; } if (typeof arg !== 'object') return state; // `arg` should be of type `StageArg`, loose typing as `any` here for historic reasons // stages previously did not enforce minMoves, this behaviour is kept intentionally supportDeprecatedMoveLimit(arg); let { ctx } = state; let { activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, _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.minMoves) { if (_activePlayersMinMoves === null) { _activePlayersMinMoves = {}; } _activePlayersMinMoves[playerID] = arg.minMoves; } if (arg.maxMoves) { if (_activePlayersMaxMoves === null) { _activePlayersMaxMoves = {}; } _activePlayersMaxMoves[playerID] = arg.maxMoves; } } ctx = { ...ctx, activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, _activePlayersNumMoves, }; return { ...state, ctx }; } function UpdateActivePlayers(state, { arg }) { return { ...state, ctx: SetActivePlayers(state.ctx, arg) }; } /////////////// // ShouldEnd // /////////////// function ShouldEndGame(state) { return wrapped.endIf(state); } function ShouldEndPhase(state) { const phaseConfig = GetPhase(state.ctx); return phaseConfig.wrapped.endIf(state); } function ShouldEndTurn(state) { const phaseConfig = GetPhase(state.ctx); // End the turn if the required number of moves has been made. const currentPlayerMoves = state.ctx.numMoves || 0; if (phaseConfig.turn.maxMoves && currentPlayerMoves >= phaseConfig.turn.maxMoves) { return true; } return phaseConfig.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: initialTurn, automatic }) { // End the turn first. state = EndTurn(state, { turn: initialTurn, force: true, automatic: true }); const { phase, turn } = state.ctx; if (next) { next.push({ fn: UpdatePhase, arg, phase }); } // If we aren't in a phase, there is nothing else to do. if (phase === null) { return state; } // Run any cleanup code for the phase that is about to end. const phaseConfig = GetPhase(state.ctx); const G = phaseConfig.wrapped.onEnd(state); // Reset the phase. const ctx = { ...state.ctx, phase: null }; // Add log entry. const action = gameEvent('endPhase', arg); const { _stateID } = state; const logEntry = { action, _stateID, turn, phase }; if (automatic) logEntry.automatic = true; const deltalog = [...(state.deltalog || []), logEntry]; return { ...state, G, ctx, deltalog }; } function EndTurn(state, { arg, next, turn: initialTurn, force, automatic, playerID }) { // This is not the turn that EndTurn was originally // called for. The turn was probably ended some other way. if (initialTurn !== state.ctx.turn) { return state; } const { currentPlayer, numMoves, phase, turn } = state.ctx; const phaseConfig = GetPhase(state.ctx); // Prevent ending the turn if minMoves haven't been reached. const currentPlayerMoves = numMoves || 0; if (!force && phaseConfig.turn.minMoves && currentPlayerMoves < phaseConfig.turn.minMoves) { info(`cannot end turn before making ${phaseConfig.turn.minMoves} moves`); return state; } // Run turn-end triggers. const G = phaseConfig.turn.wrapped.onEnd(state); if (next) { next.push({ fn: UpdateTurn, arg, currentPlayer }); } // Reset activePlayers. let ctx = { ...state.ctx, activePlayers: null }; // Remove player from playerOrder if (arg && arg.remove) { playerID = playerID || 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, phase }); return state; } } // Create log entry. const action = gameEvent('endTurn', arg); const { _stateID } = state; const logEntry = { action, _stateID, turn, 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, _stateID } = state; let { activePlayers, _activePlayersNumMoves, _activePlayersMinMoves, _activePlayersMaxMoves, phase, turn, } = ctx; const playerInStage = activePlayers !== null && playerID in activePlayers; const phaseConfig = GetPhase(ctx); if (!arg && playerInStage) { const stage = phaseConfig.turn.stages[activePlayers[playerID]]; if (stage && stage.next) { arg = stage.next; } } // Checking if arg is a valid stage, even Stage.NULL if (next) { next.push({ fn: UpdateStage, arg, playerID }); } // If player isn’t in a stage, there is nothing else to do. if (!playerInStage) return state; // Prevent ending the stage if minMoves haven't been reached. const currentPlayerMoves = _activePlayersNumMoves[playerID] || 0; if (_activePlayersMinMoves && _activePlayersMinMoves[playerID] && currentPlayerMoves < _activePlayersMinMoves[playerID]) { info(`cannot end stage before making ${_activePlayersMinMoves[playerID]} moves`); return state; } // Remove player from activePlayers. activePlayers = { ...activePlayers }; delete activePlayers[playerID]; if (_activePlayersMinMoves) { // Remove player from _activePlayersMinMoves. _activePlayersMinMoves = { ..._activePlayersMinMoves }; delete _activePlayersMinMoves[playerID]; } if (_activePlayersMaxMoves) { // Remove player from _activePlayersMaxMoves. _activePlayersMaxMoves = { ..._activePlayersMaxMoves }; delete _activePlayersMaxMoves[playerID]; } ctx = UpdateActivePlayersOnceEmpty({ ...ctx, activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, }); // Create log entry. const action = gameEvent('endStage', arg); const logEntry = { action, _stateID, turn, 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 phaseConfig = GetPhase(ctx); const stages = phaseConfig.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 (phaseConfig.moves) { // Check if moves are defined for the current phase. if (name in phaseConfig.moves) { return phaseConfig.moves[name]; } } else if (name in moves) { // Check for the move globally. return moves[name]; } return null; } function ProcessMove(state, action) { const { playerID, type } = action; const { currentPlayer, activePlayers, _activePlayersMaxMoves } = state.ctx; const move = GetMove(state.ctx, type, playerID); const shouldCount = !move || typeof move === 'function' || move.noLimit !== true; let { numMoves, _activePlayersNumMoves } = state.ctx; if (shouldCount) { if (playerID === currentPlayer) numMoves++; if (activePlayers) _activePlayersNumMoves[playerID]++; } state = { ...state, ctx: { ...state.ctx, numMoves, _activePlayersNumMoves, }, }; if (_activePlayersMaxMoves && _activePlayersNumMoves[playerID] >= _activePlayersMaxMoves[playerID]) { state = EndStage(state, { playerID, automatic: true }); } const phaseConfig = GetPhase(state.ctx); const G = phaseConfig.turn.wrapped.onMove({ ...state, ctx: { ...state.ctx, playerID }, }); 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 SetActivePlayersEvent(state, _playerID, arg) { return Process(state, [{ fn: UpdateActivePlayers, arg }]); } 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 (typeof eventHandlers[type] !== 'function') return state; return eventHandlers[type](state, playerID, ...(Array.isArray(args) ? args : [args])); } 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: [...Array.from({ length: numPlayers })].map((_, 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.deltaState === undefined) game.deltaState = false; 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, GameMethod.MOVE, game.plugins); const ctxWithAPI = { ...EnhanceCtx(state), playerID: action.playerID, }; let args = []; if (action.args !== undefined) { args = Array.isArray(action.args) ? action.args : [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. */ var UpdateErrorType; (function (UpdateErrorType) { // The action’s credentials were missing or invalid UpdateErrorType["UnauthorizedAction"] = "update/unauthorized_action"; // The action’s matchID was not found UpdateErrorType["MatchNotFound"] = "update/match_not_found"; // Could not apply Patch operation (rfc6902). UpdateErrorType["PatchFailed"] = "update/patch_failed"; })(UpdateErrorType || (UpdateErrorType = {})); var ActionErrorType; (function (ActionErrorType) { // The action contained a stale state ID ActionErrorType["StaleStateId"] = "action/stale_state_id"; // The requested move is unknown or not currently available ActionErrorType["UnavailableMove"] = "action/unavailable_move"; // The move declared it was invalid (INVALID_MOVE constant) ActionErrorType["InvalidMove"] = "action/invalid_move"; // The player making the action is not currently active ActionErrorType["InactivePlayer"] = "action/inactive_player"; // The game has finished ActionErrorType["GameOver"] = "action/gameover"; // The requested action is disabled (e.g. undo/redo, events) ActionErrorType["ActionDisabled"] = "action/action_disabled"; // The requested action is not currently possible ActionErrorType["ActionInvalid"] = "action/action_invalid"; // The requested action was declared invalid by a plugin ActionErrorType["PluginActionInvalid"] = "action/plugin_invalid"; })(ActionErrorType || (ActionErrorType = {})); /* * 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], }; } /** * Update plugin state after move/event & check if plugins consider the action to be valid. * @param state Current version of state in the reducer. * @param oldState State to revert to in case of error. * @param pluginOpts Plugin configuration options. * @returns Tuple of the new state updated after flushing plugins and the old * state augmented with an error if a plugin declared the action invalid. */ function flushAndValidatePlugins(state, oldState, pluginOpts) { const [newState, isInvalid] = FlushAndValidate(state, pluginOpts); if (!isInvalid) return [newState]; return [ newState, WithError(oldState, ActionErrorType.PluginActionInvalid, isInvalid), ]; } /** * ExtractTransientsFromState * * Split out transients from the a TransientState */ function ExtractTransients(transientState) { if (!transientState) { // We preserve null for the state for legacy callers, but the transient // field should be undefined if not present to be consistent with the // code path below. return [null, undefined]; } const { transients, ...state } = transientState; return [state, transients]; } /** * WithError * * Augment a State instance with transient error information. */ function WithError(state, errorType, payload) { const error = { type: errorType, payload, }; return { ...state, transients: { error, }, }; } /** * Middleware for processing TransientState associated with the reducer * returned by CreateGameReducer. * This should pretty much be used everywhere you want realistic state * transitions and error handling. */ const TransientHandlingMiddleware = (store) => (next) => (action) => { const result = next(action); switch (action.type) { case STRIP_TRANSIENTS: { return result; } default: { const [, transients] = ExtractTransients(store.getState()); if (typeof transients !== 'undefined') { store.dispatch(stripTransients()); // Dev Note: If parent middleware needs to correlate the spawned // StripTransients action to the triggering action, instrument here. // // This is a bit tricky; for more details, see: // https://github.com/boardgameio/boardgame.io/pull/940#discussion_r636200648 return { ...result, transients, }; } return result; } } }; /** * 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 (stateWithTransients = null, action) => { let [state /*, transients */] = ExtractTransients(stateWithTransients); switch (action.type) { case STRIP_TRANSIENTS: { // This action indicates that transient metadata in the state has been // consumed and should now be stripped from the state.. return state; } 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 WithError(state, ActionErrorType.GameOver); } // 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 WithError(state, ActionErrorType.InactivePlayer); } // Execute plugins. state = Enhance(state, { game, isClient: false, playerID: action.payload.playerID, }); // Process event. let newState = game.flow.processEvent(state, action); // Execute plugins. let stateWithError; [newState, stateWithError] = flushAndValidatePlugins(newState, state, { game, isClient: false, }); if (stateWithError) return stateWithError; // Update undo / redo state. newState = updateUndoRedoState(newState, { game, action }); return { ...newState, _stateID: state._stateID + 1 }; } case MAKE_MOVE: { const oldState = (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 WithError(state, ActionErrorType.UnavailableMove); } // 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 WithError(state, ActionErrorType.GameOver); } // 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 WithError(state, ActionErrorType.InactivePlayer); } // 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}`); // TODO(#723): Marshal a nice error payload with the processed move. return WithError(state, ActionErrorType.InvalidMove); } 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) { let stateWithError; [state, stateWithError] = flushAndValidatePlugins(state, oldState, { game, isClient: true, }); if (stateWithError) return stateWithError; 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); let stateWithError; [state, stateWithError] = flushAndValidatePlugins(state, oldState, { game, }); if (stateWithError) return stateWithError; // 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 WithError(state, ActionErrorType.ActionDisabled); } const { G, ctx, _undo, _redo, _stateID } = state; if (_undo.length < 2) { error(`No moves to undo`); return WithError(state, ActionErrorType.ActionInvalid); } 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) { error(`Cannot undo other players' moves`); return WithError(state, ActionErrorType.ActionInvalid); } // If undoing a move, check it is undoable. if (last.moveType) { const lastMove = game.flow.getMove(restore.ctx, last.moveType, last.playerID); if (!CanUndoMove(G, ctx, lastMove)) { error(`Move cannot be undone`); return WithError(state, ActionErrorType.ActionInvalid); } } state = initializeDeltalog(state, action); return { ...state, G: restore.G, ctx: restore.ctx, plugins: restore.plugins, _stateID: _stateID + 1, _undo: _undo.slice(0, -1), _redo: [last, ..._redo], }; } case REDO: { state = { ...state, deltalog: [] }; if (game.disableUndo) { error('Redo is not enabled'); return WithError(state, ActionErrorType.ActionDisabled); } const { _undo, _redo, _stateID } = state; if (_redo.length === 0) { error(`No moves to redo`); return WithError(state, ActionErrorType.ActionInvalid); } const first = _redo[0]; // Only allow players to redo their own undos. if (actionHasPlayerID(action) && action.payload.playerID !== first.playerID) { error(`Cannot redo other players' moves`); return WithError(state, ActionErrorType.ActionInvalid); } state = initializeDeltalog(state, action); return { ...state, G: first.G, ctx: first.ctx, plugins: first.plugins, _stateID: _stateID + 1, _undo: [..._undo, first], _redo: _redo.slice(1), }; } case PLUGIN: { // TODO(#723): Expose error semantics to plugin processing. return ProcessAction(state, action, { game }); } case PATCH: { const oldState = state; const newState = JSON.parse(JSON.stringify(oldState)); const patchError = applyPatch(newState, action.patch); const hasError = patchError.some((entry) => entry !== null); if (hasError) { error(`Patch ${JSON.stringify(action.patch)} apply failed`); return WithError(oldState, UpdateErrorType.PatchFailed, patchError); } else { return newState; } } 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] = FlushAndValidate(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({ transportDataCallback, gameName, playerID, matchID, credentials, numPlayers, }) { /** Callback to let the client know when the connection status has changed. */ this.connectionStatusCallback = () => { }; this.isConnected = false; this.transportDataCallback = transportDataCallback; this.gameName = gameName || 'default'; this.playerID = playerID || null; this.matchID = matchID || 'default'; this.credentials = credentials; this.numPlayers = numPlayers || 2; } /** Subscribe to connection state changes. */ subscribeToConnectionStatus(fn) { this.connectionStatusCallback = fn; } /** Transport implementations should call this when they connect/disconnect. */ setConnectionStatus(isConnected) { this.isConnected = isConnected; this.connectionStatusCallback(); } /** Transport implementations should call this when they receive data from a master. */ notifyClient(data) { this.transportDataCallback(data); } } /** * 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() { } sendAction() { } sendChatMessage() { } requestSync() { } 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 = new Set(); 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 (const subscriber of subscribers) { subscriber[1](); subscriber_queue.push(subscriber, 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.add(subscriber); if (subscribers.size === 1) { stop = start(set) || noop; } run(value); return () => { subscribers.delete(subscriber); if (subscribers.size === 0) { stop(); stop = null; } }; } return { set, update, subscribe }; } function cubicOut(t) { const f = t - 1.0; return f * f * f + 1.0; } /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } 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)}` }; } function crossfade(_a) { var { fallback } = _a, defaults = __rest(_a, ["fallback"]); const to_receive = new Map(); const to_send = new Map(); function crossfade(from, node, params) { const { delay = 0, duration = d => Math.sqrt(d) * 30, easing = cubicOut } = assign(assign({}, defaults), params); const to = node.getBoundingClientRect(); const dx = from.left - to.left; const dy = from.top - to.top; const dw = from.width / to.width; const dh = from.height / to.height; const d = Math.sqrt(dx * dx + dy * dy); const style = getComputedStyle(node); const transform = style.transform === 'none' ? '' : style.transform; const opacity = +style.opacity; return { delay, duration: is_function(duration) ? duration(d) : duration, easing, css: (t, u) => ` opacity: ${t * opacity}; transform-origin: top left; transform: ${transform} translate(${u * dx}px,${u * dy}px) scale(${t + (1 - t) * dw}, ${t + (1 - t) * dh}); ` }; } function transition(items, counterparts, intro) { return (node, params) => { items.set(params.key, { rect: node.getBoundingClientRect() }); return () => { if (counterparts.has(params.key)) { const { rect } = counterparts.get(params.key); counterparts.delete(params.key); return crossfade(rect, node, params); } // if the node is disappearing altogether // (i.e. wasn't claimed by the other list) // then we need to supply an outro items.delete(params.key); return fallback && fallback(node, params, intro); }; }; } return [ transition(to_send, to_receive, false), transition(to_receive, to_send, true) ]; } /* node_modules/svelte-icons/components/IconBase.svelte generated by Svelte v3.41.0 */ function add_css(target) { append_styles(target, "svelte-c8tyih", "svg.svelte-c8tyih{stroke:currentColor;fill:currentColor;stroke-width:0;width:100%;height:auto;max-height:100%}"); } // (18:2) {#if title} function create_if_block(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(ctx) { let svg; let if_block_anchor; let current; let if_block = /*title*/ ctx[0] && create_if_block(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(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 && (!current || dirty & /*$$scope*/ 4)) { update_slot_base( default_slot, default_slot_template, ctx, /*$$scope*/ ctx[2], !current ? get_all_dirty_from_scope(/*$$scope*/ ctx[2]) : get_slot_changes(default_slot_template, /*$$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($$self, $$props, $$invalidate) { let { $$slots: slots = {}, $$scope } = $$props; let { title = null } = $$props; let { viewBox } = $$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(); init(this, options, instance, create_fragment, safe_not_equal, { title: 0, viewBox: 1 }, add_css); } } /* node_modules/svelte-icons/fa/FaChevronRight.svelte generated by Svelte v3.41.0 */ function create_default_slot(ctx) { let path; return { c() { path = svg_element("path"); attr(path, "d", "M285.476 272.971L91.132 467.314c-9.373 9.373-24.569 9.373-33.941 0l-22.667-22.667c-9.357-9.357-9.375-24.522-.04-33.901L188.505 256 34.484 101.255c-9.335-9.379-9.317-24.544.04-33.901l22.667-22.667c9.373-9.373 24.569-9.373 33.941 0L285.475 239.03c9.373 9.372 9.373 24.568.001 33.941z"); }, m(target, anchor) { insert(target, path, anchor); }, d(detaching) { if (detaching) detach(path); } }; } function create_fragment$1(ctx) { let iconbase; let current; const iconbase_spread_levels = [{ viewBox: "0 0 320 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$1($$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 FaChevronRight extends SvelteComponent { constructor(options) { super(); init(this, options, instance$1, create_fragment$1, safe_not_equal, {}); } } /* src/client/debug/Menu.svelte generated by Svelte v3.41.0 */ function add_css$1(target) { append_styles(target, "svelte-1xg9v5h", ".menu.svelte-1xg9v5h{display:flex;margin-top:43px;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-1xg9v5h{line-height:25px;cursor:pointer;border:0;background:#fefefe;color:#555;padding-left:15px;padding-right:15px;text-align:center}.menu-item.svelte-1xg9v5h:first-child{border-radius:0 5px 0 0}.menu-item.svelte-1xg9v5h:last-child{border-radius:5px 0 0 0}.menu-item.active.svelte-1xg9v5h{cursor:default;font-weight:bold;background:#ddd;color:#555}.menu-item.svelte-1xg9v5h:hover,.menu-item.svelte-1xg9v5h:focus{background:#eee;color:#555}"); } 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() { return /*click_handler*/ ctx[3](/*key*/ ctx[4]); } return { c() { button = element("button"); t0 = text(t0_value); t1 = space(); attr(button, "class", "menu-item svelte-1xg9v5h"); 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$2(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-1xg9v5h"); }, 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$2($$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(); init(this, options, instance$2, create_fragment$2, safe_not_equal, { pane: 0, panes: 1 }, add_css$1); } } var contextKey = {}; /* node_modules/svelte-json-tree-auto/src/JSONArrow.svelte generated by Svelte v3.41.0 */ function add_css$2(target) { append_styles(target, "svelte-1vyml86", ".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)}"); } function create_fragment$3(ctx) { let div1; let div0; let mounted; let dispose; return { c() { div1 = element("div"); div0 = element("div"); div0.textContent = `${'\u25B6'}`; 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$3($$self, $$props, $$invalidate) { let { expanded } = $$props; function click_handler(event) { bubble.call(this, $$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(); init(this, options, instance$3, create_fragment$3, safe_not_equal, { expanded: 0 }, add_css$2); } } /* node_modules/svelte-json-tree-auto/src/JSONKey.svelte generated by Svelte v3.41.0 */ function add_css$3(target) { append_styles(target, "svelte-1vlbacg", "label.svelte-1vlbacg{display:inline-block;color:var(--label-color);padding:0}.spaced.svelte-1vlbacg{padding-right:var(--li-colon-space)}"); } // (16:0) {#if showKey && key} function create_if_block$1(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$4(ctx) { let if_block_anchor; let if_block = /*showKey*/ ctx[3] && /*key*/ ctx[0] && create_if_block$1(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$1(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$4($$self, $$props, $$invalidate) { let showKey; let { key, isParentExpanded, isParentArray = false, colon = ':' } = $$props; function click_handler(event) { bubble.call(this, $$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); }; $$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(); init( this, options, instance$4, create_fragment$4, safe_not_equal, { key: 0, isParentExpanded: 1, isParentArray: 4, colon: 2 }, add_css$3 ); } } /* node_modules/svelte-json-tree-auto/src/JSONNested.svelte generated by Svelte v3.41.0 */ function add_css$4(target) { append_styles(target, "svelte-rwxv37", "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}"); } 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$2(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$5(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$2, 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(); } else { if_block1.p(ctx, dirty); } 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$5($$self, $$props, $$invalidate) { let slicedKeys; let { key, keys, colon = ':', label = '', isParentExpanded, isParentArray, isArray = false, bracketOpen, bracketClose } = $$props; let { previewKeys = keys } = $$props; let { getKey = key => key } = $$props; let { getValue = key => key } = $$props; let { getPreviewValue = getValue } = $$props; let { expanded = false, 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); }; $$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(); init( this, options, instance$5, create_fragment$5, 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 }, add_css$4 ); } } /* node_modules/svelte-json-tree-auto/src/JSONObjectNode.svelte generated by Svelte v3.41.0 */ function create_fragment$6(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$6($$self, $$props, $$invalidate) { let keys; let { key, value, isParentExpanded, isParentArray, 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); }; $$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$6, create_fragment$6, 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.41.0 */ function create_fragment$7(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$7($$self, $$props, $$invalidate) { let keys; let previewKeys; let { key, value, isParentExpanded, 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); }; $$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$7, create_fragment$7, 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.41.0 */ function create_fragment$8(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$8($$self, $$props, $$invalidate) { let { key, value, isParentExpanded, isParentArray, 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$8, create_fragment$8, 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.41.0 */ function create_fragment$9(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$9($$self, $$props, $$invalidate) { let { key, value, isParentExpanded, isParentArray, 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$9, create_fragment$9, 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.41.0 */ function create_fragment$a(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$a($$self, $$props, $$invalidate) { let { key, value, isParentExpanded, 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$a, create_fragment$a, 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.41.0 */ function add_css$5(target) { append_styles(target, "svelte-3bjyvl", "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)}"); } function create_fragment$b(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$b($$self, $$props, $$invalidate) { let { key, value, valueGetter = null, isParentExpanded, isParentArray, 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(); init( this, options, instance$b, create_fragment$b, safe_not_equal, { key: 0, value: 1, valueGetter: 2, isParentExpanded: 3, isParentArray: 4, nodeType: 5 }, add_css$5 ); } } /* node_modules/svelte-json-tree-auto/src/ErrorNode.svelte generated by Svelte v3.41.0 */ function add_css$6(target) { append_styles(target, "svelte-1ca3gb2", "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}"); } 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$3(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$c(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$3(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$3(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$c($$self, $$props, $$invalidate) { let stack; let { key, value, isParentExpanded, 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); }; $$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(); init( this, options, instance$c, create_fragment$c, safe_not_equal, { key: 1, value: 2, isParentExpanded: 3, isParentArray: 4, expanded: 0 }, add_css$6 ); } } 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.41.0 */ function create_fragment$d(ctx) { let switch_instance; let switch_instance_anchor; let current; var switch_value = /*componentType*/ ctx[6]; 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[5] } }; } 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*/ 32) switch_instance_changes.valueGetter = /*valueGetter*/ ctx[5]; if (switch_value !== (switch_value = /*componentType*/ ctx[6])) { 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$d($$self, $$props, $$invalidate) { let nodeType; let componentType; let valueGetter; let { key, value, isParentExpanded, 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); }; $$self.$$.update = () => { if ($$self.$$.dirty & /*value*/ 2) { $$invalidate(4, nodeType = objType(value)); } if ($$self.$$.dirty & /*nodeType*/ 16) { $$invalidate(6, componentType = getComponent(nodeType)); } if ($$self.$$.dirty & /*nodeType*/ 16) { $$invalidate(5, valueGetter = getValueGetter(nodeType)); } }; return [ key, value, isParentExpanded, isParentArray, nodeType, valueGetter, componentType ]; } class JSONNode extends SvelteComponent { constructor(options) { super(); init(this, options, instance$d, create_fragment$d, safe_not_equal, { key: 0, value: 1, isParentExpanded: 2, isParentArray: 3 }); } } /* node_modules/svelte-json-tree-auto/src/Root.svelte generated by Svelte v3.41.0 */ function add_css$7(target) { append_styles(target, "svelte-773n60", "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}"); } function create_fragment$e(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$e($$self, $$props, $$invalidate) { setContext(contextKey, {}); let { key = '', 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(); init(this, options, instance$e, create_fragment$e, safe_not_equal, { key: 0, value: 1 }, add_css$7); } } /* src/client/debug/main/ClientSwitcher.svelte generated by Svelte v3.41.0 */ function add_css$8(target) { append_styles(target, "svelte-jvfq3i", ".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}"); } 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$4(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[6].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[6]) ]; 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$f(ctx) { let if_block_anchor; let if_block = /*debuggableClients*/ ctx[1].length > 1 && create_if_block$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); }, p(ctx, [dirty]) { if (/*debuggableClients*/ ctx[1].length > 1) { if (if_block) { if_block.p(ctx, dirty); } else { if_block = create_if_block$4(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$f($$self, $$props, $$invalidate) { let client; let debuggableClients; let selected; let $clientManager, $$unsubscribe_clientManager = noop, $$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(5, $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(4, client)), $$invalidate(5, $clientManager)); } $$self.$$set = $$props => { if ('clientManager' in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager)); }; $$self.$$.update = () => { if ($$self.$$.dirty & /*$clientManager*/ 32) { $$invalidate(4, { client, debuggableClients } = $clientManager, client, ($$invalidate(1, debuggableClients), $$invalidate(5, $clientManager))); } if ($$self.$$.dirty & /*debuggableClients, client*/ 18) { $$invalidate(2, selected = debuggableClients.indexOf(client)); } }; return [ clientManager, debuggableClients, selected, handleSelection, client, $clientManager, select_change_handler ]; } class ClientSwitcher extends SvelteComponent { constructor(options) { super(); init(this, options, instance$f, create_fragment$f, safe_not_equal, { clientManager: 0 }, add_css$8); } } /* src/client/debug/main/Hotkey.svelte generated by Svelte v3.41.0 */ function add_css$9(target) { append_styles(target, "svelte-1vfj1mn", ".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}"); } // (78:2) {#if label} function create_if_block$5(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$g(ctx) { let div; let button; let t0; let t1; let mounted; let dispose; let if_block = /*label*/ ctx[1] && create_if_block$5(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$5(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$g($$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(); init( this, options, instance$g, create_fragment$g, safe_not_equal, { value: 0, onPress: 8, label: 1, disable: 2 }, add_css$9 ); } } /* src/client/debug/main/InteractiveFunction.svelte generated by Svelte v3.41.0 */ function add_css$a(target) { append_styles(target, "svelte-1mppqmp", ".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}"); } function create_fragment$h(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$h($$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(); init( this, options, instance$h, create_fragment$h, safe_not_equal, { Activate: 0, Deactivate: 1, name: 2, active: 3 }, add_css$a ); } } /* src/client/debug/main/Move.svelte generated by Svelte v3.41.0 */ function add_css$b(target) { append_styles(target, "svelte-smqssc", ".move-error.svelte-smqssc{color:#a00;font-weight:bold}.wrapper.svelte-smqssc{display:flex;flex-direction:row;align-items:center}"); } // (65:2) {#if error} function create_if_block$6(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$i(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$6(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$6(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$i($$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(); init(this, options, instance$i, create_fragment$i, safe_not_equal, { shortcut: 0, name: 1, fn: 8 }, add_css$b); } } /* src/client/debug/main/Controls.svelte generated by Svelte v3.41.0 */ function add_css$c(target) { append_styles(target, "svelte-c3lavh", "ul.svelte-c3lavh{padding-left:0}li.svelte-c3lavh{list-style:none;margin:none;margin-bottom:5px}"); } function create_fragment$j(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[2], label: "save" } }); hotkey2 = new Hotkey({ props: { value: "3", onPress: /*Restore*/ ctx[3], label: "restore" } }); hotkey3 = new Hotkey({ props: { value: ".", onPress: /*ToggleVisibility*/ ctx[1], 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); const hotkey3_changes = {}; if (dirty & /*ToggleVisibility*/ 2) hotkey3_changes.onPress = /*ToggleVisibility*/ ctx[1]; hotkey3.$set(hotkey3_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$j($$self, $$props, $$invalidate) { let { client } = $$props; let { ToggleVisibility } = $$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); if ('ToggleVisibility' in $$props) $$invalidate(1, ToggleVisibility = $$props.ToggleVisibility); }; return [client, ToggleVisibility, Save, Restore]; } class Controls extends SvelteComponent { constructor(options) { super(); init(this, options, instance$j, create_fragment$j, safe_not_equal, { client: 0, ToggleVisibility: 1 }, add_css$c); } } /* src/client/debug/main/PlayerInfo.svelte generated by Svelte v3.41.0 */ function add_css$d(target) { append_styles(target, "svelte-19aan9p", ".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}"); } 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() { return /*click_handler*/ ctx[5](/*player*/ ctx[7]); } 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$k(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$k($$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(); init(this, options, instance$k, create_fragment$k, safe_not_equal, { ctx: 0, playerID: 1 }, add_css$d); } } 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 _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 _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 { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], 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; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } 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 = 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 () {}; 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 = it.call(o); }, 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.41.0 */ function add_css$e(target) { append_styles(target, "svelte-146sq5f", ".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}"); } function get_each_context$5(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[10] = list[i][0]; child_ctx[11] = list[i][1]; return child_ctx; } // (78: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[8][/*name*/ ctx[10]], fn: /*fn*/ ctx[11], name: /*name*/ ctx[10] } }); 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*/ 16) move_changes.shortcut = /*shortcuts*/ ctx[8][/*name*/ ctx[10]]; if (dirty & /*moves*/ 16) move_changes.fn = /*fn*/ ctx[11]; if (dirty & /*moves*/ 16) move_changes.name = /*name*/ ctx[10]; 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); } }; } // (90: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[5].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*/ 32) move_changes.fn = /*events*/ ctx[5].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); } }; } // (95: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[5].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*/ 32) move_changes.fn = /*events*/ ctx[5].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); } }; } // (100:2) {#if ctx.phase && events.endPhase} function create_if_block$7(ctx) { let li; let move; let current; move = new Move({ props: { name: "endPhase", shortcut: 9, fn: /*events*/ ctx[5].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*/ 32) move_changes.fn = /*events*/ ctx[5].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$l(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], ToggleVisibility: /*ToggleVisibility*/ ctx[2] } }); playerinfo = new PlayerInfo({ props: { ctx: /*ctx*/ ctx[6], playerID: /*playerID*/ ctx[3] } }); playerinfo.$on("change", /*change_handler*/ ctx[9]); let each_value = Object.entries(/*moves*/ ctx[4]); 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[6].activePlayers && /*events*/ ctx[5].endStage && create_if_block_2$2(ctx); let if_block1 = /*events*/ ctx[5].endTurn && create_if_block_1$2(ctx); let if_block2 = /*ctx*/ ctx[6].phase && /*events*/ ctx[5].endPhase && create_if_block$7(ctx); jsontree0 = new Root({ props: { value: /*G*/ ctx[7] } }); jsontree1 = new Root({ props: { value: SanitizeCtx(/*ctx*/ ctx[6]) } }); 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]; if (dirty & /*ToggleVisibility*/ 4) controls_changes.ToggleVisibility = /*ToggleVisibility*/ ctx[2]; controls.$set(controls_changes); const playerinfo_changes = {}; if (dirty & /*ctx*/ 64) playerinfo_changes.ctx = /*ctx*/ ctx[6]; if (dirty & /*playerID*/ 8) playerinfo_changes.playerID = /*playerID*/ ctx[3]; playerinfo.$set(playerinfo_changes); if (dirty & /*shortcuts, Object, moves*/ 272) { each_value = Object.entries(/*moves*/ ctx[4]); 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[6].activePlayers && /*events*/ ctx[5].endStage) { if (if_block0) { if_block0.p(ctx, dirty); if (dirty & /*ctx, events*/ 96) { 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[5].endTurn) { if (if_block1) { if_block1.p(ctx, dirty); if (dirty & /*events*/ 32) { 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[6].phase && /*events*/ ctx[5].endPhase) { if (if_block2) { if_block2.p(ctx, dirty); if (dirty & /*ctx, events*/ 96) { transition_in(if_block2, 1); } } else { if_block2 = create_if_block$7(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*/ 128) jsontree0_changes.value = /*G*/ ctx[7]; jsontree0.$set(jsontree0_changes); const jsontree1_changes = {}; if (dirty & /*ctx*/ 64) jsontree1_changes.value = SanitizeCtx(/*ctx*/ ctx[6]); 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$l($$self, $$props, $$invalidate) { let { client } = $$props; let { clientManager } = $$props; let { ToggleVisibility } = $$props; const shortcuts = AssignShortcuts(client.moves, 'mlia'); let { playerID, moves, events } = client; let ctx = {}; let G = {}; client.subscribe(state => { if (state) $$invalidate(7, { G, ctx } = state, G, $$invalidate(6, ctx)); $$invalidate(3, { playerID, moves, events } = client, playerID, $$invalidate(4, moves), $$invalidate(5, 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); if ('ToggleVisibility' in $$props) $$invalidate(2, ToggleVisibility = $$props.ToggleVisibility); }; return [ client, clientManager, ToggleVisibility, playerID, moves, events, ctx, G, shortcuts, change_handler ]; } class Main extends SvelteComponent { constructor(options) { super(); init( this, options, instance$l, create_fragment$l, safe_not_equal, { client: 0, clientManager: 1, ToggleVisibility: 2 }, add_css$e ); } } /* src/client/debug/info/Item.svelte generated by Svelte v3.41.0 */ function add_css$f(target) { append_styles(target, "svelte-13qih23", ".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}"); } function create_fragment$m(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$m($$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(); init(this, options, instance$m, create_fragment$m, safe_not_equal, { name: 0, value: 1 }, add_css$f); } } /* src/client/debug/info/Info.svelte generated by Svelte v3.41.0 */ function add_css$g(target) { append_styles(target, "svelte-1yzq5o8", ".gameinfo.svelte-1yzq5o8{padding:10px}"); } // (19:2) {#if client.multiplayer} function create_if_block$8(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$n(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$8(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$8(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$n($$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; let { ToggleVisibility } = $$props; $$self.$$set = $$props => { if ('client' in $$props) $$subscribe_client($$invalidate(0, client = $$props.client)); if ('clientManager' in $$props) $$invalidate(2, clientManager = $$props.clientManager); if ('ToggleVisibility' in $$props) $$invalidate(3, ToggleVisibility = $$props.ToggleVisibility); }; return [client, $client, clientManager, ToggleVisibility]; } class Info extends SvelteComponent { constructor(options) { super(); init( this, options, instance$n, create_fragment$n, safe_not_equal, { client: 0, clientManager: 2, ToggleVisibility: 3 }, add_css$g ); } } /* src/client/debug/log/TurnMarker.svelte generated by Svelte v3.41.0 */ function add_css$h(target) { append_styles(target, "svelte-6eza86", ".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}"); } function create_fragment$o(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$o($$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(); init(this, options, instance$o, create_fragment$o, safe_not_equal, { turn: 0, numEvents: 2 }, add_css$h); } } /* src/client/debug/log/PhaseMarker.svelte generated by Svelte v3.41.0 */ function add_css$i(target) { append_styles(target, "svelte-1t4xap", ".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%}"); } function create_fragment$p(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$p($$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(); init(this, options, instance$p, create_fragment$p, safe_not_equal, { phase: 0, numEvents: 2 }, add_css$i); } } /* src/client/debug/log/LogMetadata.svelte generated by Svelte v3.41.0 */ function create_fragment$q(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$q($$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$q, create_fragment$q, safe_not_equal, { metadata: 1 }); } } /* src/client/debug/log/LogEvent.svelte generated by Svelte v3.41.0 */ function add_css$j(target) { append_styles(target, "svelte-vajd9z", ".log-event.svelte-vajd9z{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-vajd9z:hover,.log-event.svelte-vajd9z:focus{border-style:solid;background:#eee}.log-event.pinned.svelte-vajd9z{border-style:solid;background:#eee;opacity:1}.args.svelte-vajd9z{text-align:left;white-space:pre-wrap}.player0.svelte-vajd9z{border-left-color:#ff851b}.player1.svelte-vajd9z{border-left-color:#7fdbff}.player2.svelte-vajd9z{border-left-color:#0074d9}.player3.svelte-vajd9z{border-left-color:#39cccc}.player4.svelte-vajd9z{border-left-color:#3d9970}.player5.svelte-vajd9z{border-left-color:#2ecc40}.player6.svelte-vajd9z{border-left-color:#01ff70}.player7.svelte-vajd9z{border-left-color:#ffdc00}.player8.svelte-vajd9z{border-left-color:#001f3f}.player9.svelte-vajd9z{border-left-color:#ff4136}.player10.svelte-vajd9z{border-left-color:#85144b}.player11.svelte-vajd9z{border-left-color:#f012be}.player12.svelte-vajd9z{border-left-color:#b10dc9}.player13.svelte-vajd9z{border-left-color:#111111}.player14.svelte-vajd9z{border-left-color:#aaaaaa}.player15.svelte-vajd9z{border-left-color:#dddddd}"); } // (146: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); } }; } // (144:2) {#if metadataComponent} function create_if_block$9(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$r(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$9, 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(div, "class", "args svelte-vajd9z"); attr(button, "class", button_class_value = "log-event player" + /*playerID*/ ctx[7] + " svelte-vajd9z"); 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(); } else { if_block.p(ctx, dirty); } 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$r($$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 = Array.isArray(args) ? args.map(arg => JSON.stringify(arg, null, 2)).join(',') : JSON.stringify(args, null, 2) || ''; 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(); init( this, options, instance$r, create_fragment$r, safe_not_equal, { logIndex: 0, action: 8, pinned: 1, metadata: 2, metadataComponent: 3 }, add_css$j ); } } /* node_modules/svelte-icons/fa/FaArrowAltCircleDown.svelte generated by Svelte v3.41.0 */ function create_default_slot$1(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$s(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$1] }, $$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$s($$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$s, create_fragment$s, safe_not_equal, {}); } } /* src/client/debug/mcts/Action.svelte generated by Svelte v3.41.0 */ function add_css$k(target) { append_styles(target, "svelte-1a7time", "div.svelte-1a7time{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;max-width:500px}"); } function create_fragment$t(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$t($$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(); init(this, options, instance$t, create_fragment$t, safe_not_equal, { action: 1 }, add_css$k); } } /* src/client/debug/mcts/Table.svelte generated by Svelte v3.41.0 */ function add_css$l(target) { append_styles(target, "svelte-ztcwsu", "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}"); } 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() { return /*click_handler*/ ctx[6](/*child*/ ctx[10], /*i*/ ctx[12]); } function mouseout_handler() { return /*mouseout_handler*/ ctx[7](/*i*/ ctx[12]); } function mouseover_handler() { return /*mouseover_handler*/ ctx[8](/*child*/ ctx[10], /*i*/ ctx[12]); } 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$u(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$u($$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*/ 48) { { let t = root; $$invalidate(5, 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, parents, click_handler, mouseout_handler, mouseover_handler ]; } class Table extends SvelteComponent { constructor(options) { super(); init(this, options, instance$u, create_fragment$u, safe_not_equal, { root: 4, selectedIndex: 0 }, add_css$l); } } /* src/client/debug/mcts/MCTS.svelte generated by Svelte v3.41.0 */ function add_css$m(target) { append_styles(target, "svelte-1f0amz4", ".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}"); } 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(); } else { if_block1.p(ctx, dirty); } 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$v(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$v($$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(); init(this, options, instance$v, create_fragment$v, safe_not_equal, { metadata: 4 }, add_css$m); } } /* src/client/debug/log/Log.svelte generated by Svelte v3.41.0 */ function add_css$n(target) { append_styles(target, "svelte-1pq5e4b", ".gamelog.svelte-1pq5e4b{display:grid;grid-template-columns:30px 1fr 30px;grid-auto-rows:auto;grid-auto-flow:column}"); } 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*/ 2) 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[2], 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*/ 4) logevent_changes.pinned = /*i*/ ctx[18] === /*pinned*/ ctx[2]; if (dirty & /*renderedLogEntries*/ 2) logevent_changes.action = /*action*/ ctx[19]; if (dirty & /*renderedLogEntries*/ 2) 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*/ 2) 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$w(ctx) { let div; let t0; let t1; let current; let mounted; let dispose; let each_value_2 = /*renderedLogEntries*/ ctx[1]; 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[1]; 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[1]; 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[2]); }, 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*/ 10) { each_value_2 = /*renderedLogEntries*/ ctx[1]; 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[1]; 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*/ 18) { each_value = /*renderedLogEntries*/ ctx[1]; 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*/ 4) { toggle_class(div, "pinned", /*pinned*/ ctx[2]); } }, 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$w($$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(2, pinned = null); secondaryPane.set(null); } else { $$invalidate(2, 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(2, 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*/ 1538) { { $$invalidate(9, log = $client.log); $$invalidate(1, 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, renderedLogEntries, pinned, turnBoundaries, phaseBoundaries, OnLogClick, OnMouseEnter, OnMouseLeave, OnKeyDown, log, $client ]; } class Log extends SvelteComponent { constructor(options) { super(); init(this, options, instance$w, create_fragment$w, safe_not_equal, { client: 0 }, add_css$n); } } /* src/client/debug/ai/Options.svelte generated by Svelte v3.41.0 */ function add_css$o(target) { append_styles(target, "svelte-1fu900w", "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}"); } function get_each_context$9(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[6] = list[i][0]; child_ctx[7] = list[i][1]; child_ctx[8] = list; child_ctx[9] = i; return child_ctx; } // (44:47) function create_if_block_1$5(ctx) { let input; let input_id_value; let mounted; let dispose; function input_change_handler() { /*input_change_handler*/ ctx[5].call(input, /*key*/ ctx[6]); } return { c() { input = element("input"); attr(input, "id", input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6])); attr(input, "type", "checkbox"); attr(input, "class", "svelte-1fu900w"); }, m(target, anchor) { insert(target, input, anchor); input.checked = /*values*/ ctx[1][/*key*/ ctx[6]]; 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 & /*bot*/ 1 && input_id_value !== (input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6]))) { attr(input, "id", input_id_value); } if (dirty & /*values, Object, bot*/ 3) { input.checked = /*values*/ ctx[1][/*key*/ ctx[6]]; } }, d(detaching) { if (detaching) detach(input); mounted = false; run_all(dispose); } }; } // (41:4) {#if value.range} function create_if_block$c(ctx) { let span; let t0_value = /*values*/ ctx[1][/*key*/ ctx[6]] + ""; let t0; let t1; let input; let input_id_value; let input_min_value; let input_max_value; let mounted; let dispose; function input_change_input_handler() { /*input_change_input_handler*/ ctx[4].call(input, /*key*/ ctx[6]); } return { c() { span = element("span"); t0 = text(t0_value); t1 = space(); input = element("input"); attr(span, "class", "value svelte-1fu900w"); attr(input, "id", input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6])); attr(input, "type", "range"); attr(input, "min", input_min_value = /*value*/ ctx[7].range.min); attr(input, "max", input_max_value = /*value*/ ctx[7].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[6]]); 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[6]] + "")) set_data(t0, t0_value); if (dirty & /*bot*/ 1 && input_id_value !== (input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6]))) { attr(input, "id", input_id_value); } if (dirty & /*bot*/ 1 && input_min_value !== (input_min_value = /*value*/ ctx[7].range.min)) { attr(input, "min", input_min_value); } if (dirty & /*bot*/ 1 && input_max_value !== (input_max_value = /*value*/ ctx[7].range.max)) { attr(input, "max", input_max_value); } if (dirty & /*values, Object, bot*/ 3) { set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[6]]); } }, d(detaching) { if (detaching) detach(span); if (detaching) detach(t1); if (detaching) detach(input); mounted = false; run_all(dispose); } }; } // (37:0) {#each Object.entries(bot.opts()) as [key, value]} function create_each_block$9(ctx) { let div; let label; let t0_value = /*key*/ ctx[6] + ""; let t0; let label_for_value; let t1; let t2; function select_block_type(ctx, dirty) { if (/*value*/ ctx[7].range) return create_if_block$c; if (typeof /*value*/ ctx[7].value === 'boolean') return create_if_block_1$5; } let current_block_type = select_block_type(ctx); let if_block = current_block_type && current_block_type(ctx); return { c() { div = element("div"); label = element("label"); t0 = text(t0_value); t1 = space(); if (if_block) if_block.c(); t2 = space(); attr(label, "for", label_for_value = /*makeID*/ ctx[3](/*key*/ ctx[6])); 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_block) if_block.m(div, null); append(div, t2); }, p(ctx, dirty) { if (dirty & /*bot*/ 1 && t0_value !== (t0_value = /*key*/ ctx[6] + "")) set_data(t0, t0_value); if (dirty & /*bot*/ 1 && label_for_value !== (label_for_value = /*makeID*/ ctx[3](/*key*/ ctx[6]))) { attr(label, "for", label_for_value); } if (current_block_type === (current_block_type = select_block_type(ctx)) && if_block) { if_block.p(ctx, dirty); } else { if (if_block) if_block.d(1); if_block = current_block_type && current_block_type(ctx); if (if_block) { if_block.c(); if_block.m(div, t2); } } }, d(detaching) { if (detaching) detach(div); if (if_block) { if_block.d(); } } }; } function create_fragment$x(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 & /*makeID, Object, bot, values, OnChange*/ 15) { 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$x($$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); } } const makeID = key => 'ai-option-' + key; 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, makeID, input_change_input_handler, input_change_handler ]; } class Options extends SvelteComponent { constructor(options) { super(); init(this, options, instance$x, create_fragment$x, safe_not_equal, { bot: 0 }, add_css$o); } } /* * 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.push(...this.enumerate(G, ctx, playerID)); objectives.push(this.objectives(G, ctx, playerID)); } } else { actions = this.enumerate(G, ctx, ctx.currentPlayer); objectives = 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(); setImmediate(asyncIteration); } 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.41.0 */ function add_css$p(target) { append_styles(target, "svelte-lifdi8", "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}"); } function get_each_context$a(ctx, list, i) { const child_ctx = ctx.slice(); child_ctx[7] = list[i]; return child_ctx; } // (202: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); } }; } // (200: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); } }; } // (150: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[17].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[17]), 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); } }; } // (169: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); } }; } // (175: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, "for", "ai-option-debug"); attr(label, "class", "svelte-lifdi8"); attr(input, "id", "ai-option-debug"); 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[18]), 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); } }; } // (184: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.0 && 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.0) { 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(); } }; } // (187: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); } }; } // (191: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$y(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(); } else { if_block.p(ctx, dirty); } 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$y($$self, $$props, $$invalidate) { let { client } = $$props; let { clientManager } = $$props; let { ToggleVisibility } = $$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); if ('ToggleVisibility' in $$props) $$invalidate(16, ToggleVisibility = $$props.ToggleVisibility); }; return [ client, debug, progress, iterationCounter, selectedBot, botAction, botActionArgs, bot, bots, OnDebug, ChangeBot, Step$1, Simulate, Reset, OnKeyDown, clientManager, ToggleVisibility, select_change_handler, input_change_handler ]; } class AI extends SvelteComponent { constructor(options) { super(); init( this, options, instance$y, create_fragment$y, safe_not_equal, { client: 0, clientManager: 15, ToggleVisibility: 16 }, add_css$p ); } } /* src/client/debug/Debug.svelte generated by Svelte v3.41.0 */ function add_css$q(target) { append_styles(target, "svelte-8ymctk", ".debug-panel.svelte-8ymctk.svelte-8ymctk{position:fixed;color:#555;font-family:monospace;right:0;top:0;height:100%;font-size:14px;opacity:0.9;z-index:99999}.panel.svelte-8ymctk.svelte-8ymctk{display:flex;position:relative;flex-direction:row;height:100%}.visibility-toggle.svelte-8ymctk.svelte-8ymctk{position:absolute;box-sizing:border-box;top:7px;border:1px solid #ccc;border-radius:5px;width:48px;height:48px;padding:8px;background:white;color:#555;box-shadow:0 0 5px rgba(0, 0, 0, 0.2)}.visibility-toggle.svelte-8ymctk.svelte-8ymctk:hover,.visibility-toggle.svelte-8ymctk.svelte-8ymctk:focus{background:#eee}.opener.svelte-8ymctk.svelte-8ymctk{right:10px}.closer.svelte-8ymctk.svelte-8ymctk{left:-326px}@keyframes svelte-8ymctk-rotateFromZero{from{transform:rotateZ(0deg)}to{transform:rotateZ(180deg)}}.icon.svelte-8ymctk.svelte-8ymctk{display:flex;height:100%;animation:svelte-8ymctk-rotateFromZero 0.4s cubic-bezier(0.68, -0.55, 0.27, 1.55) 0s 1\n normal forwards}.closer.svelte-8ymctk .icon.svelte-8ymctk{animation-direction:reverse}.pane.svelte-8ymctk.svelte-8ymctk{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-8ymctk.svelte-8ymctk{background:#fefefe;overflow-y:scroll}.debug-panel.svelte-8ymctk button,.debug-panel.svelte-8ymctk select{cursor:pointer;font-size:14px;font-family:monospace}.debug-panel.svelte-8ymctk select{background:#eee;border:1px solid #bbb;color:#555;padding:3px;border-radius:3px}.debug-panel.svelte-8ymctk section{margin-bottom:20px}.debug-panel.svelte-8ymctk .screen-reader-only{clip:rect(0 0 0 0);clip-path:inset(50%);height:1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px}"); } // (194:2) {:else} function create_else_block$4(ctx) { let div1; let button; let span; let chevron; let button_intro; let button_outro; let t0; let menu; let t1; let div0; let switch_instance; let t2; let div1_transition; let current; let mounted; let dispose; chevron = new FaChevronRight({}); 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], ToggleVisibility: /*ToggleVisibility*/ ctx[9] } }; } 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() { div1 = element("div"); button = element("button"); span = element("span"); create_component(chevron.$$.fragment); t0 = space(); create_component(menu.$$.fragment); t1 = space(); div0 = element("div"); if (switch_instance) create_component(switch_instance.$$.fragment); t2 = space(); if (if_block) if_block.c(); attr(span, "class", "icon svelte-8ymctk"); attr(span, "aria-hidden", "true"); attr(button, "class", "visibility-toggle closer svelte-8ymctk"); attr(button, "title", "Hide Debug Panel"); attr(div0, "class", "pane svelte-8ymctk"); attr(div0, "role", "region"); attr(div0, "aria-label", /*pane*/ ctx[2]); attr(div0, "tabindex", "-1"); attr(div1, "class", "panel svelte-8ymctk"); }, m(target, anchor) { insert(target, div1, anchor); append(div1, button); append(button, span); mount_component(chevron, span, null); append(div1, t0); mount_component(menu, div1, null); append(div1, t1); append(div1, div0); if (switch_instance) { mount_component(switch_instance, div0, null); } /*div0_binding*/ ctx[15](div0); append(div1, t2); if (if_block) if_block.m(div1, null); current = true; if (!mounted) { dispose = listen(button, "click", /*ToggleVisibility*/ ctx[9]); mounted = true; } }, p(new_ctx, dirty) { ctx = new_ctx; 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, div0, null); } else { switch_instance = null; } } else if (switch_value) { switch_instance.$set(switch_instance_changes); } if (!current || dirty & /*pane*/ 4) { attr(div0, "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(div1, 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(chevron.$$.fragment, local); add_render_callback(() => { if (button_outro) button_outro.end(1); button_intro = create_in_transition(button, /*receive*/ ctx[13], { key: 'toggle' }); button_intro.start(); }); transition_in(menu.$$.fragment, local); if (switch_instance) transition_in(switch_instance.$$.fragment, local); transition_in(if_block); add_render_callback(() => { if (!div1_transition) div1_transition = create_bidirectional_transition(div1, fly, { x: 400, .../*transitionOpts*/ ctx[11] }, true); div1_transition.run(1); }); current = true; }, o(local) { transition_out(chevron.$$.fragment, local); if (button_intro) button_intro.invalidate(); button_outro = create_out_transition(button, /*send*/ ctx[12], { key: 'toggle' }); transition_out(menu.$$.fragment, local); if (switch_instance) transition_out(switch_instance.$$.fragment, local); transition_out(if_block); if (!div1_transition) div1_transition = create_bidirectional_transition(div1, fly, { x: 400, .../*transitionOpts*/ ctx[11] }, false); div1_transition.run(0); current = false; }, d(detaching) { if (detaching) detach(div1); destroy_component(chevron); if (detaching && button_outro) button_outro.end(); destroy_component(menu); if (switch_instance) destroy_component(switch_instance); /*div0_binding*/ ctx[15](null); if (if_block) if_block.d(); if (detaching && div1_transition) div1_transition.end(); mounted = false; dispose(); } }; } // (182:2) {#if !visible} function create_if_block$e(ctx) { let button; let span; let chevron; let button_intro; let button_outro; let current; let mounted; let dispose; chevron = new FaChevronRight({}); return { c() { button = element("button"); span = element("span"); create_component(chevron.$$.fragment); attr(span, "class", "icon svelte-8ymctk"); attr(span, "aria-hidden", "true"); attr(button, "class", "visibility-toggle opener svelte-8ymctk"); attr(button, "title", "Show Debug Panel"); }, m(target, anchor) { insert(target, button, anchor); append(button, span); mount_component(chevron, span, null); current = true; if (!mounted) { dispose = listen(button, "click", /*ToggleVisibility*/ ctx[9]); mounted = true; } }, p: noop, i(local) { if (current) return; transition_in(chevron.$$.fragment, local); add_render_callback(() => { if (button_outro) button_outro.end(1); button_intro = create_in_transition(button, /*receive*/ ctx[13], { key: 'toggle' }); button_intro.start(); }); current = true; }, o(local) { transition_out(chevron.$$.fragment, local); if (button_intro) button_intro.invalidate(); button_outro = create_out_transition(button, /*send*/ ctx[12], { key: 'toggle' }); current = false; }, d(detaching) { if (detaching) detach(button); destroy_component(chevron); if (detaching && button_outro) button_outro.end(); mounted = false; dispose(); } }; } // (222:6) {#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-8ymctk"); }, 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$z(ctx) { let section; let current_block_type_index; let if_block; let current; let mounted; let dispose; const if_block_creators = [create_if_block$e, create_else_block$4]; const if_blocks = []; function select_block_type(ctx, dirty) { if (!/*visible*/ 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() { section = element("section"); if_block.c(); attr(section, "aria-label", "boardgame.io Debug Panel"); attr(section, "class", "debug-panel svelte-8ymctk"); }, m(target, anchor) { insert(target, section, anchor); if_blocks[current_block_type_index].m(section, null); current = true; if (!mounted) { dispose = listen(window, "keypress", /*Keypress*/ ctx[10]); 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(); } else { if_block.p(ctx, dirty); } 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$z($$self, $$props, $$invalidate) { let client; let $clientManager, $$unsubscribe_clientManager = noop, $$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(14, $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(); } // Toggle debugger visibilty function ToggleVisibility() { $$invalidate(3, visible = !visible); } let visible = true; function Keypress(e) { if (e.key == '.') { ToggleVisibility(); return; } // Set displayed pane if (!visible) return; Object.entries(panes).forEach(([key, { shortcut }]) => { if (e.key == shortcut) { $$invalidate(2, pane = key); } }); } const transitionOpts = { duration: 150, easing: cubicOut }; const [send, receive] = crossfade(transitionOpts); function div0_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)); }; $$self.$$.update = () => { if ($$self.$$.dirty & /*$clientManager*/ 16384) { $$invalidate(4, client = $clientManager.client); } }; return [ clientManager, paneDiv, pane, visible, client, $secondaryPane, panes, secondaryPane, MenuChange, ToggleVisibility, Keypress, transitionOpts, send, receive, $clientManager, div0_binding ]; } class Debug extends SvelteComponent { constructor(options) { super(); init(this, options, instance$z, create_fragment$z, safe_not_equal, { clientManager: 0 }, add_css$q); } } /** * 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) { const dispatchers = {}; for (const name of innerActionNames) { dispatchers[name] = (...args) => { const action = ActionCreators[storeActionType](name, args, assumedPlayerID(playerID, store, multiplayer), credentials); store.dispatch(action); }; } 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 || 'default'; 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 PATCH: 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) && action.type !== STRIP_TRANSIENTS) { this.transport.sendAction(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(TransientHandlingMiddleware, 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({ transportDataCallback: (data) => this.receiveTransportData(data), gameKey: game, game: this.game, matchID, playerID, credentials, gameName: this.game.name, numPlayers, }); this.createDispatchers(); this.chatMessages = []; this.sendChatMessage = (payload) => { this.transport.sendChatMessage(this.matchID, { id: nanoid(7), sender: this.playerID, payload: payload, }); }; } /** Handle incoming match data from a multiplayer transport. */ receiveMatchData(matchData) { this.matchData = matchData; this.notifySubscribers(); } /** Handle an incoming chat message from a multiplayer transport. */ receiveChatMessage(message) { this.chatMessages = [...this.chatMessages, message]; this.notifySubscribers(); } /** Handle all incoming updates from a multiplayer transport. */ receiveTransportData(data) { const [matchID] = data.args; if (matchID !== this.matchID) return; switch (data.type) { case 'sync': { const [, syncInfo] = data.args; const action = sync(syncInfo); this.receiveMatchData(syncInfo.filteredMetadata); this.store.dispatch(action); break; } case 'update': { const [, state, deltalog] = data.args; const currentState = this.store.getState(); if (state._stateID >= currentState._stateID) { const action = update$1(state, deltalog); this.store.dispatch(action); } break; } case 'patch': { const [, prevStateID, stateID, patch$1, deltalog] = data.args; const currentStateID = this.store.getState()._stateID; if (prevStateID !== currentStateID) break; const action = patch(prevStateID, stateID, patch$1, deltalog); this.store.dispatch(action); // Emit sync if patch apply failed. if (this.store.getState()._stateID === currentStateID) { this.transport.requestSync(); } break; } case 'matchData': { const [, matchData] = data.args; this.receiveMatchData(matchData); break; } case 'chat': { const [, chatMessage] = data.args; this.receiveChatMessage(chatMessage); break; } } } 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.subscribeToConnectionStatus(() => 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; 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({ 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; } 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$2(opts) { var _class, _temp; var game = opts.game, numPlayers = opts.numPlayers, board = opts.board, multiplayer = opts.multiplayer, enhancer = opts.enhancer; var loading = opts.loading; // Component that is displayed before the client has synced // with the game master. if (loading === undefined) { var Loading = function Loading() { return /*#__PURE__*/React.createElement(React.Fragment, null); }; 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); 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(); if (state === null) { return /*#__PURE__*/React.createElement(loading); } 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; } 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, ...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; }; /** * Creates initial state and metadata for a new match. * If the provided `setupData` doesn’t pass the game’s validation, * an error object is returned instead. */ const createMatch = ({ game, numPlayers, setupData, unlisted, }) => { if (!numPlayers || typeof numPlayers !== 'number') numPlayers = 2; const setupDataError = game.validateSetupData && game.validateSetupData(setupData, numPlayers); if (setupDataError !== undefined) return { setupDataError }; const metadata = createMetadata({ game, numPlayers, setupData, unlisted }); const initialState = InitializeGame({ game, numPlayers, setupData }); return { metadata, initialState }; }; /* * 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; }); /** * 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) { if (!credAction || !credAction.payload) { return { error: 'missing action or action payload' }; } 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 middleware = applyMiddleware(TransientHandlingMiddleware); const store = createStore(reducer, state, middleware); // 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 checks 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; } const prevState = store.getState(); // Update server's version of the store. store.dispatch(action); state = store.getState(); this.subscribeCallback({ state, action, matchID, }); if (this.game.deltaState) { this.transportAPI.sendAll({ type: 'patch', args: [matchID, stateID, prevState, state], }); } else { this.transportAPI.sendAll({ type: 'update', args: [matchID, state], }); } const { deltalog, ...stateWithoutDeltalog } = state; let newMetadata; if (metadata && (metadata.gameover === undefined || metadata.gameover === null)) { 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) { const match = createMatch({ game: this.game, unlisted: true, numPlayers, setupData: undefined, }); if ('setupDataError' in match) { return { error: 'game requires setupData' }; } initialState = state = match.initialState; metadata = match.metadata; 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 syncInfo = { state, 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, }); if (!(chatMessage && typeof chatMessage.sender === 'string')) { return { error: 'unauthorized' }; } const isAuthentic = await this.auth.authenticateCredentials({ playerID: chatMessage.sender, credentials, metadata, }); if (!isAuthentic) { return { error: 'unauthorized' }; } } this.transportAPI.sendAll({ type: 'chat', args: [matchID, chatMessage], }); } } const applyPlayerView = (game, playerID, state) => ({ ...state, G: game.playerView(state.G, state.ctx, playerID), plugins: PlayerView(state, { playerID, game }), deltalog: undefined, _undo: [], _redo: [], }); /** Gets a function that filters the TransportData for a given player and game. */ const getFilterPlayerView = (game) => (playerID, payload) => { switch (payload.type) { case 'patch': { const [matchID, stateID, prevState, state] = payload.args; const log = redactLog(state.deltalog, playerID); const filteredState = applyPlayerView(game, playerID, state); const newStateID = state._stateID; const prevFilteredState = applyPlayerView(game, playerID, prevState); const patch = createPatch(prevFilteredState, filteredState); return { type: 'patch', args: [matchID, stateID, newStateID, patch, log], }; } case 'update': { const [matchID, state] = payload.args; const log = redactLog(state.deltalog, playerID); const filteredState = applyPlayerView(game, playerID, state); return { type: 'update', args: [matchID, filteredState, log], }; } case 'sync': { const [matchID, syncInfo] = payload.args; const filteredState = applyPlayerView(game, playerID, syncInfo.state); const log = redactLog(syncInfo.log, playerID); const newSyncInfo = { ...syncInfo, state: filteredState, log, }; return { type: 'sync', args: [matchID, newSyncInfo], }; } default: { return payload; } } }; /** * 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; }); } /* * 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(filterPlayerView(playerID, data)); } }; const filterPlayerView = getFilterPlayerView(game); const transportAPI = { send, sendAll: (payload) => { for (const playerID in clientCallbacks) { send({ playerID, ...payload }); } }, }; const storage = persist ? new LocalStorage(storageKey) : new InMemory(); super(game, storage, transportAPI); this.connect = (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, ...opts }) { super(opts); this.master = master; } sendChatMessage(matchID, chatMessage) { const args = [ matchID, chatMessage, this.credentials, ]; this.master.onChatMessage(...args); } sendAction(state, action) { this.master.onUpdate(action, state._stateID, this.matchID, this.playerID); } requestSync() { this.master.onSync(this.matchID, this.playerID, this.credentials, this.numPlayers); } connect() { this.setConnectionStatus(true); this.master.connect(this.playerID, (data) => this.notifyClient(data)); this.requestSync(); } disconnect() { this.setConnectionStatus(false); } updateMatchID(id) { this.matchID = id; this.connect(); } updatePlayerID(id) { this.playerID = id; this.connect(); } updateCredentials(credentials) { this.credentials = credentials; this.connect(); } } /** * 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 Multiplayer instance. * @param {object} socket - Override for unit tests. * @param {object} socketOpts - Options to pass to socket.io. * @param {object} store - Redux store * @param {string} matchID - The game ID to connect to. * @param {string} playerID - The player ID associated with this client. * @param {string} credentials - Authentication credentials * @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, server, ...opts }) { super(opts); this.server = server; this.socket = socket; this.socketOpts = socketOpts; } sendAction(state, action) { const args = [ action, state._stateID, this.matchID, this.playerID, ]; this.socket.emit('update', ...args); } sendChatMessage(matchID, chatMessage) { const args = [ matchID, chatMessage, this.credentials, ]; this.socket.emit('chat', ...args); } 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 as a patch to other clients (including // this one). this.socket.on('patch', (matchID, prevStateID, stateID, patch, deltalog) => { this.notifyClient({ type: 'patch', args: [matchID, prevStateID, stateID, patch, deltalog], }); }); // 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) => { this.notifyClient({ type: 'update', args: [matchID, state, deltalog], }); }); // Called when the client first connects to the master // and requests the current game state. this.socket.on('sync', (matchID, syncInfo) => { this.notifyClient({ type: 'sync', args: [matchID, syncInfo] }); }); // Called when new player joins the match or changes // it's connection status this.socket.on('matchData', (matchID, matchData) => { this.notifyClient({ type: 'matchData', args: [matchID, matchData] }); }); this.socket.on('chat', (matchID, chatMessage) => { this.notifyClient({ type: 'chat', args: [matchID, chatMessage] }); }); // Keep track of connection status. this.socket.on('connect', () => { // Initial sync to get game state. this.requestSync(); this.setConnectionStatus(true); }); this.socket.on('disconnect', () => { this.setConnectionStatus(false); }); } disconnect() { this.socket.close(); this.socket = null; this.setConnectionStatus(false); } requestSync() { if (this.socket) { const args = [ this.matchID, this.playerID, this.credentials, this.numPlayers, ]; this.socket.emit('sync', ...args); } } updateMatchID(id) { this.matchID = id; this.requestSync(); } updatePlayerID(id) { this.playerID = id; this.requestSync(); } updateCredentials(credentials) { this.credentials = credentials; this.requestSync(); } } 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/material-ui/4.9.2/es/ButtonGroup/ButtonGroup.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import { isFragment } from 'react-is'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import capitalize from '../utils/capitalize'; import { fade } from '../styles/colorManipulator'; import withStyles from '../styles/withStyles'; import Button from '../Button'; // Force a side effect so we don't have any override priority issue. // eslint-disable-next-line no-unused-expressions Button.styles; export const styles = theme => ({ /* Styles applied to the root element. */ root: { display: 'inline-flex', borderRadius: theme.shape.borderRadius }, /* Styles applied to the root element if `variant="contained"`. */ contained: { boxShadow: theme.shadows[2] }, /* Pseudo-class applied to child elements if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `fullWidth={true}`. */ fullWidth: { width: '100%' }, /* Styles applied to the root element if `orientation="vertical"`. */ vertical: { flexDirection: 'column' }, /* Styles applied to the children. */ grouped: { minWidth: 40 }, /* Styles applied to the children if `orientation="horizontal"`. */ groupedHorizontal: { '&:not(:first-child)': { borderTopLeftRadius: 0, borderBottomLeftRadius: 0 }, '&:not(:last-child)': { borderTopRightRadius: 0, borderBottomRightRadius: 0 } }, /* Styles applied to the children if `orientation="vertical"`. */ groupedVertical: { '&:not(:first-child)': { borderTopRightRadius: 0, borderTopLeftRadius: 0 }, '&:not(:last-child)': { borderBottomRightRadius: 0, borderBottomLeftRadius: 0 } }, /* Styles applied to the children if `variant="text"`. */ groupedText: {}, /* Styles applied to the children if `variant="text"` and `orientation="horizontal"`. */ groupedTextHorizontal: { '&:not(:last-child)': { borderRight: `1px solid ${theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'}` } }, /* Styles applied to the children if `variant="text"` and `orientation="vertical"`. */ groupedTextVertical: { '&:not(:last-child)': { borderBottom: `1px solid ${theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'}` } }, /* Styles applied to the children if `variant="text"` and `color="primary"`. */ groupedTextPrimary: { '&:not(:last-child)': { borderColor: fade(theme.palette.primary.main, 0.5) } }, /* Styles applied to the children if `variant="text"` and `color="secondary"`. */ groupedTextSecondary: { '&:not(:last-child)': { borderColor: fade(theme.palette.secondary.main, 0.5) } }, /* Styles applied to the children if `variant="outlined"`. */ groupedOutlined: {}, /* Styles applied to the children if `variant="outlined"` and `orientation="horizontal"`. */ groupedOutlinedHorizontal: { '&:not(:first-child)': { marginLeft: -1 }, '&:not(:last-child)': { borderRightColor: 'transparent' } }, /* Styles applied to the children if `variant="outlined"` and `orientation="vertical"`. */ groupedOutlinedVertical: { '&:not(:first-child)': { marginTop: -1 }, '&:not(:last-child)': { borderBottomColor: 'transparent' } }, /* Styles applied to the children if `variant="outlined"` and `color="primary"`. */ groupedOutlinedPrimary: { '&:hover': { borderColor: theme.palette.primary.main } }, /* Styles applied to the children if `variant="outlined"` and `color="secondary"`. */ groupedOutlinedSecondary: { '&:hover': { borderColor: theme.palette.secondary.main } }, /* Styles applied to the children if `variant="contained"`. */ groupedContained: { boxShadow: 'none' }, /* Styles applied to the children if `variant="contained"` and `orientation="horizontal"`. */ groupedContainedHorizontal: { '&:not(:last-child)': { borderRight: `1px solid ${theme.palette.grey[400]}`, '&$disabled': { borderRight: `1px solid ${theme.palette.action.disabled}` } } }, /* Styles applied to the children if `variant="contained"` and `orientation="vertical"`. */ groupedContainedVertical: { '&:not(:last-child)': { borderBottom: `1px solid ${theme.palette.grey[400]}`, '&$disabled': { borderBottom: `1px solid ${theme.palette.action.disabled}` } } }, /* Styles applied to the children if `variant="contained"` and `color="primary"`. */ groupedContainedPrimary: { '&:not(:last-child)': { borderColor: theme.palette.primary.dark } }, /* Styles applied to the children if `variant="contained"` and `color="secondary"`. */ groupedContainedSecondary: { '&:not(:last-child)': { borderColor: theme.palette.secondary.dark } } }); const ButtonGroup = React.forwardRef(function ButtonGroup(props, ref) { const { children, classes, className, color = 'default', component: Component = 'div', disabled = false, disableFocusRipple = false, disableRipple = false, fullWidth = false, orientation = 'horizontal', size = 'medium', variant = 'outlined' } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "color", "component", "disabled", "disableFocusRipple", "disableRipple", "fullWidth", "orientation", "size", "variant"]); const buttonClassName = clsx(classes.grouped, classes[`grouped${capitalize(orientation)}`], classes[`grouped${capitalize(variant)}`], classes[`grouped${capitalize(variant)}${capitalize(orientation)}`], classes[`grouped${capitalize(variant)}${color !== 'default' ? capitalize(color) : ''}`], disabled && classes.disabled); return React.createElement(Component, _extends({ role: "group", className: clsx(classes.root, className, fullWidth && classes.fullWidth, { contained: classes.contained }[variant], { vertical: classes.vertical }[orientation]), ref: ref }, other), React.Children.map(children, child => { if (!React.isValidElement(child)) { return null; } if (process.env.NODE_ENV !== 'production') { if (isFragment(child)) { console.error(["Material-UI: the ButtonGroup component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n')); } } return React.cloneElement(child, { className: clsx(buttonClassName, child.props.className), disabled: child.props.disabled || disabled, color: child.props.color || color, disableFocusRipple, disableRipple, fullWidth, size: child.props.size || size, variant: child.props.variant || variant }); })); }); process.env.NODE_ENV !== "production" ? ButtonGroup.propTypes = { /** * The content of the button group. */ 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 buttons will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the button keyboard focus ripple will be disabled. * `disableRipple` must also be true. */ disableFocusRipple: PropTypes.bool, /** * If `true`, the button ripple effect will be disabled. */ disableRipple: PropTypes.bool, /** * If `true`, the buttons will take up the full width of its container. */ fullWidth: PropTypes.bool, /** * The group orientation. */ orientation: PropTypes.oneOf(['vertical', 'horizontal']), /** * The size of the button. * `small` is equivalent to the dense button styling. */ size: PropTypes.oneOf(['small', 'medium', 'large']), /** * The variant to use. */ variant: PropTypes.oneOf(['text', 'outlined', 'contained']) } : void 0; export default withStyles(styles, { name: 'MuiButtonGroup' })(ButtonGroup);
ajax/libs/react-native-web/0.14.0/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.0.0/progressbar/progressbar.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); 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 ProgressBar = /*#__PURE__*/function (_Component) { _inherits(ProgressBar, _Component); var _super = _createSuper(ProgressBar); function ProgressBar() { _classCallCheck(this, ProgressBar); return _super.apply(this, arguments); } _createClass(ProgressBar, [{ key: "renderLabel", value: function renderLabel() { if (this.props.showValue && this.props.value != null) { var label = this.props.displayValueTemplate ? this.props.displayValueTemplate(this.props.value) : this.props.value + this.props.unit; return /*#__PURE__*/React.createElement("div", { className: "p-progressbar-label" }, label); } return null; } }, { key: "renderDeterminate", value: function renderDeterminate() { var className = classNames('p-progressbar p-component p-progressbar-determinate', this.props.className); var label = this.renderLabel(); return /*#__PURE__*/React.createElement("div", { role: "progressbar", id: this.props.id, className: className, style: this.props.style, "aria-valuemin": "0", "aria-valuenow": this.props.value, "aria-valuemax": "100", "aria-label": this.props.value }, /*#__PURE__*/React.createElement("div", { className: "p-progressbar-value p-progressbar-value-animate", style: { width: this.props.value + '%', display: 'block', backgroundColor: this.props.color } }), label); } }, { key: "renderIndeterminate", value: function renderIndeterminate() { var className = classNames('p-progressbar p-component p-progressbar-indeterminate', this.props.className); return /*#__PURE__*/React.createElement("div", { role: "progressbar", id: this.props.id, className: className, style: this.props.style }, /*#__PURE__*/React.createElement("div", { className: "p-progressbar-indeterminate-container" }, /*#__PURE__*/React.createElement("div", { className: "p-progressbar-value p-progressbar-value-animate", style: { backgroundColor: this.props.color } }))); } }, { key: "render", value: function render() { if (this.props.mode === 'determinate') return this.renderDeterminate();else if (this.props.mode === 'indeterminate') return this.renderIndeterminate();else throw new Error(this.props.mode + " is not a valid mode for the ProgressBar. Valid values are 'determinate' and 'indeterminate'"); } }]); return ProgressBar; }(Component); _defineProperty(ProgressBar, "defaultProps", { id: null, value: null, showValue: true, unit: '%', style: null, className: null, mode: 'determinate', displayValueTemplate: null, color: null }); export { ProgressBar };
ajax/libs/material-ui/4.10.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.3/es/internal/svg-icons/createSvgIcon.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import SvgIcon from '../../SvgIcon'; export default function createSvgIcon(path, displayName) { const Component = React.memo(React.forwardRef((props, ref) => React.createElement(SvgIcon, _extends({}, props, { ref: ref }), path))); if (process.env.NODE_ENV !== 'production') { Component.displayName = `${displayName}Icon`; } Component.muiName = SvgIcon.muiName; return Component; }
ajax/libs/react-native-web/0.11.7/exports/TouchableOpacity/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 _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) 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 applyNativeMethods from '../../modules/applyNativeMethods'; import createReactClass from 'create-react-class'; import ensurePositiveDelayProps from '../Touchable/ensurePositiveDelayProps'; import { number } from 'prop-types'; import React from 'react'; import StyleSheet from '../StyleSheet'; import Touchable from '../Touchable'; import TouchableWithoutFeedback from '../TouchableWithoutFeedback'; import View from '../View'; var flattenStyle = StyleSheet.flatten; var PRESS_RETENTION_OFFSET = { top: 20, left: 20, right: 20, bottom: 30 }; /** * A wrapper for making views respond properly to touches. * On press down, the opacity of the wrapped view is decreased, dimming it. * * Opacity is controlled by wrapping the children in a View, which is * added to the view hiearchy. Be aware that this can affect layout. * * Example: * * ``` * renderButton: function() { * return ( * <TouchableOpacity onPress={this._onPressButton}> * <Image * style={styles.button} * source={require('./myButton.png')} * /> * </TouchableOpacity> * ); * }, * ``` */ /* eslint-disable react/prefer-es6-class */ var TouchableOpacity = createReactClass({ displayName: 'TouchableOpacity', mixins: [Touchable.Mixin], propTypes: _objectSpread({}, TouchableWithoutFeedback.propTypes, { /** * Determines what the opacity of the wrapped view should be when touch is * active. */ activeOpacity: number, focusedOpacity: number }), getDefaultProps: function getDefaultProps() { return { activeOpacity: 0.2, focusedOpacity: 0.7 }; }, getInitialState: function getInitialState() { return this.touchableGetInitialState(); }, componentDidMount: function componentDidMount() { ensurePositiveDelayProps(this.props); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { ensurePositiveDelayProps(nextProps); }, /** * Animate the touchable to a new opacity. */ setOpacityTo: function setOpacityTo(value, duration) { this.setNativeProps({ style: { opacity: value, transitionDuration: duration ? duration / 1000 + "s" : '0s' } }); }, /** * `Touchable.Mixin` self callbacks. The mixin will invoke these if they are * defined on your component. */ touchableHandleActivePressIn: function touchableHandleActivePressIn(e) { if (e.dispatchConfig.registrationName === 'onResponderGrant') { this._opacityActive(0); } else { this._opacityActive(150); } this.props.onPressIn && this.props.onPressIn(e); }, touchableHandleActivePressOut: function touchableHandleActivePressOut(e) { this._opacityInactive(250); this.props.onPressOut && this.props.onPressOut(e); }, touchableHandlePress: function touchableHandlePress(e) { this.props.onPress && this.props.onPress(e); }, touchableHandleLongPress: function touchableHandleLongPress(e) { this.props.onLongPress && this.props.onLongPress(e); }, touchableGetPressRectOffset: function touchableGetPressRectOffset() { return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET; }, touchableGetHitSlop: function touchableGetHitSlop() { return this.props.hitSlop; }, touchableGetHighlightDelayMS: function touchableGetHighlightDelayMS() { return this.props.delayPressIn || 0; }, touchableGetLongPressDelayMS: function touchableGetLongPressDelayMS() { return this.props.delayLongPress === 0 ? 0 : this.props.delayLongPress || 500; }, touchableGetPressOutDelayMS: function touchableGetPressOutDelayMS() { return this.props.delayPressOut; }, _opacityActive: function _opacityActive(duration) { this.setOpacityTo(this.props.activeOpacity, duration); }, _opacityInactive: function _opacityInactive(duration) { this.setOpacityTo(this._getChildStyleOpacityWithDefault(), duration); }, _opacityFocused: function _opacityFocused() { this.setOpacityTo(this.props.focusedOpacity); }, _getChildStyleOpacityWithDefault: function _getChildStyleOpacityWithDefault() { var childStyle = flattenStyle(this.props.style) || {}; return childStyle.opacity === undefined ? 1 : childStyle.opacity; }, render: function render() { var _this$props = this.props, activeOpacity = _this$props.activeOpacity, focusedOpacity = _this$props.focusedOpacity, delayLongPress = _this$props.delayLongPress, delayPressIn = _this$props.delayPressIn, delayPressOut = _this$props.delayPressOut, onLongPress = _this$props.onLongPress, onPress = _this$props.onPress, onPressIn = _this$props.onPressIn, onPressOut = _this$props.onPressOut, pressRetentionOffset = _this$props.pressRetentionOffset, other = _objectWithoutPropertiesLoose(_this$props, ["activeOpacity", "focusedOpacity", "delayLongPress", "delayPressIn", "delayPressOut", "onLongPress", "onPress", "onPressIn", "onPressOut", "pressRetentionOffset"]); return React.createElement(View, _extends({}, other, { accessible: this.props.accessible !== false, onKeyDown: this.touchableHandleKeyEvent, onKeyUp: this.touchableHandleKeyEvent, onResponderGrant: this.touchableHandleResponderGrant, onResponderMove: this.touchableHandleResponderMove, onResponderRelease: this.touchableHandleResponderRelease, onResponderTerminate: this.touchableHandleResponderTerminate, onResponderTerminationRequest: this.touchableHandleResponderTerminationRequest, onStartShouldSetResponder: this.touchableHandleStartShouldSetResponder, style: [styles.root, !this.props.disabled && styles.actionable, this.props.style] }), this.props.children, Touchable.renderDebugView({ color: 'blue', hitSlop: this.props.hitSlop })); } }); var styles = StyleSheet.create({ root: { transitionProperty: 'opacity', transitionDuration: '0.15s', userSelect: 'none' }, actionable: { cursor: 'pointer', touchAction: 'manipulation' } }); export default applyNativeMethods(TouchableOpacity);
ajax/libs/material-ui/4.9.11/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 _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); 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) { return function () { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (_isNativeReflectConstruct()) { 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 = { /** * 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/primereact/6.6.0-rc.1/slider/slider.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, classNames } 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 Slider = /*#__PURE__*/function (_Component) { _inherits(Slider, _Component); var _super = _createSuper(Slider); function Slider(props) { var _this; _classCallCheck(this, Slider); _this = _super.call(this, props); _this.onBarClick = _this.onBarClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.handleIndex = 0; return _this; } _createClass(Slider, [{ key: "spin", value: function spin(event, dir) { var value = (this.props.range ? this.props.value[this.handleIndex] : this.props.value) || 0; var step = (this.props.step || 1) * dir; this.updateValue(event, value + step); event.preventDefault(); } }, { key: "onDragStart", value: function onDragStart(event, index) { if (this.props.disabled) { return; } this.dragging = true; this.updateDomData(); this.sliderHandleClick = true; this.handleIndex = index; //event.preventDefault(); } }, { key: "onMouseDown", value: function onMouseDown(event, index) { this.bindDragListeners(); this.onDragStart(event, index); } }, { key: "onTouchStart", value: function onTouchStart(event, index) { this.bindTouchListeners(); this.onDragStart(event, index); } }, { key: "onKeyDown", value: function onKeyDown(event, index) { if (this.props.disabled) { return; } this.handleIndex = index; var key = event.key; if (key === 'ArrowRight' || key === 'ArrowUp') { this.spin(event, 1); } else if (key === 'ArrowLeft' || key === 'ArrowDown') { this.spin(event, -1); } } }, { key: "onBarClick", value: function onBarClick(event) { if (this.props.disabled) { return; } if (!this.sliderHandleClick) { this.updateDomData(); this.setValue(event); } this.sliderHandleClick = false; } }, { key: "onDrag", value: function onDrag(event) { if (this.dragging) { this.setValue(event); event.preventDefault(); } } }, { key: "onDragEnd", value: function onDragEnd(event) { if (this.dragging) { this.dragging = false; if (this.props.onSlideEnd) { this.props.onSlideEnd({ originalEvent: event, value: this.props.value }); } this.unbindDragListeners(); this.unbindTouchListeners(); } } }, { key: "bindDragListeners", value: function bindDragListeners() { if (!this.dragListener) { this.dragListener = this.onDrag.bind(this); document.addEventListener('mousemove', this.dragListener); } if (!this.dragEndListener) { this.dragEndListener = this.onDragEnd.bind(this); document.addEventListener('mouseup', this.dragEndListener); } } }, { key: "unbindDragListeners", value: function unbindDragListeners() { if (this.dragListener) { document.removeEventListener('mousemove', this.dragListener); this.dragListener = null; } if (this.dragEndListener) { document.removeEventListener('mouseup', this.dragEndListener); this.dragEndListener = null; } } }, { key: "bindTouchListeners", value: function bindTouchListeners() { if (!this.dragListener) { this.dragListener = this.onDrag.bind(this); document.addEventListener('touchmove', this.dragListener); } if (!this.dragEndListener) { this.dragEndListener = this.onDragEnd.bind(this); document.addEventListener('touchend', this.dragEndListener); } } }, { key: "unbindTouchListeners", value: function unbindTouchListeners() { if (this.dragListener) { document.removeEventListener('touchmove', this.dragListener); this.dragListener = null; } if (this.dragEndListener) { document.removeEventListener('touchend', this.dragEndListener); this.dragEndListener = null; } } }, { key: "updateDomData", value: function updateDomData() { var rect = this.el.getBoundingClientRect(); this.initX = rect.left + DomHandler.getWindowScrollLeft(); this.initY = rect.top + DomHandler.getWindowScrollTop(); this.barWidth = this.el.offsetWidth; this.barHeight = this.el.offsetHeight; } }, { key: "setValue", value: function setValue(event) { var handleValue; var pageX = event.touches ? event.touches[0].pageX : event.pageX; var pageY = event.touches ? event.touches[0].pageY : event.pageY; if (this.props.orientation === 'horizontal') handleValue = (pageX - this.initX) * 100 / this.barWidth;else handleValue = (this.initY + this.barHeight - pageY) * 100 / this.barHeight; var newValue = (this.props.max - this.props.min) * (handleValue / 100) + this.props.min; if (this.props.step) { var oldValue = this.props.range ? this.props.value[this.handleIndex] : this.props.value; var diff = newValue - oldValue; if (diff < 0) newValue = oldValue + Math.ceil(newValue / this.props.step - oldValue / this.props.step) * this.props.step;else if (diff > 0) newValue = oldValue + Math.floor(newValue / this.props.step - oldValue / this.props.step) * this.props.step; } else { newValue = Math.floor(newValue); } this.updateValue(event, newValue); } }, { key: "updateValue", value: function updateValue(event, value) { var newValue = parseFloat(value.toFixed(10)); if (this.props.range) { if (this.handleIndex === 0) { if (newValue < this.props.min) newValue = this.props.min;else if (newValue > this.props.value[1]) newValue = this.props.value[1]; } else { if (newValue > this.props.max) newValue = this.props.max;else if (newValue < this.props.value[0]) newValue = this.props.value[0]; } var newValues = _toConsumableArray(this.props.value); newValues[this.handleIndex] = newValue; if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: newValues }); } } else { if (newValue < this.props.min) newValue = this.props.min;else if (newValue > this.props.max) newValue = this.props.max; if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: newValue }); } } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindDragListeners(); this.unbindTouchListeners(); } }, { key: "renderHandle", value: function renderHandle(leftValue, bottomValue, index) { var _this2 = this; var handleClassName = classNames('p-slider-handle', { 'p-slider-handle-start': index === 0, 'p-slider-handle-end': index === 1, 'p-slider-handle-active': this.handleIndex === index }); return /*#__PURE__*/React.createElement("span", { onMouseDown: function onMouseDown(event) { return _this2.onMouseDown(event, index); }, onTouchStart: function onTouchStart(event) { return _this2.onTouchStart(event, index); }, onKeyDown: function onKeyDown(event) { return _this2.onKeyDown(event, index); }, tabIndex: this.props.tabIndex, className: handleClassName, style: { transition: this.dragging ? 'none' : null, left: leftValue !== null && leftValue + '%', bottom: bottomValue && bottomValue + '%' }, role: "slider", "aria-valuemin": this.props.min, "aria-valuemax": this.props.max, "aria-valuenow": leftValue || bottomValue, "aria-labelledby": this.props.ariaLabelledBy }); } }, { key: "renderRangeSlider", value: function renderRangeSlider() { var values = this.props.value || [0, 0]; var horizontal = this.props.orientation === 'horizontal'; var handleValueStart = (values[0] < this.props.min ? 0 : values[0] - this.props.min) * 100 / (this.props.max - this.props.min); var handleValueEnd = (values[1] > this.props.max ? 100 : values[1] - this.props.min) * 100 / (this.props.max - this.props.min); var rangeStartHandle = horizontal ? this.renderHandle(handleValueStart, null, 0) : this.renderHandle(null, handleValueStart, 0); var rangeEndHandle = horizontal ? this.renderHandle(handleValueEnd, null, 1) : this.renderHandle(null, handleValueEnd, 1); var rangeStyle = horizontal ? { left: handleValueStart + '%', width: handleValueEnd - handleValueStart + '%' } : { bottom: handleValueStart + '%', height: handleValueEnd - handleValueStart + '%' }; return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", { className: "p-slider-range", style: rangeStyle }), rangeStartHandle, rangeEndHandle); } }, { key: "renderSingleSlider", value: function renderSingleSlider() { var value = this.props.value || 0; var handleValue; if (value < this.props.min) handleValue = 0;else if (value > this.props.max) handleValue = 100;else handleValue = (value - this.props.min) * 100 / (this.props.max - this.props.min); var rangeStyle = this.props.orientation === 'horizontal' ? { width: handleValue + '%' } : { height: handleValue + '%' }; var handle = this.props.orientation === 'horizontal' ? this.renderHandle(handleValue, null, null) : this.renderHandle(null, handleValue, null); return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", { className: "p-slider-range", style: rangeStyle }), handle); } }, { key: "render", value: function render() { var _this3 = this; var className = classNames('p-slider p-component', this.props.className, { 'p-disabled': this.props.disabled, 'p-slider-horizontal': this.props.orientation === 'horizontal', 'p-slider-vertical': this.props.orientation === 'vertical' }); var content = this.props.range ? this.renderRangeSlider() : this.renderSingleSlider(); return /*#__PURE__*/React.createElement("div", { id: this.props.id, ref: function ref(el) { return _this3.el = el; }, style: this.props.style, className: className, onClick: this.onBarClick }, content); } }]); return Slider; }(Component); _defineProperty(Slider, "defaultProps", { id: null, value: null, min: 0, max: 100, orientation: 'horizontal', step: null, range: false, style: null, className: null, disabled: false, tabIndex: 0, ariaLabelledBy: null, onChange: null, onSlideEnd: null }); export { Slider };
ajax/libs/material-ui/4.9.2/esm/FormControl/useFormControl.js
cdnjs/cdnjs
import React from 'react'; import FormControlContext from './FormControlContext'; export default function useFormControl() { return React.useContext(FormControlContext); }
ajax/libs/primereact/6.5.0-rc.2/avatar/avatar.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames, ObjectUtils } 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); 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 Avatar = /*#__PURE__*/function (_Component) { _inherits(Avatar, _Component); var _super = _createSuper(Avatar); function Avatar() { _classCallCheck(this, Avatar); return _super.apply(this, arguments); } _createClass(Avatar, [{ key: "renderContent", value: function renderContent() { var _this = this; if (this.props.label) { return /*#__PURE__*/React.createElement("span", { className: "p-avatar-text" }, this.props.label); } else if (this.props.icon) { var iconClassName = classNames('p-avatar-icon', this.props.icon); return /*#__PURE__*/React.createElement("span", { className: iconClassName }); } else if (this.props.image) { var onError = function onError(e) { if (_this.props.onImageError) { _this.props.onImageError(e); } }; return /*#__PURE__*/React.createElement("img", { src: this.props.image, alt: this.props.imageAlt, onError: onError }); } return null; } }, { key: "render", value: function render() { var containerClassName = classNames('p-avatar p-component', { 'p-avatar-image': this.props.image != null, 'p-avatar-circle': this.props.shape === 'circle', 'p-avatar-lg': this.props.size === 'large', 'p-avatar-xl': this.props.size === 'xlarge', 'p-avatar-clickable': !!this.props.onClick }, 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, onClick: this.props.onClick }, content, this.props.children); } }]); return Avatar; }(Component); _defineProperty(Avatar, "defaultProps", { label: null, icon: null, image: null, size: 'normal', shape: 'square', style: null, className: null, template: null, imageAlt: 'avatar', onImageError: null, onClick: null }); _defineProperty(Avatar, "propTypes", { label: PropTypes.string, icon: PropTypes.string, image: PropTypes.string, size: PropTypes.string, shape: PropTypes.string, style: PropTypes.object, className: PropTypes.string, template: PropTypes.any, imageAlt: PropTypes.string, onImageError: PropTypes.func, onClick: PropTypes.func }); export { Avatar };
ajax/libs/material-ui/4.9.3/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/material-ui/4.9.4/es/FormControl/FormControl.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 { isFilled, isAdornedStart } from '../InputBase/utils'; import withStyles from '../styles/withStyles'; import capitalize from '../utils/capitalize'; import isMuiElement from '../utils/isMuiElement'; import FormControlContext from './FormControlContext'; export const styles = { /* Styles applied to the root element. */ root: { display: 'inline-flex', flexDirection: 'column', position: 'relative', // Reset fieldset default style. minWidth: 0, padding: 0, margin: 0, border: 0, zIndex: 0, // Fix blur label text issue verticalAlign: 'top' // Fix alignment issue on Safari. }, /* Styles applied to the root element if `margin="normal"`. */ marginNormal: { marginTop: 16, marginBottom: 8 }, /* Styles applied to the root element if `margin="dense"`. */ marginDense: { marginTop: 8, marginBottom: 4 }, /* Styles applied to the root element if `fullWidth={true}`. */ fullWidth: { width: '100%' } }; /** * Provides context such as filled/focused/error/required for form inputs. * Relying on the context provides high flexibility and ensures that the state always stays * consistent across the children of the `FormControl`. * This context is used by the following components: * * - FormLabel * - FormHelperText * - Input * - InputLabel * * You can find one composition example below and more going to [the demos](/components/text-fields/#components). * * ```jsx * <FormControl> * <InputLabel htmlFor="my-input">Email address</InputLabel> * <Input id="my-input" aria-describedby="my-helper-text" /> * <FormHelperText id="my-helper-text">We'll never share your email.</FormHelperText> * </FormControl> * ``` * * ⚠️Only one input can be used within a FormControl. */ const FormControl = React.forwardRef(function FormControl(props, ref) { const { children, classes, className, color = 'primary', component: Component = 'div', disabled = false, error = false, fullWidth = false, hiddenLabel = false, margin = 'none', required = false, size, variant = 'standard' } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "color", "component", "disabled", "error", "fullWidth", "hiddenLabel", "margin", "required", "size", "variant"]); const [adornedStart, setAdornedStart] = React.useState(() => { // We need to iterate through the children and find the Input in order // to fully support server-side rendering. let initialAdornedStart = false; if (children) { React.Children.forEach(children, child => { if (!isMuiElement(child, ['Input', 'Select'])) { return; } const input = isMuiElement(child, ['Select']) ? child.props.input : child; if (input && isAdornedStart(input.props)) { initialAdornedStart = true; } }); } return initialAdornedStart; }); const [filled, setFilled] = React.useState(() => { // We need to iterate through the children and find the Input in order // to fully support server-side rendering. let initialFilled = false; if (children) { React.Children.forEach(children, child => { if (!isMuiElement(child, ['Input', 'Select'])) { return; } if (isFilled(child.props, true)) { initialFilled = true; } }); } return initialFilled; }); const [focused, setFocused] = React.useState(false); if (disabled && focused) { setFocused(false); } let registerEffect; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks const registeredInput = React.useRef(false); registerEffect = () => { if (registeredInput.current) { console.error(['Material-UI: there are multiple InputBase components inside a FormControl.', 'This is not supported. It might cause infinite rendering loops.', 'Only use one InputBase.'].join('\n')); } registeredInput.current = true; return () => { registeredInput.current = false; }; }; } const onFilled = React.useCallback(() => { setFilled(true); }, []); const onEmpty = React.useCallback(() => { setFilled(false); }, []); const childContext = { adornedStart, setAdornedStart, color, disabled, error, filled, focused, fullWidth, hiddenLabel, margin: (size === 'small' ? 'dense' : undefined) || margin, onBlur: () => { setFocused(false); }, onEmpty, onFilled, onFocus: () => { setFocused(true); }, registerEffect, required, variant }; return React.createElement(FormControlContext.Provider, { value: childContext }, React.createElement(Component, _extends({ className: clsx(classes.root, className, margin !== 'none' && classes[`margin${capitalize(margin)}`], fullWidth && classes.fullWidth), ref: ref }, other), children)); }); process.env.NODE_ENV !== "production" ? FormControl.propTypes = { /** * The contents of the form control. */ 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, input and helper text 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 component will take up the full width of its container. */ fullWidth: PropTypes.bool, /** * If `true`, the label will be hidden. * This is used to increase density for a `FilledInput`. * Be sure to add `aria-label` to the `input` element. */ hiddenLabel: PropTypes.bool, /** * If `dense` or `normal`, will adjust vertical spacing of this and contained components. */ margin: PropTypes.oneOf(['none', 'dense', 'normal']), /** * If `true`, the label will indicate that the input is required. */ required: PropTypes.bool, /** * The size of the text field. */ size: PropTypes.oneOf(['small', 'medium']), /** * The variant to use. */ variant: PropTypes.oneOf(['standard', 'outlined', 'filled']) } : void 0; export default withStyles(styles, { name: 'MuiFormControl' })(FormControl);
ajax/libs/boardgame-io/0.39.16/esm/react.js
cdnjs/cdnjs
import './Debug-91f604ee.js'; import 'redux'; import { _ as _createClass, w as _classCallCheck, x as _inherits, y as _defineProperty, z as _possibleConstructorReturn, B as _getPrototypeOf, C as _assertThisInitialized, D as _toConsumableArray } from './turn-order-dce10a02.js'; import 'immer'; import './reducer-b11048c2.js'; import 'flatted'; import { M as MCTSBot } from './ai-9b435d0e.js'; import './initialize-63a95034.js'; import { C as Client$1 } from './client-ef3f3b30.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-043d62b9.js'; import './master-6720c47b.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, gameID: props.gameID, 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.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); } } 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, 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); } }, _a.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, }, _a.defaultProps = { gameID: '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. */ 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.11.4/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/primereact/7.2.1/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/react-native-web/0.0.0-e437e3f47/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.9.2/esm/TableBody/TableBody.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'; import Tablelvl2Context from '../Table/Tablelvl2Context'; export var styles = { /* Styles applied to the root element. */ root: { display: 'table-row-group' } }; var tablelvl2 = { variant: 'body' }; var TableBody = React.forwardRef(function TableBody(props, ref) { var classes = props.classes, className = props.className, _props$component = props.component, Component = _props$component === void 0 ? 'tbody' : _props$component, other = _objectWithoutProperties(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" ? TableBody.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: 'MuiTableBody' })(TableBody);
ajax/libs/material-ui/4.9.2/es/utils/useEventCallback.js
cdnjs/cdnjs
import React from 'react'; const useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect; /** * https://github.com/facebook/react/issues/14099#issuecomment-440013892 * * @param {function} fn */ export default function useEventCallback(fn) { const ref = React.useRef(fn); useEnhancedEffect(() => { ref.current = fn; }); return React.useCallback((...args) => (0, ref.current)(...args), []); }
ajax/libs/react-native-web/0.14.8/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.2.1/scrolltop/scrolltop.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, ZIndexUtils, classNames, IconUtils } from 'primereact/utils'; import { CSSTransition } from 'primereact/csstransition'; import { Ripple } from 'primereact/ripple'; 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); 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; } } var ScrollTop = /*#__PURE__*/function (_Component) { _inherits(ScrollTop, _Component); var _super = _createSuper(ScrollTop); function ScrollTop(props) { var _this; _classCallCheck(this, ScrollTop); _this = _super.call(this, props); _this.state = { visible: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this)); _this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this)); _this.onExited = _this.onExited.bind(_assertThisInitialized(_this)); _this.scrollElementRef = /*#__PURE__*/React.createRef(); return _this; } _createClass(ScrollTop, [{ key: "onClick", value: function onClick() { var scrollElement = this.props.target === 'window' ? window : this.helper.parentElement; scrollElement.scroll({ top: 0, behavior: this.props.behavior }); } }, { key: "checkVisibility", value: function checkVisibility(scrollY) { this.setState({ visible: scrollY > this.props.threshold }); } }, { key: "bindParentScrollListener", value: function bindParentScrollListener() { var _this2 = this; this.scrollListener = function () { _this2.checkVisibility(_this2.helper.parentElement.scrollTop); }; this.helper.parentElement.addEventListener('scroll', this.scrollListener); } }, { key: "bindDocumentScrollListener", value: function bindDocumentScrollListener() { var _this3 = this; this.scrollListener = function () { _this3.checkVisibility(DomHandler.getWindowScrollTop()); }; window.addEventListener('scroll', this.scrollListener); } }, { key: "unbindParentScrollListener", value: function unbindParentScrollListener() { if (this.scrollListener) { this.helper.parentElement.removeEventListener('scroll', this.scrollListener); this.scrollListener = null; } } }, { key: "unbindDocumentScrollListener", value: function unbindDocumentScrollListener() { if (this.scrollListener) { window.removeEventListener('scroll', this.scrollListener); this.scrollListener = null; } } }, { key: "onEnter", value: function onEnter() { ZIndexUtils.set('overlay', this.scrollElementRef.current, PrimeReact.autoZIndex, PrimeReact.zIndex['overlay']); } }, { key: "onEntered", value: function onEntered() { this.props.onShow && this.props.onShow(); } }, { key: "onExited", value: function onExited() { ZIndexUtils.clear(this.scrollElementRef.current); this.props.onHide && this.props.onHide(); } }, { key: "componentDidMount", value: function componentDidMount() { if (this.props.target === 'window') this.bindDocumentScrollListener();else if (this.props.target === 'parent') this.bindParentScrollListener(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.props.target === 'window') this.unbindDocumentScrollListener();else if (this.props.target === 'parent') this.unbindParentScrollListener(); ZIndexUtils.clear(this.scrollElementRef.current); } }, { key: "render", value: function render() { var _this4 = this; var className = classNames('p-scrolltop p-link p-component', { 'p-scrolltop-sticky': this.props.target !== 'window' }, this.props.className); var isTargetParent = this.props.target === 'parent'; return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.scrollElementRef, classNames: "p-scrolltop", "in": this.state.visible, timeout: { enter: 150, exit: 150 }, options: this.props.transitionOptions, unmountOnExit: true, onEnter: this.onEnter, onEntered: this.onEntered, onExited: this.onExited }, /*#__PURE__*/React.createElement("button", { ref: this.scrollElementRef, type: "button", className: className, style: this.props.style, onClick: this.onClick }, IconUtils.getJSXIcon(this.props.icon, { className: 'p-scrolltop-icon' }, { props: this.props }), /*#__PURE__*/React.createElement(Ripple, null))), isTargetParent && /*#__PURE__*/React.createElement("span", { ref: function ref(el) { return _this4.helper = el; }, className: "p-scrolltop-helper" })); } }]); return ScrollTop; }(Component); _defineProperty(ScrollTop, "defaultProps", { target: 'window', threshold: 400, icon: 'pi pi-chevron-up', behavior: 'smooth', className: null, style: null, transitionOptions: null, onShow: null, onHide: null }); export { ScrollTop };