path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
ajax/libs/react-native-web/0.16.2/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.11.6/exports/Touchable/index.js
cdnjs/cdnjs
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /* eslint-disable react/prop-types */ /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AccessibilityUtil from '../../modules/AccessibilityUtil'; import BoundingDimensions from './BoundingDimensions'; import findNodeHandle from '../findNodeHandle'; import normalizeColor from 'normalize-css-color'; import Position from './Position'; import React from 'react'; import TouchEventUtils from 'fbjs/lib/TouchEventUtils'; import UIManager from '../UIManager'; import View from '../View'; /** * `Touchable`: Taps done right. * * You hook your `ResponderEventPlugin` events into `Touchable`. `Touchable` * will measure time/geometry and tells you when to give feedback to the user. * * ====================== Touchable Tutorial =============================== * The `Touchable` mixin helps you handle the "press" interaction. It analyzes * the geometry of elements, and observes when another responder (scroll view * etc) has stolen the touch lock. It notifies your component when it should * give feedback to the user. (bouncing/highlighting/unhighlighting). * * - When a touch was activated (typically you highlight) * - When a touch was deactivated (typically you unhighlight) * - When a touch was "pressed" - a touch ended while still within the geometry * of the element, and no other element (like scroller) has "stolen" touch * lock ("responder") (Typically you bounce the element). * * A good tap interaction isn't as simple as you might think. There should be a * slight delay before showing a highlight when starting a touch. If a * subsequent touch move exceeds the boundary of the element, it should * unhighlight, but if that same touch is brought back within the boundary, it * should rehighlight again. A touch can move in and out of that boundary * several times, each time toggling highlighting, but a "press" is only * triggered if that touch ends while within the element's boundary and no * scroller (or anything else) has stolen the lock on touches. * * To create a new type of component that handles interaction using the * `Touchable` mixin, do the following: * * - Initialize the `Touchable` state. * * getInitialState: function() { * return merge(this.touchableGetInitialState(), yourComponentState); * } * * - Choose the rendered component who's touches should start the interactive * sequence. On that rendered node, forward all `Touchable` responder * handlers. You can choose any rendered node you like. Choose a node whose * hit target you'd like to instigate the interaction sequence: * * // In render function: * return ( * <View * onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder} * onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest} * onResponderGrant={this.touchableHandleResponderGrant} * onResponderMove={this.touchableHandleResponderMove} * onResponderRelease={this.touchableHandleResponderRelease} * onResponderTerminate={this.touchableHandleResponderTerminate}> * <View> * Even though the hit detection/interactions are triggered by the * wrapping (typically larger) node, we usually end up implementing * custom logic that highlights this inner one. * </View> * </View> * ); * * - You may set up your own handlers for each of these events, so long as you * also invoke the `touchable*` handlers inside of your custom handler. * * - Implement the handlers on your component class in order to provide * feedback to the user. See documentation for each of these class methods * that you should implement. * * touchableHandlePress: function() { * this.performBounceAnimation(); // or whatever you want to do. * }, * touchableHandleActivePressIn: function() { * this.beginHighlighting(...); // Whatever you like to convey activation * }, * touchableHandleActivePressOut: function() { * this.endHighlighting(...); // Whatever you like to convey deactivation * }, * * - There are more advanced methods you can implement (see documentation below): * touchableGetHighlightDelayMS: function() { * return 20; * } * // In practice, *always* use a predeclared constant (conserve memory). * touchableGetPressRectOffset: function() { * return {top: 20, left: 20, right: 20, bottom: 100}; * } */ /** * Touchable states. */ var States = { NOT_RESPONDER: 'NOT_RESPONDER', // Not the responder RESPONDER_INACTIVE_PRESS_IN: 'RESPONDER_INACTIVE_PRESS_IN', // Responder, inactive, in the `PressRect` RESPONDER_INACTIVE_PRESS_OUT: 'RESPONDER_INACTIVE_PRESS_OUT', // Responder, inactive, out of `PressRect` RESPONDER_ACTIVE_PRESS_IN: 'RESPONDER_ACTIVE_PRESS_IN', // Responder, active, in the `PressRect` RESPONDER_ACTIVE_PRESS_OUT: 'RESPONDER_ACTIVE_PRESS_OUT', // Responder, active, out of `PressRect` RESPONDER_ACTIVE_LONG_PRESS_IN: 'RESPONDER_ACTIVE_LONG_PRESS_IN', // Responder, active, in the `PressRect`, after long press threshold RESPONDER_ACTIVE_LONG_PRESS_OUT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT', // Responder, active, out of `PressRect`, after long press threshold ERROR: 'ERROR' }; /** * Quick lookup map for states that are considered to be "active" */ var IsActive = { RESPONDER_ACTIVE_PRESS_OUT: true, RESPONDER_ACTIVE_PRESS_IN: true }; /** * Quick lookup for states that are considered to be "pressing" and are * therefore eligible to result in a "selection" if the press stops. */ var IsPressingIn = { RESPONDER_INACTIVE_PRESS_IN: true, RESPONDER_ACTIVE_PRESS_IN: true, RESPONDER_ACTIVE_LONG_PRESS_IN: true }; var IsLongPressingIn = { RESPONDER_ACTIVE_LONG_PRESS_IN: true }; /** * Inputs to the state machine. */ var Signals = { DELAY: 'DELAY', RESPONDER_GRANT: 'RESPONDER_GRANT', RESPONDER_RELEASE: 'RESPONDER_RELEASE', RESPONDER_TERMINATED: 'RESPONDER_TERMINATED', ENTER_PRESS_RECT: 'ENTER_PRESS_RECT', LEAVE_PRESS_RECT: 'LEAVE_PRESS_RECT', LONG_PRESS_DETECTED: 'LONG_PRESS_DETECTED' }; /** * Mapping from States x Signals => States */ var Transitions = { NOT_RESPONDER: { DELAY: States.ERROR, RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN, RESPONDER_RELEASE: States.ERROR, RESPONDER_TERMINATED: States.ERROR, ENTER_PRESS_RECT: States.ERROR, LEAVE_PRESS_RECT: States.ERROR, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_INACTIVE_PRESS_IN: { DELAY: States.RESPONDER_ACTIVE_PRESS_IN, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_INACTIVE_PRESS_OUT: { DELAY: States.RESPONDER_ACTIVE_PRESS_OUT, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_ACTIVE_PRESS_IN: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN }, RESPONDER_ACTIVE_PRESS_OUT: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_ACTIVE_LONG_PRESS_IN: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT, LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN }, RESPONDER_ACTIVE_LONG_PRESS_OUT: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, error: { DELAY: States.NOT_RESPONDER, RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.NOT_RESPONDER, LEAVE_PRESS_RECT: States.NOT_RESPONDER, LONG_PRESS_DETECTED: States.NOT_RESPONDER } }; // ==== Typical Constants for integrating into UI components ==== // var HIT_EXPAND_PX = 20; // var HIT_VERT_OFFSET_PX = 10; var HIGHLIGHT_DELAY_MS = 130; var PRESS_EXPAND_PX = 20; var LONG_PRESS_THRESHOLD = 500; var LONG_PRESS_DELAY_MS = LONG_PRESS_THRESHOLD - HIGHLIGHT_DELAY_MS; var LONG_PRESS_ALLOWED_MOVEMENT = 10; // Default amount "active" region protrudes beyond box /** * By convention, methods prefixed with underscores are meant to be @private, * and not @protected. Mixers shouldn't access them - not even to provide them * as callback handlers. * * * ========== Geometry ========= * `Touchable` only assumes that there exists a `HitRect` node. The `PressRect` * is an abstract box that is extended beyond the `HitRect`. * * +--------------------------+ * | | - "Start" events in `HitRect` cause `HitRect` * | +--------------------+ | to become the responder. * | | +--------------+ | | - `HitRect` is typically expanded around * | | | | | | the `VisualRect`, but shifted downward. * | | | VisualRect | | | - After pressing down, after some delay, * | | | | | | and before letting up, the Visual React * | | +--------------+ | | will become "active". This makes it eligible * | | HitRect | | for being highlighted (so long as the * | +--------------------+ | press remains in the `PressRect`). * | PressRect o | * +----------------------|---+ * Out Region | * +-----+ This gap between the `HitRect` and * `PressRect` allows a touch to move far away * from the original hit rect, and remain * highlighted, and eligible for a "Press". * Customize this via * `touchableGetPressRectOffset()`. * * * * ======= State Machine ======= * * +-------------+ <---+ RESPONDER_RELEASE * |NOT_RESPONDER| * +-------------+ <---+ RESPONDER_TERMINATED * + * | RESPONDER_GRANT (HitRect) * v * +---------------------------+ DELAY +-------------------------+ T + DELAY +------------------------------+ * |RESPONDER_INACTIVE_PRESS_IN|+-------->|RESPONDER_ACTIVE_PRESS_IN| +------------> |RESPONDER_ACTIVE_LONG_PRESS_IN| * +---------------------------+ +-------------------------+ +------------------------------+ * + ^ + ^ + ^ * |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ * |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT * | | | | | | * v + v + v + * +----------------------------+ DELAY +--------------------------+ +-------------------------------+ * |RESPONDER_INACTIVE_PRESS_OUT|+------->|RESPONDER_ACTIVE_PRESS_OUT| |RESPONDER_ACTIVE_LONG_PRESS_OUT| * +----------------------------+ +--------------------------+ +-------------------------------+ * * T + DELAY => LONG_PRESS_DELAY_MS + DELAY * * Not drawn are the side effects of each transition. The most important side * effect is the `touchableHandlePress` abstract method invocation that occurs * when a responder is released while in either of the "Press" states. * * The other important side effects are the highlight abstract method * invocations (internal callbacks) to be implemented by the mixer. * * * @lends Touchable.prototype */ var TouchableMixin = { // HACK (part 1): basic support for touchable interactions using a keyboard componentDidMount: function componentDidMount() { var _this = this; this._touchableNode = findNodeHandle(this); if (this._touchableNode && this._touchableNode.addEventListener) { this._touchableBlurListener = function (e) { if (_this._isTouchableKeyboardActive) { if (_this.state.touchable.touchState && _this.state.touchable.touchState !== States.NOT_RESPONDER) { _this.touchableHandleResponderTerminate({ nativeEvent: e }); } _this._isTouchableKeyboardActive = false; } }; this._touchableNode.addEventListener('blur', this._touchableBlurListener); } }, /** * Clear all timeouts on unmount */ componentWillUnmount: function componentWillUnmount() { if (this._touchableNode && this._touchableNode.addEventListener) { this._touchableNode.removeEventListener('blur', this._touchableBlurListener); } this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout); this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout); this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout); }, /** * It's prefer that mixins determine state in this way, having the class * explicitly mix the state in the one and only `getInitialState` method. * * @return {object} State object to be placed inside of * `this.state.touchable`. */ touchableGetInitialState: function touchableGetInitialState() { return { touchable: { touchState: undefined, responderID: null } }; }, // ==== Hooks to Gesture Responder system ==== /** * Must return true if embedded in a native platform scroll view. */ touchableHandleResponderTerminationRequest: function touchableHandleResponderTerminationRequest() { return !this.props.rejectResponderTermination; }, /** * Must return true to start the process of `Touchable`. */ touchableHandleStartShouldSetResponder: function touchableHandleStartShouldSetResponder() { return !this.props.disabled; }, /** * Return true to cancel press on long press. */ touchableLongPressCancelsPress: function touchableLongPressCancelsPress() { return true; }, /** * Place as callback for a DOM element's `onResponderGrant` event. */ touchableHandleResponderGrant: function touchableHandleResponderGrant(e) { var dispatchID = e.currentTarget; // Since e is used in a callback invoked on another event loop // (as in setTimeout etc), we need to call e.persist() on the // event to make sure it doesn't get reused in the event object pool. e.persist(); this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout); this.pressOutDelayTimeout = null; this.state.touchable.touchState = States.NOT_RESPONDER; this.state.touchable.responderID = dispatchID; this._receiveSignal(Signals.RESPONDER_GRANT, e); var delayMS = this.touchableGetHighlightDelayMS !== undefined ? Math.max(this.touchableGetHighlightDelayMS(), 0) : HIGHLIGHT_DELAY_MS; delayMS = isNaN(delayMS) ? HIGHLIGHT_DELAY_MS : delayMS; if (delayMS !== 0) { this.touchableDelayTimeout = setTimeout(this._handleDelay.bind(this, e), delayMS); } else { this.state.touchable.positionOnActivate = null; this._handleDelay(e); } var longDelayMS = this.touchableGetLongPressDelayMS !== undefined ? Math.max(this.touchableGetLongPressDelayMS(), 10) : LONG_PRESS_DELAY_MS; longDelayMS = isNaN(longDelayMS) ? LONG_PRESS_DELAY_MS : longDelayMS; this.longPressDelayTimeout = setTimeout(this._handleLongDelay.bind(this, e), longDelayMS + delayMS); }, /** * Place as callback for a DOM element's `onResponderRelease` event. */ touchableHandleResponderRelease: function touchableHandleResponderRelease(e) { this._receiveSignal(Signals.RESPONDER_RELEASE, e); }, /** * Place as callback for a DOM element's `onResponderTerminate` event. */ touchableHandleResponderTerminate: function touchableHandleResponderTerminate(e) { this._receiveSignal(Signals.RESPONDER_TERMINATED, e); }, /** * Place as callback for a DOM element's `onResponderMove` event. */ touchableHandleResponderMove: function touchableHandleResponderMove(e) { // Not enough time elapsed yet, wait for highlight - // this is just a perf optimization. if (this.state.touchable.touchState === States.RESPONDER_INACTIVE_PRESS_IN) { return; } // Measurement may not have returned yet. if (!this.state.touchable.positionOnActivate) { return; } var positionOnActivate = this.state.touchable.positionOnActivate; var dimensionsOnActivate = this.state.touchable.dimensionsOnActivate; var pressRectOffset = this.touchableGetPressRectOffset ? this.touchableGetPressRectOffset() : { left: PRESS_EXPAND_PX, right: PRESS_EXPAND_PX, top: PRESS_EXPAND_PX, bottom: PRESS_EXPAND_PX }; var pressExpandLeft = pressRectOffset.left; var pressExpandTop = pressRectOffset.top; var pressExpandRight = pressRectOffset.right; var pressExpandBottom = pressRectOffset.bottom; var hitSlop = this.touchableGetHitSlop ? this.touchableGetHitSlop() : null; if (hitSlop) { pressExpandLeft += hitSlop.left; pressExpandTop += hitSlop.top; pressExpandRight += hitSlop.right; pressExpandBottom += hitSlop.bottom; } var touch = TouchEventUtils.extractSingleTouch(e.nativeEvent); var pageX = touch && touch.pageX; var pageY = touch && touch.pageY; if (this.pressInLocation) { var movedDistance = this._getDistanceBetweenPoints(pageX, pageY, this.pressInLocation.pageX, this.pressInLocation.pageY); if (movedDistance > LONG_PRESS_ALLOWED_MOVEMENT) { this._cancelLongPressDelayTimeout(); } } var isTouchWithinActive = pageX > positionOnActivate.left - pressExpandLeft && pageY > positionOnActivate.top - pressExpandTop && pageX < positionOnActivate.left + dimensionsOnActivate.width + pressExpandRight && pageY < positionOnActivate.top + dimensionsOnActivate.height + pressExpandBottom; if (isTouchWithinActive) { this._receiveSignal(Signals.ENTER_PRESS_RECT, e); var curState = this.state.touchable.touchState; if (curState === States.RESPONDER_INACTIVE_PRESS_IN) { // fix for t7967420 this._cancelLongPressDelayTimeout(); } } else { this._cancelLongPressDelayTimeout(); this._receiveSignal(Signals.LEAVE_PRESS_RECT, e); } }, // ==== Abstract Application Callbacks ==== /** * Invoked when the item should be highlighted. Mixers should implement this * to visually distinguish the `VisualRect` so that the user knows that * releasing a touch will result in a "selection" (analog to click). * * @abstract * touchableHandleActivePressIn: function, */ /** * Invoked when the item is "active" (in that it is still eligible to become * a "select") but the touch has left the `PressRect`. Usually the mixer will * want to unhighlight the `VisualRect`. If the user (while pressing) moves * back into the `PressRect` `touchableHandleActivePressIn` will be invoked * again and the mixer should probably highlight the `VisualRect` again. This * event will not fire on an `touchEnd/mouseUp` event, only move events while * the user is depressing the mouse/touch. * * @abstract * touchableHandleActivePressOut: function */ /** * Invoked when the item is "selected" - meaning the interaction ended by * letting up while the item was either in the state * `RESPONDER_ACTIVE_PRESS_IN` or `RESPONDER_INACTIVE_PRESS_IN`. * * @abstract * touchableHandlePress: function */ /** * Invoked when the item is long pressed - meaning the interaction ended by * letting up while the item was in `RESPONDER_ACTIVE_LONG_PRESS_IN`. If * `touchableHandleLongPress` is *not* provided, `touchableHandlePress` will * be called as it normally is. If `touchableHandleLongPress` is provided, by * default any `touchableHandlePress` callback will not be invoked. To * override this default behavior, override `touchableLongPressCancelsPress` * to return false. As a result, `touchableHandlePress` will be called when * lifting up, even if `touchableHandleLongPress` has also been called. * * @abstract * touchableHandleLongPress: function */ /** * Returns the number of millis to wait before triggering a highlight. * * @abstract * touchableGetHighlightDelayMS: function */ /** * Returns the amount to extend the `HitRect` into the `PressRect`. Positive * numbers mean the size expands outwards. * * @abstract * touchableGetPressRectOffset: function */ // ==== Internal Logic ==== /** * Measures the `HitRect` node on activation. The Bounding rectangle is with * respect to viewport - not page, so adding the `pageXOffset/pageYOffset` * should result in points that are in the same coordinate system as an * event's `globalX/globalY` data values. * * - Consider caching this for the lifetime of the component, or possibly * being able to share this cache between any `ScrollMap` view. * * @sideeffects * @private */ _remeasureMetricsOnActivation: function _remeasureMetricsOnActivation() { var tag = this.state.touchable.responderID; if (tag == null) { return; } UIManager.measure(tag, this._handleQueryLayout); }, _handleQueryLayout: function _handleQueryLayout(x, y, width, height, globalX, globalY) { // don't do anything if UIManager failed to measure node if (!x && !y && !width && !height && !globalX && !globalY) { return; } this.state.touchable.positionOnActivate && Position.release(this.state.touchable.positionOnActivate); this.state.touchable.dimensionsOnActivate && // $FlowFixMe BoundingDimensions.release(this.state.touchable.dimensionsOnActivate); this.state.touchable.positionOnActivate = Position.getPooled(globalX, globalY); // $FlowFixMe this.state.touchable.dimensionsOnActivate = BoundingDimensions.getPooled(width, height); }, _handleDelay: function _handleDelay(e) { this.touchableDelayTimeout = null; this._receiveSignal(Signals.DELAY, e); }, _handleLongDelay: function _handleLongDelay(e) { this.longPressDelayTimeout = null; var curState = this.state.touchable.touchState; if (curState !== States.RESPONDER_ACTIVE_PRESS_IN && curState !== States.RESPONDER_ACTIVE_LONG_PRESS_IN) { console.error('Attempted to transition from state `' + curState + '` to `' + States.RESPONDER_ACTIVE_LONG_PRESS_IN + '`, which is not supported. This is ' + 'most likely due to `Touchable.longPressDelayTimeout` not being cancelled.'); } else { this._receiveSignal(Signals.LONG_PRESS_DETECTED, e); } }, /** * Receives a state machine signal, performs side effects of the transition * and stores the new state. Validates the transition as well. * * @param {Signals} signal State machine signal. * @throws Error if invalid state transition or unrecognized signal. * @sideeffects */ _receiveSignal: function _receiveSignal(signal, e) { var responderID = this.state.touchable.responderID; var curState = this.state.touchable.touchState; var nextState = Transitions[curState] && Transitions[curState][signal]; if (!responderID && signal === Signals.RESPONDER_RELEASE) { return; } if (!nextState) { throw new Error('Unrecognized signal `' + signal + '` or state `' + curState + '` for Touchable responder `' + responderID + '`'); } if (nextState === States.ERROR) { throw new Error('Touchable cannot transition from `' + curState + '` to `' + signal + '` for responder `' + responderID + '`'); } if (curState !== nextState) { this._performSideEffectsForTransition(curState, nextState, signal, e); this.state.touchable.touchState = nextState; } }, _cancelLongPressDelayTimeout: function _cancelLongPressDelayTimeout() { this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout); this.longPressDelayTimeout = null; }, _isHighlight: function _isHighlight(state) { return state === States.RESPONDER_ACTIVE_PRESS_IN || state === States.RESPONDER_ACTIVE_LONG_PRESS_IN; }, _savePressInLocation: function _savePressInLocation(e) { var touch = TouchEventUtils.extractSingleTouch(e.nativeEvent); var pageX = touch && touch.pageX; var pageY = touch && touch.pageY; this.pressInLocation = { pageX: pageX, pageY: pageY, get locationX() { return touch && touch.locationX; }, get locationY() { return touch && touch.locationY; } }; }, _getDistanceBetweenPoints: function _getDistanceBetweenPoints(aX, aY, bX, bY) { var deltaX = aX - bX; var deltaY = aY - bY; return Math.sqrt(deltaX * deltaX + deltaY * deltaY); }, /** * Will perform a transition between touchable states, and identify any * highlighting or unhighlighting that must be performed for this particular * transition. * * @param {States} curState Current Touchable state. * @param {States} nextState Next Touchable state. * @param {Signal} signal Signal that triggered the transition. * @param {Event} e Native event. * @sideeffects */ _performSideEffectsForTransition: function _performSideEffectsForTransition(curState, nextState, signal, e) { var curIsHighlight = this._isHighlight(curState); var newIsHighlight = this._isHighlight(nextState); var isFinalSignal = signal === Signals.RESPONDER_TERMINATED || signal === Signals.RESPONDER_RELEASE; if (isFinalSignal) { this._cancelLongPressDelayTimeout(); } if (!IsActive[curState] && IsActive[nextState]) { this._remeasureMetricsOnActivation(); } if (IsPressingIn[curState] && signal === Signals.LONG_PRESS_DETECTED) { this.touchableHandleLongPress && this.touchableHandleLongPress(e); } if (newIsHighlight && !curIsHighlight) { this._startHighlight(e); } else if (!newIsHighlight && curIsHighlight) { this._endHighlight(e); } if (IsPressingIn[curState] && signal === Signals.RESPONDER_RELEASE) { var hasLongPressHandler = !!this.props.onLongPress; var pressIsLongButStillCallOnPress = IsLongPressingIn[curState] && ( // We *are* long pressing.. !hasLongPressHandler || // But either has no long handler !this.touchableLongPressCancelsPress()); // or we're told to ignore it. var shouldInvokePress = !IsLongPressingIn[curState] || pressIsLongButStillCallOnPress; if (shouldInvokePress && this.touchableHandlePress) { if (!newIsHighlight && !curIsHighlight) { // we never highlighted because of delay, but we should highlight now this._startHighlight(e); this._endHighlight(e); } this.touchableHandlePress(e); } } this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout); this.touchableDelayTimeout = null; }, _startHighlight: function _startHighlight(e) { this._savePressInLocation(e); this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e); }, _endHighlight: function _endHighlight(e) { var _this2 = this; if (this.touchableHandleActivePressOut) { if (this.touchableGetPressOutDelayMS && this.touchableGetPressOutDelayMS()) { this.pressOutDelayTimeout = setTimeout(function () { _this2.touchableHandleActivePressOut(e); }, this.touchableGetPressOutDelayMS()); } else { this.touchableHandleActivePressOut(e); } } }, // HACK (part 2): basic support for touchable interactions using a keyboard (including // delays and longPress) touchableHandleKeyEvent: function touchableHandleKeyEvent(e) { var ENTER = 13; var SPACE = 32; var type = e.type, which = e.which; if (which === ENTER || which === SPACE) { if (type === 'keydown') { if (!this._isTouchableKeyboardActive) { if (!this.state.touchable.touchState || this.state.touchable.touchState === States.NOT_RESPONDER) { this.touchableHandleResponderGrant(e); this._isTouchableKeyboardActive = true; } } } else if (type === 'keyup') { if (this._isTouchableKeyboardActive) { if (this.state.touchable.touchState && this.state.touchable.touchState !== States.NOT_RESPONDER) { this.touchableHandleResponderRelease(e); this._isTouchableKeyboardActive = false; } } } e.stopPropagation(); // prevent the default behaviour unless the Touchable functions as a link // and Enter is pressed if (!(which === ENTER && AccessibilityUtil.propsToAriaRole(this.props) === 'link')) { e.preventDefault(); } } } }; var Touchable = { Mixin: TouchableMixin, TOUCH_TARGET_DEBUG: false, // Highlights all touchable targets. Toggle with Inspector. /** * Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android). */ renderDebugView: function renderDebugView(_ref) { var color = _ref.color, hitSlop = _ref.hitSlop; if (process.env.NODE_ENV !== 'production') { if (!Touchable.TOUCH_TARGET_DEBUG) { return null; } var debugHitSlopStyle = {}; hitSlop = hitSlop || { top: 0, bottom: 0, left: 0, right: 0 }; for (var key in hitSlop) { debugHitSlopStyle[key] = -hitSlop[key]; } var hexColor = '#' + ('00000000' + normalizeColor(color).toString(16)).substr(-8); return React.createElement(View, { pointerEvents: "none", style: _objectSpread({ position: 'absolute', borderColor: hexColor.slice(0, -2) + '55', // More opaque borderWidth: 1, borderStyle: 'dashed', backgroundColor: hexColor.slice(0, -2) + '0F' }, debugHitSlopStyle) }); } } }; export default Touchable;
ajax/libs/react-native-web/0.13.1/exports/createElement/index.js
cdnjs/cdnjs
/** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AccessibilityUtil from '../../modules/AccessibilityUtil'; import createDOMProps from '../../modules/createDOMProps'; import React from 'react'; var createElement = function createElement(component, props) { // Use equivalent platform elements where possible. var accessibilityComponent; if (component && component.constructor === String) { accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props); } var Component = accessibilityComponent || component; var domProps = createDOMProps(Component, props); for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } return React.createElement.apply(React, [Component, domProps].concat(children)); }; export default createElement;
ajax/libs/primereact/7.2.1/csstransition/csstransition.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { CSSTransition as CSSTransition$1 } from 'react-transition-group'; import PrimeReact from 'primereact/api'; import { ObjectUtils } from 'primereact/utils'; 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); 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 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 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: "disabled", get: function get() { return this.props.disabled || this.props.options && this.props.options.disabled || !PrimeReact.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: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props["in"] !== prevProps["in"] && this.disabled) { // no animation var node = ObjectUtils.getRefElement(this.props.nodeRef); if (this.props["in"]) { this.onEnter(node, true); this.onEntering(node, true); this.onEntered(node, true); } else { this.onExit(node); this.onExiting(node); this.onExited(node); } } } }, { key: "render", value: function render() { if (this.disabled) { return this.props["in"] ? this.props.children : null; } else { 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/react-native-web/0.0.0-c60417ab3/exports/AppRegistry/renderApplication.js
cdnjs/cdnjs
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AppContainer from './AppContainer'; import invariant from 'fbjs/lib/invariant'; import render, { hydrate } from '../render'; import styleResolver from '../StyleSheet/styleResolver'; import React from 'react'; export default function renderApplication(RootComponent, WrapperComponent, callback, options) { var shouldHydrate = options.hydrate, initialProps = options.initialProps, rootTag = options.rootTag; var renderFn = shouldHydrate ? hydrate : render; invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag); renderFn(React.createElement(AppContainer, { rootTag: rootTag, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)), rootTag, callback); } export function getApplication(RootComponent, initialProps, WrapperComponent) { var element = React.createElement(AppContainer, { rootTag: {}, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)); // Don't escape CSS text var getStyleElement = function getStyleElement(props) { var sheet = styleResolver.getStyleSheet(); return React.createElement("style", _extends({}, props, { dangerouslySetInnerHTML: { __html: sheet.textContent }, id: sheet.id })); }; return { element: element, getStyleElement: getStyleElement }; }
ajax/libs/primereact/7.0.0/datatable/datatable.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { Paginator } from 'primereact/paginator'; import { classNames, ObjectUtils, DomHandler, ZIndexUtils, ConnectedOverlayScrollHandler, UniqueComponentId } from 'primereact/utils'; import PrimeReact, { localeOption, FilterOperator, FilterMatchMode as FilterMatchMode$1, FilterService } from 'primereact/api'; import { OverlayService } from 'primereact/overlayservice'; import { Ripple } from 'primereact/ripple'; import { CSSTransition } from 'primereact/csstransition'; import { Portal } from 'primereact/portal'; import { InputText } from 'primereact/inputtext'; import { Dropdown } from 'primereact/dropdown'; import { Button } from 'primereact/button'; import { VirtualScroller } from 'primereact/virtualscroller'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _createSuper$c(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$c(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$c() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var RowRadioButton = /*#__PURE__*/function (_Component) { _inherits(RowRadioButton, _Component); var _super = _createSuper$c(RowRadioButton); function RowRadioButton(props) { var _this; _classCallCheck(this, RowRadioButton); _this = _super.call(this, props); _this.state = { focused: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onChange = _this.onChange.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(RowRadioButton, [{ key: "onClick", value: function onClick(event) { if (!this.props.disabled) { this.props.onChange({ originalEvent: event, data: this.props.value }); this.input.focus(); } } }, { key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onChange", value: function onChange(event) { this.onClick(event); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.code === 'Space') { this.onClick(event); event.preventDefault(); } } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-radiobutton-box p-component', { 'p-highlight': this.props.checked, 'p-focus': this.state.focused, 'p-disabled': this.props.disabled }); var name = "".concat(this.props.tableSelector, "_dt_radio"); return /*#__PURE__*/React.createElement("div", { className: "p-radiobutton p-component" }, /*#__PURE__*/React.createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React.createElement("input", { name: name, ref: function ref(el) { return _this2.input = el; }, type: "radio", checked: this.props.checked, onFocus: this.onFocus, onBlur: this.onBlur, onChange: this.onChange, onKeyDown: this.onKeyDown })), /*#__PURE__*/React.createElement("div", { className: className, onClick: this.onClick, role: "radio", "aria-checked": this.props.checked }, /*#__PURE__*/React.createElement("div", { className: "p-radiobutton-icon" }))); } }]); return RowRadioButton; }(Component); function _createSuper$b(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$b(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$b() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var RowCheckbox = /*#__PURE__*/function (_Component) { _inherits(RowCheckbox, _Component); var _super = _createSuper$b(RowCheckbox); function RowCheckbox(props) { var _this; _classCallCheck(this, RowCheckbox); _this = _super.call(this, props); _this.state = { focused: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(RowCheckbox, [{ key: "onClick", value: function onClick(event) { if (!this.props.disabled) { this.setState({ focused: true }); this.props.onChange({ originalEvent: event, data: this.props.value }); } } }, { key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.code === 'Space') { this.onClick(event); event.preventDefault(); } } }, { key: "render", value: function render() { var className = classNames('p-checkbox-box p-component', { 'p-highlight': this.props.checked, 'p-disabled': this.props.disabled, 'p-focus': this.state.focused }); var iconClassName = classNames('p-checkbox-icon', { 'pi pi-check': this.props.checked }); var tabIndex = this.props.disabled ? null : '0'; return /*#__PURE__*/React.createElement("div", { className: "p-checkbox p-component", onClick: this.onClick }, /*#__PURE__*/React.createElement("div", { className: className, role: "checkbox", "aria-checked": this.props.checked, tabIndex: tabIndex, onKeyDown: this.onKeyDown, onFocus: this.onFocus, onBlur: this.onBlur }, /*#__PURE__*/React.createElement("span", { className: iconClassName }))); } }]); return RowCheckbox; }(Component); function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$7(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$a(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$a(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$a() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var BodyCell = /*#__PURE__*/function (_Component) { _inherits(BodyCell, _Component); var _super = _createSuper$a(BodyCell); function BodyCell(props) { var _this; _classCallCheck(this, BodyCell); _this = _super.call(this, props); _this.state = { editing: props.editing, editingRowData: props.rowData, styleObject: {} }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this)); _this.onMouseUp = _this.onMouseUp.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onEditorFocus = _this.onEditorFocus.bind(_assertThisInitialized(_this)); _this.onRowToggle = _this.onRowToggle.bind(_assertThisInitialized(_this)); _this.onRowEditSave = _this.onRowEditSave.bind(_assertThisInitialized(_this)); _this.onRowEditCancel = _this.onRowEditCancel.bind(_assertThisInitialized(_this)); _this.onRowEditInit = _this.onRowEditInit.bind(_assertThisInitialized(_this)); _this.editorCallback = _this.editorCallback.bind(_assertThisInitialized(_this)); return _this; } _createClass(BodyCell, [{ key: "field", get: function get() { return this.getColumnProp('field') || "field_".concat(this.props.index); } }, { key: "isEditable", value: function isEditable() { return this.getColumnProp('editor'); } }, { key: "isSelected", value: function isSelected() { return this.props.selection ? this.props.selection instanceof Array ? this.findIndex(this.props.selection) > -1 : this.equals(this.props.selection) : false; } }, { key: "equalsData", value: function equalsData(data) { return this.props.compareSelectionBy === 'equals' ? data === this.props.rowData : ObjectUtils.equals(data, this.props.rowData, this.props.dataKey); } }, { key: "equals", value: function equals(selectedCell) { return (selectedCell.rowIndex === this.props.rowIndex || this.equalsData(selectedCell.rowData)) && (selectedCell.field === this.field || selectedCell.cellIndex === this.props.index); } }, { key: "isOutsideClicked", value: function isOutsideClicked(target) { return this.el && !(this.el.isSameNode(target) || this.el.contains(target)); } }, { key: "getColumnProp", value: function getColumnProp(prop) { return this.props.column ? this.props.column.props[prop] : null; } }, { key: "getVirtualScrollerOption", value: function getVirtualScrollerOption(option) { return this.props.virtualScrollerOptions ? this.props.virtualScrollerOptions[option] : null; } }, { key: "getStyle", value: function getStyle() { var bodyStyle = this.getColumnProp('bodyStyle'); var columnStyle = this.getColumnProp('style'); return this.getColumnProp('frozen') ? Object.assign({}, columnStyle, bodyStyle, this.state.styleObject) : Object.assign({}, columnStyle, bodyStyle); } }, { key: "getCellCallbackParams", value: function getCellCallbackParams(event) { return { originalEvent: event, value: this.resolveFieldData(), field: this.field, rowData: this.props.rowData, rowIndex: this.props.rowIndex, cellIndex: this.props.index, selected: this.isSelected(), column: this.props.column, props: this.props }; } }, { key: "resolveFieldData", value: function resolveFieldData(data) { return ObjectUtils.resolveFieldData(data || this.props.rowData, this.field); } }, { key: "getEditingRowData", value: function getEditingRowData() { return this.props.editingMeta && this.props.editingMeta[this.props.rowIndex] ? this.props.editingMeta[this.props.rowIndex].data : this.props.rowData; } }, { key: "getTabIndex", value: function getTabIndex(cellSelected) { return this.props.allowCellSelection ? cellSelected ? 0 : this.props.rowIndex === 0 && this.props.index === 0 ? this.props.tabIndex : -1 : null; } }, { key: "findIndex", value: function findIndex(collection) { var _this2 = this; return (collection || []).findIndex(function (data) { return _this2.equals(data); }); } }, { key: "closeCell", value: function closeCell(event) { var _this3 = this; var params = this.getCellCallbackParams(event); var onBeforeCellEditHide = this.getColumnProp('onBeforeCellEditHide'); if (onBeforeCellEditHide) { onBeforeCellEditHide(params); } /* When using the 'tab' key, the focus event of the next cell is not called in IE. */ setTimeout(function () { _this3.setState({ editing: false }, function () { _this3.unbindDocumentEditListener(); OverlayService.off('overlay-click', _this3.overlayEventListener); _this3.overlayEventListener = null; }); }, 1); } }, { key: "switchCellToViewMode", value: function switchCellToViewMode(event, submit) { var callbackParams = this.getCellCallbackParams(event); var newRowData = this.state.editingRowData; var newValue = this.resolveFieldData(newRowData); var params = _objectSpread$7(_objectSpread$7({}, callbackParams), {}, { newRowData: newRowData, newValue: newValue }); var onCellEditCancel = this.getColumnProp('onCellEditCancel'); var cellEditValidator = this.getColumnProp('cellEditValidator'); var onCellEditComplete = this.getColumnProp('onCellEditComplete'); if (!submit && onCellEditCancel) { onCellEditCancel(params); } var valid = true; if (cellEditValidator) { valid = cellEditValidator(params); } if (valid) { if (submit && onCellEditComplete) { onCellEditComplete(params); } this.closeCell(event); } else { event.preventDefault(); } } }, { key: "findNextSelectableCell", value: function findNextSelectableCell(cell) { var nextCell = cell.nextElementSibling; return nextCell ? DomHandler.hasClass(nextCell, 'p-selectable-cell') ? nextCell : this.findNextSelectableRow(nextCell) : null; } }, { key: "findPrevSelectableCell", value: function findPrevSelectableCell(cell) { var prevCell = cell.previousElementSibling; return prevCell ? DomHandler.hasClass(prevCell, 'p-selectable-cell') ? prevCell : this.findPrevSelectableRow(prevCell) : null; } }, { key: "findNextSelectableRow", value: function findNextSelectableRow(row) { var nextRow = row.nextElementSibling; return nextRow ? DomHandler.hasClass(nextRow, 'p-selectable-row') ? nextRow : this.findNextSelectableRow(nextRow) : null; } }, { key: "findPrevSelectableRow", value: function findPrevSelectableRow(row) { var prevRow = row.previousElementSibling; if (prevRow) { return DomHandler.hasClass(prevRow, 'p-selectable-row') ? prevRow : this.findPrevSelectableRow(prevRow); } return null; } }, { key: "changeTabIndex", value: function changeTabIndex(currentCell, nextCell) { if (currentCell && nextCell) { currentCell.tabIndex = -1; nextCell.tabIndex = this.props.tabIndex; } } }, { key: "focusOnElement", value: function focusOnElement() { var _this4 = this; clearTimeout(this.tabindexTimeout); this.tabindexTimeout = setTimeout(function () { if (_this4.state.editing) { var focusableEl = DomHandler.getFirstFocusableElement(_this4.el, ':not(.p-cell-editor-key-helper)'); focusableEl && focusableEl.focus(); } _this4.keyHelper && (_this4.keyHelper.tabIndex = _this4.state.editing ? -1 : 0); }, 1); } }, { key: "updateStickyPosition", value: function updateStickyPosition() { if (this.getColumnProp('frozen')) { var styleObject = _objectSpread$7({}, this.state.styleObject); var align = this.getColumnProp('alignFrozen'); if (align === 'right') { var right = 0; var next = this.el.nextElementSibling; if (next) { right = DomHandler.getOuterWidth(next) + parseFloat(next.style.right || 0); } styleObject['right'] = right + 'px'; } else { var left = 0; var prev = this.el.previousElementSibling; if (prev) { left = DomHandler.getOuterWidth(prev) + parseFloat(prev.style.left || 0); } styleObject['left'] = left + 'px'; } var isSameStyle = this.state.styleObject['left'] === styleObject['left'] && this.state.styleObject['right'] === styleObject['right']; !isSameStyle && this.setState({ styleObject: styleObject }); } } }, { key: "editorCallback", value: function editorCallback(val) { var editingRowData = _objectSpread$7({}, this.state.editingRowData); editingRowData[this.field] = val; this.setState({ editingRowData: editingRowData }); // update editing meta for complete methods on row mode this.props.editingMeta[this.props.rowIndex].data[this.field] = val; } }, { key: "onClick", value: function onClick(event) { var _this5 = this; var params = this.getCellCallbackParams(event); if (this.props.editMode !== 'row' && this.isEditable() && !this.state.editing && (this.props.selectOnEdit || !this.props.selectOnEdit && this.props.selected)) { this.selfClick = true; var onBeforeCellEditShow = this.getColumnProp('onBeforeCellEditShow'); var onCellEditInit = this.getColumnProp('onCellEditInit'); var cellEditValidatorEvent = this.getColumnProp('cellEditValidatorEvent'); if (onBeforeCellEditShow) { onBeforeCellEditShow(params); } // If the data is sorted using sort icon, it has been added to wait for the sort operation when any cell is wanted to be opened. setTimeout(function () { _this5.setState({ editing: true }, function () { if (onCellEditInit) { onCellEditInit(params); } if (cellEditValidatorEvent === 'click') { _this5.bindDocumentEditListener(); _this5.overlayEventListener = function (e) { if (!_this5.isOutsideClicked(e.target)) { _this5.selfClick = true; } }; OverlayService.on('overlay-click', _this5.overlayEventListener); } }); }, 1); } if (this.props.allowCellSelection && this.props.onClick) { this.props.onClick(params); } } }, { key: "onMouseDown", value: function onMouseDown(event) { var params = this.getCellCallbackParams(event); if (this.props.onMouseDown) { this.props.onMouseDown(params); } } }, { key: "onMouseUp", value: function onMouseUp(event) { var params = this.getCellCallbackParams(event); if (this.props.onMouseUp) { this.props.onMouseUp(params); } } }, { key: "onKeyDown", value: function onKeyDown(event) { if (this.props.editMode !== 'row') { if (event.which === 13 || event.which === 9) { // tab || enter this.switchCellToViewMode(event, true); } if (event.which === 27) { // escape this.switchCellToViewMode(event, false); } } if (this.props.allowCellSelection) { var target = event.target, cell = event.currentTarget; switch (event.which) { //left arrow case 37: var prevCell = this.findPrevSelectableCell(cell); if (prevCell) { this.changeTabIndex(cell, prevCell); prevCell.focus(); } event.preventDefault(); break; //right arrow case 39: var nextCell = this.findNextSelectableCell(cell); if (nextCell) { this.changeTabIndex(cell, nextCell); nextCell.focus(); } event.preventDefault(); break; //up arrow case 38: var prevRow = this.findPrevSelectableRow(cell.parentElement); if (prevRow) { var upCell = prevRow.children[this.props.index]; this.changeTabIndex(cell, upCell); upCell.focus(); } event.preventDefault(); break; //down arrow case 40: var nextRow = this.findNextSelectableRow(cell.parentElement); if (nextRow) { var downCell = nextRow.children[this.props.index]; this.changeTabIndex(cell, downCell); downCell.focus(); } event.preventDefault(); break; //enter case 13: // @deprecated if (!DomHandler.isClickable(target)) { this.onClick(event); event.preventDefault(); } break; //space case 32: if (!DomHandler.isClickable(target) && !target.readOnly) { this.onClick(event); event.preventDefault(); } break; } } } }, { key: "onBlur", value: function onBlur(event) { this.selfClick = false; if (this.props.editMode !== 'row' && this.state.editing && this.getColumnProp('cellEditValidatorEvent') === 'blur') { this.switchCellToViewMode(event, true); } } }, { key: "onEditorFocus", value: function onEditorFocus(event) { this.onClick(event); } }, { key: "onRowToggle", value: function onRowToggle(event) { this.props.onRowToggle({ originalEvent: event, data: this.props.rowData }); event.preventDefault(); } }, { key: "onRowEditInit", value: function onRowEditInit(event) { this.props.onRowEditInit({ originalEvent: event, data: this.props.rowData, newData: this.getEditingRowData(), field: this.field, index: this.props.rowIndex }); } }, { key: "onRowEditSave", value: function onRowEditSave(event) { this.props.onRowEditSave({ originalEvent: event, data: this.props.rowData, newData: this.getEditingRowData(), field: this.field, index: this.props.rowIndex }); } }, { key: "onRowEditCancel", value: function onRowEditCancel(event) { this.props.onRowEditCancel({ originalEvent: event, data: this.props.rowData, newData: this.getEditingRowData(), field: this.field, index: this.props.rowIndex }); } }, { key: "bindDocumentEditListener", value: function bindDocumentEditListener() { var _this6 = this; if (!this.documentEditListener) { this.documentEditListener = function (e) { if (!_this6.selfClick && _this6.isOutsideClicked(e.target)) { _this6.switchCellToViewMode(e, true); } _this6.selfClick = false; }; document.addEventListener('click', this.documentEditListener, true); } } }, { key: "unbindDocumentEditListener", value: function unbindDocumentEditListener() { if (this.documentEditListener) { document.removeEventListener('click', this.documentEditListener, true); this.documentEditListener = null; this.selfClick = false; } } }, { key: "componentDidMount", value: function componentDidMount() { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } if (this.props.editMode === 'cell' || this.props.editMode === 'row') { this.focusOnElement(); if (prevProps.editingMeta !== this.props.editingMeta) { this.setState({ editingRowData: this.getEditingRowData() }); } if (prevState.editing !== this.state.editing) { var callbackParams = this.getCellCallbackParams(); var params = _objectSpread$7(_objectSpread$7({}, callbackParams), {}, { editing: this.state.editing }); this.props.onEditingMetaChange(params); } } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindDocumentEditListener(); if (this.overlayEventListener) { OverlayService.off('overlay-click', this.overlayEventListener); this.overlayEventListener = null; } } }, { key: "renderLoading", value: function renderLoading() { var options = this.getVirtualScrollerOption('getLoaderOptions')(this.props.rowIndex, { cellIndex: this.props.index, cellFirst: this.props.index === 0, cellLast: this.props.index === this.getVirtualScrollerOption('columns').length - 1, cellEven: this.props.index % 2 === 0, cellOdd: this.props.index % 2 !== 0, column: this.props.column, field: this.field }); var content = ObjectUtils.getJSXElement(this.getVirtualScrollerOption('loadingTemplate'), options); return /*#__PURE__*/React.createElement("td", null, content); } }, { key: "renderElement", value: function renderElement() { var _this7 = this; var content, editorKeyHelper; var cellSelected = this.props.allowCellSelection && this.isSelected(); var isRowEditor = this.props.editMode === 'row'; var tabIndex = this.getTabIndex(cellSelected); var selectionMode = this.getColumnProp('selectionMode'); var rowReorder = this.getColumnProp('rowReorder'); var expander = this.getColumnProp('expander'); var rowEditor = this.getColumnProp('rowEditor'); var header = this.getColumnProp('header'); var body = this.getColumnProp('body'); var editor = this.getColumnProp('editor'); var frozen = this.getColumnProp('frozen'); var value = this.resolveFieldData(); var cellClassName = ObjectUtils.getPropValue(this.props.cellClassName, value, { props: this.props.tableProps, rowData: this.props.rowData }); var className = classNames(this.getColumnProp('bodyClassName'), this.getColumnProp('class'), cellClassName, { 'p-selection-column': selectionMode !== null, 'p-editable-column': editor, 'p-cell-editing': editor && this.state.editing, 'p-frozen-column': frozen, 'p-selectable-cell': this.props.allowCellSelection, 'p-highlight': cellSelected }); var style = this.getStyle(); var title = this.props.responsiveLayout === 'stack' && /*#__PURE__*/React.createElement("span", { className: "p-column-title" }, ObjectUtils.getJSXElement(header, { props: this.props.tableProps })); if (body && !this.state.editing) { content = body ? ObjectUtils.getJSXElement(body, this.props.rowData, { column: this.props.column, field: this.field, rowIndex: this.props.rowIndex, frozenRow: this.props.frozenRow, props: this.props.tableProps }) : value; } else if (editor && this.state.editing) { content = ObjectUtils.getJSXElement(editor, { rowData: this.state.editingRowData, value: this.resolveFieldData(this.state.editingRowData), column: this.props.column, field: this.field, rowIndex: this.props.rowIndex, frozenRow: this.props.frozenRow, props: this.props.tableProps, editorCallback: this.editorCallback }); } else if (selectionMode) { var showSelection = this.props.showSelectionElement ? this.props.showSelectionElement(this.props.rowData, { rowIndex: this.props.rowIndex, props: this.props.tableProps }) : true; content = showSelection && /*#__PURE__*/React.createElement(React.Fragment, null, selectionMode === 'single' && /*#__PURE__*/React.createElement(RowRadioButton, { value: this.props.rowData, checked: this.props.selected, onChange: this.props.onRadioChange, tabIndex: this.props.tabIndex, tableSelector: this.props.tableSelector }), selectionMode === 'multiple' && /*#__PURE__*/React.createElement(RowCheckbox, { value: this.props.rowData, checked: this.props.selected, onChange: this.props.onCheckboxChange, tabIndex: this.props.tabIndex })); } else if (rowReorder) { var showReorder = this.props.showRowReorderElement ? this.props.showRowReorderElement(this.props.rowData, { rowIndex: this.props.rowIndex, props: this.props.tableProps }) : true; content = showReorder && /*#__PURE__*/React.createElement("i", { className: classNames('p-datatable-reorderablerow-handle', this.getColumnProp('rowReorderIcon')) }); } else if (expander) { var iconClassName = classNames('p-row-toggler-icon', this.props.expanded ? this.props.expandedRowIcon : this.props.collapsedRowIcon); var ariaControls = "".concat(this.props.tableSelector, "_content_").concat(this.props.rowIndex, "_expanded"); var expanderProps = { onClick: this.onRowToggle, className: 'p-row-toggler p-link', iconClassName: iconClassName }; content = /*#__PURE__*/React.createElement("button", { className: expanderProps.className, onClick: expanderProps.onClick, type: "button", "aria-expanded": this.props.expanded, "aria-controls": ariaControls, tabIndex: this.props.tabIndex }, /*#__PURE__*/React.createElement("span", { className: expanderProps.iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (body) { expanderProps['element'] = content; content = ObjectUtils.getJSXElement(body, this.props.rowData, { column: this.props.column, field: this.field, rowIndex: this.props.rowIndex, frozenRow: this.props.frozenRow, props: this.props.tableProps, expander: expanderProps }); } } else if (isRowEditor && rowEditor) { var rowEditorProps = {}; if (this.state.editing) { rowEditorProps = { editing: true, onSaveClick: this.onRowEditSave, saveClassName: 'p-row-editor-save p-link', saveIconClassName: 'p-row-editor-save-icon pi pi-fw pi-check', onCancelClick: this.onRowEditCancel, cancelClassName: 'p-row-editor-cancel p-link', cancelIconClassName: 'p-row-editor-cancel-icon pi pi-fw pi-times' }; content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("button", { type: "button", onClick: rowEditorProps.onSaveClick, className: rowEditorProps.saveClassName, tabIndex: this.props.tabIndex }, /*#__PURE__*/React.createElement("span", { className: rowEditorProps.saveIconClassName }), /*#__PURE__*/React.createElement(Ripple, null)), /*#__PURE__*/React.createElement("button", { type: "button", onClick: rowEditorProps.onCancelClick, className: rowEditorProps.cancelClassName, tabIndex: this.props.tabIndex }, /*#__PURE__*/React.createElement("span", { className: rowEditorProps.cancelIconClassName }), /*#__PURE__*/React.createElement(Ripple, null))); } else { rowEditorProps = { editing: false, onInitClick: this.onRowEditInit, initClassName: 'p-row-editor-init p-link', initIconClassName: 'p-row-editor-init-icon pi pi-fw pi-pencil' }; content = /*#__PURE__*/React.createElement("button", { type: "button", onClick: rowEditorProps.onInitClick, className: rowEditorProps.initClassName, tabIndex: this.props.tabIndex }, /*#__PURE__*/React.createElement("span", { className: rowEditorProps.initIconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); } if (body) { rowEditorProps['element'] = content; content = ObjectUtils.getJSXElement(body, this.props.rowData, { column: this.props.column, field: this.field, rowIndex: this.props.rowIndex, frozenRow: this.props.frozenRow, props: this.props.tableProps, rowEditor: rowEditorProps }); } } else { content = value; } if (!isRowEditor && editor) { /* eslint-disable */ editorKeyHelper = /*#__PURE__*/React.createElement("a", { tabIndex: "0", ref: function ref(el) { return _this7.keyHelper = el; }, className: "p-cell-editor-key-helper p-hidden-accessible", onFocus: this.onEditorFocus }, /*#__PURE__*/React.createElement("span", null)); /* eslint-enable */ } return /*#__PURE__*/React.createElement("td", { ref: function ref(el) { return _this7.el = el; }, style: style, className: className, rowSpan: this.props.rowSpan, tabIndex: tabIndex, role: "cell", onClick: this.onClick, onKeyDown: this.onKeyDown, onBlur: this.onBlur, onMouseDown: this.onMouseDown, onMouseUp: this.onMouseUp }, editorKeyHelper, title, content); } }, { key: "render", value: function render() { return this.getVirtualScrollerOption('loading') ? this.renderLoading() : this.renderElement(); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { if (nextProps.editMode === 'row' && nextProps.editing !== prevState.editing) { return { editing: nextProps.editing }; } return null; } }]); return BodyCell; }(Component); function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$6(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$9(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$9(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$9() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var BodyRow = /*#__PURE__*/function (_Component) { _inherits(BodyRow, _Component); var _super = _createSuper$9(BodyRow); function BodyRow(props) { var _this; _classCallCheck(this, BodyRow); _this = _super.call(this, props); if (!_this.props.onRowEditChange) { _this.state = { editing: false }; } _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onDoubleClick = _this.onDoubleClick.bind(_assertThisInitialized(_this)); _this.onRightClick = _this.onRightClick.bind(_assertThisInitialized(_this)); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this)); _this.onMouseUp = _this.onMouseUp.bind(_assertThisInitialized(_this)); _this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this)); _this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this)); _this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_this)); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); _this.onEditInit = _this.onEditInit.bind(_assertThisInitialized(_this)); _this.onEditSave = _this.onEditSave.bind(_assertThisInitialized(_this)); _this.onEditCancel = _this.onEditCancel.bind(_assertThisInitialized(_this)); return _this; } _createClass(BodyRow, [{ key: "isFocusable", value: function isFocusable() { return this.props.selectionMode && this.props.selectionModeInColumn !== 'single' && this.props.selectionModeInColumn !== 'multiple'; } }, { key: "isGrouped", value: function isGrouped(column) { if (this.props.groupRowsBy && this.getColumnProp(column, 'field')) { if (Array.isArray(this.props.groupRowsBy)) return this.props.groupRowsBy.indexOf(column.props.field) > -1;else return this.props.groupRowsBy === column.props.field; } return false; } }, { key: "equals", value: function equals(data1, data2) { return this.props.compareSelectionBy === 'equals' ? data1 === data2 : ObjectUtils.equals(data1, data2, this.props.dataKey); } }, { key: "getColumnProp", value: function getColumnProp(col, prop) { return col ? col.props[prop] : null; } }, { key: "getEditing", value: function getEditing() { return this.props.onRowEditChange ? this.props.editing : this.state.editing; } }, { key: "getTabIndex", value: function getTabIndex() { return this.isFocusable() && !this.props.allowCellSelection ? this.props.index === 0 ? this.props.tabIndex : -1 : null; } }, { key: "findIndex", value: function findIndex(collection, rowData) { var _this2 = this; return (collection || []).findIndex(function (data) { return _this2.equals(rowData, data); }); } }, { key: "changeTabIndex", value: function changeTabIndex(currentRow, nextRow) { if (currentRow && nextRow) { currentRow.tabIndex = -1; nextRow.tabIndex = this.props.tabIndex; } } }, { key: "findNextSelectableRow", value: function findNextSelectableRow(row) { var nextRow = row.nextElementSibling; return nextRow ? DomHandler.hasClass(nextRow, 'p-selectable-row') ? nextRow : this.findNextSelectableRow(nextRow) : null; } }, { key: "findPrevSelectableRow", value: function findPrevSelectableRow(row) { var prevRow = row.previousElementSibling; return prevRow ? DomHandler.hasClass(prevRow, 'p-selectable-row') ? prevRow : this.findPrevSelectableRow(prevRow) : null; } }, { key: "shouldRenderBodyCell", value: function shouldRenderBodyCell(value, column, i) { if (this.getColumnProp(column, 'hidden')) { return false; } else if (this.props.rowGroupMode && this.props.rowGroupMode === 'rowspan' && this.isGrouped(column)) { var prevRowData = value[i - 1]; if (prevRowData) { var currentRowFieldData = ObjectUtils.resolveFieldData(value[i], this.getColumnProp(column, 'field')); var previousRowFieldData = ObjectUtils.resolveFieldData(prevRowData, this.getColumnProp(column, 'field')); return currentRowFieldData !== previousRowFieldData; } } return true; } }, { key: "calculateRowGroupSize", value: function calculateRowGroupSize(value, column, index) { if (this.isGrouped(column)) { var currentRowFieldData = ObjectUtils.resolveFieldData(value[index], this.getColumnProp(column, 'field')); var nextRowFieldData = currentRowFieldData; var groupRowSpan = 0; while (currentRowFieldData === nextRowFieldData) { groupRowSpan++; var nextRowData = value[++index]; if (nextRowData) { nextRowFieldData = ObjectUtils.resolveFieldData(nextRowData, this.getColumnProp(column, 'field')); } else { break; } } return groupRowSpan === 1 ? null : groupRowSpan; } else { return null; } } }, { key: "onClick", value: function onClick(event) { this.props.onRowClick({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDoubleClick", value: function onDoubleClick(event) { this.props.onRowDoubleClick({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onRightClick", value: function onRightClick(event) { this.props.onRowRightClick({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onTouchEnd", value: function onTouchEnd(event) { this.props.onRowTouchEnd(event); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (this.isFocusable() && !this.props.allowCellSelection) { var target = event.target, row = event.currentTarget; switch (event.which) { //down arrow case 40: var nextRow = this.findNextSelectableRow(row); if (nextRow) { this.changeTabIndex(row, nextRow); nextRow.focus(); } event.preventDefault(); break; //up arrow case 38: var prevRow = this.findPrevSelectableRow(row); if (prevRow) { this.changeTabIndex(row, prevRow); prevRow.focus(); } event.preventDefault(); break; //enter case 13: // @deprecated if (!DomHandler.isClickable(target)) { this.onClick(event); event.preventDefault(); } break; //space case 32: if (!DomHandler.isClickable(target) && !target.readOnly) { this.onClick(event); event.preventDefault(); } break; } } } }, { key: "onMouseDown", value: function onMouseDown(event) { this.props.onRowMouseDown({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onMouseUp", value: function onMouseUp(event) { this.props.onRowMouseUp({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDragStart", value: function onDragStart(event) { this.props.onRowDragStart({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDragOver", value: function onDragOver(event) { this.props.onRowDragOver({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDragLeave", value: function onDragLeave(event) { this.props.onRowDragLeave({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDragEnd", value: function onDragEnd(event) { this.props.onRowDragEnd({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onDrop", value: function onDrop(event) { this.props.onRowDrop({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } }, { key: "onEditChange", value: function onEditChange(e, editing) { if (this.props.onRowEditChange) { var editingRows; var dataKey = this.props.dataKey; var originalEvent = e.originalEvent, data = e.data, index = e.index; if (dataKey) { var dataKeyValue = String(ObjectUtils.resolveFieldData(data, dataKey)); editingRows = this.props.editingRows ? _objectSpread$6({}, this.props.editingRows) : {}; if (editingRows[dataKeyValue] != null) delete editingRows[dataKeyValue];else editingRows[dataKeyValue] = true; } else { var editingRowIndex = this.findIndex(this.props.editingRows, data); editingRows = this.props.editingRows ? _toConsumableArray(this.props.editingRows) : []; if (editingRowIndex !== -1) editingRows = editingRows.filter(function (val, i) { return i !== editingRowIndex; });else editingRows.push(data); } this.props.onRowEditChange({ originalEvent: originalEvent, data: editingRows, index: index }); } else { this.setState({ editing: editing }); } } }, { key: "onEditInit", value: function onEditInit(e) { var event = e.originalEvent; if (this.props.onRowEditInit) { this.props.onRowEditInit({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } this.onEditChange(e, true); event.preventDefault(); } }, { key: "onEditSave", value: function onEditSave(e) { var event = e.originalEvent; var valid = this.props.rowEditValidator ? this.props.rowEditValidator(this.props.rowData, { props: this.props.tableProps }) : true; if (this.props.onRowEditSave) { this.props.onRowEditSave({ originalEvent: event, data: this.props.rowData, index: this.props.index, valid: valid }); } if (valid) { if (this.props.onRowEditComplete) { this.props.onRowEditComplete(e); } this.onEditChange(e, false); } event.preventDefault(); } }, { key: "onEditCancel", value: function onEditCancel(e) { var event = e.originalEvent; if (this.props.onRowEditCancel) { this.props.onRowEditCancel({ originalEvent: event, data: this.props.rowData, index: this.props.index }); } this.onEditChange(e, false); event.preventDefault(); } }, { key: "renderContent", value: function renderContent() { var _this3 = this; return this.props.columns.map(function (col, i) { if (_this3.shouldRenderBodyCell(_this3.props.value, col, _this3.props.index)) { var key = "".concat(_this3.getColumnProp(col, 'columnKey') || _this3.getColumnProp(col, 'field'), "_").concat(i); var rowSpan = _this3.props.rowGroupMode === 'rowspan' ? _this3.calculateRowGroupSize(_this3.props.value, col, _this3.props.index) : null; var editing = _this3.getEditing(); return /*#__PURE__*/React.createElement(BodyCell, { key: key, value: _this3.props.value, tableProps: _this3.props.tableProps, tableSelector: _this3.props.tableSelector, column: col, rowData: _this3.props.rowData, rowIndex: _this3.props.index, index: i, rowSpan: rowSpan, dataKey: _this3.props.dataKey, editing: editing, editingMeta: _this3.props.editingMeta, editMode: _this3.props.editMode, onRowEditInit: _this3.onEditInit, onRowEditSave: _this3.onEditSave, onRowEditCancel: _this3.onEditCancel, onEditingMetaChange: _this3.props.onEditingMetaChange, onRowToggle: _this3.props.onRowToggle, selection: _this3.props.selection, allowCellSelection: _this3.props.allowCellSelection, compareSelectionBy: _this3.props.compareSelectionBy, selectOnEdit: _this3.props.selectOnEdit, selected: _this3.props.selected, onClick: _this3.props.onCellClick, onMouseDown: _this3.props.onCellMouseDown, onMouseUp: _this3.props.onCellMouseUp, tabIndex: _this3.props.tabIndex, cellClassName: _this3.props.cellClassName, responsiveLayout: _this3.props.responsiveLayout, frozenRow: _this3.props.frozenRow, showSelectionElement: _this3.props.showSelectionElement, showRowReorderElement: _this3.props.showRowReorderElement, onRadioChange: _this3.props.onRadioChange, onCheckboxChange: _this3.props.onCheckboxChange, expanded: _this3.props.expanded, expandedRowIcon: _this3.props.expandedRowIcon, collapsedRowIcon: _this3.props.collapsedRowIcon, virtualScrollerOptions: _this3.props.virtualScrollerOptions }); } return null; }); } }, { key: "render", value: function render() { var _this4 = this; var rowClassName = ObjectUtils.getPropValue(this.props.rowClassName, this.props.rowData, { props: this.props.tableProps }); var className = classNames(rowClassName, { 'p-highlight': !this.props.allowCellSelection && this.props.selected, 'p-highlight-contextmenu': this.props.contextMenuSelected, 'p-selectable-row': this.props.allowRowSelection, 'p-row-odd': this.props.index % 2 !== 0 }); var content = this.renderContent(); var tabIndex = this.getTabIndex(); return /*#__PURE__*/React.createElement("tr", { ref: function ref(el) { return _this4.el = el; }, role: "row", tabIndex: tabIndex, className: className, onMouseDown: this.onMouseDown, onMouseUp: this.onMouseUp, onClick: this.onClick, onDoubleClick: this.onDoubleClick, onContextMenu: this.onRightClick, onTouchEnd: this.onTouchEnd, onKeyDown: this.onKeyDown, onDragStart: this.onDragStart, onDragOver: this.onDragOver, onDragLeave: this.onDragLeave, onDragEnd: this.onDragEnd, onDrop: this.onDrop }, content); } }]); return BodyRow; }(Component); function _createSuper$8(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$8(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$8() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var RowTogglerButton = /*#__PURE__*/function (_Component) { _inherits(RowTogglerButton, _Component); var _super = _createSuper$8(RowTogglerButton); function RowTogglerButton(props) { var _this; _classCallCheck(this, RowTogglerButton); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); return _this; } _createClass(RowTogglerButton, [{ key: "onClick", value: function onClick(event) { this.props.onClick({ originalEvent: event, data: this.props.rowData }); } }, { key: "render", value: function render() { var iconClassName = classNames('p-row-toggler-icon', this.props.expanded ? this.props.expandedRowIcon : this.props.collapsedRowIcon); return /*#__PURE__*/React.createElement("button", { type: "button", onClick: this.onClick, className: "p-row-toggler p-link", tabIndex: this.props.tabIndex }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); } }]); return RowTogglerButton; }(Component); var _excluded = ["originalEvent"]; function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$5(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$7(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$7(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$7() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TableBody = /*#__PURE__*/function (_Component) { _inherits(TableBody, _Component); var _super = _createSuper$7(TableBody); function TableBody(props) { var _this; _classCallCheck(this, TableBody); _this = _super.call(this, props); _this.state = { rowGroupHeaderStyleObject: {} }; // row _this.onRowClick = _this.onRowClick.bind(_assertThisInitialized(_this)); _this.onRowDoubleClick = _this.onRowDoubleClick.bind(_assertThisInitialized(_this)); _this.onRowRightClick = _this.onRowRightClick.bind(_assertThisInitialized(_this)); _this.onRowTouchEnd = _this.onRowTouchEnd.bind(_assertThisInitialized(_this)); _this.onRowMouseDown = _this.onRowMouseDown.bind(_assertThisInitialized(_this)); _this.onRowMouseUp = _this.onRowMouseUp.bind(_assertThisInitialized(_this)); _this.onRowToggle = _this.onRowToggle.bind(_assertThisInitialized(_this)); // drag _this.onRowDragStart = _this.onRowDragStart.bind(_assertThisInitialized(_this)); _this.onRowDragOver = _this.onRowDragOver.bind(_assertThisInitialized(_this)); _this.onRowDragLeave = _this.onRowDragLeave.bind(_assertThisInitialized(_this)); _this.onRowDragEnd = _this.onRowDragEnd.bind(_assertThisInitialized(_this)); _this.onRowDrop = _this.onRowDrop.bind(_assertThisInitialized(_this)); // selection _this.onRadioChange = _this.onRadioChange.bind(_assertThisInitialized(_this)); _this.onCheckboxChange = _this.onCheckboxChange.bind(_assertThisInitialized(_this)); _this.onDragSelectionMouseMove = _this.onDragSelectionMouseMove.bind(_assertThisInitialized(_this)); _this.onDragSelectionMouseUp = _this.onDragSelectionMouseUp.bind(_assertThisInitialized(_this)); // cell _this.onCellClick = _this.onCellClick.bind(_assertThisInitialized(_this)); _this.onCellMouseDown = _this.onCellMouseDown.bind(_assertThisInitialized(_this)); _this.onCellMouseUp = _this.onCellMouseUp.bind(_assertThisInitialized(_this)); _this.ref = _this.ref.bind(_assertThisInitialized(_this)); return _this; } _createClass(TableBody, [{ key: "ref", value: function ref(el) { this.el = el; this.props.virtualScrollerContentRef && this.props.virtualScrollerContentRef(el); } }, { key: "equals", value: function equals(data1, data2) { if (this.allowCellSelection()) return (data1.rowIndex === data2.rowIndex || data1.rowData === data2.rowData) && (data1.field === data2.field || data1.cellIndex === data2.cellIndex);else return this.compareSelectionBy === 'equals' ? data1 === data2 : ObjectUtils.equals(data1, data2, this.props.dataKey); } }, { key: "isSubheaderGrouping", value: function isSubheaderGrouping() { return this.props.rowGroupMode && this.props.rowGroupMode === 'subheader'; } }, { key: "isSelectionEnabled", value: function isSelectionEnabled() { return this.props.selectionMode || this.props.selectionModeInColumn !== null || this.props.columns && this.props.columns.some(function (col) { return col && !!col.props.selectionMode; }); } }, { key: "isRadioSelectionMode", value: function isRadioSelectionMode() { return this.props.selectionMode === 'radiobutton'; } }, { key: "isCheckboxSelectionMode", value: function isCheckboxSelectionMode() { return this.props.selectionMode === 'checkbox'; } }, { key: "isRadioSelectionModeInColumn", value: function isRadioSelectionModeInColumn() { return this.props.selectionModeInColumn === 'single'; } }, { key: "isCheckboxSelectionModeInColumn", value: function isCheckboxSelectionModeInColumn() { return this.props.selectionModeInColumn === 'multiple'; } }, { key: "isSingleSelection", value: function isSingleSelection() { return this.props.selectionMode === 'single' && !this.isCheckboxSelectionModeInColumn() || !this.isRadioSelectionMode() && this.isRadioSelectionModeInColumn(); } }, { key: "isMultipleSelection", value: function isMultipleSelection() { return this.props.selectionMode === 'multiple' && !this.isRadioSelectionModeInColumn() || this.isCheckboxSelectionModeInColumn(); } }, { key: "isRadioOnlySelection", value: function isRadioOnlySelection() { return this.isRadioSelectionMode() && this.isRadioSelectionModeInColumn(); } }, { key: "isCheckboxOnlySelection", value: function isCheckboxOnlySelection() { return this.isCheckboxSelectionMode() && this.isCheckboxSelectionModeInColumn(); } }, { key: "isSelected", value: function isSelected(rowData) { if (rowData && this.props.selection) { return this.props.selection instanceof Array ? this.findIndex(this.props.selection, rowData) > -1 : this.equals(rowData, this.props.selection); } return false; } }, { key: "isContextMenuSelected", value: function isContextMenuSelected(rowData) { if (rowData && this.props.contextMenuSelection) { return this.equals(rowData, this.props.contextMenuSelection); } return false; } }, { key: "isRowExpanded", value: function isRowExpanded(rowData) { if (rowData && this.props.expandedRows) { if (this.isSubheaderGrouping() && this.props.expandableRowGroups) { return this.isRowGroupExpanded(rowData); } else { if (this.props.dataKey) return this.props.expandedRows ? this.props.expandedRows[ObjectUtils.resolveFieldData(rowData, this.props.dataKey)] !== undefined : false;else return this.findIndex(this.props.expandedRows, rowData) !== -1; } } return false; } }, { key: "isRowGroupExpanded", value: function isRowGroupExpanded(rowData) { var _this2 = this; if (this.props.dataKey === this.props.groupRowsBy) return Object.keys(this.props.expandedRows).some(function (data) { return ObjectUtils.equals(data, ObjectUtils.resolveFieldData(rowData, _this2.props.dataKey)); });else return this.props.expandedRows.some(function (data) { return ObjectUtils.equals(data, rowData, _this2.props.groupRowsBy); }); } }, { key: "isRowEditing", value: function isRowEditing(rowData) { if (this.props.editMode === 'row' && rowData && this.props.editingRows) { if (this.props.dataKey) return this.props.editingRows ? this.props.editingRows[ObjectUtils.resolveFieldData(rowData, this.props.dataKey)] !== undefined : false;else return this.findIndex(this.props.editingRows, rowData) !== -1; } return false; } }, { key: "allowDrag", value: function allowDrag(event) { return this.props.dragSelection && this.isMultipleSelection() && !event.originalEvent.shiftKey; } }, { key: "allowRowDrag", value: function allowRowDrag(event) { return !this.allowCellSelection() && this.allowDrag(event); } }, { key: "allowCellDrag", value: function allowCellDrag(event) { return this.allowCellSelection() && this.allowDrag(event); } }, { key: "allowSelection", value: function allowSelection(event) { return !DomHandler.isClickable(event.originalEvent.target); } }, { key: "allowMetaKeySelection", value: function allowMetaKeySelection(event) { return !this.rowTouched && (!this.props.metaKeySelection || this.props.metaKeySelection && (event.originalEvent.metaKey || event.originalEvent.ctrlKey)); } }, { key: "allowRangeSelection", value: function allowRangeSelection(event) { return this.isMultipleSelection() && event.originalEvent.shiftKey && this.anchorRowIndex !== null; } }, { key: "allowRowSelection", value: function allowRowSelection() { return (this.props.selectionMode || this.props.selectionModeInColumn) && !this.isRadioOnlySelection() && !this.isCheckboxOnlySelection(); } }, { key: "allowCellSelection", value: function allowCellSelection() { return this.props.cellSelection && !this.isRadioSelectionModeInColumn() && !this.isCheckboxSelectionModeInColumn(); } }, { key: "getColumnsLength", value: function getColumnsLength() { return this.props.columns ? this.props.columns.length : 0; } }, { key: "getVirtualScrollerOption", value: function getVirtualScrollerOption(option, options) { options = options || this.props.virtualScrollerOptions; return options ? options[option] : null; } }, { key: "findIndex", value: function findIndex(collection, rowData) { var _this3 = this; return (collection || []).findIndex(function (data) { return _this3.equals(rowData, data); }); } }, { key: "rowGroupHeaderStyle", value: function rowGroupHeaderStyle() { if (this.props.scrollable) { return { top: this.state.rowGroupHeaderStyleObject['top'] }; } return null; } }, { key: "getRowKey", value: function getRowKey(rowData, index) { return this.props.dataKey ? ObjectUtils.resolveFieldData(rowData, this.props.dataKey) + '_' + index : index; } }, { key: "shouldRenderRowGroupHeader", value: function shouldRenderRowGroupHeader(value, rowData, i) { var currentRowFieldData = ObjectUtils.resolveFieldData(rowData, this.props.groupRowsBy); var prevRowData = value[i - 1]; if (prevRowData) { var previousRowFieldData = ObjectUtils.resolveFieldData(prevRowData, this.props.groupRowsBy); return currentRowFieldData !== previousRowFieldData; } else { return true; } } }, { key: "shouldRenderRowGroupFooter", value: function shouldRenderRowGroupFooter(value, rowData, i, expanded) { if (this.props.expandableRowGroups && !expanded) { return false; } else { var currentRowFieldData = ObjectUtils.resolveFieldData(rowData, this.props.groupRowsBy); var nextRowData = value[i + 1]; if (nextRowData) { var nextRowFieldData = ObjectUtils.resolveFieldData(nextRowData, this.props.groupRowsBy); return currentRowFieldData !== nextRowFieldData; } else { return true; } } } }, { key: "updateFrozenRowStickyPosition", value: function updateFrozenRowStickyPosition() { this.el.style.top = DomHandler.getOuterHeight(this.el.previousElementSibling) + 'px'; } }, { key: "updateFrozenRowGroupHeaderStickyPosition", value: function updateFrozenRowGroupHeaderStickyPosition() { var tableHeaderHeight = DomHandler.getOuterHeight(this.el.previousElementSibling); var top = tableHeaderHeight + 'px'; if (this.state.rowGroupHeaderStyleObject && this.state.rowGroupHeaderStyleObject.top !== top) { this.setState({ rowGroupHeaderStyleObject: { top: top } }); } } }, { key: "updateVirtualScrollerPosition", value: function updateVirtualScrollerPosition() { var tableHeaderHeight = DomHandler.getOuterHeight(this.el.previousElementSibling); this.el.style.top = (this.el.style.top || 0) + tableHeaderHeight + 'px'; } }, { key: "onSingleSelection", value: function onSingleSelection(_ref) { var originalEvent = _ref.originalEvent, data = _ref.data, toggleable = _ref.toggleable, type = _ref.type; var selected = this.isSelected(data); var selection = this.props.selection; if (selected) { if (toggleable) { selection = null; this.onUnselect({ originalEvent: originalEvent, data: data, type: type }); } } else { selection = data; this.onSelect({ originalEvent: originalEvent, data: data, type: type }); } this.focusOnElement(originalEvent, true); if (this.props.onSelectionChange && selection !== this.props.selection) { this.props.onSelectionChange({ originalEvent: originalEvent, value: selection }); } } }, { key: "onMultipleSelection", value: function onMultipleSelection(_ref2) { var _this4 = this; var originalEvent = _ref2.originalEvent, data = _ref2.data, toggleable = _ref2.toggleable, type = _ref2.type; var selected = this.isSelected(data); var selection = this.props.selection || []; if (selected) { if (toggleable) { var selectionIndex = this.findIndex(selection, data); selection = this.props.selection.filter(function (val, i) { return i !== selectionIndex; }); this.onUnselect({ originalEvent: originalEvent, data: data, type: type }); } else if (selection.length) { this.props.selection.forEach(function (d) { return _this4.onUnselect({ originalEvent: originalEvent, data: d, type: type }); }); selection = [data]; this.onSelect({ originalEvent: originalEvent, data: data, type: type }); } } else { selection = toggleable && this.isMultipleSelection() ? [].concat(_toConsumableArray(selection), [data]) : [data]; this.onSelect({ originalEvent: originalEvent, data: data, type: type }); } this.focusOnElement(originalEvent, true); if (this.props.onSelectionChange && selection !== this.props.selection) { this.props.onSelectionChange({ originalEvent: originalEvent, value: selection }); } } }, { key: "onRangeSelection", value: function onRangeSelection(event) { DomHandler.clearSelection(); this.rangeRowIndex = this.allowCellSelection() ? event.rowIndex : event.index; var selectionInRange = this.selectRange(event); var selection = this.isMultipleSelection() ? _toConsumableArray(new Set([].concat(_toConsumableArray(this.props.selection || []), _toConsumableArray(selectionInRange)))) : selectionInRange; if (this.props.onSelectionChange && selection !== this.props.selection) { this.props.onSelectionChange({ originalEvent: event.originalEvent, value: selection }); } this.anchorRowIndex = this.rangeRowIndex; this.anchorCellIndex = event.cellIndex; this.focusOnElement(event.originalEvent, false); } }, { key: "selectRange", value: function selectRange(event) { var rangeStart, rangeEnd; var isLazyAndPaginator = this.props.lazy && this.props.paginator; if (isLazyAndPaginator) { this.anchorRowIndex += this.anchorRowFirst; this.rangeRowIndex += this.props.first; } if (this.rangeRowIndex > this.anchorRowIndex) { rangeStart = this.anchorRowIndex; rangeEnd = this.rangeRowIndex; } else if (this.rangeRowIndex < this.anchorRowIndex) { rangeStart = this.rangeRowIndex; rangeEnd = this.anchorRowIndex; } else { rangeStart = rangeEnd = this.rangeRowIndex; } if (isLazyAndPaginator) { rangeStart = Math.max(rangeStart - this.props.first, 0); rangeEnd -= this.props.first; } return this.allowCellSelection() ? this.selectRangeOnCell(event, rangeStart, rangeEnd) : this.selectRangeOnRow(event, rangeStart, rangeEnd); } }, { key: "selectRangeOnRow", value: function selectRangeOnRow(event, rowRangeStart, rowRangeEnd) { var value = this.props.value; var selection = []; for (var i = rowRangeStart; i <= rowRangeEnd; i++) { var rangeRowData = value[i]; selection.push(rangeRowData); this.onSelect({ originalEvent: event.originalEvent, data: rangeRowData, type: 'row' }); } return selection; } }, { key: "selectRangeOnCell", value: function selectRangeOnCell(event, rowRangeStart, rowRangeEnd) { var cellRangeStart, cellRangeEnd, cellIndex = event.cellIndex; if (cellIndex > this.anchorCellIndex) { cellRangeStart = this.anchorCellIndex; cellRangeEnd = cellIndex; } else if (cellIndex < this.anchorCellIndex) { cellRangeStart = cellIndex; cellRangeEnd = this.anchorCellIndex; } else { cellRangeStart = cellRangeEnd = cellIndex; } var value = this.props.value; var selection = []; for (var i = rowRangeStart; i <= rowRangeEnd; i++) { var rowData = value[i]; var columns = this.props.columns; for (var j = cellRangeStart; j <= cellRangeEnd; j++) { var field = columns[j].props.field; var rangeRowData = { value: ObjectUtils.resolveFieldData(rowData, field), field: field, rowData: rowData, rowIndex: i, cellIndex: j, selected: true }; selection.push(rangeRowData); this.onSelect({ originalEvent: event.originalEvent, data: rangeRowData, type: 'cell' }); } } return selection; } }, { key: "onSelect", value: function onSelect(event) { if (this.allowCellSelection()) this.props.onCellSelect && this.props.onCellSelect(_objectSpread$5(_objectSpread$5({ originalEvent: event.originalEvent }, event.data), {}, { type: event.type }));else this.props.onRowSelect && this.props.onRowSelect(event); } }, { key: "onUnselect", value: function onUnselect(event) { if (this.allowCellSelection()) this.props.onCellUnselect && this.props.onCellUnselect(_objectSpread$5(_objectSpread$5({ originalEvent: event.originalEvent }, event.data), {}, { type: event.type }));else this.props.onRowUnselect && this.props.onRowUnselect(event); } }, { key: "enableDragSelection", value: function enableDragSelection(event) { if (this.props.dragSelection && !this.dragSelectionHelper) { this.dragSelectionHelper = document.createElement('div'); DomHandler.addClass(this.dragSelectionHelper, 'p-datatable-drag-selection-helper'); this.initialDragPosition = { x: event.clientX, y: event.clientY }; this.dragSelectionHelper.style.top = "".concat(event.pageY, "px"); this.dragSelectionHelper.style.left = "".concat(event.pageX, "px"); this.bindDragSelectionEvents(); } } }, { key: "focusOnElement", value: function focusOnElement(event, isFocused) { var target = event.currentTarget; if (!this.allowCellSelection()) { if (this.isCheckboxSelectionModeInColumn()) { var checkbox = DomHandler.findSingle(target, 'td.p-selection-column .p-checkbox-box'); checkbox && checkbox.focus(); } else if (this.isRadioSelectionModeInColumn()) { var radio = DomHandler.findSingle(target, 'td.p-selection-column input[type="radio"]'); radio && radio.focus(); } } !isFocused && target && target.focus(); } }, { key: "onRowClick", value: function onRowClick(event) { if (this.allowCellSelection() || !this.allowSelection(event)) { return; } this.props.onRowClick && this.props.onRowClick(event); if (this.allowRowSelection()) { if (this.allowRangeSelection(event)) { this.onRangeSelection(event); } else { var toggleable = this.isRadioSelectionModeInColumn() || this.isCheckboxSelectionModeInColumn() || this.allowMetaKeySelection(event); this.anchorRowIndex = event.index; this.rangeRowIndex = event.index; this.anchorRowFirst = this.props.first; if (this.isSingleSelection()) { this.onSingleSelection(_objectSpread$5(_objectSpread$5({}, event), {}, { toggleable: toggleable, type: 'row' })); } else { this.onMultipleSelection(_objectSpread$5(_objectSpread$5({}, event), {}, { toggleable: toggleable, type: 'row' })); } } } else { this.focusOnElement(event.originalEvent); } this.rowTouched = false; } }, { key: "onRowDoubleClick", value: function onRowDoubleClick(e) { var event = e.originalEvent; if (DomHandler.isClickable(event.target)) { return; } if (this.props.onRowDoubleClick) { this.props.onRowDoubleClick(e); } } }, { key: "onRowRightClick", value: function onRowRightClick(event) { if (this.props.onContextMenu || this.props.onContextMenuSelectionChange) { DomHandler.clearSelection(); if (this.props.onContextMenuSelectionChange) { this.props.onContextMenuSelectionChange({ originalEvent: event.originalEvent, value: event.data }); } if (this.props.onContextMenu) { this.props.onContextMenu({ originalEvent: event.originalEvent, data: event.data }); } event.originalEvent.preventDefault(); } } }, { key: "onRowTouchEnd", value: function onRowTouchEnd() { this.rowTouched = true; } }, { key: "onRowMouseDown", value: function onRowMouseDown(e) { DomHandler.clearSelection(); var event = e.originalEvent; if (DomHandler.hasClass(event.target, 'p-datatable-reorderablerow-handle')) event.currentTarget.draggable = true;else event.currentTarget.draggable = false; if (this.allowRowDrag(e)) { this.enableDragSelection(event); this.anchorRowIndex = e.index; this.rangeRowIndex = e.index; this.anchorRowFirst = this.props.first; } } }, { key: "onRowMouseUp", value: function onRowMouseUp(event) { var isSameRow = event.index === this.anchorRowIndex; if (this.allowRowDrag(event) && !isSameRow) { this.onRangeSelection(event); } } }, { key: "onRowToggle", value: function onRowToggle(event) { var expandedRows; var dataKey = this.props.dataKey; var hasDataKey = this.props.groupRowsBy ? dataKey === this.props.groupRowsBy : !!dataKey; if (hasDataKey) { var dataKeyValue = String(ObjectUtils.resolveFieldData(event.data, dataKey)); expandedRows = this.props.expandedRows ? _objectSpread$5({}, this.props.expandedRows) : {}; if (expandedRows[dataKeyValue] != null) { delete expandedRows[dataKeyValue]; if (this.props.onRowCollapse) { this.props.onRowCollapse({ originalEvent: event, data: event.data }); } } else { expandedRows[dataKeyValue] = true; if (this.props.onRowExpand) { this.props.onRowExpand({ originalEvent: event, data: event.data }); } } } else { var expandedRowIndex = this.findIndex(this.props.expandedRows, event.data); expandedRows = this.props.expandedRows ? _toConsumableArray(this.props.expandedRows) : []; if (expandedRowIndex !== -1) { expandedRows = expandedRows.filter(function (val, i) { return i !== expandedRowIndex; }); if (this.props.onRowCollapse) { this.props.onRowCollapse({ originalEvent: event, data: event.data }); } } else { expandedRows.push(event.data); if (this.props.onRowExpand) { this.props.onRowExpand({ originalEvent: event, data: event.data }); } } } if (this.props.onRowToggle) { this.props.onRowToggle({ data: expandedRows }); } } }, { key: "onRowDragStart", value: function onRowDragStart(e) { var event = e.originalEvent, index = e.index; this.rowDragging = true; this.draggedRowIndex = index; event.dataTransfer.setData('text', 'b'); // For firefox } }, { key: "onRowDragOver", value: function onRowDragOver(e) { var event = e.originalEvent, index = e.index; if (this.rowDragging && this.draggedRowIndex !== index) { var rowElement = event.currentTarget; var rowY = DomHandler.getOffset(rowElement).top + DomHandler.getWindowScrollTop(); var pageY = event.pageY; var rowMidY = rowY + DomHandler.getOuterHeight(rowElement) / 2; var prevRowElement = rowElement.previousElementSibling; if (pageY < rowMidY) { DomHandler.removeClass(rowElement, 'p-datatable-dragpoint-bottom'); this.droppedRowIndex = index; if (prevRowElement) DomHandler.addClass(prevRowElement, 'p-datatable-dragpoint-bottom');else DomHandler.addClass(rowElement, 'p-datatable-dragpoint-top'); } else { if (prevRowElement) DomHandler.removeClass(prevRowElement, 'p-datatable-dragpoint-bottom');else DomHandler.addClass(rowElement, 'p-datatable-dragpoint-top'); this.droppedRowIndex = index + 1; DomHandler.addClass(rowElement, 'p-datatable-dragpoint-bottom'); } } event.preventDefault(); } }, { key: "onRowDragLeave", value: function onRowDragLeave(e) { var event = e.originalEvent; var rowElement = event.currentTarget; var prevRowElement = rowElement.previousElementSibling; if (prevRowElement) { DomHandler.removeClass(prevRowElement, 'p-datatable-dragpoint-bottom'); } DomHandler.removeClass(rowElement, 'p-datatable-dragpoint-bottom'); DomHandler.removeClass(rowElement, 'p-datatable-dragpoint-top'); } }, { key: "onRowDragEnd", value: function onRowDragEnd(e) { var event = e.originalEvent; this.rowDragging = false; this.draggedRowIndex = null; this.droppedRowIndex = null; event.currentTarget.draggable = false; } }, { key: "onRowDrop", value: function onRowDrop(e) { var event = e.originalEvent; if (this.droppedRowIndex != null) { var dropIndex = this.draggedRowIndex > this.droppedRowIndex ? this.droppedRowIndex : this.droppedRowIndex === 0 ? 0 : this.droppedRowIndex - 1; var val = _toConsumableArray(this.props.value); ObjectUtils.reorderArray(val, this.draggedRowIndex, dropIndex); if (this.props.onRowReorder) { this.props.onRowReorder({ originalEvent: event, value: val, dragIndex: this.draggedRowIndex, dropIndex: this.droppedRowIndex }); } } //cleanup this.onRowDragLeave(e); this.onRowDragEnd(e); event.preventDefault(); } }, { key: "onRadioChange", value: function onRadioChange(event) { this.onSingleSelection(_objectSpread$5(_objectSpread$5({}, event), {}, { toggleable: true, type: 'radio' })); } }, { key: "onCheckboxChange", value: function onCheckboxChange(event) { this.onMultipleSelection(_objectSpread$5(_objectSpread$5({}, event), {}, { toggleable: true, type: 'checkbox' })); } }, { key: "onDragSelectionMouseMove", value: function onDragSelectionMouseMove(event) { var _this$initialDragPosi = this.initialDragPosition, x = _this$initialDragPosi.x, y = _this$initialDragPosi.y; var dx = event.clientX - x; var dy = event.clientY - y; if (dy < 0) this.dragSelectionHelper.style.top = "".concat(event.pageY + 5, "px"); if (dx < 0) this.dragSelectionHelper.style.left = "".concat(event.pageX + 5, "px"); this.dragSelectionHelper.style.height = "".concat(Math.abs(dy), "px"); this.dragSelectionHelper.style.width = "".concat(Math.abs(dx), "px"); event.preventDefault(); } }, { key: "onDragSelectionMouseUp", value: function onDragSelectionMouseUp() { if (this.dragSelectionHelper) { this.dragSelectionHelper.remove(); this.dragSelectionHelper = null; } document.removeEventListener('mousemove', this.onDragSelectionMouseMove); document.removeEventListener('mouseup', this.onDragSelectionMouseUp); } }, { key: "onCellClick", value: function onCellClick(event) { if (!this.allowSelection(event)) { return; } this.props.onCellClick && this.props.onCellClick(event); if (this.allowCellSelection()) { if (this.allowRangeSelection(event)) { this.onRangeSelection(event); } else { var toggleable = this.allowMetaKeySelection(event); var originalEvent = event.originalEvent, data = _objectWithoutProperties(event, _excluded); this.anchorRowIndex = event.rowIndex; this.rangeRowIndex = event.rowIndex; this.anchorRowFirst = this.props.first; this.anchorCellIndex = event.cellIndex; if (this.isSingleSelection()) { this.onSingleSelection({ originalEvent: originalEvent, data: data, toggleable: toggleable, type: 'cell' }); } else { this.onMultipleSelection({ originalEvent: originalEvent, data: data, toggleable: toggleable, type: 'cell' }); } } } this.rowTouched = false; } }, { key: "onCellMouseDown", value: function onCellMouseDown(event) { if (this.allowCellDrag(event)) { this.enableDragSelection(event.originalEvent); this.anchorRowIndex = event.rowIndex; this.rangeRowIndex = event.rowIndex; this.anchorRowFirst = this.props.first; this.anchorCellIndex = event.cellIndex; } } }, { key: "onCellMouseUp", value: function onCellMouseUp(event) { var isSameCell = event.rowIndex === this.anchorRowIndex && event.cellIndex === this.anchorCellIndex; if (this.allowCellDrag(event) && !isSameCell) { this.onRangeSelection(event); } } }, { key: "bindDragSelectionEvents", value: function bindDragSelectionEvents() { document.addEventListener('mousemove', this.onDragSelectionMouseMove); document.addEventListener('mouseup', this.onDragSelectionMouseUp); document.body.appendChild(this.dragSelectionHelper); } }, { key: "unbindDragSelectionEvents", value: function unbindDragSelectionEvents() { this.onDragSelectionMouseUp(); } }, { key: "componentDidMount", value: function componentDidMount() { if (this.props.frozenRow) { this.updateFrozenRowStickyPosition(); } if (this.props.scrollable && this.props.rowGroupMode === 'subheader') { this.updateFrozenRowGroupHeaderStickyPosition(); } if (!this.props.isVirtualScrollerDisabled && this.getVirtualScrollerOption('vertical')) { this.updateVirtualScrollerPosition(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.props.frozenRow) { this.updateFrozenRowStickyPosition(); } if (this.props.scrollable && this.props.rowGroupMode === 'subheader') { this.updateFrozenRowGroupHeaderStickyPosition(); } if (!this.props.isVirtualScrollerDisabled && this.getVirtualScrollerOption('vertical') && this.getVirtualScrollerOption('itemSize', prevProps.virtualScrollerOptions) !== this.getVirtualScrollerOption('itemSize')) { this.updateVirtualScrollerPosition(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.props.dragSelection) { this.unbindDragSelectionEvents(); } } }, { key: "renderEmptyContent", value: function renderEmptyContent() { if (!this.props.loading) { var colSpan = this.getColumnsLength(); var content = ObjectUtils.getJSXElement(this.props.emptyMessage, { props: this.props, frozen: this.props.frozenRow }) || localeOption('emptyMessage'); return /*#__PURE__*/React.createElement("tr", { className: "p-datatable-emptymessage", role: "row" }, /*#__PURE__*/React.createElement("td", { colSpan: colSpan, role: "cell" }, content)); } return null; } }, { key: "renderGroupHeader", value: function renderGroupHeader(rowData, index, expanded, isSubheaderGrouping, colSpan) { if (isSubheaderGrouping && this.shouldRenderRowGroupHeader(this.props.value, rowData, index)) { var style = this.rowGroupHeaderStyle(); var toggler = this.props.expandableRowGroups && /*#__PURE__*/React.createElement(RowTogglerButton, { onClick: this.onRowToggle, rowData: rowData, expanded: expanded, expandedRowIcon: this.props.expandedRowIcon, collapsedRowIcon: this.props.collapsedRowIcon }); var content = ObjectUtils.getJSXElement(this.props.rowGroupHeaderTemplate, rowData, { index: index, props: this.props.tableProps }); return /*#__PURE__*/React.createElement("tr", { className: "p-rowgroup-header", style: style, role: "row" }, /*#__PURE__*/React.createElement("td", { colSpan: colSpan }, toggler, /*#__PURE__*/React.createElement("span", { className: "p-rowgroup-header-name" }, content))); } return null; } }, { key: "renderRow", value: function renderRow(rowData, index, expanded) { if (!this.props.expandableRowGroups || expanded) { var selected = this.isSelectionEnabled() ? this.isSelected(rowData) : false; var contextMenuSelected = this.isContextMenuSelected(rowData); var allowRowSelection = this.allowRowSelection(); var allowCellSelection = this.allowCellSelection(); var editing = this.isRowEditing(rowData); return /*#__PURE__*/React.createElement(BodyRow, { tableProps: this.props.tableProps, tableSelector: this.props.tableSelector, value: this.props.value, columns: this.props.columns, rowData: rowData, index: index, selected: selected, contextMenuSelected: contextMenuSelected, onRowClick: this.onRowClick, onRowDoubleClick: this.onRowDoubleClick, onRowRightClick: this.onRowRightClick, tabIndex: this.props.tabIndex, onRowTouchEnd: this.onRowTouchEnd, onRowMouseDown: this.onRowMouseDown, onRowMouseUp: this.onRowMouseUp, onRowToggle: this.onRowToggle, onRowDragStart: this.onRowDragStart, onRowDragOver: this.onRowDragOver, onRowDragLeave: this.onRowDragLeave, onRowDragEnd: this.onRowDragEnd, onRowDrop: this.onRowDrop, onRadioChange: this.onRadioChange, onCheckboxChange: this.onCheckboxChange, onCellClick: this.onCellClick, onCellMouseDown: this.onCellMouseDown, onCellMouseUp: this.onCellMouseUp, editing: editing, editingRows: this.props.editingRows, editingMeta: this.props.editingMeta, editMode: this.props.editMode, onRowEditChange: this.props.onRowEditChange, onEditingMetaChange: this.props.onEditingMetaChange, groupRowsBy: this.props.groupRowsBy, compareSelectionBy: this.props.compareSelectionBy, dataKey: this.props.dataKey, rowGroupMode: this.props.rowGroupMode, onRowEditInit: this.props.onRowEditInit, rowEditValidator: this.props.rowEditValidator, onRowEditSave: this.props.onRowEditSave, onRowEditComplete: this.props.onRowEditComplete, onRowEditCancel: this.props.onRowEditCancel, selection: this.props.selection, allowRowSelection: allowRowSelection, allowCellSelection: allowCellSelection, selectOnEdit: this.props.selectOnEdit, selectionMode: this.props.selectionMode, selectionModeInColumn: this.props.selectionModeInColumn, cellClassName: this.props.cellClassName, responsiveLayout: this.props.responsiveLayout, frozenRow: this.props.frozenRow, showSelectionElement: this.props.showSelectionElement, showRowReorderElement: this.props.showRowReorderElement, expanded: expanded, expandedRowIcon: this.props.expandedRowIcon, collapsedRowIcon: this.props.collapsedRowIcon, rowClassName: this.props.rowClassName, virtualScrollerOptions: this.props.virtualScrollerOptions }); } } }, { key: "renderExpansion", value: function renderExpansion(rowData, index, expanded, isSubheaderGrouping, colSpan) { if (expanded && !(isSubheaderGrouping && this.props.expandableRowGroups)) { var content = ObjectUtils.getJSXElement(this.props.rowExpansionTemplate, rowData, { index: index }); var id = "".concat(this.props.tableSelector, "_content_").concat(index, "_expanded"); return /*#__PURE__*/React.createElement("tr", { id: id, className: "p-datatable-row-expansion", role: "row" }, /*#__PURE__*/React.createElement("td", { role: "cell", colSpan: colSpan }, content)); } return null; } }, { key: "renderGroupFooter", value: function renderGroupFooter(rowData, index, expanded, isSubheaderGrouping, colSpan) { if (isSubheaderGrouping && this.shouldRenderRowGroupFooter(this.props.value, rowData, index, expanded)) { var content = ObjectUtils.getJSXElement(this.props.rowGroupFooterTemplate, rowData, { index: index, colSpan: colSpan, props: this.props.tableProps }); return /*#__PURE__*/React.createElement("tr", { className: "p-rowgroup-footer", role: "row" }, content); } return null; } }, { key: "renderContent", value: function renderContent() { var _this5 = this; return this.props.value.map(function (rowData, i) { var index = _this5.getVirtualScrollerOption('getItemOptions') ? _this5.getVirtualScrollerOption('getItemOptions')(i).index : _this5.props.first + i; var key = _this5.getRowKey(rowData, index); var expanded = _this5.isRowExpanded(rowData); var isSubheaderGrouping = _this5.isSubheaderGrouping(); var colSpan = _this5.getColumnsLength(); var groupHeader = _this5.renderGroupHeader(rowData, index, expanded, isSubheaderGrouping, colSpan); var row = _this5.renderRow(rowData, index, expanded); var expansion = _this5.renderExpansion(rowData, index, expanded, isSubheaderGrouping, colSpan); var groupFooter = _this5.renderGroupFooter(rowData, index, expanded, isSubheaderGrouping, colSpan); return /*#__PURE__*/React.createElement(React.Fragment, { key: key }, groupHeader, row, expansion, groupFooter); }); } }, { key: "render", value: function render() { var className = classNames('p-datatable-tbody', this.props.className); var content = this.props.empty ? this.renderEmptyContent() : this.renderContent(); return /*#__PURE__*/React.createElement("tbody", { ref: this.ref, className: className }, content); } }]); return TableBody; }(Component); function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$4(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$6(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$6(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$6() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var FooterCell = /*#__PURE__*/function (_Component) { _inherits(FooterCell, _Component); var _super = _createSuper$6(FooterCell); function FooterCell(props) { var _this; _classCallCheck(this, FooterCell); _this = _super.call(this, props); _this.state = { styleObject: {} }; return _this; } _createClass(FooterCell, [{ key: "getColumnProp", value: function getColumnProp(prop) { return this.props.column.props[prop]; } }, { key: "getStyle", value: function getStyle() { var footerStyle = this.getColumnProp('footerStyle'); var columnStyle = this.getColumnProp('style'); return this.getColumnProp('frozen') ? Object.assign({}, columnStyle, footerStyle, this.state.styleObject) : Object.assign({}, columnStyle, footerStyle); } }, { key: "updateStickyPosition", value: function updateStickyPosition() { if (this.getColumnProp('frozen')) { var styleObject = _objectSpread$4({}, this.state.styleObject); var align = this.getColumnProp('alignFrozen'); if (align === 'right') { var right = 0; var next = this.el.nextElementSibling; if (next) { right = DomHandler.getOuterWidth(next) + parseFloat(next.style.right || 0); } styleObject['right'] = right + 'px'; } else { var left = 0; var prev = this.el.previousElementSibling; if (prev) { left = DomHandler.getOuterWidth(prev) + parseFloat(prev.style.left || 0); } styleObject['left'] = left + 'px'; } this.setState({ styleObject: styleObject }); } } }, { key: "componentDidMount", value: function componentDidMount() { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } } }, { key: "render", value: function render() { var _this2 = this; var style = this.getStyle(); var className = classNames(this.getColumnProp('footerClassName'), this.getColumnProp('className'), { 'p-frozen-column': this.getColumnProp('frozen') }); var colSpan = this.getColumnProp('colSpan'); var rowSpan = this.getColumnProp('rowSpan'); var content = ObjectUtils.getJSXElement(this.getColumnProp('footer'), { props: this.props.tableProps }); return /*#__PURE__*/React.createElement("td", { ref: function ref(el) { return _this2.el = el; }, style: style, className: className, role: "cell", colSpan: colSpan, rowSpan: rowSpan }, content); } }]); return FooterCell; }(Component); function _createSuper$5(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$5(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$5() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TableFooter = /*#__PURE__*/function (_Component) { _inherits(TableFooter, _Component); var _super = _createSuper$5(TableFooter); function TableFooter() { _classCallCheck(this, TableFooter); return _super.apply(this, arguments); } _createClass(TableFooter, [{ key: "hasFooter", value: function hasFooter() { return this.props.footerColumnGroup ? true : this.props.columns ? this.props.columns.some(function (col) { return col && col.props.footer; }) : false; } }, { key: "renderGroupFooterCells", value: function renderGroupFooterCells(row) { var columns = React.Children.toArray(row.props.children); return this.renderFooterCells(columns); } }, { key: "renderFooterCells", value: function renderFooterCells(columns) { var _this = this; return React.Children.map(columns, function (col, i) { var isVisible = col ? !col.props.hidden : true; var key = col ? col.props.columnKey || col.props.field || i : i; return isVisible && /*#__PURE__*/React.createElement(FooterCell, { key: key, tableProps: _this.props.tableProps, column: col }); }); } }, { key: "renderContent", value: function renderContent() { var _this2 = this; if (this.props.footerColumnGroup) { var rows = React.Children.toArray(this.props.footerColumnGroup.props.children); return rows.map(function (row, i) { return /*#__PURE__*/React.createElement("tr", { key: i, role: "row" }, _this2.renderGroupFooterCells(row)); }); } return /*#__PURE__*/React.createElement("tr", { role: "row" }, this.renderFooterCells(this.props.columns)); } }, { key: "render", value: function render() { if (this.hasFooter()) { var content = this.renderContent(); return /*#__PURE__*/React.createElement("tfoot", { className: "p-datatable-tfoot" }, content); } return null; } }]); return TableFooter; }(Component); function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var HeaderCheckbox = /*#__PURE__*/function (_Component) { _inherits(HeaderCheckbox, _Component); var _super = _createSuper$4(HeaderCheckbox); function HeaderCheckbox(props) { var _this; _classCallCheck(this, HeaderCheckbox); _this = _super.call(this, props); _this.state = { focused: false }; _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(HeaderCheckbox, [{ key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onClick", value: function onClick(event) { if (!this.props.disabled) { this.setState({ focused: true }); this.props.onChange({ originalEvent: event, checked: this.props.checked }); } } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.code === 'Space') { this.onClick(event); event.preventDefault(); } } }, { key: "render", value: function render() { var boxClassName = classNames('p-checkbox-box p-component', { 'p-highlight': this.props.checked, 'p-disabled': this.props.disabled, 'p-focus': this.state.focused }); var iconClassName = classNames('p-checkbox-icon', { 'pi pi-check': this.props.checked }); var tabIndex = this.props.disabled ? null : 0; return /*#__PURE__*/React.createElement("div", { className: "p-checkbox p-component", onClick: this.onClick }, /*#__PURE__*/React.createElement("div", { className: boxClassName, role: "checkbox", "aria-checked": this.props.checked, tabIndex: tabIndex, onFocus: this.onFocus, onBlur: this.onBlur, onKeyDown: this.onKeyDown }, /*#__PURE__*/React.createElement("span", { className: iconClassName }))); } }]); return HeaderCheckbox; }(Component); var FilterMatchMode = Object.freeze({ STARTS_WITH: 'startsWith', CONTAINS: 'contains', NOT_CONTAINS: 'notContains', ENDS_WITH: 'endsWith', EQUALS: 'equals', NOT_EQUALS: 'notEquals', IN: 'in', LESS_THAN: 'lt', LESS_THAN_OR_EQUAL_TO: 'lte', GREATER_THAN: 'gt', GREATER_THAN_OR_EQUAL_TO: 'gte', BETWEEN: 'between', DATE_IS: 'dateIs', DATE_IS_NOT: 'dateIsNot', DATE_BEFORE: 'dateBefore', DATE_AFTER: 'dateAfter', CUSTOM: 'custom' }); function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var ColumnFilter = /*#__PURE__*/function (_Component) { _inherits(ColumnFilter, _Component); var _super = _createSuper$3(ColumnFilter); function ColumnFilter(props) { var _this; _classCallCheck(this, ColumnFilter); _this = _super.call(this, props); _this.state = { overlayVisible: false }; _this.overlayRef = /*#__PURE__*/React.createRef(); _this.filterCallback = _this.filterCallback.bind(_assertThisInitialized(_this)); _this.filterApplyCallback = _this.filterApplyCallback.bind(_assertThisInitialized(_this)); _this.onOperatorChange = _this.onOperatorChange.bind(_assertThisInitialized(_this)); _this.addConstraint = _this.addConstraint.bind(_assertThisInitialized(_this)); _this.clearFilter = _this.clearFilter.bind(_assertThisInitialized(_this)); _this.applyFilter = _this.applyFilter.bind(_assertThisInitialized(_this)); _this.onInputChange = _this.onInputChange.bind(_assertThisInitialized(_this)); _this.toggleMenu = _this.toggleMenu.bind(_assertThisInitialized(_this)); _this.onOverlayEnter = _this.onOverlayEnter.bind(_assertThisInitialized(_this)); _this.onOverlayExit = _this.onOverlayExit.bind(_assertThisInitialized(_this)); _this.onOverlayExited = _this.onOverlayExited.bind(_assertThisInitialized(_this)); _this.onContentKeyDown = _this.onContentKeyDown.bind(_assertThisInitialized(_this)); _this.onContentClick = _this.onContentClick.bind(_assertThisInitialized(_this)); _this.onContentMouseDown = _this.onContentMouseDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(ColumnFilter, [{ key: "field", get: function get() { return this.getColumnProp('filterField') || this.getColumnProp('field'); } }, { key: "overlay", get: function get() { return this.overlayRef ? this.overlayRef.current : null; } }, { key: "filterModel", get: function get() { return this.props.filters[this.field]; } }, { key: "filterStoreModel", get: function get() { return this.props.filtersStore[this.field]; } }, { key: "hasFilter", value: function hasFilter() { if (this.props.filtersStore) { var fieldFilter = this.props.filtersStore[this.field]; return fieldFilter && (fieldFilter.operator ? !this.isFilterBlank(fieldFilter.constraints[0].value) : !this.isFilterBlank(fieldFilter.value)); } return false; } }, { key: "hasRowFilter", value: function hasRowFilter() { return this.filterModel && !this.isFilterBlank(this.filterModel.value); } }, { key: "isFilterBlank", value: function isFilterBlank(filter) { return ObjectUtils.isEmpty(filter); } }, { key: "isRowMatchModeSelected", value: function isRowMatchModeSelected(matchMode) { return this.filterModel.matchMode === matchMode; } }, { key: "showMenuButton", value: function showMenuButton() { return this.getColumnProp('showFilterMenu') && (this.props.display === 'row' ? this.getColumnProp('dataType') !== 'boolean' : true); } }, { key: "matchModes", value: function matchModes() { return this.getColumnProp('filterMatchModeOptions') || PrimeReact.filterMatchModeOptions[this.findDataType()].map(function (key) { return { label: localeOption(key), value: key }; }); } }, { key: "isShowMatchModes", value: function isShowMatchModes() { return this.getColumnProp('dataType') !== 'boolean' && this.getColumnProp('showFilterMatchModes') && this.matchModes() && this.getColumnProp('showFilterMenuOptions'); } }, { key: "isShowOperator", value: function isShowOperator() { return this.getColumnProp('showFilterOperator') && this.filterModel && this.filterModel.operator && this.getColumnProp('showFilterMenuOptions'); } }, { key: "showRemoveIcon", value: function showRemoveIcon() { return this.fieldConstraints().length > 1; } }, { key: "isShowAddConstraint", value: function isShowAddConstraint() { return this.getColumnProp('showAddButton') && this.filterModel && this.filterModel.operator && this.fieldConstraints() && this.fieldConstraints().length < this.getColumnProp('maxConstraints') && this.getColumnProp('showFilterMenuOptions'); } }, { key: "isOutsideClicked", value: function isOutsideClicked(target) { return !this.isTargetClicked(target) && this.overlayRef && this.overlayRef.current && !(this.overlayRef.current.isSameNode(target) || this.overlayRef.current.contains(target)); } }, { key: "isTargetClicked", value: function isTargetClicked(target) { return this.icon && (this.icon.isSameNode(target) || this.icon.contains(target)); } }, { key: "getColumnProp", value: function getColumnProp(prop) { return this.props.column.props[prop]; } }, { key: "getDefaultConstraint", value: function getDefaultConstraint() { if (this.props.filtersStore && this.filterStoreModel) { if (this.filterStoreModel.operator) { return { matchMode: this.filterStoreModel.constraints[0].matchMode, operator: this.filterStoreModel.operator }; } else { return { matchMode: this.filterStoreModel.matchMode }; } } } }, { key: "findDataType", value: function findDataType() { var dataType = this.getColumnProp('dataType'); var matchMode = this.getColumnProp('filterMatchMode'); var hasMatchMode = function hasMatchMode(key) { return PrimeReact.filterMatchModeOptions[key].some(function (mode) { return mode === matchMode; }); }; if (matchMode === 'custom' && !hasMatchMode(dataType)) { PrimeReact.filterMatchModeOptions[dataType].push(FilterMatchMode.CUSTOM); return dataType; } else if (matchMode) { return Object.keys(PrimeReact.filterMatchModeOptions).find(function (key) { return hasMatchMode(key); }) || dataType; } return dataType; } }, { key: "clearFilter", value: function clearFilter() { var field = this.field; var filterClearCallback = this.getColumnProp('onFilterClear'); var defaultConstraint = this.getDefaultConstraint(); var filters = _objectSpread$3({}, this.props.filters); if (filters[field].operator) { filters[field].constraints.splice(1); filters[field].operator = defaultConstraint.operator; filters[field].constraints[0] = { value: null, matchMode: defaultConstraint.matchMode }; } else { filters[field].value = null; filters[field].matchMode = defaultConstraint.matchMode; } filterClearCallback && filterClearCallback(); this.props.onFilterChange(filters); this.props.onFilterApply(); this.hide(); } }, { key: "applyFilter", value: function applyFilter() { var filterApplyClickCallback = this.getColumnProp('onFilterApplyClick'); filterApplyClickCallback && filterApplyClickCallback({ field: this.field, constraints: this.filterModel }); this.props.onFilterApply(); this.hide(); } }, { key: "toggleMenu", value: function toggleMenu() { this.setState(function (prevState) { return { overlayVisible: !prevState.overlayVisible }; }); } }, { key: "onToggleButtonKeyDown", value: function onToggleButtonKeyDown(event) { switch (event.key) { case 'Escape': case 'Tab': this.hide(); break; case 'ArrowDown': if (this.state.overlayVisible) { var focusable = DomHandler.getFirstFocusableElement(this.overlay); focusable && focusable.focus(); event.preventDefault(); } else if (event.altKey) { this.setState({ overlayVisible: true }); event.preventDefault(); } break; } } }, { key: "onContentKeyDown", value: function onContentKeyDown(event) { if (event.key === 'Escape') { this.hide(); this.icon && this.icon.focus(); } } }, { key: "onInputChange", value: function onInputChange(event, index) { var filters = _objectSpread$3({}, this.props.filters); var value = event.target.value; if (this.props.display === 'menu') { filters[this.field].constraints[index].value = value; } else { filters[this.field].value = value; } this.props.onFilterChange(filters); if (!this.getColumnProp('showApplyButton') || this.props.display === 'row') { this.props.onFilterApply(); } } }, { key: "onRowMatchModeChange", value: function onRowMatchModeChange(matchMode) { var filterMatchModeChangeCallback = this.getColumnProp('onFilterMatchModeChange'); var filters = _objectSpread$3({}, this.props.filters); filters[this.field].matchMode = matchMode; filterMatchModeChangeCallback && filterMatchModeChangeCallback({ field: this.field, matchMode: matchMode }); this.props.onFilterChange(filters); this.props.onFilterApply(); this.hide(); } }, { key: "onRowMatchModeKeyDown", value: function onRowMatchModeKeyDown(event, matchMode, clear) { var item = event.target; switch (event.key) { case 'ArrowDown': var nextItem = this.findNextItem(item); if (nextItem) { item.removeAttribute('tabindex'); nextItem.tabIndex = 0; nextItem.focus(); } event.preventDefault(); break; case 'ArrowUp': var prevItem = this.findPrevItem(item); if (prevItem) { item.removeAttribute('tabindex'); prevItem.tabIndex = 0; prevItem.focus(); } event.preventDefault(); break; case 'Enter': clear ? this.clearFilter() : this.onRowMatchModeChange(matchMode.value); event.preventDefault(); break; } } }, { key: "onOperatorChange", value: function onOperatorChange(e) { var filterOperationChangeCallback = this.getColumnProp('onFilterOperatorChange'); var value = e.value; var filters = _objectSpread$3({}, this.props.filters); filters[this.field].operator = value; this.props.onFilterChange(filters); filterOperationChangeCallback && filterOperationChangeCallback({ field: this.field, operator: value }); if (!this.getColumnProp('showApplyButton')) { this.props.onFilterApply(); } } }, { key: "onMenuMatchModeChange", value: function onMenuMatchModeChange(value, index) { var filterMatchModeChangeCallback = this.getColumnProp('onFilterMatchModeChange'); var filters = _objectSpread$3({}, this.props.filters); filters[this.field].constraints[index].matchMode = value; this.props.onFilterChange(filters); filterMatchModeChangeCallback && filterMatchModeChangeCallback({ field: this.field, matchMode: value, index: index }); if (!this.getColumnProp('showApplyButton')) { this.props.onFilterApply(); } } }, { key: "addConstraint", value: function addConstraint() { var filterConstraintAddCallback = this.getColumnProp('onFilterConstraintAdd'); var defaultConstraint = this.getDefaultConstraint(); var filters = _objectSpread$3({}, this.props.filters); var newConstraint = { value: null, matchMode: defaultConstraint.matchMode }; filters[this.field].constraints.push(newConstraint); filterConstraintAddCallback && filterConstraintAddCallback({ field: this.field, constraing: newConstraint }); this.props.onFilterChange(filters); if (!this.getColumnProp('showApplyButton')) { this.props.onFilterApply(); } } }, { key: "removeConstraint", value: function removeConstraint(index) { var filterConstraintRemoveCallback = this.getColumnProp('onFilterConstraintRemove'); var filters = _objectSpread$3({}, this.props.filters); var removedConstraint = filters[this.field].constraints.splice(index, 1); filterConstraintRemoveCallback && filterConstraintRemoveCallback({ field: this.field, constraing: removedConstraint }); this.props.onFilterChange(filters); if (!this.getColumnProp('showApplyButton')) { this.props.onFilterApply(); } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return DomHandler.hasClass(nextItem, 'p-column-filter-separator') ? this.findNextItem(nextItem) : nextItem;else return item.parentElement.firstElementChild; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return DomHandler.hasClass(prevItem, 'p-column-filter-separator') ? this.findPrevItem(prevItem) : prevItem;else return item.parentElement.lastElementChild; } }, { key: "hide", value: function hide() { this.setState({ overlayVisible: false }); } }, { key: "onContentClick", value: function onContentClick(event) { this.selfClick = true; OverlayService.emit('overlay-click', { originalEvent: event, target: this.overlay }); } }, { key: "onContentMouseDown", value: function onContentMouseDown() { this.selfClick = true; } }, { key: "onOverlayEnter", value: function onOverlayEnter() { var _this2 = this; ZIndexUtils.set('overlay', this.overlay, PrimeReact.autoZIndex, PrimeReact.zIndex['overlay']); DomHandler.alignOverlay(this.overlay, this.icon, PrimeReact.appendTo, false); this.bindOutsideClickListener(); this.bindScrollListener(); this.bindResizeListener(); this.overlayEventListener = function (e) { if (!_this2.isOutsideClicked(e.target)) { _this2.selfClick = true; } }; OverlayService.on('overlay-click', this.overlayEventListener); } }, { key: "onOverlayExit", value: function onOverlayExit() { this.onOverlayHide(); } }, { key: "onOverlayExited", value: function onOverlayExited() { ZIndexUtils.clear(this.overlay); } }, { key: "onOverlayHide", value: function onOverlayHide() { this.unbindOutsideClickListener(); this.unbindResizeListener(); this.unbindScrollListener(); OverlayService.off('overlay-click', this.overlayEventListener); this.overlayEventListener = null; } }, { key: "bindOutsideClickListener", value: function bindOutsideClickListener() { var _this3 = this; if (!this.outsideClickListener) { this.outsideClickListener = function (event) { if (!_this3.selfClick && _this3.isOutsideClicked(event.target)) { _this3.hide(); } _this3.selfClick = false; }; document.addEventListener('click', this.outsideClickListener); } } }, { key: "unbindOutsideClickListener", value: function unbindOutsideClickListener() { if (this.outsideClickListener) { document.removeEventListener('click', this.outsideClickListener); this.outsideClickListener = null; this.selfClick = false; } } }, { key: "bindScrollListener", value: function bindScrollListener() { var _this4 = this; if (!this.scrollHandler) { this.scrollHandler = new ConnectedOverlayScrollHandler(this.icon, function () { if (_this4.state.overlayVisible) { _this4.hide(); } }); } this.scrollHandler.bindScrollListener(); } }, { key: "unbindScrollListener", value: function unbindScrollListener() { if (this.scrollHandler) { this.scrollHandler.unbindScrollListener(); } } }, { key: "bindResizeListener", value: function bindResizeListener() { var _this5 = this; if (!this.resizeListener) { this.resizeListener = function () { if (_this5.state.overlayVisible) { _this5.hide(); } }; window.addEventListener('resize', this.resizeListener); } } }, { key: "unbindResizeListener", value: function unbindResizeListener() { if (this.resizeListener) { window.removeEventListener('resize', this.resizeListener); this.resizeListener = null; } } }, { key: "fieldConstraints", value: function fieldConstraints() { return this.filterModel ? this.filterModel.constraints || [this.filterModel] : []; } }, { key: "operator", value: function operator() { return this.filterModel.operator; } }, { key: "operatorOptions", value: function operatorOptions() { return [{ label: localeOption('matchAll'), value: FilterOperator.AND }, { label: localeOption('matchAny'), value: FilterOperator.OR }]; } }, { key: "noFilterLabel", value: function noFilterLabel() { return localeOption('noFilter'); } }, { key: "removeRuleButtonLabel", value: function removeRuleButtonLabel() { return localeOption('removeRule'); } }, { key: "addRuleButtonLabel", value: function addRuleButtonLabel() { return localeOption('addRule'); } }, { key: "clearButtonLabel", value: function clearButtonLabel() { return localeOption('clear'); } }, { key: "applyButtonLabel", value: function applyButtonLabel() { return localeOption('apply'); } }, { key: "filterCallback", value: function filterCallback(value) { var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var filters = _objectSpread$3({}, this.props.filters); var meta = filters[this.field]; this.props.display === 'menu' && meta && meta.operator ? filters[this.field].constraints[index].value = value : filters[this.field].value = value; this.props.onFilterChange(filters); } }, { key: "filterApplyCallback", value: function filterApplyCallback() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args && this.filterCallback(args[0], args[1]); this.props.onFilterApply(); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.props.display === 'menu' && this.state.overlayVisible) { DomHandler.alignOverlay(this.overlay, this.icon, PrimeReact.appendTo, false); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.overlayEventListener) { OverlayService.off('overlay-click', this.overlayEventListener); this.overlayEventListener = null; } if (this.overlay) { ZIndexUtils.clear(this.overlay); this.onOverlayHide(); } } }, { key: "renderFilterElement", value: function renderFilterElement(model, index) { var _this6 = this; return this.getColumnProp('filterElement') ? ObjectUtils.getJSXElement(this.getColumnProp('filterElement'), { field: this.field, index: index, filterModel: model, value: model.value, filterApplyCallback: this.filterApplyCallback, filterCallback: this.filterCallback }) : /*#__PURE__*/React.createElement(InputText, { type: this.getColumnProp('filterType'), value: model.value || '', onChange: function onChange(e) { return _this6.onInputChange(e, index); }, className: "p-column-filter", placeholder: this.getColumnProp('filterPlaceholder'), maxLength: this.getColumnProp('filterMaxLength') }); } }, { key: "renderRowFilterElement", value: function renderRowFilterElement() { if (this.props.display === 'row') { var content = this.renderFilterElement(this.filterModel, 0); return /*#__PURE__*/React.createElement("div", { className: "p-fluid p-column-filter-element" }, content); } return null; } }, { key: "renderMenuFilterElement", value: function renderMenuFilterElement(fieldConstraint, index) { if (this.props.display === 'menu') { return this.renderFilterElement(fieldConstraint, index); } return null; } }, { key: "renderMenuButton", value: function renderMenuButton() { var _this7 = this; if (this.showMenuButton()) { var className = classNames('p-column-filter-menu-button p-link', { 'p-column-filter-menu-button-open': this.state.overlayVisible, 'p-column-filter-menu-button-active': this.hasFilter() }); return /*#__PURE__*/React.createElement("button", { ref: function ref(el) { return _this7.icon = el; }, type: "button", className: className, "aria-haspopup": true, "aria-expanded": this.state.overlayVisible, onClick: this.toggleMenu, onKeyDown: this.onToggleButtonKeyDown }, /*#__PURE__*/React.createElement("span", { className: "pi pi-filter-icon pi-filter" })); } return null; } }, { key: "renderClearButton", value: function renderClearButton() { if (this.getColumnProp('showClearButton') && this.props.display === 'row') { var className = classNames('p-column-filter-clear-button p-link', { 'p-hidden-space': !this.hasRowFilter() }); return /*#__PURE__*/React.createElement("button", { className: className, type: "button", onClick: this.clearFilter }, /*#__PURE__*/React.createElement("span", { className: "pi pi-filter-slash" })); } return null; } }, { key: "renderRowItems", value: function renderRowItems() { var _this8 = this; if (this.isShowMatchModes()) { var matchModes = this.matchModes(); var noFilterLabel = this.noFilterLabel(); return /*#__PURE__*/React.createElement("ul", { className: "p-column-filter-row-items" }, matchModes.map(function (matchMode, i) { var value = matchMode.value, label = matchMode.label; var className = classNames('p-column-filter-row-item', { 'p-highlight': _this8.isRowMatchModeSelected(value) }); var tabIndex = i === 0 ? 0 : null; return /*#__PURE__*/React.createElement("li", { className: className, key: label, onClick: function onClick() { return _this8.onRowMatchModeChange(value); }, onKeyDown: function onKeyDown(e) { return _this8.onRowMatchModeKeyDown(e, matchMode); }, tabIndex: tabIndex }, label); }), /*#__PURE__*/React.createElement("li", { className: "p-column-filter-separator" }), /*#__PURE__*/React.createElement("li", { className: "p-column-filter-row-item", onClick: this.clearFilter, onKeyDown: function onKeyDown(e) { return _this8.onRowMatchModeKeyDown(e, null, true); } }, noFilterLabel)); } return null; } }, { key: "renderOperator", value: function renderOperator() { if (this.isShowOperator()) { var options = this.operatorOptions(); var value = this.operator(); return /*#__PURE__*/React.createElement("div", { className: "p-column-filter-operator" }, /*#__PURE__*/React.createElement(Dropdown, { options: options, value: value, onChange: this.onOperatorChange, className: "p-column-filter-operator-dropdown" })); } return null; } }, { key: "renderMatchModeDropdown", value: function renderMatchModeDropdown(constraint, index) { var _this9 = this; if (this.isShowMatchModes()) { var options = this.matchModes(); return /*#__PURE__*/React.createElement(Dropdown, { options: options, value: constraint.matchMode, onChange: function onChange(e) { return _this9.onMenuMatchModeChange(e.value, index); }, className: "p-column-filter-matchmode-dropdown" }); } return null; } }, { key: "renderRemoveButton", value: function renderRemoveButton(index) { var _this10 = this; if (this.showRemoveIcon()) { var removeRuleLabel = this.removeRuleButtonLabel(); return /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-trash", className: "p-column-filter-remove-button p-button-text p-button-danger p-button-sm", onClick: function onClick() { return _this10.removeConstraint(index); }, label: removeRuleLabel }); } return null; } }, { key: "renderConstraints", value: function renderConstraints() { var _this11 = this; var fieldConstraints = this.fieldConstraints(); return /*#__PURE__*/React.createElement("div", { className: "p-column-filter-constraints" }, fieldConstraints.map(function (fieldConstraint, i) { var matchModeDropdown = _this11.renderMatchModeDropdown(fieldConstraint, i); var menuFilterElement = _this11.renderMenuFilterElement(fieldConstraint, i); var removeButton = _this11.renderRemoveButton(i); return /*#__PURE__*/React.createElement("div", { key: i, className: "p-column-filter-constraint" }, matchModeDropdown, menuFilterElement, /*#__PURE__*/React.createElement("div", null, removeButton)); })); } }, { key: "renderAddRule", value: function renderAddRule() { if (this.isShowAddConstraint()) { var addRuleLabel = this.addRuleButtonLabel(); return /*#__PURE__*/React.createElement("div", { className: "p-column-filter-add-rule" }, /*#__PURE__*/React.createElement(Button, { type: "button", label: addRuleLabel, icon: "pi pi-plus", className: "p-column-filter-add-button p-button-text p-button-sm", onClick: this.addConstraint })); } return null; } }, { key: "renderFilterClearButton", value: function renderFilterClearButton() { if (this.getColumnProp('showClearButton')) { if (!this.getColumnProp('filterClear')) { var clearLabel = this.clearButtonLabel(); return /*#__PURE__*/React.createElement(Button, { type: "button", className: "p-button-outlined p-button-sm", onClick: this.clearFilter, label: clearLabel }); } return ObjectUtils.getJSXElement(this.getColumnProp('filterClear'), { field: this.field, filterModel: this.filterModel, filterClearCallback: this.clearFilter }); } return null; } }, { key: "renderFilterApplyButton", value: function renderFilterApplyButton() { if (this.getColumnProp('showApplyButton')) { if (!this.getColumnProp('filterApply')) { var applyLabel = this.applyButtonLabel(); return /*#__PURE__*/React.createElement(Button, { type: "button", className: "p-button-sm", onClick: this.applyFilter, label: applyLabel }); } return ObjectUtils.getJSXElement(this.getColumnProp('filterApply'), { field: this.field, filterModel: this.filterModel, filterApplyCallback: this.applyFilter }); } return null; } }, { key: "renderButtonBar", value: function renderButtonBar() { var clearButton = this.renderFilterClearButton(); var applyButton = this.renderFilterApplyButton(); return /*#__PURE__*/React.createElement("div", { className: "p-column-filter-buttonbar" }, clearButton, applyButton); } }, { key: "renderItems", value: function renderItems() { var operator = this.renderOperator(); var constraints = this.renderConstraints(); var addRule = this.renderAddRule(); var buttonBar = this.renderButtonBar(); return /*#__PURE__*/React.createElement(React.Fragment, null, operator, constraints, addRule, buttonBar); } }, { key: "renderOverlay", value: function renderOverlay() { var style = this.getColumnProp('filterMenuStyle'); var className = classNames('p-column-filter-overlay p-component p-fluid', this.getColumnProp('filterMenuClassName'), { 'p-column-filter-overlay-menu': this.props.display === 'menu', 'p-input-filled': PrimeReact.inputStyle === 'filled', 'p-ripple-disabled': PrimeReact.ripple === false }); var filterHeader = ObjectUtils.getJSXElement(this.getColumnProp('filterHeader'), { field: this.field, filterModel: this.filterModel, filterApplyCallback: this.filterApplyCallback }); var filterFooter = ObjectUtils.getJSXElement(this.getColumnProp('filterFooter'), { field: this.field, filterModel: this.filterModel, filterApplyCallback: this.filterApplyCallback }); var items = this.props.display === 'row' ? this.renderRowItems() : this.renderItems(); return /*#__PURE__*/React.createElement(Portal, null, /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.overlayRef, classNames: "p-connected-overlay", in: this.state.overlayVisible, timeout: { enter: 120, exit: 100 }, unmountOnExit: true, onEnter: this.onOverlayEnter, onExit: this.onOverlayExit, onExited: this.onOverlayExited }, /*#__PURE__*/React.createElement("div", { ref: this.overlayRef, style: style, className: className, onKeyDown: this.onContentKeyDown, onClick: this.onContentClick, onMouseDown: this.onContentMouseDown }, filterHeader, items, filterFooter))); } }, { key: "render", value: function render() { var className = classNames('p-column-filter p-fluid', { 'p-column-filter-row': this.props.display === 'row', 'p-column-filter-menu': this.props.display === 'menu' }); var rowFilterElement = this.renderRowFilterElement(); var menuButton = this.renderMenuButton(); var clearButton = this.renderClearButton(); var overlay = this.renderOverlay(); return /*#__PURE__*/React.createElement("div", { className: className }, rowFilterElement, menuButton, clearButton, overlay); } }]); return ColumnFilter; }(Component); function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var HeaderCell = /*#__PURE__*/function (_Component) { _inherits(HeaderCell, _Component); var _super = _createSuper$2(HeaderCell); function HeaderCell(props) { var _this; _classCallCheck(this, HeaderCell); _this = _super.call(this, props); _this.state = { styleObject: {} }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); // drag _this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this)); _this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_this)); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); // resize _this.onResizerMouseDown = _this.onResizerMouseDown.bind(_assertThisInitialized(_this)); _this.onResizerClick = _this.onResizerClick.bind(_assertThisInitialized(_this)); _this.onResizerDoubleClick = _this.onResizerDoubleClick.bind(_assertThisInitialized(_this)); return _this; } _createClass(HeaderCell, [{ key: "isBadgeVisible", value: function isBadgeVisible() { return this.props.multiSortMeta && this.props.multiSortMeta.length > 1; } }, { key: "isSortableDisabled", value: function isSortableDisabled() { return !this.getColumnProp('sortable') || this.getColumnProp('sortable') && (this.props.allSortableDisabled || this.getColumnProp('sortableDisabled')); } }, { key: "getColumnProp", value: function getColumnProp() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return this.props.column ? typeof args[0] === 'string' ? this.props.column.props[args[0]] : (args[0] || this.props.column).props[args[1]] : null; } }, { key: "getStyle", value: function getStyle() { var headerStyle = this.getColumnProp('headerStyle'); var columnStyle = this.getColumnProp('style'); return this.getColumnProp('frozen') ? Object.assign({}, columnStyle, headerStyle, this.state.styleObject) : Object.assign({}, columnStyle, headerStyle); } }, { key: "getMultiSortMetaIndex", value: function getMultiSortMetaIndex() { var _this2 = this; return this.props.multiSortMeta.findIndex(function (meta) { return meta.field === _this2.getColumnProp('field') || meta.field === _this2.getColumnProp('sortField'); }); } }, { key: "getSortMeta", value: function getSortMeta() { var sorted = false; var sortOrder = 0; var metaIndex = -1; if (this.props.sortMode === 'single') { sorted = this.props.sortField && (this.props.sortField === this.getColumnProp('field') || this.props.sortField === this.getColumnProp('sortField')); sortOrder = sorted ? this.props.sortOrder : 0; } else if (this.props.sortMode === 'multiple') { metaIndex = this.getMultiSortMetaIndex(); if (metaIndex > -1) { sorted = true; sortOrder = this.props.multiSortMeta[metaIndex].order; } } return { sorted: sorted, sortOrder: sortOrder, metaIndex: metaIndex }; } }, { key: "getAriaSort", value: function getAriaSort(_ref) { var sorted = _ref.sorted, sortOrder = _ref.sortOrder; if (this.getColumnProp('sortable')) { var sortIcon = sorted ? sortOrder < 0 ? 'pi-sort-amount-down' : 'pi-sort-amount-up-alt' : 'pi-sort-alt'; if (sortIcon === 'pi-sort-amount-down') return 'descending';else if (sortIcon === 'pi-sort-amount-up-alt') return 'ascending';else return 'none'; } return null; } }, { key: "updateStickyPosition", value: function updateStickyPosition() { if (this.getColumnProp('frozen')) { var styleObject = _objectSpread$2({}, this.state.styleObject); var align = this.getColumnProp('alignFrozen'); if (align === 'right') { var right = 0; var next = this.el.nextElementSibling; if (next) { right = DomHandler.getOuterWidth(next) + parseFloat(next.style.right || 0); } styleObject['right'] = right + 'px'; } else { var left = 0; var prev = this.el.previousElementSibling; if (prev) { left = DomHandler.getOuterWidth(prev) + parseFloat(prev.style.left || 0); } styleObject['left'] = left + 'px'; } var filterRow = this.el.parentElement.nextElementSibling; if (filterRow) { var index = DomHandler.index(this.el); filterRow.children[index].style.left = styleObject['left']; filterRow.children[index].style.right = styleObject['right']; } var isSameStyle = this.state.styleObject['left'] === styleObject['left'] && this.state.styleObject['right'] === styleObject['right']; !isSameStyle && this.setState({ styleObject: styleObject }); } } }, { key: "updateSortableDisabled", value: function updateSortableDisabled(prevColumn) { if (this.getColumnProp(prevColumn, 'sortableDisabled') !== this.getColumnProp('sortableDisabled') || this.getColumnProp(prevColumn, 'sortable') !== this.getColumnProp('sortable')) { this.props.onSortableChange(); } } }, { key: "onClick", value: function onClick(event) { if (!this.isSortableDisabled()) { var targetNode = event.target; if (DomHandler.hasClass(targetNode, 'p-sortable-column') || DomHandler.hasClass(targetNode, 'p-column-title') || DomHandler.hasClass(targetNode, 'p-column-header-content') || DomHandler.hasClass(targetNode, 'p-sortable-column-icon') || DomHandler.hasClass(targetNode.parentElement, 'p-sortable-column-icon')) { DomHandler.clearSelection(); this.props.onSortChange({ originalEvent: event, column: this.props.column, sortableDisabledFields: this.props.sortableDisabledFields }); } } } }, { key: "onMouseDown", value: function onMouseDown(event) { this.props.onColumnMouseDown({ originalEvent: event, column: this.props.column }); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.key === 'Enter' && event.currentTarget === this.el && DomHandler.hasClass(event.currentTarget, 'p-sortable-column')) { this.onClick(event); event.preventDefault(); } } }, { key: "onDragStart", value: function onDragStart(event) { this.props.onColumnDragStart({ originalEvent: event, column: this.props.column }); } }, { key: "onDragOver", value: function onDragOver(event) { this.props.onColumnDragOver({ originalEvent: event, column: this.props.column }); } }, { key: "onDragLeave", value: function onDragLeave(event) { this.props.onColumnDragLeave({ originalEvent: event, column: this.props.column }); } }, { key: "onDrop", value: function onDrop(event) { this.props.onColumnDrop({ originalEvent: event, column: this.props.column }); } }, { key: "onResizerMouseDown", value: function onResizerMouseDown(event) { this.props.onColumnResizeStart({ originalEvent: event, column: this.props.column }); } }, { key: "onResizerClick", value: function onResizerClick(event) { if (this.props.onColumnResizerClick) { this.props.onColumnResizerClick({ originalEvent: event, element: event.currentTarget.parentElement, column: this.props.column }); event.preventDefault(); } } }, { key: "onResizerDoubleClick", value: function onResizerDoubleClick(event) { if (this.props.onColumnResizerDoubleClick) { this.props.onColumnResizerDoubleClick({ originalEvent: event, element: event.currentTarget.parentElement, column: this.props.column }); event.preventDefault(); } } }, { key: "componentDidMount", value: function componentDidMount() { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.getColumnProp('frozen')) { this.updateStickyPosition(); } this.updateSortableDisabled(prevProps.column); } }, { key: "renderResizer", value: function renderResizer() { if (this.props.resizableColumns && !this.getColumnProp('frozen')) { return /*#__PURE__*/React.createElement("span", { className: "p-column-resizer", onMouseDown: this.onResizerMouseDown, onClick: this.onResizerClick, onDoubleClick: this.onResizerDoubleClick }); } return null; } }, { key: "renderTitle", value: function renderTitle() { var title = ObjectUtils.getJSXElement(this.getColumnProp('header'), { props: this.props.tableProps }); return /*#__PURE__*/React.createElement("span", { className: "p-column-title" }, title); } }, { key: "renderSortIcon", value: function renderSortIcon(_ref2) { var sorted = _ref2.sorted, sortOrder = _ref2.sortOrder; if (this.getColumnProp('sortable')) { var sortIcon = sorted ? sortOrder < 0 ? 'pi-sort-amount-down' : 'pi-sort-amount-up-alt' : 'pi-sort-alt'; var className = classNames('p-sortable-column-icon pi pi-fw', sortIcon); return /*#__PURE__*/React.createElement("span", { className: className }); } return null; } }, { key: "renderBadge", value: function renderBadge(_ref3) { var metaIndex = _ref3.metaIndex; if (metaIndex !== -1 && this.isBadgeVisible()) { var value = this.props.groupRowsBy && this.props.groupRowsBy === this.props.groupRowSortField ? metaIndex : metaIndex + 1; return /*#__PURE__*/React.createElement("span", { className: "p-sortable-column-badge" }, value); } return null; } }, { key: "renderCheckbox", value: function renderCheckbox() { if (this.getColumnProp('selectionMode') === 'multiple' && this.props.filterDisplay !== 'row') { var allRowsSelected = this.props.allRowsSelected(this.props.value); return /*#__PURE__*/React.createElement(HeaderCheckbox, { checked: allRowsSelected, onChange: this.props.onColumnCheckboxChange, disabled: this.props.empty }); } return null; } }, { key: "renderFilter", value: function renderFilter() { if (this.props.filterDisplay === 'menu' && this.getColumnProp('filter')) { return /*#__PURE__*/React.createElement(ColumnFilter, { display: "menu", column: this.props.column, filters: this.props.filters, onFilterChange: this.props.onFilterChange, onFilterApply: this.props.onFilterApply, filtersStore: this.props.filtersStore }); } return null; } }, { key: "renderHeader", value: function renderHeader(sortMeta) { var title = this.renderTitle(); var sortIcon = this.renderSortIcon(sortMeta); var badge = this.renderBadge(sortMeta); var checkbox = this.renderCheckbox(); var filter = this.renderFilter(); return /*#__PURE__*/React.createElement("div", { className: "p-column-header-content" }, title, sortIcon, badge, checkbox, filter); } }, { key: "renderElement", value: function renderElement() { var _this3 = this; var isSortableDisabled = this.isSortableDisabled(); var sortMeta = this.getSortMeta(); var style = this.getStyle(); var className = classNames(this.getColumnProp('headerClassName'), this.getColumnProp('className'), { 'p-sortable-column': this.getColumnProp('sortable'), 'p-resizable-column': this.props.resizableColumns, 'p-highlight': sortMeta.sorted, 'p-frozen-column': this.getColumnProp('frozen'), 'p-selection-column': this.getColumnProp('selectionMode'), 'p-sortable-disabled': this.getColumnProp('sortable') && isSortableDisabled, 'p-reorderable-column': this.props.reorderableColumns && this.getColumnProp('reorderable') }); var tabIndex = this.getColumnProp('sortable') && !isSortableDisabled ? this.props.tabIndex : null; var colSpan = this.getColumnProp('colSpan'); var rowSpan = this.getColumnProp('rowSpan'); var ariaSort = this.getAriaSort(sortMeta); var resizer = this.renderResizer(); var header = this.renderHeader(sortMeta); return /*#__PURE__*/React.createElement("th", { ref: function ref(el) { return _this3.el = el; }, style: style, className: className, tabIndex: tabIndex, role: "columnheader", onClick: this.onClick, onKeyDown: this.onKeyDown, onMouseDown: this.onMouseDown, onDragStart: this.onDragStart, onDragOver: this.onDragOver, onDragLeave: this.onDragLeave, onDrop: this.onDrop, colSpan: colSpan, rowSpan: rowSpan, "aria-sort": ariaSort }, resizer, header); } }, { key: "render", value: function render() { return this.renderElement(); } }]); return HeaderCell; }(Component); function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TableHeader = /*#__PURE__*/function (_Component) { _inherits(TableHeader, _Component); var _super = _createSuper$1(TableHeader); function TableHeader(props) { var _this; _classCallCheck(this, TableHeader); _this = _super.call(this, props); _this.state = { sortableDisabledFields: [], allSortableDisabled: false, styleObject: {} }; _this.onSortableChange = _this.onSortableChange.bind(_assertThisInitialized(_this)); _this.onCheckboxChange = _this.onCheckboxChange.bind(_assertThisInitialized(_this)); return _this; } _createClass(TableHeader, [{ key: "isSingleSort", value: function isSingleSort() { return this.props.sortMode === 'single'; } }, { key: "isMultipleSort", value: function isMultipleSort() { return this.props.sortMode === 'multiple'; } }, { key: "isAllSortableDisabled", value: function isAllSortableDisabled() { return this.isSingleSort() && this.state.allSortableDisabled; } }, { key: "isColumnSorted", value: function isColumnSorted(column) { return this.props.sortField !== null ? column.props.field === this.props.sortField || column.props.sortField === this.props.sortField : false; } }, { key: "updateSortableDisabled", value: function updateSortableDisabled() { var _this2 = this; if (this.isSingleSort() || this.isMultipleSort() && this.props.onSortChange) { var sortableDisabledFields = []; var allSortableDisabled = false; this.props.columns.forEach(function (column) { if (column.props.sortableDisabled) { sortableDisabledFields.push(column.props.sortField || column.props.field); if (!allSortableDisabled && _this2.isColumnSorted(column)) { allSortableDisabled = true; } } }); this.setState({ sortableDisabledFields: sortableDisabledFields, allSortableDisabled: allSortableDisabled }); } } }, { key: "onSortableChange", value: function onSortableChange() { this.updateSortableDisabled(); } }, { key: "onCheckboxChange", value: function onCheckboxChange(e) { this.props.onColumnCheckboxChange(e, this.props.value); } }, { key: "componentDidMount", value: function componentDidMount() { this.updateSortableDisabled(); } }, { key: "renderGroupHeaderCells", value: function renderGroupHeaderCells(row) { var columns = React.Children.toArray(row.props.children); return this.renderHeaderCells(columns); } }, { key: "renderHeaderCells", value: function renderHeaderCells(columns) { var _this3 = this; return React.Children.map(columns, function (col, i) { var isVisible = col ? !col.props.hidden : true; var key = col ? col.props.columnKey || col.props.field || i : i; return isVisible && /*#__PURE__*/React.createElement(HeaderCell, { key: key, value: _this3.props.value, tableProps: _this3.props.tableProps, column: col, tabIndex: _this3.props.tabIndex, empty: _this3.props.empty, resizableColumns: _this3.props.resizableColumns, groupRowsBy: _this3.props.groupRowsBy, groupRowSortField: _this3.props.groupRowSortField, sortMode: _this3.props.sortMode, sortField: _this3.props.sortField, sortOrder: _this3.props.sortOrder, multiSortMeta: _this3.props.multiSortMeta, allSortableDisabled: _this3.isAllSortableDisabled(), onSortableChange: _this3.onSortableChange, sortableDisabledFields: _this3.state.sortableDisabledFields, filterDisplay: _this3.props.filterDisplay, filters: _this3.props.filters, filtersStore: _this3.props.filtersStore, onFilterChange: _this3.props.onFilterChange, onFilterApply: _this3.props.onFilterApply, onColumnMouseDown: _this3.props.onColumnMouseDown, onColumnDragStart: _this3.props.onColumnDragStart, onColumnDragOver: _this3.props.onColumnDragOver, onColumnDragLeave: _this3.props.onColumnDragLeave, onColumnDrop: _this3.props.onColumnDrop, onColumnResizeStart: _this3.props.onColumnResizeStart, onColumnResizerClick: _this3.props.onColumnResizerClick, onColumnResizerDoubleClick: _this3.props.onColumnResizerDoubleClick, allRowsSelected: _this3.props.allRowsSelected, onColumnCheckboxChange: _this3.onCheckboxChange, reorderableColumns: _this3.props.reorderableColumns, onSortChange: _this3.props.onSortChange }); }); } }, { key: "renderFilterCells", value: function renderFilterCells() { var _this4 = this; return React.Children.map(this.props.columns, function (col, i) { var isVisible = !col.props.hidden; if (isVisible) { var _col$props = col.props, filterHeaderStyle = _col$props.filterHeaderStyle, style = _col$props.style, filterHeaderClassName = _col$props.filterHeaderClassName, className = _col$props.className, frozen = _col$props.frozen, columnKey = _col$props.columnKey, field = _col$props.field, selectionMode = _col$props.selectionMode, filter = _col$props.filter; var colStyle = _objectSpread$1(_objectSpread$1({}, filterHeaderStyle || {}), style || {}); var colClassName = classNames('p-filter-column', filterHeaderClassName, className, { 'p-frozen-column': frozen }); var colKey = columnKey || field || i; var allRowsSelected = selectionMode === 'multiple' && _this4.props.allRowsSelected(_this4.props.value); return /*#__PURE__*/React.createElement("th", { key: colKey, style: colStyle, className: colClassName }, selectionMode === 'multiple' && /*#__PURE__*/React.createElement(HeaderCheckbox, { checked: allRowsSelected, onChange: _this4.onCheckboxChange, disabled: _this4.props.empty }), filter && /*#__PURE__*/React.createElement(ColumnFilter, { display: "row", column: col, filters: _this4.props.filters, filtersStore: _this4.props.filtersStore, onFilterChange: _this4.props.onFilterChange, onFilterApply: _this4.props.onFilterApply })); } return null; }); } }, { key: "renderContent", value: function renderContent() { var _this5 = this; if (this.props.headerColumnGroup) { var rows = React.Children.toArray(this.props.headerColumnGroup.props.children); return rows.map(function (row, i) { return /*#__PURE__*/React.createElement("tr", { key: i, role: "row" }, _this5.renderGroupHeaderCells(row)); }); } else { var headerRow = /*#__PURE__*/React.createElement("tr", { role: "row" }, this.renderHeaderCells(this.props.columns)); var filterRow = this.props.filterDisplay === 'row' && /*#__PURE__*/React.createElement("tr", { role: "row" }, this.renderFilterCells()); return /*#__PURE__*/React.createElement(React.Fragment, null, headerRow, filterRow); } } }, { key: "render", value: function render() { var content = this.renderContent(); return /*#__PURE__*/React.createElement("thead", { className: "p-datatable-thead" }, content); } }]); return TableHeader; }(Component); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var DataTable = /*#__PURE__*/function (_Component) { _inherits(DataTable, _Component); var _super = _createSuper(DataTable); function DataTable(props) { var _this; _classCallCheck(this, DataTable); _this = _super.call(this, props); _this.state = { d_rows: props.rows, columnOrder: [], groupRowsSortMeta: null, editingMeta: {} }; if (!_this.props.onPage) { _this.state.first = props.first; _this.state.rows = props.rows; } if (!_this.props.onSort) { _this.state.sortField = props.sortField; _this.state.sortOrder = props.sortOrder; _this.state.multiSortMeta = props.multiSortMeta; } _this.state.d_filters = _this.cloneFilters(props.filters); if (!_this.props.onFilter) { _this.state.filters = props.filters; } if (_this.isStateful()) { _this.restoreState(_this.state); } _this.attributeSelector = UniqueComponentId(); // header _this.onSortChange = _this.onSortChange.bind(_assertThisInitialized(_this)); _this.onFilterChange = _this.onFilterChange.bind(_assertThisInitialized(_this)); _this.onFilterApply = _this.onFilterApply.bind(_assertThisInitialized(_this)); _this.onColumnHeaderMouseDown = _this.onColumnHeaderMouseDown.bind(_assertThisInitialized(_this)); _this.onColumnHeaderDragStart = _this.onColumnHeaderDragStart.bind(_assertThisInitialized(_this)); _this.onColumnHeaderDragOver = _this.onColumnHeaderDragOver.bind(_assertThisInitialized(_this)); _this.onColumnHeaderDragLeave = _this.onColumnHeaderDragLeave.bind(_assertThisInitialized(_this)); _this.onColumnHeaderDrop = _this.onColumnHeaderDrop.bind(_assertThisInitialized(_this)); _this.onColumnResizeStart = _this.onColumnResizeStart.bind(_assertThisInitialized(_this)); _this.onColumnHeaderCheckboxChange = _this.onColumnHeaderCheckboxChange.bind(_assertThisInitialized(_this)); _this.allRowsSelected = _this.allRowsSelected.bind(_assertThisInitialized(_this)); // body _this.onEditingMetaChange = _this.onEditingMetaChange.bind(_assertThisInitialized(_this)); //paginator _this.onPageChange = _this.onPageChange.bind(_assertThisInitialized(_this)); return _this; } _createClass(DataTable, [{ key: "isCustomStateStorage", value: function isCustomStateStorage() { return this.props.stateStorage === 'custom'; } }, { key: "isStateful", value: function isStateful() { return this.props.stateKey != null || this.isCustomStateStorage(); } }, { key: "isVirtualScrollerDisabled", value: function isVirtualScrollerDisabled() { return ObjectUtils.isEmpty(this.props.virtualScrollerOptions) || !this.props.scrollable; } }, { key: "hasFilter", value: function hasFilter() { return ObjectUtils.isNotEmpty(this.getFilters()) || this.props.globalFilter; } }, { key: "getFirst", value: function getFirst() { return this.props.onPage ? this.props.first : this.state.first; } }, { key: "getRows", value: function getRows() { return this.props.onPage ? this.props.rows : this.state.rows; } }, { key: "getSortField", value: function getSortField() { return this.props.onSort ? this.props.sortField : this.state.sortField; } }, { key: "getSortOrder", value: function getSortOrder() { return this.props.onSort ? this.props.sortOrder : this.state.sortOrder; } }, { key: "getMultiSortMeta", value: function getMultiSortMeta() { return (this.props.onSort ? this.props.multiSortMeta : this.state.multiSortMeta) || []; } }, { key: "getFilters", value: function getFilters() { return this.props.onFilter ? this.props.filters : this.state.filters; } }, { key: "getColumnProp", value: function getColumnProp(col, prop) { return col.props[prop]; } }, { key: "getColumns", value: function getColumns(ignoreReorderable) { var _this2 = this; var columns = React.Children.toArray(this.props.children); if (!columns) { return null; } if (!ignoreReorderable && this.props.reorderableColumns && this.state.columnOrder) { var orderedColumns = this.state.columnOrder.reduce(function (arr, columnKey) { var column = _this2.findColumnByKey(columns, columnKey); column && arr.push(column); return arr; }, []); return [].concat(_toConsumableArray(orderedColumns), _toConsumableArray(columns.filter(function (col) { return orderedColumns.indexOf(col) < 0; }))); } return columns; } }, { key: "getStorage", value: function getStorage() { switch (this.props.stateStorage) { case 'local': return window.localStorage; case 'session': return window.sessionStorage; case 'custom': return null; default: throw new Error(this.props.stateStorage + ' is not a valid value for the state storage, supported values are "local", "session" and "custom".'); } } }, { key: "saveState", value: function saveState() { var state = {}; if (this.props.paginator) { state.first = this.getFirst(); state.rows = this.getRows(); } var sortField = this.getSortField(); if (sortField) { state.sortField = sortField; state.sortOrder = this.getSortOrder(); } var multiSortMeta = this.getMultiSortMeta(); if (multiSortMeta) { state.multiSortMeta = multiSortMeta; } if (this.hasFilter()) { state.filters = this.getFilters(); } if (this.props.resizableColumns) { this.saveColumnWidths(state); } if (this.props.reorderableColumns) { state.columnOrder = this.state.columnOrder; } if (this.props.expandedRows) { state.expandedRows = this.props.expandedRows; } if (this.props.selection && this.props.onSelectionChange) { state.selection = this.props.selection; } if (this.isCustomStateStorage()) { if (this.props.customSaveState) { this.props.customSaveState(state); } } else { var storage = this.getStorage(); if (ObjectUtils.isNotEmpty(state)) { storage.setItem(this.props.stateKey, JSON.stringify(state)); } } if (this.props.onStateSave) { this.props.onStateSave(state); } } }, { key: "clearState", value: function clearState() { var storage = this.getStorage(); if (storage && this.props.stateKey) { storage.removeItem(this.props.stateKey); } } }, { key: "restoreState", value: function restoreState(state) { var restoredState = {}; if (this.isCustomStateStorage()) { if (this.props.customRestoreState) { restoredState = this.props.customRestoreState(); } } else { var storage = this.getStorage(); var stateString = storage.getItem(this.props.stateKey); var dateFormat = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/; var reviver = function reviver(key, value) { return typeof value === "string" && dateFormat.test(value) ? new Date(value) : value; }; if (stateString) { restoredState = JSON.parse(stateString, reviver); } } this._restoreState(restoredState, state); } }, { key: "restoreTableState", value: function restoreTableState(restoredState) { var state = this._restoreState(restoredState); if (ObjectUtils.isNotEmpty(state)) { this.setState(state); } } }, { key: "_restoreState", value: function _restoreState(restoredState) { var _this3 = this; var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (ObjectUtils.isNotEmpty(restoredState)) { if (this.props.paginator) { if (this.props.onPage) { var getOnPageParams = function getOnPageParams(first, rows) { var totalRecords = _this3.getTotalRecords(_this3.processedData()); var pageCount = Math.ceil(totalRecords / rows) || 1; var page = Math.floor(first / rows); return { first: first, rows: rows, page: page, pageCount: pageCount }; }; this.props.onPage(getOnPageParams(restoredState.first, restoredState.rows)); } else { state.first = restoredState.first; state.rows = restoredState.rows; } } if (restoredState.sortField) { if (this.props.onSort) { this.props.onSort({ sortField: restoredState.sortField, sortOrder: restoredState.sortOrder }); } else { state.sortField = restoredState.sortField; state.sortOrder = restoredState.sortOrder; } } if (restoredState.multiSortMeta) { if (this.props.onSort) { this.props.onSort({ multiSortMeta: restoredState.multiSortMeta }); } else { state.multiSortMeta = restoredState.multiSortMeta; } } if (restoredState.filters) { state.d_filters = this.cloneFilters(restoredState.filters); if (this.props.onFilter) { this.props.onFilter({ filters: restoredState.filters }); } else { state.filters = this.cloneFilters(restoredState.filters); } } if (this.props.resizableColumns) { this.columnWidthsState = restoredState.columnWidths; this.tableWidthState = restoredState.tableWidth; } if (this.props.reorderableColumns) { state.columnOrder = restoredState.columnOrder; } if (restoredState.expandedRows && this.props.onRowToggle) { this.props.onRowToggle({ data: restoredState.expandedRows }); } if (restoredState.selection && this.props.onSelectionChange) { this.props.onSelectionChange({ value: restoredState.selection }); } if (this.props.onStateRestore) { this.props.onStateRestore(restoredState); } } return state; } }, { key: "saveColumnWidths", value: function saveColumnWidths(state) { var widths = []; var headers = DomHandler.find(this.el, '.p-datatable-thead > tr > th'); headers.forEach(function (header) { return widths.push(DomHandler.getOuterWidth(header)); }); state.columnWidths = widths.join(','); if (this.props.columnResizeMode === 'expand') { state.tableWidth = DomHandler.getOuterWidth(this.table) + 'px'; } } }, { key: "restoreColumnWidths", value: function restoreColumnWidths() { var _this4 = this; if (this.columnWidthsState) { var widths = this.columnWidthsState.split(','); if (this.props.columnResizeMode === 'expand' && this.tableWidthState) { this.table.style.width = this.tableWidthState; this.table.style.minWidth = this.tableWidthState; this.el.style.width = this.tableWidthState; } this.createStyleElement(); if (this.props.scrollable && widths && widths.length > 0) { var innerHTML = ''; widths.forEach(function (width, index) { innerHTML += "\n .p-datatable[".concat(_this4.attributeSelector, "] .p-datatable-thead > tr > th:nth-child(").concat(index + 1, ") {\n flex: 0 0 ").concat(width, "px;\n }\n\n .p-datatable[").concat(_this4.attributeSelector, "] .p-datatable-tbody > tr > td:nth-child(").concat(index + 1, ") {\n flex: 0 0 ").concat(width, "px;\n }\n "); }); this.styleElement.innerHTML = innerHTML; } else { DomHandler.find(this.table, '.p-datatable-thead > tr > th').forEach(function (header, index) { return header.style.width = widths[index] + 'px'; }); } } } }, { key: "findParentHeader", value: function findParentHeader(element) { if (element.nodeName === 'TH') { return element; } else { var parent = element.parentElement; while (parent.nodeName !== 'TH') { parent = parent.parentElement; if (!parent) break; } return parent; } } }, { key: "getGroupRowSortField", value: function getGroupRowSortField() { return this.props.sortMode === 'single' ? this.props.sortField : this.state.groupRowsSortMeta ? this.state.groupRowsSortMeta.field : null; } }, { key: "allRowsSelected", value: function allRowsSelected(processedData) { var _this5 = this; var val = this.props.frozenValue ? [].concat(_toConsumableArray(this.props.frozenValue), _toConsumableArray(processedData)) : processedData; var selectableVal = this.props.showSelectionElement ? val.filter(function (data, index) { return _this5.props.showSelectionElement(data, { rowIndex: index, props: _this5.props }); }) : val; var length = this.props.lazy ? this.props.totalRecords : selectableVal ? selectableVal.length : 0; return selectableVal && length > 0 && this.props.selection && this.props.selection.length > 0 && this.props.selection.length === length; } }, { key: "getSelectionModeInColumn", value: function getSelectionModeInColumn(columns) { if (columns) { var col = columns.find(function (c) { return !!c.props.selectionMode; }); return col ? col.props.selectionMode : null; } return null; } }, { key: "findColumnByKey", value: function findColumnByKey(columns, key) { return ObjectUtils.isNotEmpty(columns) ? columns.find(function (col) { return col.props.columnKey === key || col.props.field === key; }) : null; } }, { key: "getTotalRecords", value: function getTotalRecords(data) { return this.props.lazy ? this.props.totalRecords : data ? data.length : 0; } }, { key: "onEditingMetaChange", value: function onEditingMetaChange(e) { var rowData = e.rowData, field = e.field, rowIndex = e.rowIndex, editing = e.editing; var editingMeta = _objectSpread({}, this.state.editingMeta); var meta = editingMeta[rowIndex]; if (editing) { !meta && (meta = editingMeta[rowIndex] = { data: _objectSpread({}, rowData), fields: [] }); meta['fields'].push(field); } else if (meta) { var fields = meta['fields'].filter(function (f) { return f !== field; }); !fields.length ? delete editingMeta[rowIndex] : meta['fields'] = fields; } this.setState({ editingMeta: editingMeta }); } }, { key: "clearEditingMetaData", value: function clearEditingMetaData() { if (this.props.editMode && ObjectUtils.isNotEmpty(this.state.editingMeta)) { this.setState({ editingMeta: {} }); } } }, { key: "onColumnResizeStart", value: function onColumnResizeStart(e) { var event = e.originalEvent, column = e.column; var containerLeft = DomHandler.getOffset(this.el).left; this.resizeColumn = column; this.resizeColumnElement = event.currentTarget.parentElement; this.columnResizing = true; this.lastResizeHelperX = event.pageX - containerLeft + this.el.scrollLeft; this.bindColumnResizeEvents(); } }, { key: "onColumnResize", value: function onColumnResize(event) { var containerLeft = DomHandler.getOffset(this.el).left; DomHandler.addClass(this.el, 'p-unselectable-text'); this.resizeHelper.style.height = this.el.offsetHeight + 'px'; this.resizeHelper.style.top = 0 + 'px'; this.resizeHelper.style.left = event.pageX - containerLeft + this.el.scrollLeft + 'px'; this.resizeHelper.style.display = 'block'; } }, { key: "onColumnResizeEnd", value: function onColumnResizeEnd() { var delta = this.resizeHelper.offsetLeft - this.lastResizeHelperX; var columnWidth = this.resizeColumnElement.offsetWidth; var newColumnWidth = columnWidth + delta; var minWidth = this.resizeColumnElement.style.minWidth || 15; if (columnWidth + delta > parseInt(minWidth, 10)) { if (this.props.columnResizeMode === 'fit') { var nextColumn = this.resizeColumnElement.nextElementSibling; var nextColumnWidth = nextColumn.offsetWidth - delta; if (newColumnWidth > 15 && nextColumnWidth > 15) { this.resizeTableCells(newColumnWidth, nextColumnWidth); } } else if (this.props.columnResizeMode === 'expand') { var tableWidth = this.table.offsetWidth + delta + 'px'; this.table.style.width = tableWidth; this.table.style.minWidth = tableWidth; this.resizeTableCells(newColumnWidth); } if (this.props.onColumnResizeEnd) { this.props.onColumnResizeEnd({ element: this.resizeColumnElement, column: this.resizeColumn, delta: delta }); } if (this.isStateful()) { this.saveState(); } } this.resizeHelper.style.display = 'none'; this.resizeColumn = null; this.resizeColumnElement = null; DomHandler.removeClass(this.el, 'p-unselectable-text'); this.unbindColumnResizeEvents(); } }, { key: "resizeTableCells", value: function resizeTableCells(newColumnWidth, nextColumnWidth) { var _this6 = this; var widths = []; var colIndex = DomHandler.index(this.resizeColumnElement); var headers = DomHandler.find(this.table, '.p-datatable-thead > tr > th'); headers.forEach(function (header) { return widths.push(DomHandler.getOuterWidth(header)); }); this.destroyStyleElement(); this.createStyleElement(); var innerHTML = ''; widths.forEach(function (width, index) { var colWidth = index === colIndex ? newColumnWidth : nextColumnWidth && index === colIndex + 1 ? nextColumnWidth : width; var style = _this6.props.scrollable ? "flex: 0 0 ".concat(colWidth, "px !important") : "width: ".concat(colWidth, "px !important"); innerHTML += "\n .p-datatable[".concat(_this6.attributeSelector, "] .p-datatable-thead > tr > th:nth-child(").concat(index + 1, "),\n .p-datatable[").concat(_this6.attributeSelector, "] .p-datatable-tbody > tr > td:nth-child(").concat(index + 1, "),\n .p-datatable[").concat(_this6.attributeSelector, "] .p-datatable-tfoot > tr > td:nth-child(").concat(index + 1, ") {\n ").concat(style, "\n }\n "); }); this.styleElement.innerHTML = innerHTML; } }, { key: "bindColumnResizeEvents", value: function bindColumnResizeEvents() { var _this7 = this; if (!this.documentColumnResizeListener) { this.documentColumnResizeListener = document.addEventListener('mousemove', function (event) { if (_this7.columnResizing) { _this7.onColumnResize(event); } }); } if (!this.documentColumnResizeEndListener) { this.documentColumnResizeEndListener = document.addEventListener('mouseup', function () { if (_this7.columnResizing) { _this7.columnResizing = false; _this7.onColumnResizeEnd(); } }); } } }, { key: "unbindColumnResizeEvents", value: function unbindColumnResizeEvents() { if (this.documentColumnResizeListener) { document.removeEventListener('document', this.documentColumnResizeListener); this.documentColumnResizeListener = null; } if (this.documentColumnResizeEndListener) { document.removeEventListener('document', this.documentColumnResizeEndListener); this.documentColumnResizeEndListener = null; } } }, { key: "onColumnHeaderMouseDown", value: function onColumnHeaderMouseDown(e) { DomHandler.clearSelection(); var event = e.originalEvent, column = e.column; if (this.props.reorderableColumns && this.getColumnProp(column, 'reorderable') !== false) { if (event.target.nodeName === 'INPUT' || event.target.nodeName === 'TEXTAREA' || DomHandler.hasClass(event.target, 'p-column-resizer')) event.currentTarget.draggable = false;else event.currentTarget.draggable = true; } } }, { key: "onColumnHeaderCheckboxChange", value: function onColumnHeaderCheckboxChange(e, processedData) { var _this8 = this; var originalEvent = e.originalEvent, checked = e.checked; var selection; if (!checked) { selection = this.props.frozenValue ? [].concat(_toConsumableArray(this.props.frozenValue), _toConsumableArray(processedData)) : processedData; selection = this.props.showSelectionElement ? selection.filter(function (data, index) { return _this8.props.showSelectionElement(data, { rowIndex: index, props: _this8.props }); }) : selection; this.props.onAllRowsSelect && this.props.onAllRowsSelect({ originalEvent: originalEvent, data: selection, type: 'all' }); } else { selection = []; this.props.onAllRowsUnselect && this.props.onAllRowsUnselect({ originalEvent: originalEvent, data: selection, type: 'all' }); } if (this.props.onSelectionChange) { this.props.onSelectionChange({ originalEvent: originalEvent, value: selection }); } } }, { key: "onColumnHeaderDragStart", value: function onColumnHeaderDragStart(e) { var event = e.originalEvent, column = e.column; if (this.columnResizing) { event.preventDefault(); return; } this.colReorderIconWidth = DomHandler.getHiddenElementOuterWidth(this.reorderIndicatorUp); this.colReorderIconHeight = DomHandler.getHiddenElementOuterHeight(this.reorderIndicatorUp); this.draggedColumn = column; this.draggedColumnElement = this.findParentHeader(event.currentTarget); event.dataTransfer.setData('text', 'b'); // Firefox requires this to make dragging possible } }, { key: "onColumnHeaderDragOver", value: function onColumnHeaderDragOver(e) { var event = e.originalEvent; var dropHeader = this.findParentHeader(event.currentTarget); if (this.props.reorderableColumns && this.draggedColumnElement && dropHeader) { event.preventDefault(); if (this.draggedColumnElement !== dropHeader) { var containerOffset = DomHandler.getOffset(this.el); var dropHeaderOffset = DomHandler.getOffset(dropHeader); var targetLeft = dropHeaderOffset.left - containerOffset.left; var columnCenter = dropHeaderOffset.left + dropHeader.offsetWidth / 2; this.reorderIndicatorUp.style.top = dropHeaderOffset.top - containerOffset.top - (this.colReorderIconHeight - 1) + 'px'; this.reorderIndicatorDown.style.top = dropHeaderOffset.top - containerOffset.top + dropHeader.offsetHeight + 'px'; if (event.pageX > columnCenter) { this.reorderIndicatorUp.style.left = targetLeft + dropHeader.offsetWidth - Math.ceil(this.colReorderIconWidth / 2) + 'px'; this.reorderIndicatorDown.style.left = targetLeft + dropHeader.offsetWidth - Math.ceil(this.colReorderIconWidth / 2) + 'px'; this.dropPosition = 1; } else { this.reorderIndicatorUp.style.left = targetLeft - Math.ceil(this.colReorderIconWidth / 2) + 'px'; this.reorderIndicatorDown.style.left = targetLeft - Math.ceil(this.colReorderIconWidth / 2) + 'px'; this.dropPosition = -1; } this.reorderIndicatorUp.style.display = 'block'; this.reorderIndicatorDown.style.display = 'block'; } } } }, { key: "onColumnHeaderDragLeave", value: function onColumnHeaderDragLeave(e) { var event = e.originalEvent; if (this.props.reorderableColumns && this.draggedColumnElement) { event.preventDefault(); this.reorderIndicatorUp.style.display = 'none'; this.reorderIndicatorDown.style.display = 'none'; } } }, { key: "onColumnHeaderDrop", value: function onColumnHeaderDrop(e) { var _this9 = this; var event = e.originalEvent, column = e.column; event.preventDefault(); if (this.draggedColumnElement) { var dragIndex = DomHandler.index(this.draggedColumnElement); var dropIndex = DomHandler.index(this.findParentHeader(event.currentTarget)); var allowDrop = dragIndex !== dropIndex; if (allowDrop && (dropIndex - dragIndex === 1 && this.dropPosition === -1 || dragIndex - dropIndex === 1 && this.dropPosition === 1)) { allowDrop = false; } if (allowDrop) { var columns = this.getColumns(); var isSameColumn = function isSameColumn(col1, col2) { return col1.props.columnKey || col2.props.columnKey ? ObjectUtils.equals(col1.props, col2.props, 'columnKey') : ObjectUtils.equals(col1.props, col2.props, 'field'); }; var dragColIndex = columns.findIndex(function (child) { return isSameColumn(child, _this9.draggedColumn); }); var dropColIndex = columns.findIndex(function (child) { return isSameColumn(child, column); }); if (dropColIndex < dragColIndex && this.dropPosition === 1) { dropColIndex++; } if (dropColIndex > dragColIndex && this.dropPosition === -1) { dropColIndex--; } ObjectUtils.reorderArray(columns, dragColIndex, dropColIndex); var columnOrder = columns.reduce(function (orders, col) { orders.push(col.props.columnKey || col.props.field); return orders; }, []); this.setState({ columnOrder: columnOrder }); if (this.props.onColReorder) { this.props.onColReorder({ originalEvent: event, dragIndex: dragColIndex, dropIndex: dropColIndex, columns: columns }); } } this.reorderIndicatorUp.style.display = 'none'; this.reorderIndicatorDown.style.display = 'none'; this.draggedColumnElement.draggable = false; this.draggedColumnElement = null; this.draggedColumn = null; this.dropPosition = null; } } }, { key: "createStyleElement", value: function createStyleElement() { this.styleElement = document.createElement('style'); document.head.appendChild(this.styleElement); } }, { key: "createResponsiveStyle", value: function createResponsiveStyle() { if (!this.responsiveStyleElement) { this.responsiveStyleElement = document.createElement('style'); document.head.appendChild(this.responsiveStyleElement); var innerHTML = "\n@media screen and (max-width: ".concat(this.props.breakpoint, ") {\n .p-datatable[").concat(this.attributeSelector, "] .p-datatable-thead > tr > th,\n .p-datatable[").concat(this.attributeSelector, "] .p-datatable-tfoot > tr > td {\n display: none !important;\n }\n\n .p-datatable[").concat(this.attributeSelector, "] .p-datatable-tbody > tr > td {\n display: flex;\n width: 100% !important;\n align-items: center;\n justify-content: space-between;\n }\n\n .p-datatable[").concat(this.attributeSelector, "] .p-datatable-tbody > tr > td:not(:last-child) {\n border: 0 none;\n }\n\n .p-datatable[").concat(this.attributeSelector, "].p-datatable-gridlines .p-datatable-tbody > tr > td:last-child {\n border-top: 0;\n border-right: 0;\n border-left: 0;\n }\n\n .p-datatable[").concat(this.attributeSelector, "] .p-datatable-tbody > tr > td > .p-column-title {\n display: block;\n }\n}\n"); this.responsiveStyleElement.innerHTML = innerHTML; } } }, { key: "destroyResponsiveStyle", value: function destroyResponsiveStyle() { if (this.responsiveStyleElement) { document.head.removeChild(this.responsiveStyleElement); this.responsiveStyleElement = null; } } }, { key: "destroyStyleElement", value: function destroyStyleElement() { if (this.styleElement) { document.head.removeChild(this.styleElement); this.styleElement = null; } } }, { key: "onPageChange", value: function onPageChange(e) { this.clearEditingMetaData(); if (this.props.onPage) this.props.onPage(e);else this.setState({ first: e.first, rows: e.rows }); if (this.props.onValueChange) { this.props.onValueChange(this.processedData()); } } }, { key: "onSortChange", value: function onSortChange(e) { this.clearEditingMetaData(); var event = e.originalEvent, column = e.column, sortableDisabledFields = e.sortableDisabledFields; var sortField = column.props.sortField || column.props.field; var sortOrder = this.props.defaultSortOrder; var multiSortMeta; var eventMeta; this.columnSortable = column.props.sortable; this.columnSortFunction = column.props.sortFunction; this.columnField = column.props.sortField; if (this.props.sortMode === 'multiple') { var metaKey = event.metaKey || event.ctrlKey; multiSortMeta = _toConsumableArray(this.getMultiSortMeta()); var sortMeta = multiSortMeta.find(function (sortMeta) { return sortMeta.field === sortField; }); sortOrder = sortMeta ? this.getCalculatedSortOrder(sortMeta.order) : sortOrder; var newMetaData = { field: sortField, order: sortOrder }; if (sortOrder) { multiSortMeta = metaKey ? multiSortMeta : multiSortMeta.filter(function (meta) { return sortableDisabledFields.some(function (field) { return field === meta.field; }); }); this.addSortMeta(newMetaData, multiSortMeta); } else if (this.props.removableSort) { this.removeSortMeta(newMetaData, multiSortMeta); } eventMeta = { multiSortMeta: multiSortMeta }; } else { sortOrder = this.getSortField() === sortField ? this.getCalculatedSortOrder(this.getSortOrder()) : sortOrder; if (this.props.removableSort) { sortField = sortOrder ? sortField : null; } eventMeta = { sortField: sortField, sortOrder: sortOrder }; } if (this.props.onSort) { this.props.onSort(eventMeta); } else { eventMeta.first = 0; this.setState(eventMeta); } if (this.props.onValueChange) { this.props.onValueChange(this.processedData({ sortField: sortField, sortOrder: sortOrder, multiSortMeta: multiSortMeta })); } } }, { key: "getCalculatedSortOrder", value: function getCalculatedSortOrder(currentOrder) { return this.props.removableSort ? this.props.defaultSortOrder === currentOrder ? currentOrder * -1 : 0 : currentOrder * -1; } }, { key: "addSortMeta", value: function addSortMeta(meta, multiSortMeta) { var index = multiSortMeta.findIndex(function (sortMeta) { return sortMeta.field === meta.field; }); if (index >= 0) multiSortMeta[index] = meta;else multiSortMeta.push(meta); } }, { key: "removeSortMeta", value: function removeSortMeta(meta, multiSortMeta) { var index = multiSortMeta.findIndex(function (sortMeta) { return sortMeta.field === meta.field; }); if (index >= 0) { multiSortMeta.splice(index, 1); } multiSortMeta = multiSortMeta.length > 0 ? multiSortMeta : null; } }, { key: "sortSingle", value: function sortSingle(data, field, order) { if (this.props.groupRowsBy && this.props.groupRowsBy === this.props.sortField) { var multiSortMeta = [{ field: this.props.sortField, order: this.props.sortOrder || this.props.defaultSortOrder }]; this.props.sortField !== field && multiSortMeta.push({ field: field, order: order }); return this.sortMultiple(data, multiSortMeta); } var value = _toConsumableArray(data); if (this.columnSortable && this.columnSortFunction) { value = this.columnSortFunction({ field: field, order: order }); } else { value.sort(function (data1, data2) { var value1 = ObjectUtils.resolveFieldData(data1, field); var value2 = ObjectUtils.resolveFieldData(data2, field); var result = null; if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2, undefined, { numeric: true });else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0; return order * result; }); } return value; } }, { key: "sortMultiple", value: function sortMultiple(data) { var _this10 = this; var multiSortMeta = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; if (this.props.groupRowsBy && (this.groupRowsSortMeta || multiSortMeta.length && this.props.groupRowsBy === multiSortMeta[0].field)) { var firstSortMeta = multiSortMeta[0]; !this.groupRowsSortMeta && (this.groupRowsSortMeta = firstSortMeta); if (firstSortMeta.field !== this.groupRowsSortMeta.field) { multiSortMeta = [this.groupRowsSortMeta].concat(_toConsumableArray(multiSortMeta)); } } var value = _toConsumableArray(data); if (this.columnSortable && this.columnSortFunction) { var meta = multiSortMeta.find(function (meta) { return meta.field === _this10.columnField; }); var field = this.columnField; var order = meta ? meta.order : this.defaultSortOrder; value = this.columnSortFunction({ field: field, order: order }); } else { value.sort(function (data1, data2) { return _this10.multisortField(data1, data2, multiSortMeta, 0); }); } return value; } }, { key: "multisortField", value: function multisortField(data1, data2, multiSortMeta, index) { var value1 = ObjectUtils.resolveFieldData(data1, multiSortMeta[index].field); var value2 = ObjectUtils.resolveFieldData(data2, multiSortMeta[index].field); var result = null; if (typeof value1 === 'string' || value1 instanceof String) { if (value1.localeCompare && value1 !== value2) { return multiSortMeta[index].order * value1.localeCompare(value2, undefined, { numeric: true }); } } else { result = value1 < value2 ? -1 : 1; } if (value1 === value2) { return multiSortMeta.length - 1 > index ? this.multisortField(data1, data2, multiSortMeta, index + 1) : 0; } return multiSortMeta[index].order * result; } }, { key: "onFilterChange", value: function onFilterChange(filters) { this.clearEditingMetaData(); this.setState({ d_filters: filters }); } }, { key: "onFilterApply", value: function onFilterApply() { var _this11 = this; clearTimeout(this.filterTimeout); this.filterTimeout = setTimeout(function () { var filters = _this11.cloneFilters(_this11.state.d_filters); if (_this11.props.onFilter) { _this11.props.onFilter({ filters: filters }); } else { _this11.setState({ first: 0, filters: filters }); } if (_this11.props.onValueChange) { _this11.props.onValueChange(_this11.processedData({ filters: filters })); } }, this.props.filterDelay); } }, { key: "filterLocal", value: function filterLocal(data, filters) { if (!data) return; filters = filters || {}; var columns = this.getColumns(); var filteredValue = []; var isGlobalFilter = filters['global'] || this.props.globalFilter; var globalFilterFieldsArray; if (isGlobalFilter) { globalFilterFieldsArray = this.props.globalFilterFields || columns.filter(function (col) { return !col.props.excludeGlobalFilter; }).map(function (col) { return col.props.filterField || col.props.field; }); } for (var i = 0; i < data.length; i++) { var localMatch = true; var globalMatch = false; var localFiltered = false; for (var prop in filters) { if (Object.prototype.hasOwnProperty.call(filters, prop) && prop !== 'global') { localFiltered = true; var filterField = prop; var filterMeta = filters[filterField]; if (filterMeta.operator) { for (var j = 0; j < filterMeta.constraints.length; j++) { var filterConstraint = filterMeta.constraints[j]; localMatch = this.executeLocalFilter(filterField, data[i], filterConstraint, j); if (filterMeta.operator === FilterOperator.OR && localMatch || filterMeta.operator === FilterOperator.AND && !localMatch) { break; } } } else { localMatch = this.executeLocalFilter(filterField, data[i], filterMeta, 0); } if (!localMatch) { break; } } } if (isGlobalFilter && !globalMatch && globalFilterFieldsArray) { for (var _j = 0; _j < globalFilterFieldsArray.length; _j++) { var globalFilterField = globalFilterFieldsArray[_j]; var matchMode = filters['global'] ? filters['global'].matchMode : FilterMatchMode$1.CONTAINS; var value = filters['global'] ? filters['global'].value : this.props.globalFilter; globalMatch = FilterService.filters[matchMode](ObjectUtils.resolveFieldData(data[i], globalFilterField), value, this.props.filterLocale); if (globalMatch) { break; } } } var matches = void 0; if (isGlobalFilter) { matches = localFiltered ? localFiltered && localMatch && globalMatch : globalMatch; } else { matches = localFiltered && localMatch; } if (matches) { filteredValue.push(data[i]); } } if (filteredValue.length === this.props.value.length) { filteredValue = data; } return filteredValue; } }, { key: "executeLocalFilter", value: function executeLocalFilter(field, rowData, filterMeta, index) { var filterValue = filterMeta.value; var filterMatchMode = filterMeta.matchMode === 'custom' ? "custom_".concat(field) : filterMeta.matchMode || FilterMatchMode$1.STARTS_WITH; var dataFieldValue = ObjectUtils.resolveFieldData(rowData, field); var filterConstraint = FilterService.filters[filterMatchMode]; return filterConstraint(dataFieldValue, filterValue, this.props.filterLocale, index); } }, { key: "cloneFilters", value: function cloneFilters(filters) { var _this12 = this; filters = filters || this.props.filters; var cloned = {}; if (filters) { Object.entries(filters).forEach(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), prop = _ref2[0], value = _ref2[1]; cloned[prop] = value.operator ? { operator: value.operator, constraints: value.constraints.map(function (constraint) { return _objectSpread({}, constraint); }) } : _objectSpread({}, value); }); } else { var columns = this.getColumns(); cloned = columns.reduce(function (_filters, col) { if (col.props.filter) { var field = col.props.filterField || col.props.field; var filterFunction = col.props.filterFunction; var dataType = col.props.dataType; var matchMode = col.props.filterMatchMode || (PrimeReact.filterMatchModeOptions[dataType] ? PrimeReact.filterMatchModeOptions[dataType][0] : FilterMatchMode$1.STARTS_WITH); var constraint = { value: null, matchMode: matchMode }; if (filterFunction) { FilterService.register("custom_".concat(field), function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return filterFunction.apply(void 0, args.concat([{ column: col }])); }); } _filters[field] = _this12.props.filterDisplay === 'menu' ? { operator: FilterOperator.AND, constraints: [constraint] } : constraint; } return _filters; }, {}); } return cloned; } }, { key: "filter", value: function filter(value, field, matchMode) { var index = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var filters = _objectSpread({}, this.state.d_filters); var meta = filters[field]; var constraint = meta && meta.operator ? meta.constraints[index] : meta; constraint = meta ? { value: value, matchMode: matchMode || constraint.matchMode } : { value: value, matchMode: matchMode }; this.props.filterDisplay === 'menu' && meta && meta.operator ? filters[field].constraints[index] = constraint : filters[field] = constraint; this.setState({ d_filters: filters }, this.onFilterApply); } }, { key: "reset", value: function reset() { var state = { d_rows: this.props.rows, d_filters: this.cloneFilters(this.props.filters), groupRowsSortMeta: null, editingMeta: {} }; if (!this.props.onPage) { state.first = this.props.first; state.rows = this.props.rows; } if (!this.props.onSort) { state.sortField = this.props.sortField; state.sortOrder = this.props.sortOrder; state.multiSortMeta = this.props.multiSortMeta; } if (!this.props.onFilter) { state.filters = this.props.filters; } this.resetColumnOrder(); this.setState(state); } }, { key: "resetColumnOrder", value: function resetColumnOrder() { var columns = this.getColumns(true); var columnOrder = []; if (columns) { columnOrder = columns.reduce(function (orders, col) { orders.push(col.props.columnKey || col.props.field); return orders; }, []); } this.setState({ columnOrder: columnOrder }); } }, { key: "exportCSV", value: function exportCSV(options) { var _this13 = this; var data; var csv = "\uFEFF"; var columns = this.getColumns(); if (options && options.selectionOnly) { data = this.props.selection || []; } else { data = [].concat(_toConsumableArray(this.props.frozenValue || []), _toConsumableArray(this.processedData() || [])); } //headers columns.forEach(function (column, i) { var _column$props = column.props, field = _column$props.field, header = _column$props.header, exportable = _column$props.exportable; if (exportable && field) { csv += '"' + (header || field) + '"'; if (i < columns.length - 1) { csv += _this13.props.csvSeparator; } } }); //body data.forEach(function (record) { csv += '\n'; columns.forEach(function (column, i) { var _column$props2 = column.props, field = _column$props2.field, exportable = _column$props2.exportable; if (exportable && field) { var cellData = ObjectUtils.resolveFieldData(record, field); if (cellData != null) { cellData = _this13.props.exportFunction ? _this13.props.exportFunction({ data: cellData, field: field, rowData: record, column: column }) : String(cellData).replace(/"/g, '""'); } else cellData = ''; csv += '"' + cellData + '"'; if (i < columns.length - 1) { csv += _this13.props.csvSeparator; } } }); }); DomHandler.exportCSV(csv, this.props.exportFilename); } }, { key: "closeEditingCell", value: function closeEditingCell() { if (this.props.editMode !== "row") { document.body.click(); } } }, { key: "processedData", value: function processedData(localState) { var data = this.props.value || []; if (!this.props.lazy) { if (data && data.length) { var filters = localState && localState.filters || this.getFilters(); var sortField = localState && localState.sortField || this.getSortField(); var sortOrder = localState && localState.sortOrder || this.getSortOrder(); var multiSortMeta = localState && localState.multiSortMeta || this.getMultiSortMeta(); if (ObjectUtils.isNotEmpty(filters) || this.props.globalFilter) { data = this.filterLocal(data, filters); } if (sortField || ObjectUtils.isNotEmpty(multiSortMeta)) { if (this.props.sortMode === 'single') data = this.sortSingle(data, sortField, sortOrder);else if (this.props.sortMode === 'multiple') data = this.sortMultiple(data, multiSortMeta); } } } return data; } }, { key: "dataToRender", value: function dataToRender(data) { if (data && this.props.paginator) { var first = this.props.lazy ? 0 : this.getFirst(); return data.slice(first, first + this.getRows()); } return data; } }, { key: "componentDidMount", value: function componentDidMount() { this.el.setAttribute(this.attributeSelector, ''); if (this.props.responsiveLayout === 'stack' && !this.props.scrollable) { this.createResponsiveStyle(); } if (this.isStateful() && this.props.resizableColumns) { this.restoreColumnWidths(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.isStateful()) { this.saveState(); } if (prevProps.responsiveLayout !== this.props.responsiveLayout) { this.destroyResponsiveStyle(); if (this.props.responsiveLayout === 'stack' && !this.props.scrollable) { this.createResponsiveStyle(); } } if (prevProps.filters !== this.props.filters) { this.setState({ filters: this.cloneFilters(this.props.filters), d_filters: this.cloneFilters(this.props.filters) }); } if (prevProps.globalFilter !== this.props.globalFilter) { this.filter(this.props.globalFilter, 'global', 'contains'); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unbindColumnResizeEvents(); this.destroyStyleElement(); this.destroyResponsiveStyle(); } }, { key: "renderLoader", value: function renderLoader() { if (this.props.loading) { var iconClassName = classNames('p-datatable-loading-icon pi-spin', this.props.loadingIcon); return /*#__PURE__*/React.createElement("div", { className: "p-datatable-loading-overlay p-component-overlay" }, /*#__PURE__*/React.createElement("i", { className: iconClassName })); } return null; } }, { key: "renderHeader", value: function renderHeader() { if (this.props.header) { var content = ObjectUtils.getJSXElement(this.props.header, { props: this.props }); return /*#__PURE__*/React.createElement("div", { className: "p-datatable-header" }, content); } return null; } }, { key: "renderTableHeader", value: function renderTableHeader(options, empty) { var sortField = this.getSortField(); var sortOrder = this.getSortOrder(); var multiSortMeta = _toConsumableArray(this.getMultiSortMeta()); var groupRowSortField = this.getGroupRowSortField(); var filters = this.state.d_filters; var filtersStore = this.getFilters(); var processedData = options.items, columns = options.columns; return /*#__PURE__*/React.createElement(TableHeader, { value: processedData, tableProps: this.props, columns: columns, tabIndex: this.props.tabIndex, empty: empty, headerColumnGroup: this.props.headerColumnGroup, resizableColumns: this.props.resizableColumns, onColumnResizeStart: this.onColumnResizeStart, onColumnResizerClick: this.props.onColumnResizerClick, onColumnResizerDoubleClick: this.props.onColumnResizerDoubleClick, sortMode: this.props.sortMode, sortField: sortField, sortOrder: sortOrder, multiSortMeta: multiSortMeta, groupRowsBy: this.props.groupRowsBy, groupRowSortField: groupRowSortField, onSortChange: this.onSortChange, filterDisplay: this.props.filterDisplay, filters: filters, filtersStore: filtersStore, onFilterChange: this.onFilterChange, onFilterApply: this.onFilterApply, allRowsSelected: this.allRowsSelected, onColumnCheckboxChange: this.onColumnHeaderCheckboxChange, onColumnMouseDown: this.onColumnHeaderMouseDown, onColumnDragStart: this.onColumnHeaderDragStart, onColumnDragOver: this.onColumnHeaderDragOver, onColumnDragLeave: this.onColumnHeaderDragLeave, onColumnDrop: this.onColumnHeaderDrop, rowGroupMode: this.props.rowGroupMode, reorderableColumns: this.props.reorderableColumns }); } }, { key: "renderTableBody", value: function renderTableBody(options, selectionModeInColumn, empty, isVirtualScrollerDisabled) { var tableSelector = this.attributeSelector; var first = this.getFirst(); var editingMeta = this.state.editingMeta; var rows = options.rows, columns = options.columns, contentRef = options.contentRef, className = options.className; var frozenBody = this.props.frozenValue && /*#__PURE__*/React.createElement(TableBody, { value: this.props.frozenValue, className: "p-datatable-frozen-tbody", frozenRow: true, tableProps: this.props, tableSelector: tableSelector, columns: columns, selectionModeInColumn: selectionModeInColumn, first: first, editingMeta: editingMeta, onEditingMetaChange: this.onEditingMetaChange, tabIndex: this.props.tabIndex, onRowClick: this.props.onRowClick, onRowDoubleClick: this.props.onRowDoubleClick, onCellClick: this.props.onCellClick, selection: this.props.selection, onSelectionChange: this.props.onSelectionChange, lazy: this.props.lazy, paginator: this.props.paginator, onCellSelect: this.props.onCellSelect, onCellUnselect: this.props.onCellUnselect, onRowSelect: this.props.onRowSelect, onRowUnselect: this.props.onRowUnselect, dragSelection: this.props.dragSelection, onContextMenu: this.props.onContextMenu, onContextMenuSelectionChange: this.props.onContextMenuSelectionChange, metaKeySelection: this.props.metaKeySelection, selectionMode: this.props.selectionMode, cellSelection: this.props.cellSelection, contextMenuSelection: this.props.contextMenuSelection, dataKey: this.props.dataKey, expandedRows: this.props.expandedRows, onRowCollapse: this.props.onRowCollapse, onRowExpand: this.props.onRowExpand, onRowToggle: this.props.onRowToggle, editMode: this.props.editMode, editingRows: this.props.editingRows, onRowReorder: this.props.onRowReorder, scrollable: this.props.scrollable, rowGroupMode: this.props.rowGroupMode, groupRowsBy: this.props.groupRowsBy, expandableRowGroups: this.props.expandableRowGroups, loading: this.props.loading, emptyMessage: this.props.emptyMessage, rowGroupHeaderTemplate: this.props.rowGroupHeaderTemplate, rowExpansionTemplate: this.props.rowExpansionTemplate, rowGroupFooterTemplate: this.props.rowGroupFooterTemplate, onRowEditChange: this.props.onRowEditChange, compareSelectionBy: this.props.compareSelectionBy, selectOnEdit: this.props.selectOnEdit, onRowEditInit: this.props.onRowEditInit, rowEditValidator: this.props.rowEditValidator, onRowEditSave: this.props.onRowEditSave, onRowEditComplete: this.props.onRowEditComplete, onRowEditCancel: this.props.onRowEditCancel, cellClassName: this.props.cellClassName, responsiveLayout: this.props.responsiveLayout, showSelectionElement: this.props.showSelectionElement, showRowReorderElement: this.props.showRowReorderElement, expandedRowIcon: this.props.expandedRowIcon, collapsedRowIcon: this.props.collapsedRowIcon, rowClassName: this.props.rowClassName, isVirtualScrollerDisabled: true }); var body = /*#__PURE__*/React.createElement(TableBody, { value: this.dataToRender(rows), className: className, empty: empty, frozenRow: false, tableProps: this.props, tableSelector: tableSelector, columns: columns, selectionModeInColumn: selectionModeInColumn, first: first, editingMeta: editingMeta, onEditingMetaChange: this.onEditingMetaChange, tabIndex: this.props.tabIndex, onRowClick: this.props.onRowClick, onRowDoubleClick: this.props.onRowDoubleClick, onCellClick: this.props.onCellClick, selection: this.props.selection, onSelectionChange: this.props.onSelectionChange, lazy: this.props.lazy, paginator: this.props.paginator, onCellSelect: this.props.onCellSelect, onCellUnselect: this.props.onCellUnselect, onRowSelect: this.props.onRowSelect, onRowUnselect: this.props.onRowUnselect, dragSelection: this.props.dragSelection, onContextMenu: this.props.onContextMenu, onContextMenuSelectionChange: this.props.onContextMenuSelectionChange, metaKeySelection: this.props.metaKeySelection, selectionMode: this.props.selectionMode, cellSelection: this.props.cellSelection, contextMenuSelection: this.props.contextMenuSelection, dataKey: this.props.dataKey, expandedRows: this.props.expandedRows, onRowCollapse: this.props.onRowCollapse, onRowExpand: this.props.onRowExpand, onRowToggle: this.props.onRowToggle, editMode: this.props.editMode, editingRows: this.props.editingRows, onRowReorder: this.props.onRowReorder, scrollable: this.props.scrollable, rowGroupMode: this.props.rowGroupMode, groupRowsBy: this.props.groupRowsBy, expandableRowGroups: this.props.expandableRowGroups, loading: this.props.loading, emptyMessage: this.props.emptyMessage, rowGroupHeaderTemplate: this.props.rowGroupHeaderTemplate, rowExpansionTemplate: this.props.rowExpansionTemplate, rowGroupFooterTemplate: this.props.rowGroupFooterTemplate, onRowEditChange: this.props.onRowEditChange, compareSelectionBy: this.props.compareSelectionBy, selectOnEdit: this.props.selectOnEdit, onRowEditInit: this.props.onRowEditInit, rowEditValidator: this.props.rowEditValidator, onRowEditSave: this.props.onRowEditSave, onRowEditComplete: this.props.onRowEditComplete, onRowEditCancel: this.props.onRowEditCancel, cellClassName: this.props.cellClassName, responsiveLayout: this.props.responsiveLayout, showSelectionElement: this.props.showSelectionElement, showRowReorderElement: this.props.showRowReorderElement, expandedRowIcon: this.props.expandedRowIcon, collapsedRowIcon: this.props.collapsedRowIcon, rowClassName: this.props.rowClassName, virtualScrollerContentRef: contentRef, virtualScrollerOptions: options, isVirtualScrollerDisabled: isVirtualScrollerDisabled }); return /*#__PURE__*/React.createElement(React.Fragment, null, frozenBody, body); } }, { key: "renderTableFooter", value: function renderTableFooter(options) { var columns = options.columns; return /*#__PURE__*/React.createElement(TableFooter, { tableProps: this.props, columns: columns, footerColumnGroup: this.props.footerColumnGroup }); } }, { key: "renderContent", value: function renderContent(processedData, columns, selectionModeInColumn, empty) { var _this14 = this; if (!columns) return; var isVirtualScrollerDisabled = this.isVirtualScrollerDisabled(); var virtualScrollerOptions = this.props.virtualScrollerOptions || {}; return /*#__PURE__*/React.createElement("div", { className: "p-datatable-wrapper", style: { maxHeight: isVirtualScrollerDisabled ? this.props.scrollHeight : '' } }, /*#__PURE__*/React.createElement(VirtualScroller, _extends({}, virtualScrollerOptions, { items: processedData, columns: columns, style: { height: this.props.scrollHeight }, disabled: isVirtualScrollerDisabled, loaderDisabled: true, showSpacer: false, contentTemplate: function contentTemplate(options) { var ref = function ref(el) { _this14.table = el; options.spacerRef && options.spacerRef(el); }; var tableClassName = classNames('p-datatable-table', _this14.props.tableClassName); var tableHeader = _this14.renderTableHeader(options, empty); var tableBody = _this14.renderTableBody(options, selectionModeInColumn, empty, isVirtualScrollerDisabled); var tableFooter = _this14.renderTableFooter(options); return /*#__PURE__*/React.createElement("table", { ref: ref, style: _this14.props.tableStyle, className: tableClassName, role: "table" }, tableHeader, tableBody, tableFooter); } }))); } }, { key: "renderFooter", value: function renderFooter() { if (this.props.footer) { var content = ObjectUtils.getJSXElement(this.props.footer, { props: this.props }); return /*#__PURE__*/React.createElement("div", { className: "p-datatable-footer" }, content); } return null; } }, { key: "renderPaginator", value: function renderPaginator(position, totalRecords) { var className = classNames('p-paginator-' + position, this.props.paginatorClassName); return /*#__PURE__*/React.createElement(Paginator, { first: this.getFirst(), rows: this.getRows(), pageLinkSize: this.props.pageLinkSize, className: className, onPageChange: this.onPageChange, template: this.props.paginatorTemplate, totalRecords: totalRecords, rowsPerPageOptions: this.props.rowsPerPageOptions, currentPageReportTemplate: this.props.currentPageReportTemplate, leftContent: this.props.paginatorLeft, rightContent: this.props.paginatorRight, alwaysShow: this.props.alwaysShowPaginator, dropdownAppendTo: this.props.paginatorDropdownAppendTo }); } }, { key: "renderPaginatorTop", value: function renderPaginatorTop(totalRecords) { if (this.props.paginator && this.props.paginatorPosition !== 'bottom') { return this.renderPaginator('top', totalRecords); } return null; } }, { key: "renderPaginatorBottom", value: function renderPaginatorBottom(totalRecords) { if (this.props.paginator && this.props.paginatorPosition !== 'top') { return this.renderPaginator('bottom', totalRecords); } return null; } }, { key: "renderResizeHelper", value: function renderResizeHelper() { var _this15 = this; if (this.props.resizableColumns) { return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this15.resizeHelper = el; }, className: "p-column-resizer-helper", style: { display: 'none' } }); } return null; } }, { key: "renderReorderIndicators", value: function renderReorderIndicators() { var _this16 = this; if (this.props.reorderableColumns) { var style = { position: 'absolute', display: 'none' }; return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", { ref: function ref(el) { return _this16.reorderIndicatorUp = el; }, className: "pi pi-arrow-down p-datatable-reorder-indicator-up", style: style }), /*#__PURE__*/React.createElement("span", { ref: function ref(el) { return _this16.reorderIndicatorDown = el; }, className: "pi pi-arrow-up p-datatable-reorder-indicator-down", style: style })); } return null; } }, { key: "render", value: function render() { var _this17 = this; var processedData = this.processedData(); var columns = this.getColumns(); var totalRecords = this.getTotalRecords(processedData); var empty = ObjectUtils.isEmpty(processedData); var selectionModeInColumn = this.getSelectionModeInColumn(columns); var className = classNames('p-datatable p-component', { 'p-datatable-hoverable-rows': this.props.rowHover || this.props.selectionMode || selectionModeInColumn, 'p-datatable-auto-layout': this.props.autoLayout, 'p-datatable-resizable': this.props.resizableColumns, 'p-datatable-resizable-fit': this.props.resizableColumns && this.props.columnResizeMode === 'fit', 'p-datatable-scrollable': this.props.scrollable, 'p-datatable-scrollable-vertical': this.props.scrollable && this.props.scrollDirection === 'vertical', 'p-datatable-scrollable-horizontal': this.props.scrollable && this.props.scrollDirection === 'horizontal', 'p-datatable-scrollable-both': this.props.scrollable && this.props.scrollDirection === 'both', 'p-datatable-flex-scrollable': this.props.scrollable && this.props.scrollHeight === 'flex', 'p-datatable-responsive-stack': this.props.responsiveLayout === 'stack', 'p-datatable-responsive-scroll': this.props.responsiveLayout === 'scroll', 'p-datatable-striped': this.props.stripedRows, 'p-datatable-gridlines': this.props.showGridlines, 'p-datatable-grouped-header': this.props.headerColumnGroup != null, 'p-datatable-grouped-footer': this.props.footerColumnGroup != null, 'p-datatable-sm': this.props.size === 'small', 'p-datatable-lg': this.props.size === 'large' }, this.props.className); var loader = this.renderLoader(); var header = this.renderHeader(); var paginatorTop = this.renderPaginatorTop(totalRecords); var content = this.renderContent(processedData, columns, selectionModeInColumn, empty); var paginatorBottom = this.renderPaginatorBottom(totalRecords); var footer = this.renderFooter(); var resizeHelper = this.renderResizeHelper(); var reorderIndicators = this.renderReorderIndicators(); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this17.el = el; }, id: this.props.id, className: className, style: this.props.style, "data-scrollselectors": ".p-datatable-wrapper" }, loader, header, paginatorTop, content, paginatorBottom, footer, resizeHelper, reorderIndicators); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { if (nextProps.rows !== prevState.d_rows && !nextProps.onPage) { return { rows: nextProps.rows, d_rows: nextProps.rows }; } return null; } }]); return DataTable; }(Component); _defineProperty(DataTable, "defaultProps", { id: null, value: null, header: null, footer: null, style: null, className: null, tableStyle: null, tableClassName: null, paginator: false, paginatorPosition: 'bottom', alwaysShowPaginator: true, paginatorClassName: null, paginatorTemplate: 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown', paginatorLeft: null, paginatorRight: null, paginatorDropdownAppendTo: null, pageLinkSize: 5, rowsPerPageOptions: null, currentPageReportTemplate: '({currentPage} of {totalPages})', first: 0, rows: null, totalRecords: null, lazy: false, sortField: null, sortOrder: null, multiSortMeta: null, sortMode: 'single', defaultSortOrder: 1, removableSort: false, emptyMessage: null, selectionMode: null, dragSelection: false, cellSelection: false, selection: null, onSelectionChange: null, contextMenuSelection: null, onContextMenuSelectionChange: null, compareSelectionBy: 'deepEquals', dataKey: null, metaKeySelection: true, selectOnEdit: true, headerColumnGroup: null, footerColumnGroup: null, rowExpansionTemplate: null, expandedRows: null, onRowToggle: null, resizableColumns: false, columnResizeMode: 'fit', reorderableColumns: false, filters: null, globalFilter: null, filterDelay: 300, filterLocale: undefined, scrollable: false, scrollHeight: null, scrollDirection: 'vertical', virtualScrollerOptions: null, frozenWidth: null, frozenValue: null, csvSeparator: ',', exportFilename: 'download', rowGroupMode: null, autoLayout: false, rowClassName: null, cellClassName: null, rowGroupHeaderTemplate: null, rowGroupFooterTemplate: null, loading: false, loadingIcon: 'pi pi-spinner', tabIndex: 0, stateKey: null, stateStorage: 'session', groupRowsBy: null, editMode: 'cell', editingRows: null, expandableRowGroups: false, rowHover: false, showGridlines: false, stripedRows: false, size: 'normal', responsiveLayout: 'stack', breakpoint: '960px', filterDisplay: 'menu', expandedRowIcon: 'pi pi-chevron-down', collapsedRowIcon: 'pi pi-chevron-right', onRowEditComplete: null, globalFilterFields: null, showSelectionElement: null, showRowReorderElement: null, onColumnResizeEnd: null, onColumnResizerClick: null, onColumnResizerDoubleClick: null, onSort: null, onPage: null, onFilter: null, onAllRowsSelect: null, onAllRowsUnselect: null, onRowClick: null, onRowDoubleClick: null, onRowSelect: null, onRowUnselect: null, onRowExpand: null, onRowCollapse: null, onContextMenu: null, onColReorder: null, onCellClick: null, onCellSelect: null, onCellUnselect: null, onRowReorder: null, onValueChange: null, rowEditValidator: null, onRowEditInit: null, onRowEditSave: null, onRowEditCancel: null, onRowEditChange: null, exportFunction: null, customSaveState: null, customRestoreState: null, onStateSave: null, onStateRestore: null }); export { DataTable };
ajax/libs/material-ui/4.9.2/esm/internal/svg-icons/Person.js
cdnjs/cdnjs
import React from 'react'; import createSvgIcon from './createSvgIcon'; /** * @ignore - internal component. */ export default createSvgIcon(React.createElement("path", { d: "M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" }), 'Person');
ajax/libs/primereact/7.0.0/fieldset/fieldset.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { UniqueComponentId, classNames } from 'primereact/utils'; import { CSSTransition } from 'primereact/csstransition'; import { Ripple } from 'primereact/ripple'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); 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 Fieldset = /*#__PURE__*/function (_Component) { _inherits(Fieldset, _Component); var _super = _createSuper(Fieldset); function Fieldset(props) { var _this; _classCallCheck(this, Fieldset); _this = _super.call(this, props); var state = { id: props.id }; if (!_this.props.onToggle) { state = _objectSpread(_objectSpread({}, state), {}, { collapsed: props.collapsed }); } _this.state = state; _this.toggle = _this.toggle.bind(_assertThisInitialized(_this)); _this.contentRef = /*#__PURE__*/React.createRef(); return _this; } _createClass(Fieldset, [{ key: "toggle", value: function toggle(event) { if (this.props.toggleable) { var collapsed = this.props.onToggle ? this.props.collapsed : this.state.collapsed; if (collapsed) this.expand(event);else this.collapse(event); if (this.props.onToggle) { this.props.onToggle({ originalEvent: event, value: !collapsed }); } } event.preventDefault(); } }, { key: "expand", value: function expand(event) { if (!this.props.onToggle) { this.setState({ collapsed: false }); } if (this.props.onExpand) { this.props.onExpand(event); } } }, { key: "collapse", value: function collapse(event) { if (!this.props.onToggle) { this.setState({ collapsed: true }); } if (this.props.onCollapse) { this.props.onCollapse(event); } } }, { key: "isCollapsed", value: function isCollapsed() { return this.props.toggleable ? this.props.onToggle ? this.props.collapsed : this.state.collapsed : false; } }, { key: "componentDidMount", value: function componentDidMount() { if (!this.state.id) { this.setState({ id: UniqueComponentId() }); } } }, { key: "renderContent", value: function renderContent(collapsed) { var id = this.state.id + '_content'; return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.contentRef, classNames: "p-toggleable-content", timeout: { enter: 1000, exit: 450 }, in: !collapsed, unmountOnExit: true, options: this.props.transitionOptions }, /*#__PURE__*/React.createElement("div", { ref: this.contentRef, id: id, className: "p-toggleable-content", "aria-hidden": collapsed, role: "region", "aria-labelledby": this.state.id + '_header' }, /*#__PURE__*/React.createElement("div", { className: "p-fieldset-content" }, this.props.children))); } }, { key: "renderToggleIcon", value: function renderToggleIcon(collapsed) { if (this.props.toggleable) { var className = classNames('p-fieldset-toggler pi', { 'pi-plus': collapsed, 'pi-minus': !collapsed }); return /*#__PURE__*/React.createElement("span", { className: className }); } return null; } }, { key: "renderLegendContent", value: function renderLegendContent(collapsed) { if (this.props.toggleable) { var toggleIcon = this.renderToggleIcon(collapsed); var ariaControls = this.state.id + '_content'; return /*#__PURE__*/React.createElement("a", { href: '#' + ariaControls, "aria-controls": ariaControls, id: this.state.id + '_header', "aria-expanded": !collapsed, tabIndex: this.props.toggleable ? null : -1 }, toggleIcon, /*#__PURE__*/React.createElement("span", { className: "p-fieldset-legend-text" }, this.props.legend), /*#__PURE__*/React.createElement(Ripple, null)); } return /*#__PURE__*/React.createElement("span", { className: "p-fieldset-legend-text", id: this.state.id + '_header' }, this.props.legend); } }, { key: "renderLegend", value: function renderLegend(collapsed) { var legendContent = this.renderLegendContent(collapsed); if (this.props.legend != null || this.props.toggleable) { return /*#__PURE__*/React.createElement("legend", { className: "p-fieldset-legend p-unselectable-text", onClick: this.toggle }, legendContent); } } }, { key: "render", value: function render() { var className = classNames('p-fieldset p-component', this.props.className, { 'p-fieldset-toggleable': this.props.toggleable }); var collapsed = this.isCollapsed(); var legend = this.renderLegend(collapsed); var content = this.renderContent(collapsed); return /*#__PURE__*/React.createElement("fieldset", { id: this.props.id, className: className, style: this.props.style, onClick: this.props.onClick }, legend, content); } }]); return Fieldset; }(Component); _defineProperty(Fieldset, "defaultProps", { id: null, legend: null, className: null, style: null, toggleable: null, collapsed: null, transitionOptions: null, onExpand: null, onCollapse: null, onToggle: null, onClick: null }); export { Fieldset };
ajax/libs/react-native-web/0.15.1/vendor/react-native/Animated/createAnimatedComponent.js
cdnjs/cdnjs
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ 'use strict'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } import { AnimatedEvent } from './AnimatedEvent'; import AnimatedProps from './nodes/AnimatedProps'; import React from 'react'; import invariant from 'fbjs/lib/invariant'; import mergeRefs from '../../../modules/mergeRefs'; function createAnimatedComponent(Component, defaultProps) { invariant(typeof Component !== 'function' || Component.prototype && Component.prototype.isReactComponent, '`createAnimatedComponent` does not support stateless functional components; ' + 'use a class component instead.'); var AnimatedComponent = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(AnimatedComponent, _React$Component); function AnimatedComponent(props) { var _this; _this = _React$Component.call(this, props) || this; _this._invokeAnimatedPropsCallbackOnMount = false; _this._eventDetachers = []; _this._animatedPropsCallback = function () { if (_this._component == null) { // AnimatedProps is created in will-mount because it's used in render. // But this callback may be invoked before mount in async mode, // In which case we should defer the setNativeProps() call. // React may throw away uncommitted work in async mode, // So a deferred call won't always be invoked. _this._invokeAnimatedPropsCallbackOnMount = true; } else if (AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY || typeof _this._component.setNativeProps !== 'function') { _this.forceUpdate(); } else if (!_this._propsAnimated.__isNative) { _this._component.setNativeProps(_this._propsAnimated.__getAnimatedValue()); } else { throw new Error('Attempting to run JS driven animation on animated ' + 'node that has been moved to "native" earlier by starting an ' + 'animation with `useNativeDriver: true`'); } }; _this._setComponentRef = mergeRefs(_this.props.forwardedRef, function (ref) { _this._prevComponent = _this._component; _this._component = ref; // TODO: Delete this in a future release. if (ref != null && ref.getNode == null) { ref.getNode = function () { var _ref$constructor$name; console.warn('%s: Calling `getNode()` on the ref of an Animated component ' + 'is no longer necessary. You can now directly use the ref ' + 'instead. This method will be removed in a future release.', (_ref$constructor$name = ref.constructor.name) !== null && _ref$constructor$name !== void 0 ? _ref$constructor$name : '<<anonymous>>'); return ref; }; } }); return _this; } var _proto = AnimatedComponent.prototype; _proto.componentWillUnmount = function componentWillUnmount() { this._propsAnimated && this._propsAnimated.__detach(); this._detachNativeEvents(); }; _proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() { this._attachProps(this.props); }; _proto.componentDidMount = function componentDidMount() { if (this._invokeAnimatedPropsCallbackOnMount) { this._invokeAnimatedPropsCallbackOnMount = false; this._animatedPropsCallback(); } this._propsAnimated.setNativeView(this._component); this._attachNativeEvents(); }; _proto._attachNativeEvents = function _attachNativeEvents() { var _this2 = this; // Make sure to get the scrollable node for components that implement // `ScrollResponder.Mixin`. var scrollableNode = this._component && this._component.getScrollableNode ? this._component.getScrollableNode() : this._component; var _loop = function _loop(key) { var prop = _this2.props[key]; if (prop instanceof AnimatedEvent && prop.__isNative) { prop.__attach(scrollableNode, key); _this2._eventDetachers.push(function () { return prop.__detach(scrollableNode, key); }); } }; for (var key in this.props) { _loop(key); } }; _proto._detachNativeEvents = function _detachNativeEvents() { this._eventDetachers.forEach(function (remove) { return remove(); }); this._eventDetachers = []; } // The system is best designed when setNativeProps is implemented. It is // able to avoid re-rendering and directly set the attributes that changed. // However, setNativeProps can only be implemented on leaf native // components. If you want to animate a composite component, you need to // re-render it. In this case, we have a fallback that uses forceUpdate. ; _proto._attachProps = function _attachProps(nextProps) { var oldPropsAnimated = this._propsAnimated; this._propsAnimated = new AnimatedProps(nextProps, this._animatedPropsCallback); // When you call detach, it removes the element from the parent list // of children. If it goes to 0, then the parent also detaches itself // and so on. // An optimization is to attach the new elements and THEN detach the old // ones instead of detaching and THEN attaching. // This way the intermediate state isn't to go to 0 and trigger // this expensive recursive detaching to then re-attach everything on // the very next operation. oldPropsAnimated && oldPropsAnimated.__detach(); }; _proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(newProps) { this._attachProps(newProps); }; _proto.componentDidUpdate = function componentDidUpdate(prevProps) { if (this._component !== this._prevComponent) { this._propsAnimated.setNativeView(this._component); } if (this._component !== this._prevComponent || prevProps !== this.props) { this._detachNativeEvents(); this._attachNativeEvents(); } }; _proto.render = function render() { var props = this._propsAnimated.__getValue(); return ( /*#__PURE__*/ React.createElement(Component, _extends({}, defaultProps, props, { ref: this._setComponentRef })) ); }; return AnimatedComponent; }(React.Component); AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY = false; var propTypes = Component.propTypes; return ( /*#__PURE__*/ React.forwardRef(function AnimatedComponentWrapper(props, ref) { return ( /*#__PURE__*/ React.createElement(AnimatedComponent, _extends({}, props, ref == null ? null : { forwardedRef: ref })) ); }) ); } export default createAnimatedComponent;
ajax/libs/material-ui/4.9.2/esm/ListItem/ListItem.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 { chainPropTypes } from '@material-ui/utils'; import withStyles from '../styles/withStyles'; import ButtonBase from '../ButtonBase'; import isMuiElement from '../utils/isMuiElement'; import useForkRef from '../utils/useForkRef'; import ListContext from '../List/ListContext'; import ReactDOM from 'react-dom'; export var styles = function styles(theme) { return { /* Styles applied to the (normally root) `component` element. May be wrapped by a `container`. */ root: { display: 'flex', justifyContent: 'flex-start', alignItems: 'center', position: 'relative', textDecoration: 'none', width: '100%', boxSizing: 'border-box', textAlign: 'left', paddingTop: 8, paddingBottom: 8, '&$focusVisible': { backgroundColor: theme.palette.action.selected }, '&$selected, &$selected:hover': { backgroundColor: theme.palette.action.selected }, '&$disabled': { opacity: 0.5 } }, /* Styles applied to the `container` element if `children` includes `ListItemSecondaryAction`. */ container: { position: 'relative' }, /* Pseudo-class applied to the `component`'s `focusVisibleClassName` prop if `button={true}`. */ focusVisible: {}, /* Styles applied to the `component` element if dense. */ dense: { paddingTop: 4, paddingBottom: 4 }, /* Styles applied to the `component` element if `alignItems="flex-start"`. */ alignItemsFlexStart: { alignItems: 'flex-start' }, /* Pseudo-class applied to the inner `component` element if `disabled={true}`. */ disabled: {}, /* Styles applied to the inner `component` element if `divider={true}`. */ divider: { borderBottom: "1px solid ".concat(theme.palette.divider), backgroundClip: 'padding-box' }, /* Styles applied to the inner `component` element if `disableGutters={false}`. */ gutters: { paddingLeft: 16, paddingRight: 16 }, /* Styles applied to the inner `component` element if `button={true}`. */ button: { transition: theme.transitions.create('background-color', { duration: theme.transitions.duration.shortest }), '&:hover': { textDecoration: 'none', backgroundColor: theme.palette.action.hover, // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor: 'transparent' } } }, /* Styles applied to the `component` element if `children` includes `ListItemSecondaryAction`. */ secondaryAction: { // Add some space to avoid collision as `ListItemSecondaryAction` // is absolutely positioned. paddingRight: 48 }, /* Pseudo-class applied to the root element if `selected={true}`. */ selected: {} }; }; var useEnhancedEffect = typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect; /** * Uses an additional container component if `ListItemSecondaryAction` is the last child. */ var ListItem = React.forwardRef(function ListItem(props, ref) { var _props$alignItems = props.alignItems, alignItems = _props$alignItems === void 0 ? 'center' : _props$alignItems, _props$autoFocus = props.autoFocus, autoFocus = _props$autoFocus === void 0 ? false : _props$autoFocus, _props$button = props.button, button = _props$button === void 0 ? false : _props$button, childrenProp = props.children, classes = props.classes, className = props.className, componentProp = props.component, _props$ContainerCompo = props.ContainerComponent, ContainerComponent = _props$ContainerCompo === void 0 ? 'li' : _props$ContainerCompo, _props$ContainerProps = props.ContainerProps; _props$ContainerProps = _props$ContainerProps === void 0 ? {} : _props$ContainerProps; var ContainerClassName = _props$ContainerProps.className, ContainerProps = _objectWithoutProperties(_props$ContainerProps, ["className"]), _props$dense = props.dense, dense = _props$dense === void 0 ? false : _props$dense, _props$disabled = props.disabled, disabled = _props$disabled === void 0 ? false : _props$disabled, _props$disableGutters = props.disableGutters, disableGutters = _props$disableGutters === void 0 ? false : _props$disableGutters, _props$divider = props.divider, divider = _props$divider === void 0 ? false : _props$divider, focusVisibleClassName = props.focusVisibleClassName, _props$selected = props.selected, selected = _props$selected === void 0 ? false : _props$selected, other = _objectWithoutProperties(props, ["alignItems", "autoFocus", "button", "children", "classes", "className", "component", "ContainerComponent", "ContainerProps", "dense", "disabled", "disableGutters", "divider", "focusVisibleClassName", "selected"]); var context = React.useContext(ListContext); var childContext = { dense: dense || context.dense || false, alignItems: alignItems }; var listItemRef = React.useRef(null); useEnhancedEffect(function () { if (autoFocus) { if (listItemRef.current) { listItemRef.current.focus(); } else if (process.env.NODE_ENV !== 'production') { console.error('Material-UI: unable to set focus to a ListItem whose component has not been rendered.'); } } }, [autoFocus]); var children = React.Children.toArray(childrenProp); var hasSecondaryAction = children.length && isMuiElement(children[children.length - 1], ['ListItemSecondaryAction']); var handleOwnRef = React.useCallback(function (instance) { // #StrictMode ready listItemRef.current = ReactDOM.findDOMNode(instance); }, []); var handleRef = useForkRef(handleOwnRef, ref); var componentProps = _extends({ className: clsx(classes.root, className, childContext.dense && classes.dense, !disableGutters && classes.gutters, divider && classes.divider, disabled && classes.disabled, button && classes.button, alignItems !== "center" && classes.alignItemsFlexStart, hasSecondaryAction && classes.secondaryAction, selected && classes.selected), disabled: disabled }, other); var Component = componentProp || 'li'; if (button) { componentProps.component = componentProp || 'div'; componentProps.focusVisibleClassName = clsx(classes.focusVisible, focusVisibleClassName); Component = ButtonBase; } if (hasSecondaryAction) { // Use div by default. Component = !componentProps.component && !componentProp ? 'div' : Component; // Avoid nesting of li > li. if (ContainerComponent === 'li') { if (Component === 'li') { Component = 'div'; } else if (componentProps.component === 'li') { componentProps.component = 'div'; } } return React.createElement(ListContext.Provider, { value: childContext }, React.createElement(ContainerComponent, _extends({ className: clsx(classes.container, ContainerClassName), ref: handleRef }, ContainerProps), React.createElement(Component, componentProps, children), children.pop())); } return React.createElement(ListContext.Provider, { value: childContext }, React.createElement(Component, _extends({ ref: handleRef }, componentProps), children)); }); process.env.NODE_ENV !== "production" ? ListItem.propTypes = { /** * Defines the `align-items` style property. */ alignItems: PropTypes.oneOf(['flex-start', 'center']), /** * If `true`, the list item will be focused during the first mount. * Focus will also be triggered if the value changes from false to true. */ autoFocus: PropTypes.bool, /** * If `true`, the list item will be a button (using `ButtonBase`). Props intended * for `ButtonBase` can then be applied to `ListItem`. */ button: PropTypes.bool, /** * The content of the component. If a `ListItemSecondaryAction` is used it must * be the last child. */ children: chainPropTypes(PropTypes.node, function (props) { var children = React.Children.toArray(props.children); // React.Children.toArray(props.children).findLastIndex(isListItemSecondaryAction) var secondaryActionIndex = -1; for (var i = children.length - 1; i >= 0; i -= 1) { var child = children[i]; if (isMuiElement(child, ['ListItemSecondaryAction'])) { secondaryActionIndex = i; break; } } // is ListItemSecondaryAction the last child of ListItem if (secondaryActionIndex !== -1 && secondaryActionIndex !== children.length - 1) { return new Error('Material-UI: you used an element after ListItemSecondaryAction. ' + 'For ListItem to detect that it has a secondary action ' + 'you must pass it as the last child to ListItem.'); } return null; }), /** * 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. * By default, it's a `li` when `button` is `false` and a `div` when `button` is `true`. */ component: PropTypes.elementType, /** * The container component used when a `ListItemSecondaryAction` is the last child. */ ContainerComponent: PropTypes.elementType, /** * Props applied to the container component if used. */ ContainerProps: PropTypes.object, /** * If `true`, compact vertical padding designed for keyboard and mouse input will be used. */ dense: PropTypes.bool, /** * If `true`, the list item will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the left and right padding is removed. */ disableGutters: PropTypes.bool, /** * If `true`, a 1px light border is added to the bottom of the list item. */ divider: PropTypes.bool, /** * @ignore */ focusVisibleClassName: PropTypes.string, /** * Use to apply selected styling. */ selected: PropTypes.bool } : void 0; export default withStyles(styles, { name: 'MuiListItem' })(ListItem);
ajax/libs/material-ui/4.9.3/es/Fade/Fade.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 { Transition } from 'react-transition-group'; import { duration } from '../styles/transitions'; import useTheme from '../styles/useTheme'; import { reflow, getTransitionProps } from '../transitions/utils'; import useForkRef from '../utils/useForkRef'; const styles = { entering: { opacity: 1 }, entered: { opacity: 1 } }; const defaultTimeout = { enter: duration.enteringScreen, exit: duration.leavingScreen }; /** * The Fade transition is used by the [Modal](/components/modal/) component. * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally. */ const Fade = React.forwardRef(function Fade(props, ref) { const { children, in: inProp, onEnter, onExit, style, timeout = defaultTimeout } = props, other = _objectWithoutPropertiesLoose(props, ["children", "in", "onEnter", "onExit", "style", "timeout"]); const theme = useTheme(); const handleRef = useForkRef(children.ref, ref); const handleEnter = (node, isAppearing) => { reflow(node); // So the animation always start from the start. const transitionProps = getTransitionProps({ style, timeout }, { mode: 'enter' }); node.style.webkitTransition = theme.transitions.create('opacity', transitionProps); node.style.transition = theme.transitions.create('opacity', transitionProps); if (onEnter) { onEnter(node, isAppearing); } }; const handleExit = node => { const transitionProps = getTransitionProps({ style, timeout }, { mode: 'exit' }); node.style.webkitTransition = theme.transitions.create('opacity', transitionProps); node.style.transition = theme.transitions.create('opacity', transitionProps); if (onExit) { onExit(node); } }; return React.createElement(Transition, _extends({ appear: true, in: inProp, onEnter: handleEnter, onExit: handleExit, timeout: timeout }, other), (state, childProps) => { return React.cloneElement(children, _extends({ style: _extends({ opacity: 0, visibility: state === 'exited' && !inProp ? 'hidden' : undefined }, styles[state], {}, style, {}, children.props.style), ref: handleRef }, childProps)); }); }); process.env.NODE_ENV !== "production" ? Fade.propTypes = { /** * A single child content element. */ children: PropTypes.element, /** * If `true`, the component will transition in. */ in: PropTypes.bool, /** * @ignore */ onEnter: PropTypes.func, /** * @ignore */ onExit: PropTypes.func, /** * @ignore */ style: PropTypes.object, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ timeout: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number })]) } : void 0; export default Fade;
ajax/libs/react-native-web/0.11.5/exports/RefreshControl/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 _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 ColorPropType from '../ColorPropType'; import View from '../View'; import ViewPropTypes from '../ViewPropTypes'; import { arrayOf, bool, func, number, oneOf, string } from 'prop-types'; import React, { Component } from 'react'; var RefreshControl = /*#__PURE__*/ function (_Component) { _inheritsLoose(RefreshControl, _Component); function RefreshControl() { return _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; }(Component); RefreshControl.propTypes = process.env.NODE_ENV !== "production" ? _objectSpread({}, ViewPropTypes, { colors: arrayOf(ColorPropType), enabled: bool, onRefresh: func, progressBackgroundColor: ColorPropType, progressViewOffset: number, refreshing: bool.isRequired, size: oneOf([0, 1]), tintColor: ColorPropType, title: string, titleColor: ColorPropType }) : {}; export default RefreshControl;
ajax/libs/react-native-web/0.15.7/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; _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) 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 /*#__PURE__*/React.createElement(View, _extends({ onLayout: this.onLayout }, rest)); }; return KeyboardAvoidingView; }(React.Component); export default KeyboardAvoidingView;
ajax/libs/react-native-web/0.13.14/exports/AppRegistry/renderApplication.js
cdnjs/cdnjs
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AppContainer from './AppContainer'; import invariant from 'fbjs/lib/invariant'; import render, { hydrate } from '../render'; import styleResolver from '../StyleSheet/styleResolver'; import React from 'react'; export default function renderApplication(RootComponent, WrapperComponent, callback, options) { var shouldHydrate = options.hydrate, initialProps = options.initialProps, rootTag = options.rootTag; var renderFn = shouldHydrate ? hydrate : render; invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag); renderFn(React.createElement(AppContainer, { rootTag: rootTag, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)), rootTag, callback); } export function getApplication(RootComponent, initialProps, WrapperComponent) { var element = React.createElement(AppContainer, { rootTag: {}, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)); // Don't escape CSS text var getStyleElement = function getStyleElement(props) { var sheet = styleResolver.getStyleSheet(); return React.createElement("style", _extends({}, props, { dangerouslySetInnerHTML: { __html: sheet.textContent }, id: sheet.id })); }; return { element: element, getStyleElement: getStyleElement }; }
ajax/libs/material-ui/4.9.2/es/Menu/Menu.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 withStyles from '../styles/withStyles'; import Popover from '../Popover'; import MenuList from '../MenuList'; import ReactDOM from 'react-dom'; import setRef from '../utils/setRef'; import useTheme from '../styles/useTheme'; const RTL_ORIGIN = { vertical: 'top', horizontal: 'right' }; const LTR_ORIGIN = { vertical: 'top', horizontal: 'left' }; export const styles = { /* Styles applied to the `Paper` component. */ paper: { // specZ: The maximum height of a simple menu should be one or more rows less than the view // height. This ensures a tapable area outside of the simple menu with which to dismiss // the menu. maxHeight: 'calc(100% - 96px)', // Add iOS momentum scrolling. WebkitOverflowScrolling: 'touch' }, /* Styles applied to the `List` component via `MenuList`. */ list: { // We disable the focus ring for mouse, touch and keyboard users. outline: 0 } }; const Menu = React.forwardRef(function Menu(props, ref) { const { autoFocus = true, children, classes, disableAutoFocusItem = false, MenuListProps = {}, onClose, onEntering, open, PaperProps = {}, PopoverClasses, transitionDuration = 'auto', variant = 'selectedMenu' } = props, other = _objectWithoutPropertiesLoose(props, ["autoFocus", "children", "classes", "disableAutoFocusItem", "MenuListProps", "onClose", "onEntering", "open", "PaperProps", "PopoverClasses", "transitionDuration", "variant"]); const theme = useTheme(); const autoFocusItem = autoFocus && !disableAutoFocusItem && open; const menuListActionsRef = React.useRef(null); const contentAnchorRef = React.useRef(null); const getContentAnchorEl = () => contentAnchorRef.current; const handleEntering = (element, isAppearing) => { if (menuListActionsRef.current) { menuListActionsRef.current.adjustStyleForScrollbar(element, theme); } if (onEntering) { onEntering(element, isAppearing); } }; const handleListKeyDown = event => { if (event.key === 'Tab') { event.preventDefault(); if (onClose) { onClose(event, 'tabKeyDown'); } } }; /** * the index of the item should receive focus * in a `variant="selectedMenu"` it's the first `selected` item * otherwise it's the very first item. */ let activeItemIndex = -1; // since we inject focus related props into children we have to do a lookahead // to check if there is a `selected` item. We're looking for the last `selected` // item and use the first valid item as a fallback React.Children.map(children, (child, index) => { if (!React.isValidElement(child)) { return; } if (process.env.NODE_ENV !== 'production') { if (isFragment(child)) { console.error(["Material-UI: the Menu component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n')); } } if (!child.props.disabled) { if (variant !== "menu" && child.props.selected) { activeItemIndex = index; } else if (activeItemIndex === -1) { activeItemIndex = index; } } }); const items = React.Children.map(children, (child, index) => { if (index === activeItemIndex) { return React.cloneElement(child, { ref: instance => { // #StrictMode ready contentAnchorRef.current = ReactDOM.findDOMNode(instance); setRef(child.ref, instance); } }); } return child; }); return React.createElement(Popover, _extends({ getContentAnchorEl: getContentAnchorEl, classes: PopoverClasses, onClose: onClose, onEntering: handleEntering, anchorOrigin: theme.direction === 'rtl' ? RTL_ORIGIN : LTR_ORIGIN, transformOrigin: theme.direction === 'rtl' ? RTL_ORIGIN : LTR_ORIGIN, PaperProps: _extends({}, PaperProps, { classes: _extends({}, PaperProps.classes, { root: classes.paper }) }), open: open, ref: ref, transitionDuration: transitionDuration }, other), React.createElement(MenuList, _extends({ onKeyDown: handleListKeyDown, actions: menuListActionsRef, autoFocus: autoFocus && (activeItemIndex === -1 || disableAutoFocusItem), autoFocusItem: autoFocusItem, variant: variant }, MenuListProps, { className: clsx(classes.list, MenuListProps.className) }), items)); }); process.env.NODE_ENV !== "production" ? Menu.propTypes = { /** * The DOM element used to set the position of the menu. */ anchorEl: PropTypes.oneOfType([PropTypes.object, PropTypes.func]), /** * If `true` (Default) will focus the `[role="menu"]` if no focusable child is found. Disabled * children are not focusable. If you set this prop to `false` focus will be placed * on the parent modal container. This has severe accessibility implications * and should only be considered if you manage focus otherwise. */ autoFocus: PropTypes.bool, /** * Menu contents, normally `MenuItem`s. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * When opening the menu will not focus the active item but the `[role="menu"]` * unless `autoFocus` is also set to `false`. Not using the default means not * following WAI-ARIA authoring practices. Please be considerate about possible * accessibility implications. */ disableAutoFocusItem: PropTypes.bool, /** * Props applied to the [`MenuList`](/api/menu-list/) element. */ MenuListProps: PropTypes.object, /** * Callback fired when the component requests to be closed. * * @param {object} event The event source of the callback. * @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`, `"tabKeyDown"`. */ onClose: PropTypes.func, /** * Callback fired before the Menu enters. */ onEnter: PropTypes.func, /** * Callback fired when the Menu has entered. */ onEntered: PropTypes.func, /** * Callback fired when the Menu is entering. */ onEntering: PropTypes.func, /** * Callback fired before the Menu exits. */ onExit: PropTypes.func, /** * Callback fired when the Menu has exited. */ onExited: PropTypes.func, /** * Callback fired when the Menu is exiting. */ onExiting: PropTypes.func, /** * If `true`, the menu is visible. */ open: PropTypes.bool.isRequired, /** * @ignore */ PaperProps: PropTypes.object, /** * `classes` prop applied to the [`Popover`](/api/popover/) element. */ PopoverClasses: PropTypes.object, /** * The length of the transition in `ms`, or 'auto' */ transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }), PropTypes.oneOf(['auto'])]), /** * The variant to use. Use `menu` to prevent selected items from impacting the initial focus * and the vertical alignment relative to the anchor element. */ variant: PropTypes.oneOf(['menu', 'selectedMenu']) } : void 0; export default withStyles(styles, { name: 'MuiMenu' })(Menu);
ajax/libs/primereact/7.0.0-rc.2/tree/tree.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, ObjectUtils, classNames, Ripple } from 'primereact/core'; 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 _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$2(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } 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 _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$2(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _createForOfIteratorHelper$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 ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var UITreeNode = /*#__PURE__*/function (_Component) { _inherits(UITreeNode, _Component); var _super = _createSuper$1(UITreeNode); function UITreeNode(props) { var _this; _classCallCheck(this, UITreeNode); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onDoubleClick = _this.onDoubleClick.bind(_assertThisInitialized(_this)); _this.onRightClick = _this.onRightClick.bind(_assertThisInitialized(_this)); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this)); _this.onTogglerClick = _this.onTogglerClick.bind(_assertThisInitialized(_this)); _this.onNodeKeyDown = _this.onNodeKeyDown.bind(_assertThisInitialized(_this)); _this.propagateUp = _this.propagateUp.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); _this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_this)); _this.onDragEnter = _this.onDragEnter.bind(_assertThisInitialized(_this)); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this)); _this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this)); _this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this)); _this.onDropPointDragOver = _this.onDropPointDragOver.bind(_assertThisInitialized(_this)); _this.onDropPointDragEnter = _this.onDropPointDragEnter.bind(_assertThisInitialized(_this)); _this.onDropPointDragLeave = _this.onDropPointDragLeave.bind(_assertThisInitialized(_this)); return _this; } _createClass(UITreeNode, [{ key: "isLeaf", value: function isLeaf() { return this.props.isNodeLeaf(this.props.node); } }, { key: "expand", value: function expand(event) { var expandedKeys = this.props.expandedKeys ? _objectSpread$1({}, 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$1({}, this.props.expandedKeys); delete expandedKeys[this.props.node.key]; this.props.onToggle({ originalEvent: event, value: expandedKeys }); this.invokeToggleEvents(event, false); } }, { key: "onTogglerClick", value: function onTogglerClick(event) { if (this.props.disabled) { return; } if (this.isExpanded()) this.collapse(event);else this.expand(event); } }, { 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: "isExpanded", value: function isExpanded() { return (this.props.expandedKeys ? this.props.expandedKeys[this.props.node.key] !== undefined : false) || this.props.node.expanded; } }, { key: "onNodeKeyDown", value: function onNodeKeyDown(event) { if (this.props.disabled) { return; } var nodeElement = event.target.parentElement; if (!DomHandler.hasClass(nodeElement, 'p-treenode')) { return; } switch (event.which) { //down arrow case 40: var listElement = nodeElement.children[1]; if (listElement) { this.focusNode(listElement.children[0]); } else { var nextNodeElement = nodeElement.nextElementSibling; if (nextNodeElement) { this.focusNode(nextNodeElement); } else { var nextSiblingAncestor = this.findNextSiblingOfAncestor(nodeElement); if (nextSiblingAncestor) { this.focusNode(nextSiblingAncestor); } } } event.preventDefault(); break; //up arrow case 38: if (nodeElement.previousElementSibling) { this.focusNode(this.findLastVisibleDescendant(nodeElement.previousElementSibling)); } else { var parentNodeElement = this.getParentNodeElement(nodeElement); if (parentNodeElement) { this.focusNode(parentNodeElement); } } 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: "findNextSiblingOfAncestor", value: function findNextSiblingOfAncestor(nodeElement) { var parentNodeElement = this.getParentNodeElement(nodeElement); if (parentNodeElement) { if (parentNodeElement.nextElementSibling) return parentNodeElement.nextElementSibling;else return this.findNextSiblingOfAncestor(parentNodeElement); } else { return null; } } }, { key: "findLastVisibleDescendant", value: function findLastVisibleDescendant(nodeElement) { var childrenListElement = nodeElement.children[1]; if (childrenListElement) { var lastChildElement = childrenListElement.children[childrenListElement.children.length - 1]; return this.findLastVisibleDescendant(lastChildElement); } else { return nodeElement; } } }, { key: "getParentNodeElement", value: function getParentNodeElement(nodeElement) { var parentNodeElement = nodeElement.parentElement.parentElement; return DomHandler.hasClass(parentNodeElement, 'p-treenode') ? parentNodeElement : null; } }, { key: "focusNode", value: function focusNode(element) { element.children[0].focus(); } }, { key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, node: this.props.node }); } if (event.target.className && event.target.className.constructor === String && event.target.className.indexOf('p-tree-toggler') === 0 || this.props.disabled) { return; } if (this.props.selectionMode && this.props.node.selectable !== false) { var selectionKeys; if (this.isCheckboxSelectionMode()) { var checked = this.isChecked(); selectionKeys = this.props.selectionKeys ? _objectSpread$1({}, 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 }); } } } else { var selected = this.isSelected(); var metaSelection = this.nodeTouched ? false : this.props.metaKeySelection; 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[this.props.node.key]; } if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: this.props.node }); } } else { if (this.isSingleSelectionMode()) { selectionKeys = this.props.node.key; } else if (this.isMultipleSelectionMode()) { selectionKeys = !metaKey ? {} : this.props.selectionKeys ? _objectSpread$1({}, this.props.selectionKeys) : {}; selectionKeys[this.props.node.key] = true; } if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: this.props.node }); } } } else { if (this.isSingleSelectionMode()) { if (selected) { selectionKeys = null; if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: this.props.node }); } } else { selectionKeys = this.props.node.key; if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: this.props.node }); } } } else { if (selected) { selectionKeys = _objectSpread$1({}, this.props.selectionKeys); delete selectionKeys[this.props.node.key]; if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: this.props.node }); } } else { selectionKeys = this.props.selectionKeys ? _objectSpread$1({}, this.props.selectionKeys) : {}; selectionKeys[this.props.node.key] = true; if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: this.props.node }); } } } } } if (this.props.onSelectionChange) { this.props.onSelectionChange({ originalEvent: event, value: selectionKeys }); } } this.nodeTouched = false; } }, { key: "onDoubleClick", value: function onDoubleClick(event) { if (this.props.onDoubleClick) { this.props.onDoubleClick({ originalEvent: event, node: this.props.node }); } } }, { key: "onRightClick", value: function onRightClick(event) { if (this.props.disabled) { return; } DomHandler.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: "propagateUp", value: function propagateUp(event) { var check = event.check; var selectionKeys = event.selectionKeys; var checkedChildCount = 0; var childPartialSelected = false; var _iterator = _createForOfIteratorHelper$1(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 delete selectionKeys[this.props.node.key]; } 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: "isSelected", value: function isSelected() { if (this.props.selectionMode && this.props.selectionKeys) return this.isSingleSelectionMode() ? 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: "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: "isCheckboxSelectionMode", value: function isCheckboxSelectionMode() { return this.props.selectionMode && this.props.selectionMode === 'checkbox'; } }, { key: "onTouchEnd", value: function onTouchEnd() { this.nodeTouched = true; } }, { key: "onDropPoint", value: function onDropPoint(event, position) { event.preventDefault(); if (this.props.node.droppable !== false) { DomHandler.removeClass(event.target, 'p-treenode-droppoint-active'); if (this.props.onDropPoint) { this.props.onDropPoint({ originalEvent: event, path: this.props.path, index: this.props.index, position: position }); } } } }, { key: "onDropPointDragOver", value: function onDropPointDragOver(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) { event.dataTransfer.dropEffect = 'move'; event.preventDefault(); } } }, { key: "onDropPointDragEnter", value: function onDropPointDragEnter(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) { DomHandler.addClass(event.target, 'p-treenode-droppoint-active'); } } }, { key: "onDropPointDragLeave", value: function onDropPointDragLeave(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) { DomHandler.removeClass(event.target, 'p-treenode-droppoint-active'); } } }, { key: "onDrop", value: function onDrop(event) { if (this.props.dragdropScope && this.props.node.droppable !== false) { DomHandler.removeClass(this.contentElement, 'p-treenode-dragover'); event.preventDefault(); event.stopPropagation(); if (this.props.onDrop) { this.props.onDrop({ originalEvent: event, path: this.props.path, index: this.props.index }); } } } }, { key: "onDragOver", value: function onDragOver(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) { event.dataTransfer.dropEffect = 'move'; event.preventDefault(); event.stopPropagation(); } } }, { key: "onDragEnter", value: function onDragEnter(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) { DomHandler.addClass(this.contentElement, 'p-treenode-dragover'); } } }, { key: "onDragLeave", value: function onDragLeave(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) { var rect = event.currentTarget.getBoundingClientRect(); if (event.nativeEvent.x > rect.left + rect.width || event.nativeEvent.x < rect.left || event.nativeEvent.y >= Math.floor(rect.top + rect.height) || event.nativeEvent.y < rect.top) { DomHandler.removeClass(this.contentElement, 'p-treenode-dragover'); } } } }, { key: "onDragStart", value: function onDragStart(event) { event.dataTransfer.setData("text", this.props.dragdropScope); event.dataTransfer.setData(this.props.dragdropScope, this.props.dragdropScope); if (this.props.onDragStart) { this.props.onDragStart({ originalEvent: event, path: this.props.path, index: this.props.index }); } } }, { key: "onDragEnd", value: function onDragEnd(event) { if (this.props.onDragEnd) { this.props.onDragEnd({ originalEvent: event }); } } }, { key: "renderLabel", value: function renderLabel() { var content = /*#__PURE__*/React.createElement("span", { className: "p-treenode-label" }, this.props.node.label); if (this.props.nodeTemplate) { var defaultContentOptions = { onTogglerClick: this.onTogglerClick, className: 'p-treenode-label', element: content, props: this.props, expanded: this.isExpanded() }; content = ObjectUtils.getJSXElement(this.props.nodeTemplate, this.props.node, defaultContentOptions); } return content; } }, { key: "renderCheckbox", value: function renderCheckbox() { if (this.isCheckboxSelectionMode() && 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, 'p-disabled': this.props.disabled }); 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-component" }, /*#__PURE__*/React.createElement("div", { className: className, role: "checkbox", "aria-checked": checked }, /*#__PURE__*/React.createElement("span", { className: icon }))); } return null; } }, { key: "renderIcon", value: function renderIcon(expanded) { var icon = this.props.node.icon || (expanded ? this.props.node.expandedIcon : this.props.node.collapsedIcon); if (icon) { var className = classNames('p-treenode-icon', icon); return /*#__PURE__*/React.createElement("span", { className: className }); } return null; } }, { key: "renderToggler", value: function renderToggler(expanded) { var iconClassName = classNames('p-tree-toggler-icon pi pi-fw', { 'pi-chevron-right': !expanded, 'pi-chevron-down': expanded }); var content = /*#__PURE__*/React.createElement("button", { type: "button", className: "p-tree-toggler p-link", tabIndex: -1, onClick: this.onTogglerClick }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (this.props.togglerTemplate) { var defaultContentOptions = { onClick: this.onTogglerClick, containerClassName: 'p-tree-toggler p-link', iconClassName: 'p-tree-toggler-icon', element: content, props: this.props, expanded: expanded }; content = ObjectUtils.getJSXElement(this.props.togglerTemplate, this.props.node, defaultContentOptions); } return content; } }, { key: "renderDropPoint", value: function renderDropPoint(position) { var _this2 = this; if (this.props.dragdropScope) { return /*#__PURE__*/React.createElement("li", { className: "p-treenode-droppoint", onDrop: function onDrop(event) { return _this2.onDropPoint(event, position); }, onDragOver: this.onDropPointDragOver, onDragEnter: this.onDropPointDragEnter, onDragLeave: this.onDropPointDragLeave }); } return null; } }, { key: "renderContent", value: function renderContent() { var _this3 = this; var selected = this.isSelected(); var checked = this.isChecked(); var className = classNames('p-treenode-content', this.props.node.className, { 'p-treenode-selectable': this.props.selectionMode && this.props.node.selectable !== false, 'p-highlight': this.isCheckboxSelectionMode() ? checked : selected, 'p-highlight-contextmenu': this.props.contextMenuSelectionKey && this.props.contextMenuSelectionKey === this.props.node.key, 'p-disabled': this.props.disabled }); var expanded = this.isExpanded(); var toggler = this.renderToggler(expanded); var checkbox = this.renderCheckbox(); var icon = this.renderIcon(expanded); var label = this.renderLabel(); var tabIndex = this.props.disabled ? undefined : 0; return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this3.contentElement = el; }, className: className, style: this.props.node.style, onClick: this.onClick, onDoubleClick: this.onDoubleClick, onContextMenu: this.onRightClick, onTouchEnd: this.onTouchEnd, draggable: this.props.dragdropScope && this.props.node.draggable !== false && !this.props.disabled, onDrop: this.onDrop, onDragOver: this.onDragOver, onDragEnter: this.onDragEnter, onDragLeave: this.onDragLeave, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd, tabIndex: tabIndex, onKeyDown: this.onNodeKeyDown, role: "treeitem", "aria-posinset": this.props.index + 1, "aria-expanded": this.isExpanded(), "aria-selected": checked || selected }, toggler, checkbox, icon, label); } }, { key: "renderChildren", value: function renderChildren() { var _this4 = this; if (this.props.node.children && this.props.node.children.length && this.isExpanded()) { return /*#__PURE__*/React.createElement("ul", { className: "p-treenode-children", role: "group" }, this.props.node.children.map(function (childNode, index) { return /*#__PURE__*/React.createElement(UITreeNode, { key: childNode.key || childNode.label, node: childNode, parent: _this4.props.node, index: index, last: index === _this4.props.node.children.length - 1, path: _this4.props.path + '-' + index, disabled: _this4.props.disabled, selectionMode: _this4.props.selectionMode, selectionKeys: _this4.props.selectionKeys, onSelectionChange: _this4.props.onSelectionChange, metaKeySelection: _this4.props.metaKeySelection, propagateSelectionDown: _this4.props.propagateSelectionDown, propagateSelectionUp: _this4.props.propagateSelectionUp, contextMenuSelectionKey: _this4.props.contextMenuSelectionKey, onContextMenuSelectionChange: _this4.props.onContextMenuSelectionChange, onContextMenu: _this4.props.onContextMenu, onExpand: _this4.props.onExpand, onCollapse: _this4.props.onCollapse, onSelect: _this4.props.onSelect, onUnselect: _this4.props.onUnselect, expandedKeys: _this4.props.expandedKeys, onToggle: _this4.props.onToggle, onPropagateUp: _this4.propagateUp, nodeTemplate: _this4.props.nodeTemplate, togglerTemplate: _this4.props.togglerTemplate, isNodeLeaf: _this4.props.isNodeLeaf, dragdropScope: _this4.props.dragdropScope, onDragStart: _this4.props.onDragStart, onDragEnd: _this4.props.onDragEnd, onDrop: _this4.props.onDrop, onDropPoint: _this4.props.onDropPoint }); })); } return null; } }, { key: "renderNode", value: function renderNode() { var className = classNames('p-treenode', { 'p-treenode-leaf': this.isLeaf() }, this.props.node.className); var content = this.renderContent(); var children = this.renderChildren(); return /*#__PURE__*/React.createElement("li", { className: className, style: this.props.node.style }, content, children); } }, { key: "render", value: function render() { var node = this.renderNode(); if (this.props.dragdropScope && !this.props.disabled) { var beforeDropPoint = this.renderDropPoint(-1); var afterDropPoint = this.props.last ? this.renderDropPoint(1) : null; return /*#__PURE__*/React.createElement(React.Fragment, null, beforeDropPoint, node, afterDropPoint); } else { return node; } } }]); return UITreeNode; }(Component); _defineProperty(UITreeNode, "defaultProps", { node: null, index: null, last: null, parent: null, path: null, disabled: false, selectionMode: null, selectionKeys: null, contextMenuSelectionKey: null, metaKeySelection: true, expandedKeys: null, propagateSelectionUp: true, propagateSelectionDown: true, dragdropScope: null, ariaLabel: null, ariaLabelledBy: null, nodeTemplate: null, togglerTemplate: null, isNodeLeaf: null, onSelect: null, onUnselect: null, onExpand: null, onCollapse: null, onToggle: null, onSelectionChange: null, onContextMenuSelectionChange: null, onPropagateUp: null, onDragStart: null, onDragEnd: null, onDrop: null, onDropPoint: null, onContextMenu: null, onNodeClick: null, onNodeDoubleClick: 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 Tree = /*#__PURE__*/function (_Component) { _inherits(Tree, _Component); var _super = _createSuper(Tree); function Tree(props) { var _this; _classCallCheck(this, Tree); _this = _super.call(this, props); _this.state = {}; if (!_this.props.onFilterValueChange) { _this.state['filterValue'] = ''; } if (!_this.props.onToggle) { _this.state['expandedKeys'] = _this.props.expandedKeys; } _this.isNodeLeaf = _this.isNodeLeaf.bind(_assertThisInitialized(_this)); _this.onToggle = _this.onToggle.bind(_assertThisInitialized(_this)); _this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this)); _this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); _this.onDropPoint = _this.onDropPoint.bind(_assertThisInitialized(_this)); _this.onFilterInputChange = _this.onFilterInputChange.bind(_assertThisInitialized(_this)); _this.onFilterInputKeyDown = _this.onFilterInputKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(Tree, [{ key: "getFilterValue", value: function getFilterValue() { return this.props.onFilterValueChange ? this.props.filterValue : this.state.filterValue; } }, { key: "getExpandedKeys", value: function getExpandedKeys() { return this.props.onToggle ? this.props.expandedKeys : this.state.expandedKeys; } }, { key: "getRootNode", value: function getRootNode() { return this.props.filter && this.filteredNodes ? this.filteredNodes : this.props.value; } }, { key: "onToggle", value: function onToggle(event) { if (this.props.onToggle) { this.props.onToggle(event); } else { this.setState({ expandedKeys: event.value }); } } }, { key: "onDragStart", value: function onDragStart(event) { this.dragState = { path: event.path, index: event.index }; } }, { key: "onDragEnd", value: function onDragEnd() { this.dragState = null; } }, { key: "onDrop", value: function onDrop(event) { if (this.validateDropNode(this.dragState.path, event.path)) { var value = JSON.parse(JSON.stringify(this.props.value)); var dragPaths = this.dragState.path.split('-'); dragPaths.pop(); var dragNodeParent = this.findNode(value, dragPaths); var dragNode = dragNodeParent ? dragNodeParent.children[this.dragState.index] : value[this.dragState.index]; var dropNode = this.findNode(value, event.path.split('-')); if (dropNode.children) dropNode.children.push(dragNode);else dropNode.children = [dragNode]; if (dragNodeParent) dragNodeParent.children.splice(this.dragState.index, 1);else value.splice(this.dragState.index, 1); if (this.props.onDragDrop) { this.props.onDragDrop({ originalEvent: event.originalEvent, value: value, dragNode: dragNode, dropNode: dropNode, dropIndex: event.index }); } } } }, { key: "onDropPoint", value: function onDropPoint(event) { if (this.validateDropPoint(event)) { var value = JSON.parse(JSON.stringify(this.props.value)); var dragPaths = this.dragState.path.split('-'); dragPaths.pop(); var dropPaths = event.path.split('-'); dropPaths.pop(); var dragNodeParent = this.findNode(value, dragPaths); var dropNodeParent = this.findNode(value, dropPaths); var dragNode = dragNodeParent ? dragNodeParent.children[this.dragState.index] : value[this.dragState.index]; var siblings = this.areSiblings(this.dragState.path, event.path); if (dragNodeParent) dragNodeParent.children.splice(this.dragState.index, 1);else value.splice(this.dragState.index, 1); if (event.position < 0) { var dropIndex = siblings ? this.dragState.index > event.index ? event.index : event.index - 1 : event.index; if (dropNodeParent) dropNodeParent.children.splice(dropIndex, 0, dragNode);else value.splice(dropIndex, 0, dragNode); } else { if (dropNodeParent) dropNodeParent.children.push(dragNode);else value.push(dragNode); } if (this.props.onDragDrop) { this.props.onDragDrop({ originalEvent: event.originalEvent, value: value, dragNode: dragNode, dropNode: dropNodeParent, dropIndex: event.index }); } } } }, { key: "validateDrop", value: function validateDrop(dragPath, dropPath) { if (!dragPath) { return false; } else { //same node if (dragPath === dropPath) { return false; } //parent dropped on an descendant if (dropPath.indexOf(dragPath) === 0) { return false; } return true; } } }, { key: "validateDropNode", value: function validateDropNode(dragPath, dropPath) { var validateDrop = this.validateDrop(dragPath, dropPath); if (validateDrop) { //child dropped on parent if (dragPath.indexOf('-') > 0 && dragPath.substring(0, dragPath.lastIndexOf('-')) === dropPath) { return false; } return true; } else { return false; } } }, { key: "validateDropPoint", value: function validateDropPoint(event) { var validateDrop = this.validateDrop(this.dragState.path, event.path); if (validateDrop) { //child dropped to next sibling's drop point if (event.position === -1 && this.areSiblings(this.dragState.path, event.path) && this.dragState.index + 1 === event.index) { return false; } return true; } else { return false; } } }, { key: "areSiblings", value: function areSiblings(path1, path2) { if (path1.length === 1 && path2.length === 1) return true;else return path1.substring(0, path1.lastIndexOf('-')) === path2.substring(0, path2.lastIndexOf('-')); } }, { key: "findNode", value: function findNode(value, path) { if (path.length === 0) { return null; } else { var index = parseInt(path[0], 10); var nextSearchRoot = value.children ? value.children[index] : value[index]; if (path.length === 1) { return nextSearchRoot; } else { path.shift(); return this.findNode(nextSearchRoot, path); } } } }, { key: "isNodeLeaf", value: function isNodeLeaf(node) { return node.leaf === false ? false : !(node.children && node.children.length); } }, { key: "onFilterInputKeyDown", value: function onFilterInputKeyDown(event) { //enter if (event.which === 13) { event.preventDefault(); } } }, { key: "onFilterInputChange", value: function onFilterInputChange(event) { this.filterChanged = true; var filterValue = event.target.value; if (this.props.onFilterValueChange) { this.props.onFilterValueChange({ originalEvent: event, value: filterValue }); } else { this.setState({ filterValue: filterValue }); } } }, { key: "filter", value: function filter(value) { this.setState({ filterValue: ObjectUtils.isNotEmpty(value) ? value : '' }, this._filter); } }, { key: "_filter", value: function _filter() { if (!this.filterChanged) { return; } var filterValue = this.getFilterValue(); if (ObjectUtils.isEmpty(filterValue)) { this.filteredNodes = this.props.value; } else { this.filteredNodes = []; var searchFields = this.props.filterBy.split(','); var filterText = filterValue.toLocaleLowerCase(this.props.filterLocale); var isStrictMode = this.props.filterMode === 'strict'; var _iterator = _createForOfIteratorHelper(this.props.value), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var node = _step.value; var copyNode = _objectSpread({}, node); var paramsWithoutNode = { searchFields: searchFields, filterText: filterText, isStrictMode: isStrictMode }; if (isStrictMode && (this.findFilteredNodes(copyNode, paramsWithoutNode) || this.isFilterMatched(copyNode, paramsWithoutNode)) || !isStrictMode && (this.isFilterMatched(copyNode, paramsWithoutNode) || this.findFilteredNodes(copyNode, paramsWithoutNode))) { this.filteredNodes.push(copyNode); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } this.filterChanged = false; } }, { key: "findFilteredNodes", value: function findFilteredNodes(node, paramsWithoutNode) { if (node) { var matched = false; if (node.children) { var childNodes = _toConsumableArray(node.children); node.children = []; var _iterator2 = _createForOfIteratorHelper(childNodes), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var childNode = _step2.value; var copyChildNode = _objectSpread({}, childNode); if (this.isFilterMatched(copyChildNode, paramsWithoutNode)) { matched = true; node.children.push(copyChildNode); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } if (matched) { node.expanded = true; return true; } } } }, { key: "isFilterMatched", value: function isFilterMatched(node, _ref) { var searchFields = _ref.searchFields, filterText = _ref.filterText, isStrictMode = _ref.isStrictMode; var matched = false; var _iterator3 = _createForOfIteratorHelper(searchFields), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var field = _step3.value; var fieldValue = String(ObjectUtils.resolveFieldData(node, field)).toLocaleLowerCase(this.props.filterLocale); if (fieldValue.indexOf(filterText) > -1) { matched = true; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } if (!matched || isStrictMode && !this.isNodeLeaf(node)) { matched = this.findFilteredNodes(node, { searchFields: searchFields, filterText: filterText, isStrictMode: isStrictMode }) || matched; } return matched; } }, { key: "renderRootChild", value: function renderRootChild(node, index, last) { return /*#__PURE__*/React.createElement(UITreeNode, { key: node.key || node.label, node: node, index: index, last: last, path: String(index), disabled: this.props.disabled, selectionMode: this.props.selectionMode, selectionKeys: this.props.selectionKeys, onSelectionChange: this.props.onSelectionChange, metaKeySelection: this.props.metaKeySelection, contextMenuSelectionKey: this.props.contextMenuSelectionKey, onContextMenuSelectionChange: this.props.onContextMenuSelectionChange, onContextMenu: this.props.onContextMenu, propagateSelectionDown: this.props.propagateSelectionDown, propagateSelectionUp: this.props.propagateSelectionUp, onExpand: this.props.onExpand, onCollapse: this.props.onCollapse, onSelect: this.props.onSelect, onUnselect: this.props.onUnselect, expandedKeys: this.getExpandedKeys(), onToggle: this.onToggle, nodeTemplate: this.props.nodeTemplate, togglerTemplate: this.props.togglerTemplate, isNodeLeaf: this.isNodeLeaf, dragdropScope: this.props.dragdropScope, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd, onDrop: this.onDrop, onDropPoint: this.onDropPoint, onNodeClick: this.props.onNodeClick, onNodeDoubleClick: this.props.onNodeDoubleClick }); } }, { key: "renderRootChildren", value: function renderRootChildren() { var _this2 = this; if (this.props.filter) { this.filterChanged = true; this._filter(); } var value = this.getRootNode(); return value.map(function (node, index) { return _this2.renderRootChild(node, index, index === value.length - 1); }); } }, { key: "renderModel", value: function renderModel() { if (this.props.value) { var rootNodes = this.renderRootChildren(); var contentClass = classNames('p-tree-container', this.props.contentClassName); return /*#__PURE__*/React.createElement("ul", { className: contentClass, role: "tree", "aria-label": this.props.ariaLabel, "aria-labelledby": this.props.ariaLabelledBy, style: this.props.contentStyle }, rootNodes); } return null; } }, { key: "renderLoader", value: function renderLoader() { if (this.props.loading) { var icon = classNames('p-tree-loading-icon pi-spin', this.props.loadingIcon); return /*#__PURE__*/React.createElement("div", { className: "p-tree-loading-overlay p-component-overlay" }, /*#__PURE__*/React.createElement("i", { className: icon })); } return null; } }, { key: "renderFilter", value: function renderFilter() { if (this.props.filter) { var filterValue = this.getFilterValue(); filterValue = ObjectUtils.isNotEmpty(filterValue) ? filterValue : ''; return /*#__PURE__*/React.createElement("div", { className: "p-tree-filter-container" }, /*#__PURE__*/React.createElement("input", { type: "text", value: filterValue, autoComplete: "off", className: "p-tree-filter p-inputtext p-component", placeholder: this.props.filterPlaceholder, onKeyDown: this.onFilterInputKeyDown, onChange: this.onFilterInputChange, disabled: this.props.disabled }), /*#__PURE__*/React.createElement("span", { className: "p-tree-filter-icon pi pi-search" })); } return null; } }, { key: "renderHeader", value: function renderHeader() { if (this.props.showHeader) { var filterElement = this.renderFilter(); var content = filterElement; if (this.props.header) { var defaultContentOptions = { filterContainerClassName: 'p-tree-filter-container', filterIconClasssName: 'p-tree-filter-icon pi pi-search', filterInput: { className: 'p-tree-filter p-inputtext p-component', onKeyDown: this.onFilterInputKeyDown, onChange: this.onFilterInputChange }, filterElement: filterElement, element: content, props: this.props }; content = ObjectUtils.getJSXElement(this.props.header, defaultContentOptions); } return /*#__PURE__*/React.createElement("div", { className: "p-tree-header" }, content); } return null; } }, { key: "renderFooter", value: function renderFooter() { var content = ObjectUtils.getJSXElement(this.props.footer, this.props); return /*#__PURE__*/React.createElement("div", { className: "p-tree-footer" }, content); } }, { key: "render", value: function render() { var className = classNames('p-tree p-component', this.props.className, { 'p-tree-selectable': this.props.selectionMode, 'p-tree-loading': this.props.loading, 'p-disabled': this.props.disabled }); var loader = this.renderLoader(); var content = this.renderModel(); var header = this.renderHeader(); var footer = this.renderFooter(); return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: className, style: this.props.style }, loader, header, content, footer); } }]); return Tree; }(Component); _defineProperty(Tree, "defaultProps", { id: null, value: null, disabled: false, selectionMode: null, selectionKeys: null, onSelectionChange: null, contextMenuSelectionKey: null, onContextMenuSelectionChange: null, expandedKeys: null, style: null, className: null, contentStyle: null, contentClassName: null, metaKeySelection: true, propagateSelectionUp: true, propagateSelectionDown: true, loading: false, loadingIcon: 'pi pi-spinner', dragdropScope: null, header: null, footer: null, showHeader: true, filter: false, filterValue: null, filterBy: 'label', filterMode: 'lenient', filterPlaceholder: null, filterLocale: undefined, nodeTemplate: null, togglerTemplate: null, onSelect: null, onUnselect: null, onExpand: null, onCollapse: null, onToggle: null, onDragDrop: null, onContextMenu: null, onFilterValueChange: null, onNodeClick: null, onNodeDoubleClick: null }); export { Tree };
ajax/libs/primereact/6.5.0-rc.2/carousel/carousel.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { UniqueComponentId, DomHandler, classNames } from 'primereact/utils'; import { Ripple } from 'primereact/ripple'; 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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _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 CarouselItem = /*#__PURE__*/function (_Component) { _inherits(CarouselItem, _Component); var _super = _createSuper(CarouselItem); function CarouselItem() { _classCallCheck(this, CarouselItem); return _super.apply(this, arguments); } _createClass(CarouselItem, [{ key: "render", value: function render() { var content = this.props.template(this.props.item); var itemClassName = classNames(this.props.className, 'p-carousel-item', { 'p-carousel-item-active': this.props.active, 'p-carousel-item-start': this.props.start, 'p-carousel-item-end': this.props.end }); return /*#__PURE__*/React.createElement("div", { className: itemClassName }, content); } }]); return CarouselItem; }(Component); _defineProperty(CarouselItem, "defaultProps", { template: null, item: null, active: false, start: false, end: false, className: null }); _defineProperty(CarouselItem, "propTypes", { template: PropTypes.func, item: PropTypes.any, active: PropTypes.bool, start: PropTypes.bool, end: PropTypes.bool, className: PropTypes.string }); var Carousel = /*#__PURE__*/function (_Component2) { _inherits(Carousel, _Component2); var _super2 = _createSuper(Carousel); function Carousel(props) { var _this; _classCallCheck(this, Carousel); _this = _super2.call(this, props); _this.state = { numVisible: props.numVisible, numScroll: props.numScroll, totalShiftedItems: props.page * props.numScroll * -1 }; if (!_this.props.onPageChange) { _this.state = _objectSpread(_objectSpread({}, _this.state), {}, { page: props.page }); } _this.navBackward = _this.navBackward.bind(_assertThisInitialized(_this)); _this.navForward = _this.navForward.bind(_assertThisInitialized(_this)); _this.onTransitionEnd = _this.onTransitionEnd.bind(_assertThisInitialized(_this)); _this.onTouchStart = _this.onTouchStart.bind(_assertThisInitialized(_this)); _this.onTouchMove = _this.onTouchMove.bind(_assertThisInitialized(_this)); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this)); _this.totalIndicators = 0; _this.remainingItems = 0; _this.allowAutoplay = !!_this.props.autoplayInterval; _this.circular = _this.props.circular || _this.allowAutoplay; _this.attributeSelector = UniqueComponentId(); _this.swipeThreshold = 20; return _this; } _createClass(Carousel, [{ key: "step", value: function step(dir, page) { var totalShiftedItems = this.state.totalShiftedItems; var isCircular = this.isCircular(); if (page != null) { totalShiftedItems = this.state.numScroll * page * -1; if (isCircular) { totalShiftedItems -= this.state.numVisible; } this.isRemainingItemsAdded = false; } else { totalShiftedItems += this.state.numScroll * dir; if (this.isRemainingItemsAdded) { totalShiftedItems += this.remainingItems - this.state.numScroll * dir; this.isRemainingItemsAdded = false; } var originalShiftedItems = isCircular ? totalShiftedItems + this.state.numVisible : totalShiftedItems; page = Math.abs(Math.floor(originalShiftedItems / this.state.numScroll)); } if (isCircular && this.state.page === this.totalIndicators - 1 && dir === -1) { totalShiftedItems = -1 * (this.props.value.length + this.state.numVisible); page = 0; } else if (isCircular && this.state.page === 0 && dir === 1) { totalShiftedItems = 0; page = this.totalIndicators - 1; } else if (page === this.totalIndicators - 1 && this.remainingItems > 0) { totalShiftedItems += this.remainingItems * -1 - this.state.numScroll * dir; this.isRemainingItemsAdded = true; } if (this.itemsContainer) { DomHandler.removeClass(this.itemsContainer, 'p-items-hidden'); this.changePosition(totalShiftedItems); this.itemsContainer.style.transition = 'transform 500ms ease 0s'; } if (this.props.onPageChange) { this.setState({ totalShiftedItems: totalShiftedItems }); this.props.onPageChange({ page: page }); } else { this.setState({ page: page, totalShiftedItems: totalShiftedItems }); } } }, { key: "calculatePosition", value: function calculatePosition() { if (this.itemsContainer && this.responsiveOptions) { var windowWidth = window.innerWidth; var matchedResponsiveData = { numVisible: this.props.numVisible, numScroll: this.props.numScroll }; for (var i = 0; i < this.responsiveOptions.length; i++) { var res = this.responsiveOptions[i]; if (parseInt(res.breakpoint, 10) >= windowWidth) { matchedResponsiveData = res; } } var state = {}; if (this.state.numScroll !== matchedResponsiveData.numScroll) { var page = this.getPage(); page = Math.floor(page * this.state.numScroll / matchedResponsiveData.numScroll); var totalShiftedItems = matchedResponsiveData.numScroll * page * -1; if (this.isCircular()) { totalShiftedItems -= matchedResponsiveData.numVisible; } state = { totalShiftedItems: totalShiftedItems, numScroll: matchedResponsiveData.numScroll }; if (this.props.onPageChange) { this.props.onPageChange({ page: page }); } else { state = _objectSpread(_objectSpread({}, state), {}, { page: page }); } } if (this.state.numVisible !== matchedResponsiveData.numVisible) { state = _objectSpread(_objectSpread({}, state), {}, { numVisible: matchedResponsiveData.numVisible }); } if (Object.keys(state).length) { this.setState(state); } } } }, { key: "navBackward", value: function navBackward(e, page) { if (this.circular || this.getPage() !== 0) { this.step(1, page); } this.allowAutoplay = false; if (e.cancelable) { e.preventDefault(); } } }, { key: "navForward", value: function navForward(e, page) { if (this.circular || this.getPage() < this.totalIndicators - 1) { this.step(-1, page); } this.allowAutoplay = false; if (e.cancelable) { e.preventDefault(); } } }, { key: "onDotClick", value: function onDotClick(e, page) { var currentPage = this.getPage(); if (page > currentPage) { this.navForward(e, page); } else if (page < currentPage) { this.navBackward(e, page); } } }, { key: "onTransitionEnd", value: function onTransitionEnd() { if (this.itemsContainer) { DomHandler.addClass(this.itemsContainer, 'p-items-hidden'); this.itemsContainer.style.transition = ''; if ((this.state.page === 0 || this.state.page === this.totalIndicators - 1) && this.isCircular()) { this.changePosition(this.state.totalShiftedItems); } } } }, { key: "onTouchStart", value: function onTouchStart(e) { var touchobj = e.changedTouches[0]; this.startPos = { x: touchobj.pageX, y: touchobj.pageY }; } }, { key: "onTouchMove", value: function onTouchMove(e) { if (e.cancelable) { e.preventDefault(); } } }, { key: "onTouchEnd", value: function onTouchEnd(e) { var touchobj = e.changedTouches[0]; if (this.isVertical()) { this.changePageOnTouch(e, touchobj.pageY - this.startPos.y); } else { this.changePageOnTouch(e, touchobj.pageX - this.startPos.x); } } }, { key: "changePageOnTouch", value: function changePageOnTouch(e, diff) { if (Math.abs(diff) > this.swipeThreshold) { if (diff < 0) { // left this.navForward(e); } else { // right this.navBackward(e); } } } }, { key: "bindDocumentListeners", value: function bindDocumentListeners() { var _this2 = this; if (!this.documentResizeListener) { this.documentResizeListener = function () { _this2.calculatePosition(); }; window.addEventListener('resize', this.documentResizeListener); } } }, { key: "unbindDocumentListeners", value: function unbindDocumentListeners() { if (this.documentResizeListener) { window.removeEventListener('resize', this.documentResizeListener); this.documentResizeListener = null; } } }, { key: "isVertical", value: function isVertical() { return this.props.orientation === 'vertical'; } }, { key: "isCircular", value: function isCircular() { return this.circular && this.props.value.length >= this.state.numVisible; } }, { key: "getPage", value: function getPage() { return this.props.onPageChange ? this.props.page : this.state.page; } }, { key: "getTotalIndicators", value: function getTotalIndicators() { return this.props.value ? Math.ceil((this.props.value.length - this.state.numVisible) / this.state.numScroll) + 1 : 0; } }, { key: "isAutoplay", value: function isAutoplay() { return this.props.autoplayInterval && this.allowAutoplay; } }, { key: "startAutoplay", value: function startAutoplay() { var _this3 = this; this.interval = setInterval(function () { if (_this3.state.page === _this3.totalIndicators - 1) { _this3.step(-1, 0); } else { _this3.step(-1, _this3.state.page + 1); } }, this.props.autoplayInterval); } }, { key: "stopAutoplay", value: function stopAutoplay() { if (this.interval) { clearInterval(this.interval); } } }, { key: "createStyle", value: function createStyle() { if (!this.carouselStyle) { this.carouselStyle = document.createElement('style'); document.body.appendChild(this.carouselStyle); } var innerHTML = "\n .p-carousel[".concat(this.attributeSelector, "] .p-carousel-item {\n flex: 1 0 ").concat(100 / this.state.numVisible, "%\n }\n "); if (this.props.responsiveOptions) { this.responsiveOptions = _toConsumableArray(this.props.responsiveOptions); this.responsiveOptions.sort(function (data1, data2) { var value1 = data1.breakpoint; var value2 = data2.breakpoint; var result = null; if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2, undefined, { numeric: true });else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0; return -1 * result; }); for (var i = 0; i < this.responsiveOptions.length; i++) { var res = this.responsiveOptions[i]; innerHTML += "\n @media screen and (max-width: ".concat(res.breakpoint, ") {\n .p-carousel[").concat(this.attributeSelector, "] .p-carousel-item {\n flex: 1 0 ").concat(100 / res.numVisible, "%\n }\n }\n "); } } this.carouselStyle.innerHTML = innerHTML; } }, { key: "changePosition", value: function changePosition(totalShiftedItems) { if (this.itemsContainer) { this.itemsContainer.style.transform = this.isVertical() ? "translate3d(0, ".concat(totalShiftedItems * (100 / this.state.numVisible), "%, 0)") : "translate3d(".concat(totalShiftedItems * (100 / this.state.numVisible), "%, 0, 0)"); } } }, { key: "componentDidMount", value: function componentDidMount() { if (this.container) { this.container.setAttribute(this.attributeSelector, ''); } this.createStyle(); this.calculatePosition(); this.changePosition(this.state.totalShiftedItems); if (this.props.responsiveOptions) { this.bindDocumentListeners(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { var isCircular = this.isCircular(); var stateChanged = false; var totalShiftedItems = this.state.totalShiftedItems; if (this.props.autoplayInterval) { this.stopAutoplay(); } if (prevState.numScroll !== this.state.numScroll || prevState.numVisible !== this.state.numVisible || this.props.value && prevProps.value && prevProps.value.length !== this.props.value.length) { this.remainingItems = (this.props.value.length - this.state.numVisible) % this.state.numScroll; var page = this.getPage(); if (this.totalIndicators !== 0 && page >= this.totalIndicators) { page = this.totalIndicators - 1; if (this.props.onPageChange) { this.props.onPageChange({ page: page }); } else { this.setState({ page: page }); } stateChanged = true; } totalShiftedItems = page * this.state.numScroll * -1; if (isCircular) { totalShiftedItems -= this.state.numVisible; } if (page === this.totalIndicators - 1 && this.remainingItems > 0) { totalShiftedItems += -1 * this.remainingItems + this.state.numScroll; this.isRemainingItemsAdded = true; } else { this.isRemainingItemsAdded = false; } if (totalShiftedItems !== this.state.totalShiftedItems) { this.setState({ totalShiftedItems: totalShiftedItems }); stateChanged = true; } this.changePosition(totalShiftedItems); } if (isCircular) { if (this.state.page === 0) { totalShiftedItems = -1 * this.state.numVisible; } else if (totalShiftedItems === 0) { totalShiftedItems = -1 * this.props.value.length; if (this.remainingItems > 0) { this.isRemainingItemsAdded = true; } } if (totalShiftedItems !== this.state.totalShiftedItems) { this.setState({ totalShiftedItems: totalShiftedItems }); stateChanged = true; } } if (prevProps.page !== this.props.page) { if (this.props.page > prevProps.page && this.props.page <= this.totalIndicators - 1) { this.step(-1, this.props.page); } else if (this.props.page < prevProps.page) { this.step(1, this.props.page); } } if (!stateChanged && this.isAutoplay()) { this.startAutoplay(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.props.responsiveOptions) { this.unbindDocumentListeners(); } if (this.props.autoplayInterval) { this.stopAutoplay(); } } }, { key: "renderItems", value: function renderItems() { var _this4 = this; if (this.props.value && this.props.value.length) { var isCircular = this.isCircular(); var clonedItemsForStarting = null; var clonedItemsForFinishing = null; if (isCircular) { var clonedElements = null; clonedElements = this.props.value.slice(-1 * this.state.numVisible); clonedItemsForStarting = clonedElements.map(function (item, index) { var isActive = _this4.state.totalShiftedItems * -1 === _this4.props.value.length + _this4.state.numVisible, start = index === 0, end = index === clonedElements.length - 1; return /*#__PURE__*/React.createElement(CarouselItem, { key: index + '_scloned', className: "p-carousel-item-cloned", template: _this4.props.itemTemplate, item: item, active: isActive, start: start, end: end }); }); clonedElements = this.props.value.slice(0, this.state.numVisible); clonedItemsForFinishing = clonedElements.map(function (item, index) { var isActive = _this4.state.totalShiftedItems === 0, start = index === 0, end = index === clonedElements.length - 1; return /*#__PURE__*/React.createElement(CarouselItem, { key: index + '_fcloned', className: "p-carousel-item-cloned", template: _this4.props.itemTemplate, item: item, active: isActive, start: start, end: end }); }); } var items = this.props.value.map(function (item, index) { var firstIndex = isCircular ? -1 * (_this4.state.totalShiftedItems + _this4.state.numVisible) : _this4.state.totalShiftedItems * -1, lastIndex = firstIndex + _this4.state.numVisible - 1, isActive = firstIndex <= index && lastIndex >= index, start = firstIndex === index, end = lastIndex === index; return /*#__PURE__*/React.createElement(CarouselItem, { key: index, template: _this4.props.itemTemplate, item: item, active: isActive, start: start, end: end }); }); return /*#__PURE__*/React.createElement(React.Fragment, null, clonedItemsForStarting, items, clonedItemsForFinishing); } } }, { key: "renderHeader", value: function renderHeader() { if (this.props.header) { return /*#__PURE__*/React.createElement("div", { className: "p-carousel-header" }, this.props.header); } return null; } }, { key: "renderFooter", value: function renderFooter() { if (this.props.footer) { return /*#__PURE__*/React.createElement("div", { className: "p-carousel-footer" }, this.props.footer); } return null; } }, { key: "renderContent", value: function renderContent() { var _this5 = this; var items = this.renderItems(); var height = this.isVertical() ? this.props.verticalViewPortHeight : 'auto'; var backwardNavigator = this.renderBackwardNavigator(); var forwardNavigator = this.renderForwardNavigator(); var containerClassName = classNames('p-carousel-container', this.props.containerClassName); return /*#__PURE__*/React.createElement("div", { className: containerClassName }, backwardNavigator, /*#__PURE__*/React.createElement("div", { className: "p-carousel-items-content", style: { 'height': height } }, /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this5.itemsContainer = el; }, className: "p-carousel-items-container", onTransitionEnd: this.onTransitionEnd, onTouchStart: this.onTouchStart, onTouchMove: this.onTouchMove, onTouchEnd: this.onTouchEnd }, items)), forwardNavigator); } }, { key: "renderBackwardNavigator", value: function renderBackwardNavigator() { var isDisabled = (!this.circular || this.props.value && this.props.value.length < this.state.numVisible) && this.getPage() === 0; var buttonClassName = classNames('p-carousel-prev p-link', { 'p-disabled': isDisabled }), iconClassName = classNames('p-carousel-prev-icon pi', { 'pi-chevron-left': !this.isVertical(), 'pi-chevron-up': this.isVertical() }); return /*#__PURE__*/React.createElement("button", { type: "button", className: buttonClassName, onClick: this.navBackward, disabled: isDisabled }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); } }, { key: "renderForwardNavigator", value: function renderForwardNavigator() { var isDisabled = (!this.circular || this.props.value && this.props.value.length < this.state.numVisible) && (this.getPage() === this.totalIndicators - 1 || this.totalIndicators === 0); var buttonClassName = classNames('p-carousel-next p-link', { 'p-disabled': isDisabled }), iconClassName = classNames('p-carousel-next-icon pi', { 'pi-chevron-right': !this.isVertical(), 'pi-chevron-down': this.isVertical() }); return /*#__PURE__*/React.createElement("button", { type: "button", className: buttonClassName, onClick: this.navForward, disabled: isDisabled }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); } }, { key: "renderIndicator", value: function renderIndicator(index) { var _this6 = this; var isActive = this.getPage() === index, indicatorItemClassName = classNames('p-carousel-indicator', { 'p-highlight': isActive }); return /*#__PURE__*/React.createElement("li", { className: indicatorItemClassName, key: 'p-carousel-indicator-' + index }, /*#__PURE__*/React.createElement("button", { type: "button", className: "p-link", onClick: function onClick(e) { return _this6.onDotClick(e, index); } }, /*#__PURE__*/React.createElement(Ripple, null))); } }, { key: "renderIndicators", value: function renderIndicators() { var indicatorsContentClassName = classNames('p-carousel-indicators p-reset', this.props.indicatorsContentClassName); var indicators = []; for (var i = 0; i < this.totalIndicators; i++) { indicators.push(this.renderIndicator(i)); } return /*#__PURE__*/React.createElement("ul", { className: indicatorsContentClassName }, indicators); } }, { key: "render", value: function render() { var _this7 = this; var className = classNames('p-carousel p-component', { 'p-carousel-vertical': this.isVertical(), 'p-carousel-horizontal': !this.isVertical() }, this.props.className); var contentClassName = classNames('p-carousel-content', this.props.contentClassName); this.totalIndicators = this.getTotalIndicators(); var content = this.renderContent(); var indicators = this.renderIndicators(); var header = this.renderHeader(); var footer = this.renderFooter(); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this7.container = el; }, id: this.props.id, className: className, style: this.props.style }, header, /*#__PURE__*/React.createElement("div", { className: contentClassName }, content, indicators), footer); } }]); return Carousel; }(Component); _defineProperty(Carousel, "defaultProps", { id: null, value: null, page: 0, header: null, footer: null, style: null, className: null, itemTemplate: null, circular: false, autoplayInterval: 0, numVisible: 1, numScroll: 1, responsiveOptions: null, orientation: "horizontal", verticalViewPortHeight: "300px", contentClassName: null, containerClassName: null, indicatorsContentClassName: null, onPageChange: null }); _defineProperty(Carousel, "propTypes", { id: PropTypes.string, value: PropTypes.any, page: PropTypes.number, header: PropTypes.any, footer: PropTypes.any, style: PropTypes.object, className: PropTypes.string, itemTemplate: PropTypes.any, circular: PropTypes.bool, autoplayInterval: PropTypes.number, numVisible: PropTypes.number, numScroll: PropTypes.number, responsiveOptions: PropTypes.array, orientation: PropTypes.string, verticalViewPortHeight: PropTypes.string, contentClassName: PropTypes.string, containerClassName: PropTypes.string, indicatorsContentClassName: PropTypes.string, onPageChange: PropTypes.func }); export { Carousel };
ajax/libs/primereact/7.0.0-rc.2/orderlist/orderlist.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { Button } from 'primereact/button'; import { ObjectUtils, DomHandler, classNames, Ripple } from 'primereact/core'; function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } 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$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var OrderListControls = /*#__PURE__*/function (_Component) { _inherits(OrderListControls, _Component); var _super = _createSuper$2(OrderListControls); function OrderListControls() { var _this; _classCallCheck(this, OrderListControls); _this = _super.call(this); _this.moveUp = _this.moveUp.bind(_assertThisInitialized(_this)); _this.moveTop = _this.moveTop.bind(_assertThisInitialized(_this)); _this.moveDown = _this.moveDown.bind(_assertThisInitialized(_this)); _this.moveBottom = _this.moveBottom.bind(_assertThisInitialized(_this)); return _this; } _createClass(OrderListControls, [{ key: "moveUp", value: function moveUp(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = 0; i < this.props.selection.length; i++) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== 0) { var movedItem = value[selectedItemIndex]; var temp = value[selectedItemIndex - 1]; value[selectedItemIndex - 1] = movedItem; value[selectedItemIndex] = temp; } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'up' }); } } } }, { key: "moveTop", value: function moveTop(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = 0; i < this.props.selection.length; i++) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== 0) { var movedItem = value.splice(selectedItemIndex, 1)[0]; value.unshift(movedItem); } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'top' }); } } } }, { key: "moveDown", value: function moveDown(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = this.props.selection.length - 1; i >= 0; i--) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== value.length - 1) { var movedItem = value[selectedItemIndex]; var temp = value[selectedItemIndex + 1]; value[selectedItemIndex + 1] = movedItem; value[selectedItemIndex] = temp; } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'down' }); } } } }, { key: "moveBottom", value: function moveBottom(event) { if (this.props.selection) { var value = _toConsumableArray(this.props.value); for (var i = this.props.selection.length - 1; i >= 0; i--) { var selectedItem = this.props.selection[i]; var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey); if (selectedItemIndex !== value.length - 1) { var movedItem = value.splice(selectedItemIndex, 1)[0]; value.push(movedItem); } else { break; } } if (this.props.onReorder) { this.props.onReorder({ originalEvent: event, value: value, direction: 'bottom' }); } } } }, { key: "render", value: function render() { return /*#__PURE__*/React.createElement("div", { className: "p-orderlist-controls" }, /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-up", onClick: this.moveUp }), /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-double-up", onClick: this.moveTop }), /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-down", onClick: this.moveDown }), /*#__PURE__*/React.createElement(Button, { type: "button", icon: "pi pi-angle-double-down", onClick: this.moveBottom })); } }]); return OrderListControls; }(Component); function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var OrderListSubList = /*#__PURE__*/function (_Component) { _inherits(OrderListSubList, _Component); var _super = _createSuper$1(OrderListSubList); function OrderListSubList(props) { var _this; _classCallCheck(this, OrderListSubList); _this = _super.call(this, props); _this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this)); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); _this.onListMouseMove = _this.onListMouseMove.bind(_assertThisInitialized(_this)); return _this; } _createClass(OrderListSubList, [{ key: "isSelected", value: function isSelected(item) { return ObjectUtils.findIndexInList(item, this.props.selection, this.props.dataKey) !== -1; } }, { key: "onDragStart", value: function onDragStart(event, index) { this.dragging = true; this.draggedItemIndex = index; if (this.props.dragdropScope) { event.dataTransfer.setData('text', 'orderlist'); } } }, { key: "onDragOver", value: function onDragOver(event, index) { if (this.draggedItemIndex !== index && this.draggedItemIndex + 1 !== index) { this.dragOverItemIndex = index; DomHandler.addClass(event.target, 'p-orderlist-droppoint-highlight'); event.preventDefault(); } } }, { key: "onDragLeave", value: function onDragLeave(event) { this.dragOverItemIndex = null; DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight'); } }, { key: "onDrop", value: function onDrop(event) { var dropIndex = this.draggedItemIndex > this.dragOverItemIndex ? this.dragOverItemIndex : this.dragOverItemIndex === 0 ? 0 : this.dragOverItemIndex - 1; var value = _toConsumableArray(this.props.value); ObjectUtils.reorderArray(value, this.draggedItemIndex, dropIndex); this.dragOverItemIndex = null; DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight'); if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: value }); } } }, { key: "onDragEnd", value: function onDragEnd(event) { this.dragging = false; } }, { key: "onListMouseMove", value: function onListMouseMove(event) { if (this.dragging) { var offsetY = this.listElement.getBoundingClientRect().top + DomHandler.getWindowScrollTop(); var bottomDiff = offsetY + this.listElement.clientHeight - event.pageY; var topDiff = event.pageY - offsetY; if (bottomDiff < 25 && bottomDiff > 0) this.listElement.scrollTop += 15;else if (topDiff < 25 && topDiff > 0) this.listElement.scrollTop -= 15; } } }, { key: "renderDropPoint", value: function renderDropPoint(index, key) { var _this2 = this; return /*#__PURE__*/React.createElement("li", { key: key, className: "p-orderlist-droppoint", onDragOver: function onDragOver(e) { return _this2.onDragOver(e, index + 1); }, onDragLeave: this.onDragLeave, onDrop: this.onDrop }); } }, { key: "render", value: function render() { var _this3 = this; var header = null; var items = null; if (this.props.header) { header = /*#__PURE__*/React.createElement("div", { className: "p-orderlist-header" }, this.props.header); } if (this.props.value) { items = this.props.value.map(function (item, i) { var content = _this3.props.itemTemplate ? _this3.props.itemTemplate(item) : item; var itemClassName = classNames('p-orderlist-item', { 'p-highlight': _this3.isSelected(item) }, _this3.props.className); var key = JSON.stringify(item); if (_this3.props.dragdrop) { var _items = [_this3.renderDropPoint(i, key + '_droppoint'), /*#__PURE__*/React.createElement("li", { key: key, className: itemClassName, onClick: function onClick(e) { return _this3.props.onItemClick({ originalEvent: e, value: item, index: i }); }, onKeyDown: function onKeyDown(e) { return _this3.props.onItemKeyDown({ originalEvent: e, value: item, index: i }); }, role: "option", "aria-selected": _this3.isSelected(item), draggable: "true", onDragStart: function onDragStart(e) { return _this3.onDragStart(e, i); }, onDragEnd: _this3.onDragEnd, tabIndex: _this3.props.tabIndex }, content, /*#__PURE__*/React.createElement(Ripple, null))]; if (i === _this3.props.value.length - 1) { _items.push(_this3.renderDropPoint(item, i, key + '_droppoint_end')); } return _items; } else { return /*#__PURE__*/React.createElement("li", { key: JSON.stringify(item), className: itemClassName, role: "option", "aria-selected": _this3.isSelected(item), onClick: function onClick(e) { return _this3.props.onItemClick({ originalEvent: e, value: item, index: i }); }, onKeyDown: function onKeyDown(e) { return _this3.props.onItemKeyDown({ originalEvent: e, value: item, index: i }); }, tabIndex: _this3.props.tabIndex }, content); } }); } return /*#__PURE__*/React.createElement("div", { className: "p-orderlist-list-container" }, header, /*#__PURE__*/React.createElement("ul", { ref: function ref(el) { return _this3.listElement = el; }, className: "p-orderlist-list", style: this.props.listStyle, onDragOver: this.onListMouseMove, role: "listbox", "aria-multiselectable": true }, items)); } }]); return OrderListSubList; }(Component); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var OrderList = /*#__PURE__*/function (_Component) { _inherits(OrderList, _Component); var _super = _createSuper(OrderList); function OrderList(props) { var _this; _classCallCheck(this, OrderList); _this = _super.call(this, props); _this.state = { selection: [] }; _this.onItemClick = _this.onItemClick.bind(_assertThisInitialized(_this)); _this.onItemKeyDown = _this.onItemKeyDown.bind(_assertThisInitialized(_this)); _this.onReorder = _this.onReorder.bind(_assertThisInitialized(_this)); return _this; } _createClass(OrderList, [{ key: "onItemClick", value: function onItemClick(event) { var metaKey = event.originalEvent.metaKey || event.originalEvent.ctrlKey; var index = ObjectUtils.findIndexInList(event.value, this.state.selection, this.props.dataKey); var selected = index !== -1; var selection; if (selected) { if (metaKey) selection = this.state.selection.filter(function (val, i) { return i !== index; });else selection = [event.value]; } else { if (metaKey) selection = [].concat(_toConsumableArray(this.state.selection), [event.value]);else selection = [event.value]; } this.setState({ selection: selection }); } }, { key: "onItemKeyDown", value: function onItemKeyDown(event) { var listItem = event.originalEvent.currentTarget; switch (event.originalEvent.which) { //down case 40: var nextItem = this.findNextItem(listItem); if (nextItem) { nextItem.focus(); } event.originalEvent.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(listItem); if (prevItem) { prevItem.focus(); } event.originalEvent.preventDefault(); break; //enter case 13: this.onItemClick(event); event.originalEvent.preventDefault(); break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return !DomHandler.hasClass(nextItem, 'p-orderlist-item') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return !DomHandler.hasClass(prevItem, 'p-orderlist-item') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "onReorder", value: function onReorder(event) { if (this.props.onChange) { this.props.onChange({ event: event.originalEvent, value: event.value }); } this.reorderDirection = event.direction; } }, { key: "componentDidUpdate", value: function componentDidUpdate() { if (this.reorderDirection) { this.updateListScroll(); this.reorderDirection = null; } } }, { key: "updateListScroll", value: function updateListScroll() { var listItems = DomHandler.find(this.subList.listElement, '.p-orderlist-item.p-highlight'); if (listItems && listItems.length) { switch (this.reorderDirection) { case 'up': DomHandler.scrollInView(this.subList.listElement, listItems[0]); break; case 'top': this.subList.listElement.scrollTop = 0; break; case 'down': DomHandler.scrollInView(this.subList.listElement, listItems[listItems.length - 1]); break; case 'bottom': this.subList.listElement.scrollTop = this.subList.listElement.scrollHeight; break; } } } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-orderlist p-component', this.props.className); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this2.element = el; }, id: this.props.id, className: className, style: this.props.style }, /*#__PURE__*/React.createElement(OrderListControls, { value: this.props.value, selection: this.state.selection, onReorder: this.onReorder, dataKey: this.props.dataKey }), /*#__PURE__*/React.createElement(OrderListSubList, { ref: function ref(el) { return _this2.subList = el; }, value: this.props.value, selection: this.state.selection, onItemClick: this.onItemClick, onItemKeyDown: this.onItemKeyDown, itemTemplate: this.props.itemTemplate, header: this.props.header, listStyle: this.props.listStyle, dataKey: this.props.dataKey, dragdrop: this.props.dragdrop, onDragStart: this.onDragStart, onDragEnter: this.onDragEnter, onDragEnd: this.onDragEnd, onDragLeave: this.onDragEnter, onDrop: this.onDrop, onChange: this.props.onChange, tabIndex: this.props.tabIndex })); } }]); return OrderList; }(Component); _defineProperty(OrderList, "defaultProps", { id: null, value: null, header: null, style: null, className: null, listStyle: null, dragdrop: false, tabIndex: 0, dataKey: null, onChange: null, itemTemplate: null }); export { OrderList };
ajax/libs/react-native-web/0.11.6/exports/AppRegistry/AppContainer.js
cdnjs/cdnjs
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import StyleSheet from '../StyleSheet'; import View from '../View'; import { any, node } from 'prop-types'; import React, { Component } from 'react'; var AppContainer = /*#__PURE__*/ function (_Component) { _inheritsLoose(AppContainer, _Component); function AppContainer() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _Component.call.apply(_Component, [this].concat(args)) || this; _this.state = { mainKey: 1 }; return _this; } var _proto = AppContainer.prototype; _proto.getChildContext = function getChildContext() { return { rootTag: this.props.rootTag }; }; _proto.render = function render() { var _this$props = this.props, children = _this$props.children, WrapperComponent = _this$props.WrapperComponent; var innerView = React.createElement(View, { children: children, key: this.state.mainKey, pointerEvents: "box-none", style: styles.appContainer }); if (WrapperComponent) { innerView = React.createElement(WrapperComponent, null, innerView); } return React.createElement(View, { pointerEvents: "box-none", style: styles.appContainer }, innerView); }; return AppContainer; }(Component); AppContainer.childContextTypes = { rootTag: any }; export { AppContainer as default }; AppContainer.propTypes = process.env.NODE_ENV !== "production" ? { WrapperComponent: any, children: node, rootTag: any.isRequired } : {}; var styles = StyleSheet.create({ appContainer: { flex: 1 } });
ajax/libs/react-native-web/0.14.10/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.2/es/RadioGroup/RadioGroupContext.js
cdnjs/cdnjs
import React from 'react'; /** * @ignore - internal component. */ const RadioGroupContext = React.createContext(); if (process.env.NODE_ENV !== 'production') { RadioGroupContext.displayName = 'RadioGroupContext'; } export default RadioGroupContext;
ajax/libs/primereact/7.0.0-rc.2/scrollpanel/scrollpanel.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, 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 _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 ScrollPanel = /*#__PURE__*/function (_Component) { _inherits(ScrollPanel, _Component); var _super = _createSuper(ScrollPanel); function ScrollPanel(props) { var _this; _classCallCheck(this, ScrollPanel); _this = _super.call(this, props); _this.moveBar = _this.moveBar.bind(_assertThisInitialized(_this)); _this.onXBarMouseDown = _this.onXBarMouseDown.bind(_assertThisInitialized(_this)); _this.onYBarMouseDown = _this.onYBarMouseDown.bind(_assertThisInitialized(_this)); _this.onDocumentMouseMove = _this.onDocumentMouseMove.bind(_assertThisInitialized(_this)); _this.onDocumentMouseUp = _this.onDocumentMouseUp.bind(_assertThisInitialized(_this)); return _this; } _createClass(ScrollPanel, [{ key: "calculateContainerHeight", value: function calculateContainerHeight() { var containerStyles = getComputedStyle(this.container), xBarStyles = getComputedStyle(this.xBar), pureContainerHeight = DomHandler.getHeight(this.container) - parseInt(xBarStyles['height'], 10); if (containerStyles['max-height'] !== "none" && pureContainerHeight === 0) { if (this.content.offsetHeight + parseInt(xBarStyles['height'], 10) > parseInt(containerStyles['max-height'], 10)) { this.container.style.height = containerStyles['max-height']; } else { this.container.style.height = this.content.offsetHeight + parseFloat(containerStyles.paddingTop) + parseFloat(containerStyles.paddingBottom) + parseFloat(containerStyles.borderTopWidth) + parseFloat(containerStyles.borderBottomWidth) + "px"; } } } }, { key: "moveBar", value: function moveBar() { var _this2 = this; /* horizontal scroll */ var totalWidth = this.content.scrollWidth; var ownWidth = this.content.clientWidth; var bottom = (this.container.clientHeight - this.xBar.clientHeight) * -1; this.scrollXRatio = ownWidth / totalWidth; /* vertical scroll */ var totalHeight = this.content.scrollHeight; var ownHeight = this.content.clientHeight; var right = (this.container.clientWidth - this.yBar.clientWidth) * -1; this.scrollYRatio = ownHeight / totalHeight; this.frame = this.requestAnimationFrame(function () { if (_this2.scrollXRatio >= 1) { DomHandler.addClass(_this2.xBar, 'p-scrollpanel-hidden'); } else { DomHandler.removeClass(_this2.xBar, 'p-scrollpanel-hidden'); _this2.xBar.style.cssText = 'width:' + Math.max(_this2.scrollXRatio * 100, 10) + '%; left:' + _this2.content.scrollLeft / totalWidth * 100 + '%;bottom:' + bottom + 'px;'; } if (_this2.scrollYRatio >= 1) { DomHandler.addClass(_this2.yBar, 'p-scrollpanel-hidden'); } else { DomHandler.removeClass(_this2.yBar, 'p-scrollpanel-hidden'); _this2.yBar.style.cssText = 'height:' + Math.max(_this2.scrollYRatio * 100, 10) + '%; top: calc(' + _this2.content.scrollTop / totalHeight * 100 + '% - ' + _this2.xBar.clientHeight + 'px);right:' + right + 'px;'; } }); } }, { key: "onYBarMouseDown", value: function onYBarMouseDown(e) { this.isYBarClicked = true; this.lastPageY = e.pageY; DomHandler.addClass(this.yBar, 'p-scrollpanel-grabbed'); DomHandler.addClass(document.body, 'p-scrollpanel-grabbed'); document.addEventListener('mousemove', this.onDocumentMouseMove); document.addEventListener('mouseup', this.onDocumentMouseUp); e.preventDefault(); } }, { key: "onXBarMouseDown", value: function onXBarMouseDown(e) { this.isXBarClicked = true; this.lastPageX = e.pageX; DomHandler.addClass(this.xBar, 'p-scrollpanel-grabbed'); DomHandler.addClass(document.body, 'p-scrollpanel-grabbed'); document.addEventListener('mousemove', this.onDocumentMouseMove); document.addEventListener('mouseup', this.onDocumentMouseUp); e.preventDefault(); } }, { key: "onDocumentMouseMove", value: function onDocumentMouseMove(e) { if (this.isXBarClicked) { this.onMouseMoveForXBar(e); } else if (this.isYBarClicked) { this.onMouseMoveForYBar(e); } else { this.onMouseMoveForXBar(e); this.onMouseMoveForYBar(e); } } }, { key: "onMouseMoveForXBar", value: function onMouseMoveForXBar(e) { var _this3 = this; var deltaX = e.pageX - this.lastPageX; this.lastPageX = e.pageX; this.frame = this.requestAnimationFrame(function () { _this3.content.scrollLeft += deltaX / _this3.scrollXRatio; }); } }, { key: "onMouseMoveForYBar", value: function onMouseMoveForYBar(e) { var _this4 = this; var deltaY = e.pageY - this.lastPageY; this.lastPageY = e.pageY; this.frame = this.requestAnimationFrame(function () { _this4.content.scrollTop += deltaY / _this4.scrollYRatio; }); } }, { key: "onDocumentMouseUp", value: function onDocumentMouseUp(e) { DomHandler.removeClass(this.yBar, 'p-scrollpanel-grabbed'); DomHandler.removeClass(this.xBar, 'p-scrollpanel-grabbed'); DomHandler.removeClass(document.body, 'p-scrollpanel-grabbed'); document.removeEventListener('mousemove', this.onDocumentMouseMove); document.removeEventListener('mouseup', this.onDocumentMouseUp); this.isXBarClicked = false; this.isYBarClicked = false; } }, { key: "requestAnimationFrame", value: function requestAnimationFrame(f) { var frame = window.requestAnimationFrame || this.timeoutFrame; return frame(f); } }, { key: "refresh", value: function refresh() { this.moveBar(); } }, { key: "componentDidMount", value: function componentDidMount() { this.moveBar(); this.moveBar = this.moveBar.bind(this); window.addEventListener('resize', this.moveBar); this.calculateContainerHeight(); this.initialized = true; } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.initialized) { window.removeEventListener('resize', this.moveBar); } if (this.frame) { window.cancelAnimationFrame(this.frame); } } }, { key: "render", value: function render() { var _this5 = this; var className = classNames('p-scrollpanel p-component', this.props.className); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this5.container = el; }, id: this.props.id, className: className, style: this.props.style }, /*#__PURE__*/React.createElement("div", { className: "p-scrollpanel-wrapper" }, /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this5.content = el; }, className: "p-scrollpanel-content", onScroll: this.moveBar, onMouseEnter: this.moveBar }, this.props.children)), /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this5.xBar = el; }, className: "p-scrollpanel-bar p-scrollpanel-bar-x", onMouseDown: this.onXBarMouseDown }), /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this5.yBar = el; }, className: "p-scrollpanel-bar p-scrollpanel-bar-y", onMouseDown: this.onYBarMouseDown })); } }]); return ScrollPanel; }(Component); _defineProperty(ScrollPanel, "defaultProps", { id: null, style: null, className: null }); export { ScrollPanel };
ajax/libs/primereact/7.0.0-rc.2/panel/panel.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { UniqueComponentId, Ripple, ObjectUtils, CSSTransition, 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 _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 Panel = /*#__PURE__*/function (_Component) { _inherits(Panel, _Component); var _super = _createSuper(Panel); function Panel(props) { var _this; _classCallCheck(this, Panel); _this = _super.call(this, props); var state = { id: _this.props.id }; if (!_this.props.onToggle) { state = _objectSpread(_objectSpread({}, state), {}, { collapsed: _this.props.collapsed }); } _this.state = state; _this.toggle = _this.toggle.bind(_assertThisInitialized(_this)); _this.contentRef = /*#__PURE__*/React.createRef(); return _this; } _createClass(Panel, [{ key: "toggle", value: function toggle(event) { if (this.props.toggleable) { var collapsed = this.props.onToggle ? this.props.collapsed : this.state.collapsed; if (collapsed) this.expand(event);else this.collapse(event); if (this.props.onToggle) { this.props.onToggle({ originalEvent: event, value: !collapsed }); } } event.preventDefault(); } }, { key: "expand", value: function expand(event) { if (!this.props.onToggle) { this.setState({ collapsed: false }); } if (this.props.onExpand) { this.props.onExpand(event); } } }, { key: "collapse", value: function collapse(event) { if (!this.props.onToggle) { this.setState({ collapsed: true }); } if (this.props.onCollapse) { this.props.onCollapse(event); } } }, { key: "isCollapsed", value: function isCollapsed() { return this.props.toggleable ? this.props.onToggle ? this.props.collapsed : this.state.collapsed : false; } }, { key: "componentDidMount", value: function componentDidMount() { if (!this.state.id) { this.setState({ id: UniqueComponentId() }); } } }, { key: "renderToggleIcon", value: function renderToggleIcon(collapsed) { if (this.props.toggleable) { var id = this.state.id + '_label'; var ariaControls = this.state.id + '_content'; var toggleIcon = collapsed ? this.props.expandIcon : this.props.collapseIcon; return /*#__PURE__*/React.createElement("button", { className: "p-panel-header-icon p-panel-toggler p-link", onClick: this.toggle, id: id, "aria-controls": ariaControls, "aria-expanded": !collapsed, role: "tab" }, /*#__PURE__*/React.createElement("span", { className: toggleIcon }), /*#__PURE__*/React.createElement(Ripple, null)); } return null; } }, { key: "renderHeader", value: function renderHeader(collapsed) { var header = ObjectUtils.getJSXElement(this.props.header, this.props); var icons = ObjectUtils.getJSXElement(this.props.icons, this.props); var togglerElement = this.renderToggleIcon(collapsed); var titleElement = /*#__PURE__*/React.createElement("span", { className: "p-panel-title", id: this.state.id + '_header' }, header); var iconsElement = /*#__PURE__*/React.createElement("div", { className: "p-panel-icons" }, icons, togglerElement); var content = /*#__PURE__*/React.createElement("div", { className: "p-panel-header" }, titleElement, iconsElement); if (this.props.headerTemplate) { var defaultContentOptions = { className: 'p-panel-header', titleClassName: 'p-panel-title', iconsClassName: 'p-panel-icons', togglerClassName: 'p-panel-header-icon p-panel-toggler p-link', togglerIconClassName: collapsed ? this.props.expandIcon : this.props.collapseIcon, onTogglerClick: this.toggle, titleElement: titleElement, iconsElement: iconsElement, togglerElement: togglerElement, element: content, props: this.props, collapsed: collapsed }; return ObjectUtils.getJSXElement(this.props.headerTemplate, defaultContentOptions); } else if (this.props.header || this.props.toggleable) { return content; } return null; } }, { key: "renderContent", value: function renderContent(collapsed) { var id = this.state.id + '_content'; return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.contentRef, classNames: "p-toggleable-content", timeout: { enter: 1000, exit: 450 }, in: !collapsed, unmountOnExit: true, options: this.props.transitionOptions }, /*#__PURE__*/React.createElement("div", { ref: this.contentRef, className: "p-toggleable-content", "aria-hidden": collapsed, role: "region", id: id, "aria-labelledby": this.state.id + '_header' }, /*#__PURE__*/React.createElement("div", { className: "p-panel-content" }, this.props.children))); } }, { key: "render", value: function render() { var className = classNames('p-panel p-component', { 'p-panel-toggleable': this.props.toggleable }, this.props.className); var collapsed = this.isCollapsed(); var header = this.renderHeader(collapsed); var content = this.renderContent(collapsed); return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: className, style: this.props.style }, header, content); } }]); return Panel; }(Component); _defineProperty(Panel, "defaultProps", { id: null, header: null, headerTemplate: null, toggleable: null, style: null, className: null, collapsed: null, expandIcon: 'pi pi-plus', collapseIcon: 'pi pi-minus', icons: null, transitionOptions: null, onExpand: null, onCollapse: null, onToggle: null }); export { Panel };
ajax/libs/boardgame-io/0.47.10/esm/react.js
cdnjs/cdnjs
import 'nanoid/non-secure'; import './Debug-03577ad8.js'; import 'redux'; import './turn-order-5ed45dd0.js'; import 'immer'; import 'lodash.isplainobject'; import './reducer-ac0d57b2.js'; import 'rfc6902'; import './initialize-0d56e9b2.js'; import './transport-0079de87.js'; import { C as Client$1 } from './client-ff5014b9.js'; import 'flatted'; import 'setimmediate'; import { M as MCTSBot } from './ai-9c97f29f.js'; import { L as LobbyClient } from './client-99609c4d.js'; import React from 'react'; import PropTypes from 'prop-types'; import Cookies from 'react-cookies'; import './base-13e38c3e.js'; import { S as SocketIO, L as Local } from './socketio-bbc1061d.js'; import './master-6007db7a.js'; import 'socket.io-client'; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Client * * boardgame.io React client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} debug - Enables the Debug UI. * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET, * UNDO and REDO. */ function Client(opts) { var _a; let { game, numPlayers, loading, board, multiplayer, enhancer, debug } = opts; // Component that is displayed before the client has synced // with the game master. if (loading === undefined) { const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting..."); loading = Loading; } /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _a = class WrappedBoard extends React.Component { constructor(props) { super(props); if (debug === undefined) { debug = props.debug; } this.client = Client$1({ game, debug, numPlayers, multiplayer, matchID: props.matchID, playerID: props.playerID, credentials: props.credentials, enhancer, }); } componentDidMount() { this.unsubscribe = this.client.subscribe(() => this.forceUpdate()); this.client.start(); } componentWillUnmount() { this.client.stop(); this.unsubscribe(); } componentDidUpdate(prevProps) { if (this.props.matchID != prevProps.matchID) { this.client.updateMatchID(this.props.matchID); } if (this.props.playerID != prevProps.playerID) { this.client.updatePlayerID(this.props.playerID); } if (this.props.credentials != prevProps.credentials) { this.client.updateCredentials(this.props.credentials); } } render() { const state = this.client.getState(); if (state === null) { return React.createElement(loading); } let _board = null; if (board) { _board = React.createElement(board, { ...state, ...this.props, isMultiplayer: !!multiplayer, moves: this.client.moves, events: this.client.events, matchID: this.client.matchID, playerID: this.client.playerID, reset: this.client.reset, undo: this.client.undo, redo: this.client.redo, log: this.client.log, matchData: this.client.matchData, sendChatMessage: this.client.sendChatMessage, chatMessages: this.client.chatMessages, }); } return React.createElement("div", { className: "bgio-client" }, _board); } }, _a.propTypes = { // The ID of a game to connect to. // Only relevant in multiplayer. matchID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string, // Enable / disable the Debug UI. debug: PropTypes.any, }, _a.defaultProps = { matchID: 'default', playerID: null, credentials: null, debug: true, }, _a; } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class _LobbyConnectionImpl { constructor({ server, gameComponents, playerName, playerCredentials, }) { this.client = new LobbyClient({ server }); this.gameComponents = gameComponents; this.playerName = playerName || 'Visitor'; this.playerCredentials = playerCredentials; this.matches = []; } async refresh() { try { this.matches = []; const games = await this.client.listGames(); for (const game of games) { if (!this._getGameComponents(game)) continue; const { matches } = await this.client.listMatches(game); this.matches.push(...matches); } } catch (error) { throw new Error('failed to retrieve list of matches (' + error + ')'); } } _getMatchInstance(matchID) { for (const inst of this.matches) { if (inst['matchID'] === matchID) return inst; } } _getGameComponents(gameName) { for (const comp of this.gameComponents) { if (comp.game.name === gameName) return comp; } } _findPlayer(playerName) { for (const inst of this.matches) { if (inst.players.some((player) => player.name === playerName)) return inst; } } async join(gameName, matchID, playerID) { try { let inst = this._findPlayer(this.playerName); if (inst) { throw new Error('player has already joined ' + inst.matchID); } inst = this._getMatchInstance(matchID); if (!inst) { throw new Error('game instance ' + matchID + ' not found'); } const json = await this.client.joinMatch(gameName, matchID, { playerID, playerName: this.playerName, }); inst.players[Number.parseInt(playerID)].name = this.playerName; this.playerCredentials = json.playerCredentials; } catch (error) { throw new Error('failed to join match ' + matchID + ' (' + error + ')'); } } async leave(gameName, matchID) { try { const inst = this._getMatchInstance(matchID); if (!inst) throw new Error('match instance not found'); for (const player of inst.players) { if (player.name === this.playerName) { await this.client.leaveMatch(gameName, matchID, { playerID: player.id.toString(), credentials: this.playerCredentials, }); delete player.name; delete this.playerCredentials; return; } } throw new Error('player not found in match'); } catch (error) { throw new Error('failed to leave match ' + matchID + ' (' + error + ')'); } } async disconnect() { const inst = this._findPlayer(this.playerName); if (inst) { await this.leave(inst.gameName, inst.matchID); } this.matches = []; this.playerName = 'Visitor'; } async create(gameName, numPlayers) { try { const comp = this._getGameComponents(gameName); if (!comp) throw new Error('game not found'); if (numPlayers < comp.game.minPlayers || numPlayers > comp.game.maxPlayers) throw new Error('invalid number of players ' + numPlayers); await this.client.createMatch(gameName, { numPlayers }); } catch (error) { throw new Error('failed to create match for ' + gameName + ' (' + error + ')'); } } } /** * LobbyConnection * * Lobby model. * * @param {string} server - '<host>:<port>' of the server. * @param {Array} gameComponents - A map of Board and Game objects for the supported games. * @param {string} playerName - The name of the player. * @param {string} playerCredentials - The credentials currently used by the player, if any. * * Returns: * A JS object that synchronizes the list of running game instances with the server and provides an API to create/join/start instances. */ function LobbyConnection(opts) { return new _LobbyConnectionImpl(opts); } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyLoginForm extends React.Component { constructor() { super(...arguments); this.state = { playerName: this.props.playerName, nameErrorMsg: '', }; this.onClickEnter = () => { if (this.state.playerName === '') return; this.props.onEnter(this.state.playerName); }; this.onKeyPress = (event) => { if (event.key === 'Enter') { this.onClickEnter(); } }; this.onChangePlayerName = (event) => { const name = event.target.value.trim(); this.setState({ playerName: name, nameErrorMsg: name.length > 0 ? '' : 'empty player name', }); }; } render() { return (React.createElement("div", null, React.createElement("p", { className: "phase-title" }, "Choose a player name:"), React.createElement("input", { type: "text", value: this.state.playerName, onChange: this.onChangePlayerName, onKeyPress: this.onKeyPress }), React.createElement("span", { className: "buttons" }, React.createElement("button", { className: "buttons", onClick: this.onClickEnter }, "Enter")), React.createElement("br", null), React.createElement("span", { className: "error-msg" }, this.state.nameErrorMsg, React.createElement("br", null)))); } } LobbyLoginForm.defaultProps = { playerName: '', }; /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyMatchInstance extends React.Component { constructor() { super(...arguments); this._createSeat = (player) => { return player.name || '[free]'; }; this._createButtonJoin = (inst, seatId) => (React.createElement("button", { key: 'button-join-' + inst.matchID, onClick: () => this.props.onClickJoin(inst.gameName, inst.matchID, '' + seatId) }, "Join")); this._createButtonLeave = (inst) => (React.createElement("button", { key: 'button-leave-' + inst.matchID, onClick: () => this.props.onClickLeave(inst.gameName, inst.matchID) }, "Leave")); this._createButtonPlay = (inst, seatId) => (React.createElement("button", { key: 'button-play-' + inst.matchID, onClick: () => this.props.onClickPlay(inst.gameName, { matchID: inst.matchID, playerID: '' + seatId, numPlayers: inst.players.length, }) }, "Play")); this._createButtonSpectate = (inst) => (React.createElement("button", { key: 'button-spectate-' + inst.matchID, onClick: () => this.props.onClickPlay(inst.gameName, { matchID: inst.matchID, numPlayers: inst.players.length, }) }, "Spectate")); this._createInstanceButtons = (inst) => { const playerSeat = inst.players.find((player) => player.name === this.props.playerName); const freeSeat = inst.players.find((player) => !player.name); if (playerSeat && freeSeat) { // already seated: waiting for match to start return this._createButtonLeave(inst); } if (freeSeat) { // at least 1 seat is available return this._createButtonJoin(inst, freeSeat.id); } // match is full if (playerSeat) { return (React.createElement("div", null, [ this._createButtonPlay(inst, playerSeat.id), this._createButtonLeave(inst), ])); } // allow spectating return this._createButtonSpectate(inst); }; } render() { const match = this.props.match; let status = 'OPEN'; if (!match.players.some((player) => !player.name)) { status = 'RUNNING'; } return (React.createElement("tr", { key: 'line-' + match.matchID }, React.createElement("td", { key: 'cell-name-' + match.matchID }, match.gameName), React.createElement("td", { key: 'cell-status-' + match.matchID }, status), React.createElement("td", { key: 'cell-seats-' + match.matchID }, match.players.map((player) => this._createSeat(player)).join(', ')), React.createElement("td", { key: 'cell-buttons-' + match.matchID }, this._createInstanceButtons(match)))); } } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class LobbyCreateMatchForm extends React.Component { constructor(props) { super(props); this.state = { selectedGame: 0, numPlayers: 2, }; this._createGameNameOption = (game, idx) => { return (React.createElement("option", { key: 'name-option-' + idx, value: idx }, game.game.name)); }; this._createNumPlayersOption = (idx) => { return (React.createElement("option", { key: 'num-option-' + idx, value: idx }, idx)); }; this._createNumPlayersRange = (game) => { return Array.from({ length: game.maxPlayers + 1 }) .map((_, i) => i) .slice(game.minPlayers); }; this.onChangeNumPlayers = (event) => { this.setState({ numPlayers: Number.parseInt(event.target.value), }); }; this.onChangeSelectedGame = (event) => { const idx = Number.parseInt(event.target.value); this.setState({ selectedGame: idx, numPlayers: this.props.games[idx].game.minPlayers, }); }; this.onClickCreate = () => { this.props.createMatch(this.props.games[this.state.selectedGame].game.name, this.state.numPlayers); }; /* fix min and max number of players */ for (const game of props.games) { const matchDetails = game.game; if (!matchDetails.minPlayers) { matchDetails.minPlayers = 1; } if (!matchDetails.maxPlayers) { matchDetails.maxPlayers = 4; } console.assert(matchDetails.maxPlayers >= matchDetails.minPlayers); } this.state = { selectedGame: 0, numPlayers: props.games[0].game.minPlayers, }; } render() { return (React.createElement("div", null, React.createElement("select", { value: this.state.selectedGame, onChange: (evt) => this.onChangeSelectedGame(evt) }, this.props.games.map((game, index) => this._createGameNameOption(game, index))), React.createElement("span", null, "Players:"), React.createElement("select", { value: this.state.numPlayers, onChange: this.onChangeNumPlayers }, this._createNumPlayersRange(this.props.games[this.state.selectedGame].game).map((number) => this._createNumPlayersOption(number))), React.createElement("span", { className: "buttons" }, React.createElement("button", { onClick: this.onClickCreate }, "Create")))); } } /* * Copyright 2018 The boardgame.io Authors. * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ var LobbyPhases; (function (LobbyPhases) { LobbyPhases["ENTER"] = "enter"; LobbyPhases["PLAY"] = "play"; LobbyPhases["LIST"] = "list"; })(LobbyPhases || (LobbyPhases = {})); /** * Lobby * * React lobby component. * * @param {Array} gameComponents - An array of Board and Game objects for the supported games. * @param {string} lobbyServer - Address of the lobby server (for example 'localhost:8000'). * If not set, defaults to the server that served the page. * @param {string} gameServer - Address of the game server (for example 'localhost:8001'). * If not set, defaults to the server that served the page. * @param {function} clientFactory - Function that is used to create the game clients. * @param {number} refreshInterval - Interval between server updates (default: 2000ms). * @param {bool} debug - Enable debug information (default: false). * * Returns: * A React component that provides a UI to create, list, join, leave, play or * spectate matches (game instances). */ class Lobby extends React.Component { constructor(props) { super(props); this.state = { phase: LobbyPhases.ENTER, playerName: 'Visitor', runningMatch: null, errorMsg: '', credentialStore: {}, }; this._createConnection = (props) => { const name = this.state.playerName; this.connection = LobbyConnection({ server: props.lobbyServer, gameComponents: props.gameComponents, playerName: name, playerCredentials: this.state.credentialStore[name], }); }; this._updateCredentials = (playerName, credentials) => { this.setState((prevState) => { // clone store or componentDidUpdate will not be triggered const store = Object.assign({}, prevState.credentialStore); store[playerName] = credentials; return { credentialStore: store }; }); }; this._updateConnection = async () => { await this.connection.refresh(); this.forceUpdate(); }; this._enterLobby = (playerName) => { this.setState({ playerName, phase: LobbyPhases.LIST }); }; this._exitLobby = async () => { await this.connection.disconnect(); this.setState({ phase: LobbyPhases.ENTER, errorMsg: '' }); }; this._createMatch = async (gameName, numPlayers) => { try { await this.connection.create(gameName, numPlayers); await this.connection.refresh(); // rerender this.setState({}); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._joinMatch = async (gameName, matchID, playerID) => { try { await this.connection.join(gameName, matchID, playerID); await this.connection.refresh(); this._updateCredentials(this.connection.playerName, this.connection.playerCredentials); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._leaveMatch = async (gameName, matchID) => { try { await this.connection.leave(gameName, matchID); await this.connection.refresh(); this._updateCredentials(this.connection.playerName, this.connection.playerCredentials); } catch (error) { this.setState({ errorMsg: error.message }); } }; this._startMatch = (gameName, matchOpts) => { const gameCode = this.connection._getGameComponents(gameName); if (!gameCode) { this.setState({ errorMsg: 'game ' + gameName + ' not supported', }); return; } let multiplayer = undefined; if (matchOpts.numPlayers > 1) { multiplayer = this.props.gameServer ? SocketIO({ server: this.props.gameServer }) : SocketIO(); } if (matchOpts.numPlayers == 1) { const maxPlayers = gameCode.game.maxPlayers; const bots = {}; for (let i = 1; i < maxPlayers; i++) { bots[i + ''] = MCTSBot; } multiplayer = Local({ bots }); } const app = this.props.clientFactory({ game: gameCode.game, board: gameCode.board, debug: this.props.debug, multiplayer, }); const match = { app: app, matchID: matchOpts.matchID, playerID: matchOpts.numPlayers > 1 ? matchOpts.playerID : '0', credentials: this.connection.playerCredentials, }; this.setState({ phase: LobbyPhases.PLAY, runningMatch: match }); }; this._exitMatch = () => { this.setState({ phase: LobbyPhases.LIST, runningMatch: null }); }; this._getPhaseVisibility = (phase) => { return this.state.phase !== phase ? 'hidden' : 'phase'; }; this.renderMatches = (matches, playerName) => { return matches.map((match) => { const { matchID, gameName, players } = match; return (React.createElement(LobbyMatchInstance, { key: 'instance-' + matchID, match: { matchID, gameName, players: Object.values(players) }, playerName: playerName, onClickJoin: this._joinMatch, onClickLeave: this._leaveMatch, onClickPlay: this._startMatch })); }); }; this._createConnection(this.props); } componentDidMount() { const cookie = Cookies.load('lobbyState') || {}; if (cookie.phase && cookie.phase === LobbyPhases.PLAY) { cookie.phase = LobbyPhases.LIST; } this.setState({ phase: cookie.phase || LobbyPhases.ENTER, playerName: cookie.playerName || 'Visitor', credentialStore: cookie.credentialStore || {}, }); this._startRefreshInterval(); } componentDidUpdate(prevProps, prevState) { const name = this.state.playerName; const creds = this.state.credentialStore[name]; if (prevState.phase !== this.state.phase || prevState.credentialStore[name] !== creds || prevState.playerName !== name) { this._createConnection(this.props); this._updateConnection(); const cookie = { phase: this.state.phase, playerName: name, credentialStore: this.state.credentialStore, }; Cookies.save('lobbyState', cookie, { path: '/' }); } if (prevProps.refreshInterval !== this.props.refreshInterval) { this._startRefreshInterval(); } } componentWillUnmount() { this._clearRefreshInterval(); } _startRefreshInterval() { this._clearRefreshInterval(); this._currentInterval = setInterval(this._updateConnection, this.props.refreshInterval); } _clearRefreshInterval() { clearInterval(this._currentInterval); } render() { const { gameComponents, renderer } = this.props; const { errorMsg, playerName, phase, runningMatch } = this.state; if (renderer) { return renderer({ errorMsg, gameComponents, matches: this.connection.matches, phase, playerName, runningMatch, handleEnterLobby: this._enterLobby, handleExitLobby: this._exitLobby, handleCreateMatch: this._createMatch, handleJoinMatch: this._joinMatch, handleLeaveMatch: this._leaveMatch, handleExitMatch: this._exitMatch, handleRefreshMatches: this._updateConnection, handleStartMatch: this._startMatch, }); } return (React.createElement("div", { id: "lobby-view", style: { padding: 50 } }, React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.ENTER) }, React.createElement(LobbyLoginForm, { key: playerName, playerName: playerName, onEnter: this._enterLobby })), React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.LIST) }, React.createElement("p", null, "Welcome, ", playerName), React.createElement("div", { className: "phase-title", id: "match-creation" }, React.createElement("span", null, "Create a match:"), React.createElement(LobbyCreateMatchForm, { games: gameComponents, createMatch: this._createMatch })), React.createElement("p", { className: "phase-title" }, "Join a match:"), React.createElement("div", { id: "instances" }, React.createElement("table", null, React.createElement("tbody", null, this.renderMatches(this.connection.matches, playerName))), React.createElement("span", { className: "error-msg" }, errorMsg, React.createElement("br", null))), React.createElement("p", { className: "phase-title" }, "Matches that become empty are automatically deleted.")), React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.PLAY) }, runningMatch && (React.createElement(runningMatch.app, { matchID: runningMatch.matchID, playerID: runningMatch.playerID, credentials: runningMatch.credentials })), React.createElement("div", { className: "buttons", id: "match-exit" }, React.createElement("button", { onClick: this._exitMatch }, "Exit match"))), React.createElement("div", { className: "buttons", id: "lobby-exit" }, React.createElement("button", { onClick: this._exitLobby }, "Exit lobby")))); } } Lobby.propTypes = { gameComponents: PropTypes.array.isRequired, lobbyServer: PropTypes.string, gameServer: PropTypes.string, debug: PropTypes.bool, clientFactory: PropTypes.func, refreshInterval: PropTypes.number, }; Lobby.defaultProps = { debug: false, clientFactory: Client, refreshInterval: 2000, }; export { Client, Lobby };
ajax/libs/material-ui/4.9.4/esm/ListItemSecondaryAction/ListItemSecondaryAction.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; export var styles = { /* Styles applied to the root element. */ root: { position: 'absolute', right: 16, top: '50%', transform: 'translateY(-50%)' } }; /** * Must be used as the last child of ListItem to function properly. */ var ListItemSecondaryAction = React.forwardRef(function ListItemSecondaryAction(props, ref) { var classes = props.classes, className = props.className, other = _objectWithoutProperties(props, ["classes", "className"]); return React.createElement("div", _extends({ className: clsx(classes.root, className), ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? ListItemSecondaryAction.propTypes = { /** * The content of the component, normally an `IconButton` or selection 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 } : void 0; ListItemSecondaryAction.muiName = 'ListItemSecondaryAction'; export default withStyles(styles, { name: 'MuiListItemSecondaryAction' })(ListItemSecondaryAction);
ajax/libs/react-native-web/0.0.0-20f889ecc/vendor/react-native/Animated/createAnimatedComponent.js
cdnjs/cdnjs
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ 'use strict'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } import { AnimatedEvent } from './AnimatedEvent'; import AnimatedProps from './nodes/AnimatedProps'; import React from 'react'; import invariant from 'fbjs/lib/invariant'; import mergeRefs from '../../../modules/mergeRefs'; function createAnimatedComponent(Component, defaultProps) { invariant(typeof Component !== 'function' || Component.prototype && Component.prototype.isReactComponent, '`createAnimatedComponent` does not support stateless functional components; ' + 'use a class component instead.'); var AnimatedComponent = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(AnimatedComponent, _React$Component); function AnimatedComponent(props) { var _this; _this = _React$Component.call(this, props) || this; _this._invokeAnimatedPropsCallbackOnMount = false; _this._eventDetachers = []; _this._animatedPropsCallback = function () { if (_this._component == null) { // AnimatedProps is created in will-mount because it's used in render. // But this callback may be invoked before mount in async mode, // In which case we should defer the setNativeProps() call. // React may throw away uncommitted work in async mode, // So a deferred call won't always be invoked. _this._invokeAnimatedPropsCallbackOnMount = true; } else if (AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY || typeof _this._component.setNativeProps !== 'function') { _this.forceUpdate(); } else if (!_this._propsAnimated.__isNative) { _this._component.setNativeProps(_this._propsAnimated.__getAnimatedValue()); } else { throw new Error('Attempting to run JS driven animation on animated ' + 'node that has been moved to "native" earlier by starting an ' + 'animation with `useNativeDriver: true`'); } }; return _this; } var _proto = AnimatedComponent.prototype; _proto.componentWillUnmount = function componentWillUnmount() { this._propsAnimated && this._propsAnimated.__detach(); this._detachNativeEvents(); }; _proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() { this._attachProps(this.props); }; _proto.componentDidMount = function componentDidMount() { if (this._invokeAnimatedPropsCallbackOnMount) { this._invokeAnimatedPropsCallbackOnMount = false; this._animatedPropsCallback(); } this._propsAnimated.setNativeView(this._component); this._attachNativeEvents(); }; _proto._attachNativeEvents = function _attachNativeEvents() { var _this2 = this; // Make sure to get the scrollable node for components that implement // `ScrollResponder.Mixin`. var scrollableNode = this._component && this._component.getScrollableNode ? this._component.getScrollableNode() : this._component; var _loop = function _loop(key) { var prop = _this2.props[key]; if (prop instanceof AnimatedEvent && prop.__isNative) { prop.__attach(scrollableNode, key); _this2._eventDetachers.push(function () { return prop.__detach(scrollableNode, key); }); } }; for (var key in this.props) { _loop(key); } }; _proto._detachNativeEvents = function _detachNativeEvents() { this._eventDetachers.forEach(function (remove) { return remove(); }); this._eventDetachers = []; } // The system is best designed when setNativeProps is implemented. It is // able to avoid re-rendering and directly set the attributes that changed. // However, setNativeProps can only be implemented on leaf native // components. If you want to animate a composite component, you need to // re-render it. In this case, we have a fallback that uses forceUpdate. ; _proto._attachProps = function _attachProps(nextProps) { var oldPropsAnimated = this._propsAnimated; this._propsAnimated = new AnimatedProps(nextProps, this._animatedPropsCallback); // When you call detach, it removes the element from the parent list // of children. If it goes to 0, then the parent also detaches itself // and so on. // An optimization is to attach the new elements and THEN detach the old // ones instead of detaching and THEN attaching. // This way the intermediate state isn't to go to 0 and trigger // this expensive recursive detaching to then re-attach everything on // the very next operation. oldPropsAnimated && oldPropsAnimated.__detach(); }; _proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(newProps) { this._attachProps(newProps); }; _proto.componentDidUpdate = function componentDidUpdate(prevProps) { if (this._component !== this._prevComponent) { this._propsAnimated.setNativeView(this._component); } if (this._component !== this._prevComponent || prevProps !== this.props) { this._detachNativeEvents(); this._attachNativeEvents(); } }; _proto._setComponentRef = function _setComponentRef() { var _this3 = this; var setLocalRef = function setLocalRef(ref) { _this3._prevComponent = _this3._component; _this3._component = ref; // TODO: Delete this in a future release. if (ref != null && ref.getNode == null) { ref.getNode = function () { var _ref$constructor$name; console.warn('%s: Calling `getNode()` on the ref of an Animated component ' + 'is no longer necessary. You can now directly use the ref ' + 'instead. This method will be removed in a future release.', (_ref$constructor$name = ref.constructor.name) !== null && _ref$constructor$name !== void 0 ? _ref$constructor$name : '<<anonymous>>'); return ref; }; } }; mergeRefs(this.props.forwardedRef, setLocalRef); }; _proto.render = function render() { var props = this._propsAnimated.__getValue(); return React.createElement(Component, _extends({}, defaultProps, props, { ref: this._setComponentRef // The native driver updates views directly through the UI thread so we // have to make sure the view doesn't get optimized away because it cannot // go through the NativeViewHierarchyManager since it operates on the shadow // thread. , collapsable: false })); }; return AnimatedComponent; }(React.Component); AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY = false; var propTypes = Component.propTypes; return React.forwardRef(function AnimatedComponentWrapper(props, ref) { return React.createElement(AnimatedComponent, _extends({}, props, ref == null ? null : { forwardedRef: ref })); }); } export default createAnimatedComponent;
ajax/libs/primereact/6.5.0/message/message.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { ObjectUtils, classNames } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } 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 Message = /*#__PURE__*/function (_Component) { _inherits(Message, _Component); var _super = _createSuper(Message); function Message() { _classCallCheck(this, Message); return _super.apply(this, arguments); } _createClass(Message, [{ key: "getContent", value: function getContent() { if (this.props.content) { return ObjectUtils.getJSXElement(this.props.content, this.props); } var icon = classNames('p-inline-message-icon pi', { 'pi-info-circle': this.props.severity === 'info', 'pi-exclamation-triangle': this.props.severity === 'warn', 'pi-times-circle': this.props.severity === 'error', 'pi-check': this.props.severity === 'success' }); return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", { className: icon }), /*#__PURE__*/React.createElement("span", { className: "p-inline-message-text" }, this.props.text)); } }, { key: "render", value: function render() { var className = classNames('p-inline-message p-component', { 'p-inline-message-info': this.props.severity === 'info', 'p-inline-message-warn': this.props.severity === 'warn', 'p-inline-message-error': this.props.severity === 'error', 'p-inline-message-success': this.props.severity === 'success', 'p-inline-message-icon-only': !this.props.text }, this.props.className); var content = this.getContent(); return /*#__PURE__*/React.createElement("div", { id: this.props.id, "aria-live": "polite", className: className, style: this.props.style, role: "alert" }, content); } }]); return Message; }(Component); _defineProperty(Message, "defaultProps", { id: null, className: null, style: null, text: null, severity: 'info', content: null }); export { Message };
ajax/libs/boardgame-io/0.39.7/boardgameio.es.js
cdnjs/cdnjs
import { compose, applyMiddleware, createStore } from 'redux'; import produce from 'immer'; import { stringify, parse } from 'flatted'; import React from 'react'; import PropTypes from 'prop-types'; import io from 'socket.io-client'; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (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 _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } 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"); } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const MAKE_MOVE = 'MAKE_MOVE'; const GAME_EVENT = 'GAME_EVENT'; const REDO = 'REDO'; const RESET = 'RESET'; const SYNC = 'SYNC'; const UNDO = 'UNDO'; const UPDATE = 'UPDATE'; const PLUGIN = 'PLUGIN'; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Generate a move to be dispatched to the game move reducer. * * @param {string} type - The move type. * @param {Array} args - Additional arguments. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const makeMove = (type, args, playerID, credentials) => ({ type: MAKE_MOVE, payload: { type, args, playerID, credentials }, }); /** * Generate a game event to be dispatched to the flow reducer. * * @param {string} type - The event type. * @param {Array} args - Additional arguments. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const gameEvent = (type, args, playerID, credentials) => ({ type: GAME_EVENT, payload: { type, args, playerID, credentials }, }); /** * Generate an automatic game event that is a side-effect of a move. * @param {string} type - The event type. * @param {Array} args - Additional arguments. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const automaticGameEvent = (type, args, playerID, credentials) => ({ type: GAME_EVENT, payload: { type, args, playerID, credentials }, automatic: true, }); const sync = (info) => ({ type: SYNC, state: info.state, log: info.log, initialState: info.initialState, clientOnly: true, }); /** * Used to update the Redux store's state in response to * an action coming from another player. * @param {object} state - The state to restore. * @param {Array} deltalog - A log delta. */ const update = (state, deltalog) => ({ type: UPDATE, state, deltalog, clientOnly: true, }); /** * Used to reset the game state. * @param {object} state - The initial state. */ const reset = (state) => ({ type: RESET, state, clientOnly: true, }); /** * Used to undo the last move. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const undo = (playerID, credentials) => ({ type: UNDO, payload: { type: null, args: null, playerID, credentials }, }); /** * Used to redo the last undone move. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const redo = (playerID, credentials) => ({ type: REDO, payload: { type: null, args: null, playerID, credentials }, }); /** * Allows plugins to define their own actions and intercept them. */ const plugin = (type, args, playerID, credentials) => ({ type: PLUGIN, payload: { type, args, playerID, credentials }, }); var ActionCreators = /*#__PURE__*/Object.freeze({ makeMove: makeMove, gameEvent: gameEvent, automaticGameEvent: automaticGameEvent, sync: sync, update: update, reset: reset, undo: undo, redo: redo, plugin: plugin }); /* * 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 => produce(move), }; // Inlined version of Alea from https://github.com/davidbau/seedrandom. /* * Copyright 2015 David Bau. * * 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 Alea(seed) { var me = this, mash = Mash(); me.next = function () { var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32 me.s0 = me.s1; me.s1 = me.s2; return me.s2 = t - (me.c = t | 0); }; // Apply the seeding algorithm from Baagoe. me.c = 1; me.s0 = mash(' '); me.s1 = mash(' '); me.s2 = mash(' '); me.s0 -= mash(seed); if (me.s0 < 0) { me.s0 += 1; } me.s1 -= mash(seed); if (me.s1 < 0) { me.s1 += 1; } me.s2 -= mash(seed); if (me.s2 < 0) { me.s2 += 1; } mash = null; } function copy(f, t) { t.c = f.c; t.s0 = f.s0; t.s1 = f.s1; t.s2 = f.s2; return t; } function Mash() { var n = 0xefc8249d; var mash = function mash(data) { data = data.toString(); for (var i = 0; i < data.length; i++) { n += data.charCodeAt(i); var 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 alea(seed, opts) { var xg = new Alea(seed), state = opts && opts.state, prng = xg.next; prng.quick = prng; if (state) { if (_typeof(state) == 'object') copy(state, xg); prng.state = function () { return copy(xg, {}); }; } return prng; } /** * 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. */ var Random = /*#__PURE__*/ function () { /** * constructor * @param {object} ctx - The ctx object to initialize from. */ function Random(state) { _classCallCheck(this, Random); // 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; this.used = false; } _createClass(Random, [{ key: "isUsed", value: function isUsed() { return this.used; } }, { key: "getState", value: function getState() { return this.state; } /** * Generate a random number. */ }, { key: "_random", value: function _random() { this.used = true; var R = this.state; var fn; if (R.prngstate === undefined) { // No call to a random function has been made. fn = new alea(R.seed, { state: true }); } else { fn = new alea('', { state: R.prngstate }); } var number = fn(); this.state = _objectSpread2({}, R, { prngstate: fn.state() }); return number; } }, { key: "api", value: function api() { var random = this._random.bind(this); var SpotValue = { D4: 4, D6: 6, D8: 8, D10: 10, D12: 12, D20: 20 }; // Generate functions for predefined dice values D4 - D20. var predefined = {}; var _loop = function _loop(key) { var spotvalue = SpotValue[key]; predefined[key] = function (diceCount) { if (diceCount === undefined) { return Math.floor(random() * spotvalue) + 1; } else { return _toConsumableArray(new Array(diceCount).keys()).map(function () { return Math.floor(random() * spotvalue) + 1; }); } }; }; for (var key in SpotValue) { _loop(key); } return _objectSpread2({}, 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: function Die(spotvalue, diceCount) { if (spotvalue === undefined) { spotvalue = 6; } if (diceCount === undefined) { return Math.floor(random() * spotvalue) + 1; } else { return _toConsumableArray(new Array(diceCount).keys()).map(function () { return Math.floor(random() * spotvalue) + 1; }); } }, /** * Generate a random number between 0 and 1. */ Number: function Number() { return random(); }, /** * Shuffle an array. * * @param {Array} deck - The array to shuffle. Does not mutate * the input, but returns the shuffled array. */ Shuffle: function Shuffle(deck) { var clone = deck.slice(0); var srcIndex = deck.length; var dstIndex = 0; var shuffled = new Array(srcIndex); while (srcIndex) { var randIndex = srcIndex * random() | 0; shuffled[dstIndex++] = clone[randIndex]; clone[randIndex] = clone[--srcIndex]; } return shuffled; }, _obj: this }); } }]); return Random; }(); /** * Generates a new seed from the current date / time. */ Random.seed = function () { return (+new Date()).toString(36).slice(-10); }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const RandomPlugin = { name: 'random', noClient: ({ api }) => { return api._obj.isUsed(); }, flush: ({ api }) => { return api._obj.getState(); }, api: ({ data }) => { const random = new Random(data); return random.api(); }, setup: ({ game }) => { let seed = game.seed; if (seed === undefined) { seed = Random.seed(); } return { seed }; }, }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Events */ class Events { constructor(flow, playerID) { this.flow = flow; this.playerID = playerID; this.dispatch = []; } /** * Attaches the Events API to ctx. * @param {object} ctx - The ctx object to attach to. */ api(ctx) { const events = { _obj: this, }; const { phase, turn } = ctx; for (const key of this.flow.eventNames) { events[key] = (...args) => { this.dispatch.push({ key, args, phase, turn }); }; } return events; } isUsed() { return this.dispatch.length > 0; } /** * Updates ctx with the triggered events. * @param {object} state - The state object { G, ctx }. */ update(state) { for (let i = 0; i < this.dispatch.length; i++) { const item = this.dispatch[i]; // If the turn already ended some other way, // don't try to end the turn again. if (item.key === 'endTurn' && item.turn !== state.ctx.turn) { continue; } // If the phase already ended some other way, // don't try to end the phase again. if ((item.key === 'endPhase' || item.key === 'setPhase') && item.phase !== state.ctx.phase) { continue; } const action = automaticGameEvent(item.key, item.args, this.playerID); state = { ...state, ...this.flow.processEvent(state, action), }; } return state; } } /* * Copyright 2020 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const EventsPlugin = { name: 'events', noClient: ({ api }) => { return api._obj.isUsed(); }, dangerouslyFlushRawState: ({ state, api }) => { return api._obj.update(state); }, api: ({ game, playerID, ctx }) => { return new Events(game.flow, playerID).api(ctx); }, }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * List of plugins that are always added. */ const DEFAULT_PLUGINS = [ImmerPlugin, RandomPlugin, EventsPlugin]; /** * Allow plugins to intercept actions and process them. */ const ProcessAction = (state, action, opts) => { opts.game.plugins .filter(plugin => plugin.action !== undefined) .filter(plugin => plugin.name === action.payload.type) .forEach(plugin => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; const data = plugin.action(pluginState.data, action.payload); state = { ...state, plugins: { ...state.plugins, [name]: { ...pluginState, data }, }, }; }); return state; }; /** * The API's created by various plugins are stored in the plugins * section of the state object: * * { * G: {}, * ctx: {}, * plugins: { * plugin-a: { * data: {}, // this is generated by the plugin at Setup / Flush. * api: {}, // this is ephemeral and generated by Enhance. * } * } * } * * This function takes these API's and stuffs them back into * ctx for consumption inside a move function or hook. */ const EnhanceCtx = (state) => { let ctx = { ...state.ctx }; const plugins = state.plugins || {}; Object.entries(plugins).forEach(([name, { api }]) => { ctx[name] = api; }); return ctx; }; /** * Applies the provided plugins to the given move / flow function. * * @param {function} fn - The move function or trigger to apply the plugins to. * @param {object} plugins - The list of plugins. */ const FnWrap = (fn, plugins) => { const reducer = (acc, { fnWrap }) => fnWrap(acc); return [...DEFAULT_PLUGINS, ...plugins] .filter(plugin => plugin.fnWrap !== undefined) .reduce(reducer, fn); }; /** * Allows the plugin to generate its initial state. */ const Setup = (state, opts) => { [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter(plugin => plugin.setup !== undefined) .forEach(plugin => { const name = plugin.name; const data = plugin.setup({ G: state.G, ctx: state.ctx, game: opts.game, }); state = { ...state, plugins: { ...state.plugins, [name]: { data }, }, }; }); return state; }; /** * Invokes the plugin before a move or event. * The API that the plugin generates is stored inside * the `plugins` section of the state (which is subsequently * merged into ctx). */ const Enhance = (state, opts) => { [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter(plugin => plugin.api !== undefined) .forEach(plugin => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; const api = plugin.api({ G: state.G, ctx: state.ctx, data: pluginState.data, game: opts.game, playerID: opts.playerID, }); state = { ...state, plugins: { ...state.plugins, [name]: { ...pluginState, api }, }, }; }); return state; }; /** * Allows plugins to update their state after a move / event. */ const Flush = (state, opts) => { [...DEFAULT_PLUGINS, ...opts.game.plugins].forEach(plugin => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; if (plugin.flush) { const newData = plugin.flush({ G: state.G, ctx: state.ctx, game: opts.game, api: pluginState.api, data: pluginState.data, }); state = { ...state, plugins: { ...state.plugins, [plugin.name]: { data: newData }, }, }; } else if (plugin.dangerouslyFlushRawState) { state = plugin.dangerouslyFlushRawState({ state, game: opts.game, api: pluginState.api, data: pluginState.data, }); // Remove everything other than data. const data = state.plugins[name].data; state = { ...state, plugins: { ...state.plugins, [plugin.name]: { data }, }, }; } }); return state; }; /** * Allows plugins to indicate if they should not be materialized on the client. * This will cause the client to discard the state update and wait for the * master instead. */ const NoClient = (state, opts) => { return [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter(plugin => plugin.noClient !== undefined) .map(plugin => { const name = plugin.name; const pluginState = state.plugins[name]; if (pluginState) { return plugin.noClient({ G: state.G, ctx: state.ctx, game: opts.game, api: pluginState.api, data: pluginState.data, }); } return false; }) .some(value => value === true); }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const production = process.env.NODE_ENV === 'production'; const logfn = production ? () => { } : console.log; const errorfn = console.error; function info(msg) { logfn(`INFO: ${msg}`); } function error(error) { errorfn('ERROR:', error); } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Event to change the active players (and their stages) in the current turn. */ function SetActivePlayersEvent(state, _playerID, arg) { return { ...state, ctx: SetActivePlayers(state.ctx, arg) }; } function SetActivePlayers(ctx, arg) { let { _prevActivePlayers } = ctx; let activePlayers = {}; let _nextActivePlayers = null; let _activePlayersMoveLimit = {}; if (Array.isArray(arg)) { // support a simple array of player IDs as active players let value = {}; arg.forEach(v => (value[v] = Stage.NULL)); activePlayers = value; } else { // process active players argument object if (arg.next) { _nextActivePlayers = arg.next; } if (arg.revert) { _prevActivePlayers = _prevActivePlayers.concat({ activePlayers: ctx.activePlayers, _activePlayersMoveLimit: ctx._activePlayersMoveLimit, _activePlayersNumMoves: ctx._activePlayersNumMoves, }); } else { _prevActivePlayers = []; } if (arg.currentPlayer !== undefined) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, ctx.currentPlayer, arg.currentPlayer); } if (arg.others !== undefined) { for (let i = 0; i < ctx.playOrder.length; i++) { const id = ctx.playOrder[i]; if (id !== ctx.currentPlayer) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.others); } } } if (arg.all !== undefined) { for (let i = 0; i < ctx.playOrder.length; i++) { const id = ctx.playOrder[i]; ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.all); } } if (arg.value) { for (const id in arg.value) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.value[id]); } } if (arg.moveLimit) { for (const id in activePlayers) { if (_activePlayersMoveLimit[id] === undefined) { _activePlayersMoveLimit[id] = arg.moveLimit; } } } } if (Object.keys(activePlayers).length == 0) { activePlayers = null; } if (Object.keys(_activePlayersMoveLimit).length == 0) { _activePlayersMoveLimit = null; } let _activePlayersNumMoves = {}; for (const id in activePlayers) { _activePlayersNumMoves[id] = 0; } return { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, _nextActivePlayers, }; } /** * Update activePlayers, setting it to previous, next or null values * when it becomes empty. * @param ctx */ function UpdateActivePlayersOnceEmpty(ctx) { let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, } = ctx; if (activePlayers && Object.keys(activePlayers).length == 0) { if (ctx._nextActivePlayers) { ctx = SetActivePlayers(ctx, ctx._nextActivePlayers); ({ activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, } = ctx); } else if (_prevActivePlayers.length > 0) { const lastIndex = _prevActivePlayers.length - 1; ({ activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, } = _prevActivePlayers[lastIndex]); _prevActivePlayers = _prevActivePlayers.slice(0, lastIndex); } else { activePlayers = null; _activePlayersMoveLimit = null; } } return { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, }; } /** * Apply an active player argument to the given player ID * @param {Object} activePlayers * @param {Object} _activePlayersMoveLimit * @param {String} playerID The player to apply the parameter to * @param {(String|Object)} arg An active player argument */ function ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, playerID, arg) { if (typeof arg !== 'object' || arg === Stage.NULL) { arg = { stage: arg }; } if (arg.stage !== undefined) { activePlayers[playerID] = arg.stage; if (arg.moveLimit) _activePlayersMoveLimit[playerID] = arg.moveLimit; } } /** * Converts a playOrderPos index into its value in playOrder. * @param {Array} playOrder - An array of player ID's. * @param {number} playOrderPos - An index into the above. */ function getCurrentPlayer(playOrder, playOrderPos) { // convert to string in case playOrder is set to number[] return playOrder[playOrderPos] + ''; } /** * Called at the start of a turn to initialize turn order state. * * TODO: This is called inside StartTurn, which is called from * both UpdateTurn and StartPhase (so it's called at the beginning * of a new phase as well as between turns). We should probably * split it into two. */ function InitTurnOrderState(state, turn) { let { G, ctx } = state; const ctxWithAPI = EnhanceCtx(state); const order = turn.order; let playOrder = [...new Array(ctx.numPlayers)].map((_, i) => i + ''); if (order.playOrder !== undefined) { playOrder = order.playOrder(G, ctxWithAPI); } const playOrderPos = order.first(G, ctxWithAPI); const posType = typeof playOrderPos; if (posType !== 'number') { error(`invalid value returned by turn.order.first — expected number got ${posType} “${playOrderPos}”.`); } const currentPlayer = getCurrentPlayer(playOrder, playOrderPos); ctx = { ...ctx, currentPlayer, playOrderPos, playOrder }; ctx = SetActivePlayers(ctx, turn.activePlayers || {}); return ctx; } /** * Called at the end of each turn to update the turn order state. * @param {object} G - The game object G. * @param {object} ctx - The game object ctx. * @param {object} turn - A turn object for this phase. * @param {string} endTurnArg - An optional argument to endTurn that may specify the next player. */ function UpdateTurnOrderState(state, currentPlayer, turn, endTurnArg) { const order = turn.order; let { G, ctx } = state; let playOrderPos = ctx.playOrderPos; let endPhase = false; if (endTurnArg && endTurnArg !== true) { if (typeof endTurnArg !== 'object') { error(`invalid argument to endTurn: ${endTurnArg}`); } Object.keys(endTurnArg).forEach(arg => { switch (arg) { case 'remove': currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos); break; case 'next': playOrderPos = ctx.playOrder.indexOf(endTurnArg.next); currentPlayer = endTurnArg.next; break; default: error(`invalid argument to endTurn: ${arg}`); } }); } else { const ctxWithAPI = EnhanceCtx(state); const t = order.next(G, ctxWithAPI); const type = typeof t; if (t !== undefined && type !== 'number') { error(`invalid value returned by turn.order.next — expected number or undefined got ${type} “${t}”.`); } if (t === undefined) { endPhase = true; } else { playOrderPos = t; currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos); } } ctx = { ...ctx, playOrderPos, currentPlayer, }; return { endPhase, ctx }; } /** * Set of different turn orders possible in a phase. * These are meant to be passed to the `turn` setting * in the flow objects. * * Each object defines the first player when the phase / game * begins, and also a function `next` to determine who the * next player is when the turn ends. * * The phase ends if next() returns undefined. */ const TurnOrder = { /** * DEFAULT * * The default round-robin turn order. */ DEFAULT: { first: (G, ctx) => ctx.turn === 0 ? ctx.playOrderPos : (ctx.playOrderPos + 1) % ctx.playOrder.length, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * RESET * * Similar to DEFAULT, but starts from 0 each time. */ RESET: { first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * CONTINUE * * Similar to DEFAULT, but starts with the player who ended the last phase. */ CONTINUE: { first: (G, ctx) => ctx.playOrderPos, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * ONCE * * Another round-robin turn order, but goes around just once. * The phase ends after all players have played. */ ONCE: { first: () => 0, next: (G, ctx) => { if (ctx.playOrderPos < ctx.playOrder.length - 1) { return ctx.playOrderPos + 1; } }, }, /** * CUSTOM * * Identical to DEFAULT, but also sets playOrder at the * beginning of the phase. * * @param {Array} playOrder - The play order. */ CUSTOM: (playOrder) => ({ playOrder: () => playOrder, first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }), /** * CUSTOM_FROM * * Identical to DEFAULT, but also sets playOrder at the * beginning of the phase to a value specified by a field * in G. * * @param {string} playOrderField - Field in G. */ CUSTOM_FROM: (playOrderField) => ({ playOrder: (G) => G[playOrderField], first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }), }; const Stage = { NULL: null, }; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Flow * * Creates a reducer that updates ctx (analogous to how moves update G). */ function Flow({ moves, phases, endIf, onEnd, turn, events, plugins, }) { // Attach defaults. if (moves === undefined) { moves = {}; } if (events === undefined) { events = {}; } if (plugins === undefined) { plugins = []; } if (phases === undefined) { phases = {}; } if (!endIf) endIf = () => undefined; if (!onEnd) onEnd = G => G; if (!turn) turn = {}; const phaseMap = { ...phases }; if ('' in phaseMap) { error('cannot specify phase with empty name'); } phaseMap[''] = {}; let moveMap = {}; let moveNames = new Set(); let startingPhase = null; Object.keys(moves).forEach(name => moveNames.add(name)); const HookWrapper = (fn) => { const withPlugins = FnWrap(fn, plugins); return (state) => { const ctxWithAPI = EnhanceCtx(state); return withPlugins(state.G, ctxWithAPI); }; }; const TriggerWrapper = (endIf) => { return (state) => { let ctxWithAPI = EnhanceCtx(state); return endIf(state.G, ctxWithAPI); }; }; const wrapped = { onEnd: HookWrapper(onEnd), endIf: TriggerWrapper(endIf), }; for (let phase in phaseMap) { const conf = phaseMap[phase]; if (conf.start === true) { startingPhase = phase; } if (conf.moves !== undefined) { for (let move of Object.keys(conf.moves)) { moveMap[phase + '.' + move] = conf.moves[move]; moveNames.add(move); } } if (conf.endIf === undefined) { conf.endIf = () => undefined; } if (conf.onBegin === undefined) { conf.onBegin = G => G; } if (conf.onEnd === undefined) { conf.onEnd = G => G; } if (conf.turn === undefined) { conf.turn = turn; } if (conf.turn.order === undefined) { conf.turn.order = TurnOrder.DEFAULT; } if (conf.turn.onBegin === undefined) { conf.turn.onBegin = G => G; } if (conf.turn.onEnd === undefined) { conf.turn.onEnd = G => G; } if (conf.turn.endIf === undefined) { conf.turn.endIf = () => false; } if (conf.turn.onMove === undefined) { conf.turn.onMove = G => G; } if (conf.turn.stages === undefined) { conf.turn.stages = {}; } for (const stage in conf.turn.stages) { const stageConfig = conf.turn.stages[stage]; const moves = stageConfig.moves || {}; for (let move of Object.keys(moves)) { let key = phase + '.' + stage + '.' + move; moveMap[key] = moves[move]; moveNames.add(move); } } conf.wrapped = { onBegin: HookWrapper(conf.onBegin), onEnd: HookWrapper(conf.onEnd), endIf: TriggerWrapper(conf.endIf), }; conf.turn.wrapped = { onMove: HookWrapper(conf.turn.onMove), onBegin: HookWrapper(conf.turn.onBegin), onEnd: HookWrapper(conf.turn.onEnd), endIf: TriggerWrapper(conf.turn.endIf), }; } function GetPhase(ctx) { return ctx.phase ? phaseMap[ctx.phase] : phaseMap['']; } function OnMove(s) { return s; } function Process(state, events) { const phasesEnded = new Set(); const turnsEnded = new Set(); for (let i = 0; i < events.length; i++) { const { fn, arg, ...rest } = events[i]; // Detect a loop of EndPhase calls. // This could potentially even be an infinite loop // if the endIf condition of each phase blindly // returns true. The moment we detect a single // loop, we just bail out of all phases. if (fn === EndPhase) { turnsEnded.clear(); const phase = state.ctx.phase; if (phasesEnded.has(phase)) { const ctx = { ...state.ctx, phase: null }; return { ...state, ctx }; } phasesEnded.add(phase); } // Process event. let next = []; state = fn(state, { ...rest, arg, next, }); if (fn === EndGame) { break; } // Check if we should end the game. const shouldEndGame = ShouldEndGame(state); if (shouldEndGame) { events.push({ fn: EndGame, arg: shouldEndGame, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } // Check if we should end the phase. const shouldEndPhase = ShouldEndPhase(state); if (shouldEndPhase) { events.push({ fn: EndPhase, arg: shouldEndPhase, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } // Check if we should end the turn. if (fn === OnMove) { const shouldEndTurn = ShouldEndTurn(state); if (shouldEndTurn) { events.push({ fn: EndTurn, arg: shouldEndTurn, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } } events.push(...next); } return state; } /////////// // Start // /////////// function StartGame(state, { next }) { next.push({ fn: StartPhase }); return state; } function StartPhase(state, { next }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Run any phase setup code provided by the user. G = conf.wrapped.onBegin(state); next.push({ fn: StartTurn }); return { ...state, G, ctx }; } function StartTurn(state, { currentPlayer }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Initialize the turn order state. if (currentPlayer) { ctx = { ...ctx, currentPlayer }; if (conf.turn.activePlayers) { ctx = SetActivePlayers(ctx, conf.turn.activePlayers); } } else { // This is only called at the beginning of the phase // when there is no currentPlayer yet. ctx = InitTurnOrderState(state, conf.turn); } const turn = ctx.turn + 1; ctx = { ...ctx, turn, numMoves: 0, _prevActivePlayers: [] }; G = conf.turn.wrapped.onBegin({ ...state, G, ctx }); const _undo = [{ G, ctx }]; return { ...state, G, ctx, _undo, _redo: [] }; } //////////// // Update // //////////// function UpdatePhase(state, { arg, next, phase }) { const conf = GetPhase({ phase }); let { ctx } = state; if (arg && arg.next) { if (arg.next in phaseMap) { ctx = { ...ctx, phase: arg.next }; } else { error('invalid phase: ' + arg.next); return state; } } else if (conf.next !== undefined) { ctx = { ...ctx, phase: conf.next }; } else { ctx = { ...ctx, phase: null }; } state = { ...state, ctx }; // Start the new phase. next.push({ fn: StartPhase }); return state; } function UpdateTurn(state, { arg, currentPlayer, next }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Update turn order state. const { endPhase, ctx: newCtx } = UpdateTurnOrderState(state, currentPlayer, conf.turn, arg); ctx = newCtx; state = { ...state, G, ctx }; if (endPhase) { next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase }); } else { next.push({ fn: StartTurn, currentPlayer: ctx.currentPlayer }); } return state; } function UpdateStage(state, { arg, playerID }) { if (typeof arg === 'string') { arg = { stage: arg }; } let { ctx } = state; let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, } = ctx; if (arg.stage) { if (activePlayers === null) { activePlayers = {}; } activePlayers[playerID] = arg.stage; _activePlayersNumMoves[playerID] = 0; if (arg.moveLimit) { if (_activePlayersMoveLimit === null) { _activePlayersMoveLimit = {}; } _activePlayersMoveLimit[playerID] = arg.moveLimit; } } ctx = { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, }; return { ...state, ctx }; } /////////////// // ShouldEnd // /////////////// function ShouldEndGame(state) { return wrapped.endIf(state); } function ShouldEndPhase(state) { const conf = GetPhase(state.ctx); return conf.wrapped.endIf(state); } function ShouldEndTurn(state) { const conf = GetPhase(state.ctx); // End the turn if the required number of moves has been made. const currentPlayerMoves = state.ctx.numMoves || 0; if (conf.turn.moveLimit && currentPlayerMoves >= conf.turn.moveLimit) { return true; } return conf.turn.wrapped.endIf(state); } ///////// // End // ///////// function EndGame(state, { arg, phase }) { state = EndPhase(state, { phase }); if (arg === undefined) { arg = true; } state = { ...state, ctx: { ...state.ctx, gameover: arg } }; // Run game end hook. const G = wrapped.onEnd(state); return { ...state, G }; } function EndPhase(state, { arg, next, turn, automatic }) { // End the turn first. state = EndTurn(state, { turn, force: true }); let G = state.G; let ctx = state.ctx; if (next) { next.push({ fn: UpdatePhase, arg, phase: ctx.phase }); } // If we aren't in a phase, there is nothing else to do. if (ctx.phase === null) { return state; } // Run any cleanup code for the phase that is about to end. const conf = GetPhase(ctx); G = conf.wrapped.onEnd(state); // Reset the phase. ctx = { ...ctx, phase: null }; // Add log entry. const action = gameEvent('endPhase', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...state.deltalog, logEntry]; return { ...state, G, ctx, deltalog }; } function EndTurn(state, { arg, next, turn, force, automatic, playerID }) { // This is not the turn that EndTurn was originally // called for. The turn was probably ended some other way. if (turn !== state.ctx.turn) { return state; } let { G, ctx } = state; const conf = GetPhase(ctx); // Prevent ending the turn if moveLimit hasn't been reached. const currentPlayerMoves = ctx.numMoves || 0; if (!force && conf.turn.moveLimit && currentPlayerMoves < conf.turn.moveLimit) { info(`cannot end turn before making ${conf.turn.moveLimit} moves`); return state; } // Run turn-end triggers. G = conf.turn.wrapped.onEnd(state); if (next) { next.push({ fn: UpdateTurn, arg, currentPlayer: ctx.currentPlayer }); } // Reset activePlayers. ctx = { ...ctx, activePlayers: null }; // Remove player from playerOrder if (arg && arg.remove) { playerID = playerID || ctx.currentPlayer; const playOrder = ctx.playOrder.filter(i => i != playerID); const playOrderPos = ctx.playOrderPos > playOrder.length - 1 ? 0 : ctx.playOrderPos; ctx = { ...ctx, playOrder, playOrderPos }; if (playOrder.length === 0) { next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase }); return state; } } // Add log entry. const action = gameEvent('endTurn', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...(state.deltalog || []), logEntry]; return { ...state, G, ctx, deltalog, _undo: [], _redo: [] }; } function EndStage(state, { arg, next, automatic, playerID }) { playerID = playerID || state.ctx.currentPlayer; let { ctx } = state; let { activePlayers, _activePlayersMoveLimit } = ctx; const playerInStage = activePlayers !== null && playerID in activePlayers; if (!arg && playerInStage) { const conf = GetPhase(ctx); const stage = conf.turn.stages[activePlayers[playerID]]; if (stage && stage.next) arg = stage.next; } if (next && arg) { next.push({ fn: UpdateStage, arg, playerID }); } // If player isn’t in a stage, there is nothing else to do. if (!playerInStage) return state; // Remove player from activePlayers. activePlayers = Object.keys(activePlayers) .filter(id => id !== playerID) .reduce((obj, key) => { obj[key] = activePlayers[key]; return obj; }, {}); if (_activePlayersMoveLimit) { // Remove player from _activePlayersMoveLimit. _activePlayersMoveLimit = Object.keys(_activePlayersMoveLimit) .filter(id => id !== playerID) .reduce((obj, key) => { obj[key] = _activePlayersMoveLimit[key]; return obj; }, {}); } ctx = UpdateActivePlayersOnceEmpty({ ...ctx, activePlayers, _activePlayersMoveLimit, }); // Add log entry. const action = gameEvent('endStage', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...(state.deltalog || []), logEntry]; return { ...state, ctx, deltalog }; } /** * Retrieves the relevant move that can be played by playerID. * * If ctx.activePlayers is set (i.e. one or more players are in some stage), * then it attempts to find the move inside the stages config for * that turn. If the stage for a player is '', then the player is * allowed to make a move (as determined by the phase config), but * isn't restricted to a particular set as defined in the stage config. * * If not, it then looks for the move inside the phase. * * If it doesn't find the move there, it looks at the global move definition. * * @param {object} ctx * @param {string} name * @param {string} playerID */ function GetMove(ctx, name, playerID) { const conf = GetPhase(ctx); const stages = conf.turn.stages; const { activePlayers } = ctx; if (activePlayers && activePlayers[playerID] !== undefined && activePlayers[playerID] !== Stage.NULL && stages[activePlayers[playerID]] !== undefined && stages[activePlayers[playerID]].moves !== undefined) { // Check if moves are defined for the player's stage. const stage = stages[activePlayers[playerID]]; const moves = stage.moves; if (name in moves) { return moves[name]; } } else if (conf.moves) { // Check if moves are defined for the current phase. if (name in conf.moves) { return conf.moves[name]; } } else if (name in moves) { // Check for the move globally. return moves[name]; } return null; } function ProcessMove(state, action) { let conf = GetPhase(state.ctx); let { ctx } = state; let { _activePlayersNumMoves } = ctx; const { playerID } = action; if (ctx.activePlayers) _activePlayersNumMoves[playerID]++; let numMoves = state.ctx.numMoves; if (playerID == state.ctx.currentPlayer) { numMoves++; } state = { ...state, ctx: { ...ctx, numMoves, _activePlayersNumMoves, }, }; if (ctx._activePlayersMoveLimit && _activePlayersNumMoves[playerID] >= ctx._activePlayersMoveLimit[playerID]) { state = EndStage(state, { playerID, automatic: true }); } const G = conf.turn.wrapped.onMove(state); state = { ...state, G }; // Update undo / redo state. const undo = state._undo || []; const moveType = action.type; state = { ...state, _undo: [...undo, { G: state.G, ctx: state.ctx, moveType }], _redo: [], }; let events = [{ fn: OnMove }]; return Process(state, events); } function SetStageEvent(state, playerID, arg) { return Process(state, [{ fn: EndStage, arg, playerID }]); } function EndStageEvent(state, playerID) { return Process(state, [{ fn: EndStage, playerID }]); } function SetPhaseEvent(state, _playerID, newPhase) { return Process(state, [ { fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn, arg: { next: newPhase }, }, ]); } function EndPhaseEvent(state) { return Process(state, [ { fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn }, ]); } function EndTurnEvent(state, _playerID, arg) { return Process(state, [ { fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, arg }, ]); } function PassEvent(state, _playerID, arg) { return Process(state, [ { fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, force: true, arg, }, ]); } function EndGameEvent(state, _playerID, arg) { return Process(state, [ { fn: EndGame, turn: state.ctx.turn, phase: state.ctx.phase, arg }, ]); } const eventHandlers = { endStage: EndStageEvent, setStage: SetStageEvent, endTurn: EndTurnEvent, pass: PassEvent, endPhase: EndPhaseEvent, setPhase: SetPhaseEvent, endGame: EndGameEvent, setActivePlayers: SetActivePlayersEvent, }; let 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 (eventHandlers.hasOwnProperty(type)) { const eventArgs = [state, playerID].concat(args); return eventHandlers[type].apply({}, eventArgs); } return state; } function IsPlayerActive(_G, ctx, playerID) { if (ctx.activePlayers) { return playerID in ctx.activePlayers; } return ctx.currentPlayer === playerID; } return { ctx: (numPlayers) => ({ numPlayers, turn: 0, currentPlayer: '0', playOrder: [...new Array(numPlayers)].map((_d, i) => i + ''), playOrderPos: 0, phase: startingPhase, activePlayers: null, }), init: (state) => { return Process(state, [{ fn: StartGame }]); }, isPlayerActive: IsPlayerActive, eventHandlers, eventNames: Object.keys(eventHandlers), enabledEventNames, moveMap, moveNames: [...moveNames.values()], processMove: ProcessMove, processEvent: ProcessEvent, getMove: GetMove, }; } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ function IsProcessed(game) { return game.processMove !== undefined; } /** * Helper to generate the game move reducer. The returned * reducer has the following signature: * * (G, action, ctx) => {} * * You can roll your own if you like, or use any Redux * addon to generate such a reducer. * * The convention used in this framework is to * have action.type contain the name of the move, and * action.args contain any additional arguments as an * Array. */ function ProcessGameConfig(game) { // The Game() function has already been called on this // config object, so just pass it through. if (IsProcessed(game)) { return game; } if (game.name === undefined) game.name = 'default'; if (game.setup === undefined) game.setup = () => ({}); if (game.moves === undefined) game.moves = {}; if (game.playerView === undefined) game.playerView = G => G; if (game.plugins === undefined) game.plugins = []; game.plugins.forEach(plugin => { if (plugin.name === undefined) { throw new Error('Plugin missing name attribute'); } if (plugin.name.includes(' ')) { throw new Error(plugin.name + ': Plugin name must not include spaces'); } }); if (game.name.includes(' ')) { throw new Error(game.name + ': Game name must not include spaces'); } const flow = Flow(game); return { ...game, flow, moveNames: flow.moveNames, pluginNames: game.plugins.map(p => p.name), processMove: (state, action) => { let moveFn = flow.getMove(state.ctx, action.type, action.playerID); if (IsLongFormMove(moveFn)) { moveFn = moveFn.move; } if (moveFn instanceof Function) { const fn = FnWrap(moveFn, game.plugins); const ctxWithAPI = { ...EnhanceCtx(state), playerID: action.playerID, }; let args = []; if (action.args !== undefined) { args = args.concat(action.args); } return fn(state.G, ctxWithAPI, ...args); } error(`invalid move object: ${action.type}`); return state.G; }, }; } function IsLongFormMove(move) { return move instanceof Object && move.move !== undefined; } function noop() { } const identity = x => x; function assign(tar, src) { // @ts-ignore for (const k in src) tar[k] = src[k]; return tar; } function run(fn) { return fn(); } function blank_object() { return Object.create(null); } function run_all(fns) { fns.forEach(run); } function is_function(thing) { return typeof thing === 'function'; } function safe_not_equal(a, b) { return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); } function subscribe(store, callback) { const unsub = store.subscribe(callback); return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub; } function component_subscribe(component, store, callback) { component.$$.on_destroy.push(subscribe(store, callback)); } function create_slot(definition, ctx, fn) { if (definition) { const slot_ctx = get_slot_context(definition, ctx, fn); return definition[0](slot_ctx); } } function get_slot_context(definition, ctx, fn) { return definition[1] ? assign({}, assign(ctx.$$scope.ctx, definition[1](fn ? fn(ctx) : {}))) : ctx.$$scope.ctx; } function get_slot_changes(definition, ctx, changed, fn) { return definition[1] ? assign({}, assign(ctx.$$scope.changed || {}, definition[1](fn ? fn(changed) : {}))) : ctx.$$scope.changed || {}; } function exclude_internal_props(props) { const result = {}; for (const k in props) if (k[0] !== '$') result[k] = props[k]; return result; } 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(); let running = false; function run_tasks() { tasks.forEach(task => { if (!task[0](now())) { tasks.delete(task); task[1](); } }); running = tasks.size > 0; if (running) raf(run_tasks); } function loop(fn) { let task; if (!running) { running = true; raf(run_tasks); } return { promise: new Promise(fulfil => { tasks.add(task = [fn, fulfil]); }), abort() { tasks.delete(task); } }; } function append(target, node) { target.appendChild(node); } function insert(target, node, anchor) { target.insertBefore(node, anchor || null); } function detach(node) { node.parentNode.removeChild(node); } function destroy_each(iterations, detaching) { for (let i = 0; i < iterations.length; i += 1) { if (iterations[i]) iterations[i].d(detaching); } } function element(name) { return document.createElement(name); } function svg_element(name) { return document.createElementNS('http://www.w3.org/2000/svg', name); } function text(data) { return document.createTextNode(data); } function space() { return text(' '); } function empty() { return text(''); } function listen(node, event, handler, options) { node.addEventListener(event, handler, options); return () => node.removeEventListener(event, handler, options); } function attr(node, attribute, value) { if (value == null) node.removeAttribute(attribute); else node.setAttribute(attribute, value); } function to_number(value) { return value === '' ? undefined : +value; } function children(element) { return Array.from(element.childNodes); } function set_data(text, data) { data = '' + data; if (text.data !== data) text.data = data; } function set_input_value(input, value) { if (value != null || input.value) { input.value = value; } } function select_option(select, value) { for (let i = 0; i < select.options.length; i += 1) { const option = select.options[i]; if (option.__value === value) { option.selected = true; return; } } } function select_value(select) { const selected_option = select.querySelector(':checked') || select.options[0]; return selected_option && selected_option.__value; } function toggle_class(element, name, toggle) { element.classList[toggle ? 'add' : 'remove'](name); } function custom_event(type, detail) { const e = document.createEvent('CustomEvent'); e.initCustomEvent(type, false, false, detail); return e; } let stylesheet; let active = 0; let current_rules = {}; // 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}`; if (!current_rules[name]) { if (!stylesheet) { const style = element('style'); document.head.appendChild(style); stylesheet = style.sheet; } 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) { node.style.animation = (node.style.animation || '') .split(', ') .filter(name ? anim => anim.indexOf(name) < 0 // remove specific animation : anim => anim.indexOf('__svelte') === -1 // remove all Svelte animations ) .join(', '); if (name && !--active) clear_rules(); } function clear_rules() { raf(() => { if (active) return; let i = stylesheet.cssRules.length; while (i--) stylesheet.deleteRule(i); current_rules = {}; }); } 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 = 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); } 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); } function flush() { const seen_callbacks = new Set(); do { // first, call beforeUpdate functions // and update components while (dirty_components.length) { const component = dirty_components.shift(); set_current_component(component); update$1(component.$$); } 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)) { callback(); // ...so guard against infinite loops seen_callbacks.add(callback); } } render_callbacks.length = 0; } while (dirty_components.length); while (flush_callbacks.length) { flush_callbacks.pop()(); } update_scheduled = false; } function update$1($$) { if ($$.fragment) { $$.update($$.dirty); run_all($$.before_update); $$.fragment.p($$.dirty, $$.ctx); $$.dirty = null; $$.after_update.forEach(add_render_callback); } } let promise; function wait() { if (!promise) { promise = Promise.resolve(); promise.then(() => { promise = null; }); } return promise; } function dispatch(node, direction, kind) { node.dispatchEvent(custom_event(`${direction ? 'intro' : 'outro'}${kind}`)); } const outroing = new Set(); let outros; function group_outros() { outros = { r: 0, c: [], p: outros // parent group }; } function check_outros() { if (!outros.r) { run_all(outros.c); } outros = outros.p; } function transition_in(block, local) { if (block && block.i) { outroing.delete(block); block.i(local); } } function transition_out(block, local, detach, callback) { if (block && block.o) { if (outroing.has(block)) return; outroing.add(block); outros.c.push(() => { outroing.delete(block); if (callback) { if (detach) block.d(1); callback(); } }); block.o(local); } } const null_transition = { duration: 0 }; function create_bidirectional_transition(node, fn, params, intro) { let config = fn(node, params); let t = intro ? 0 : 1; let running_program = null; let pending_program = null; let animation_name = null; function clear_animation() { if (animation_name) delete_rule(node, animation_name); } function init(program, duration) { const d = program.b - t; duration *= Math.abs(d); return { a: t, b: program.b, d, duration, start: program.start, end: program.start + duration, group: program.group }; } function go(b) { const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition; const program = { start: now() + delay, b }; if (!b) { // @ts-ignore todo: improve typings program.group = outros; outros.r += 1; } if (running_program) { pending_program = program; } else { // if this is an intro, and there's a delay, we need to do // an initial tick and/or apply CSS animation immediately if (css) { clear_animation(); animation_name = create_rule(node, t, b, duration, delay, easing, css); } if (b) tick(0, 1); running_program = init(program, duration); add_render_callback(() => dispatch(node, b, 'start')); loop(now => { if (pending_program && now > pending_program.start) { running_program = init(pending_program, duration); pending_program = null; dispatch(node, running_program.b, 'start'); if (css) { clear_animation(); animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css); } } if (running_program) { if (now >= running_program.end) { tick(t = running_program.b, 1 - t); dispatch(node, running_program.b, 'end'); if (!pending_program) { // we're done if (running_program.b) { // intro — we can tidy up immediately clear_animation(); } else { // outro — needs to be coordinated if (!--running_program.group.r) run_all(running_program.group.c); } } running_program = null; } else if (now >= running_program.start) { const p = now - running_program.start; t = running_program.a + running_program.d * easing(p / running_program.duration); tick(t, 1 - t); } } return !!(running_program || pending_program); }); } } return { run(b) { if (is_function(config)) { wait().then(() => { // @ts-ignore config = config(); go(b); }); } else { go(b); } }, end() { clear_animation(); running_program = pending_program = null; } }; } const globals = (typeof window !== 'undefined' ? window : global); function get_spread_update(levels, updates) { const update = {}; const to_null_out = {}; const accounted_for = { $$scope: 1 }; let i = levels.length; while (i--) { const o = levels[i]; const n = updates[i]; if (n) { for (const key in o) { if (!(key in n)) to_null_out[key] = 1; } for (const key in n) { if (!accounted_for[key]) { update[key] = n[key]; accounted_for[key] = 1; } } levels[i] = n; } else { for (const key in o) { accounted_for[key] = 1; } } } for (const key in to_null_out) { if (!(key in update)) update[key] = undefined; } return update; } function get_spread_object(spread_props) { return typeof spread_props === 'object' && spread_props !== null ? spread_props : {}; } function mount_component(component, target, anchor) { const { fragment, on_mount, on_destroy, after_update } = component.$$; fragment.m(target, anchor); // onMount happens before the initial afterUpdate add_render_callback(() => { const new_on_destroy = on_mount.map(run).filter(is_function); if (on_destroy) { on_destroy.push(...new_on_destroy); } else { // Edge case - component was destroyed immediately, // most likely as a result of a binding initialising run_all(new_on_destroy); } component.$$.on_mount = []; }); after_update.forEach(add_render_callback); } function destroy_component(component, detaching) { if (component.$$.fragment) { run_all(component.$$.on_destroy); component.$$.fragment.d(detaching); // TODO null out other refs, including component.$$ (but need to // preserve final state?) component.$$.on_destroy = component.$$.fragment = null; component.$$.ctx = {}; } } function make_dirty(component, key) { if (!component.$$.dirty) { dirty_components.push(component); schedule_update(); component.$$.dirty = blank_object(); } component.$$.dirty[key] = true; } function init(component, options, instance, create_fragment, not_equal, prop_names) { const parent_component = current_component; set_current_component(component); const props = options.props || {}; const $$ = component.$$ = { fragment: null, ctx: null, // state props: prop_names, update: noop, not_equal, bound: blank_object(), // lifecycle on_mount: [], on_destroy: [], before_update: [], after_update: [], context: new Map(parent_component ? parent_component.$$.context : []), // everything else callbacks: blank_object(), dirty: null }; let ready = false; $$.ctx = instance ? instance(component, props, (key, ret, value = ret) => { if ($$.ctx && not_equal($$.ctx[key], $$.ctx[key] = value)) { if ($$.bound[key]) $$.bound[key](value); if (ready) make_dirty(component, key); } return ret; }) : props; $$.update(); ready = true; run_all($$.before_update); $$.fragment = create_fragment($$.ctx); if (options.target) { if (options.hydrate) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion $$.fragment.l(children(options.target)); } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion $$.fragment.c(); } if (options.intro) transition_in(component.$$.fragment); mount_component(component, options.target, options.anchor); flush(); } set_current_component(parent_component); } class SvelteComponent { $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set() { // overridden by instance, if it has props } } const subscriber_queue = []; /** * Create a `Writable` store that allows both updating and reading by subscription. * @param {*=}value initial value * @param {StartStopNotifier=}start start and stop notifications for subscriptions */ function writable(value, start = noop) { let stop; const subscribers = []; function set(new_value) { if (safe_not_equal(value, new_value)) { value = new_value; if (stop) { // store is ready const run_queue = !subscriber_queue.length; for (let i = 0; i < subscribers.length; i += 1) { const s = subscribers[i]; s[1](); subscriber_queue.push(s, value); } if (run_queue) { for (let i = 0; i < subscriber_queue.length; i += 2) { subscriber_queue[i][0](subscriber_queue[i + 1]); } subscriber_queue.length = 0; } } } } function update(fn) { set(fn(value)); } function subscribe(run, invalidate = noop) { const subscriber = [run, invalidate]; subscribers.push(subscriber); if (subscribers.length === 1) { stop = start(set) || noop; } run(value); return () => { const index = subscribers.indexOf(subscriber); if (index !== -1) { subscribers.splice(index, 1); } if (subscribers.length === 0) { stop(); stop = null; } }; } return { set, update, subscribe }; } function cubicOut(t) { const f = t - 1.0; return f * f * f + 1.0; } function fly(node, { delay = 0, duration = 400, easing = cubicOut, x = 0, y = 0, opacity = 0 }) { const style = getComputedStyle(node); const target_opacity = +style.opacity; const transform = style.transform === 'none' ? '' : style.transform; const od = target_opacity * (1 - opacity); return { delay, duration, easing, css: (t, u) => ` transform: ${transform} translate(${(1 - t) * x}px, ${(1 - t) * y}px); opacity: ${target_opacity - (od * u)}` }; } /* src/client/debug/Menu.svelte generated by Svelte v3.12.1 */ function add_css() { var style = element("style"); style.id = 'svelte-19bfq8g-style'; style.textContent = ".menu.svelte-19bfq8g{display:flex;margin-top:-10px;flex-direction:row;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-19bfq8g{line-height:25px;cursor:pointer;background:#fefefe;color:#555;padding-left:15px;padding-right:15px;text-align:center}.menu-item.svelte-19bfq8g:last-child{border-radius:0 5px 0 0}.menu-item.svelte-19bfq8g:first-child{border-radius:5px 0 0 0}.menu-item.active.svelte-19bfq8g{cursor:default;font-weight:bold;background:#ddd;color:#555}.menu-item.svelte-19bfq8g:hover{background:#ddd;color:#555}"; append(document.head, style); } function get_each_context(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.key = list[i][0]; child_ctx.label = list[i][1].label; return child_ctx; } // (55:2) {#each Object.entries(panes).reverse() as [key, {label} function create_each_block(ctx) { var div, t0_value = ctx.label + "", t0, t1, dispose; function click_handler() { return ctx.click_handler(ctx); } return { c() { div = element("div"); t0 = text(t0_value); t1 = space(); attr(div, "class", "menu-item svelte-19bfq8g"); toggle_class(div, "active", ctx.pane == ctx.key); dispose = listen(div, "click", click_handler); }, m(target, anchor) { insert(target, div, anchor); append(div, t0); append(div, t1); }, p(changed, new_ctx) { ctx = new_ctx; if ((changed.panes) && t0_value !== (t0_value = ctx.label + "")) { set_data(t0, t0_value); } if ((changed.pane || changed.panes)) { toggle_class(div, "active", ctx.pane == ctx.key); } }, d(detaching) { if (detaching) { detach(div); } dispose(); } }; } function create_fragment(ctx) { var div; let each_value = Object.entries(ctx.panes).reverse(); 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() { div = element("div"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } attr(div, "class", "menu svelte-19bfq8g"); }, m(target, anchor) { insert(target, div, anchor); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(div, null); } }, p(changed, ctx) { if (changed.pane || changed.panes) { each_value = Object.entries(ctx.panes).reverse(); 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(changed, child_ctx); } else { each_blocks[i] = create_each_block(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($$self, $$props, $$invalidate) { let { pane, panes } = $$props; const dispatch = createEventDispatcher(); const click_handler = ({ key }) => dispatch('change', key); $$self.$set = $$props => { if ('pane' in $$props) $$invalidate('pane', pane = $$props.pane); if ('panes' in $$props) $$invalidate('panes', panes = $$props.panes); }; return { pane, panes, dispatch, click_handler }; } class Menu extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-19bfq8g-style")) add_css(); init(this, options, instance, create_fragment, safe_not_equal, ["pane", "panes"]); } } /* src/client/debug/main/Hotkey.svelte generated by Svelte v3.12.1 */ function add_css$1() { var style = element("style"); style.id = 'svelte-1olzq4i-style'; style.textContent = ".key.svelte-1olzq4i{display:flex;flex-direction:row;align-items:center}.key-box.svelte-1olzq4i{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}.key-box.svelte-1olzq4i:hover{background:#ddd}.key.active.svelte-1olzq4i .key-box.svelte-1olzq4i{background:#ddd;border:1px solid #999;box-shadow:none}.label.svelte-1olzq4i{margin-left:10px}"; append(document.head, style); } // (73:2) {#if label} function create_if_block(ctx) { var div, t; return { c() { div = element("div"); t = text(ctx.label); attr(div, "class", "label svelte-1olzq4i"); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p(changed, ctx) { if (changed.label) { set_data(t, ctx.label); } }, d(detaching) { if (detaching) { detach(div); } } }; } function create_fragment$1(ctx) { var div1, div0, t0, t1, dispose; var if_block = (ctx.label) && create_if_block(ctx); return { c() { div1 = element("div"); div0 = element("div"); t0 = text(ctx.value); t1 = space(); if (if_block) if_block.c(); attr(div0, "class", "key-box svelte-1olzq4i"); attr(div1, "class", "key svelte-1olzq4i"); toggle_class(div1, "active", ctx.active); dispose = [ listen(window, "keydown", ctx.Keypress), listen(div0, "click", ctx.Activate) ]; }, m(target, anchor) { insert(target, div1, anchor); append(div1, div0); append(div0, t0); append(div1, t1); if (if_block) if_block.m(div1, null); }, p(changed, ctx) { if (changed.value) { set_data(t0, ctx.value); } if (ctx.label) { if (if_block) { if_block.p(changed, ctx); } else { if_block = create_if_block(ctx); if_block.c(); if_block.m(div1, null); } } else if (if_block) { if_block.d(1); if_block = null; } if (changed.active) { toggle_class(div1, "active", ctx.active); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div1); } if (if_block) if_block.d(); run_all(dispose); } }; } function instance$1($$self, $$props, $$invalidate) { let $disableHotkeys; let { value, onPress = null, label = null, disable = false } = $$props; const { disableHotkeys } = getContext('hotkeys'); component_subscribe($$self, disableHotkeys, $$value => { $disableHotkeys = $$value; $$invalidate('$disableHotkeys', $disableHotkeys); }); let active = false; function Deactivate() { $$invalidate('active', active = false); } function Activate() { $$invalidate('active', active = true); setTimeout(Deactivate, 200); if (onPress) { setTimeout(onPress, 1); } } function Keypress(e) { if (!$disableHotkeys && !disable && e.key == value) { e.preventDefault(); Activate(); } } $$self.$set = $$props => { if ('value' in $$props) $$invalidate('value', value = $$props.value); if ('onPress' in $$props) $$invalidate('onPress', onPress = $$props.onPress); if ('label' in $$props) $$invalidate('label', label = $$props.label); if ('disable' in $$props) $$invalidate('disable', disable = $$props.disable); }; return { value, onPress, label, disable, disableHotkeys, active, Activate, Keypress }; } class Hotkey extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1olzq4i-style")) add_css$1(); init(this, options, instance$1, create_fragment$1, safe_not_equal, ["value", "onPress", "label", "disable"]); } } /* src/client/debug/main/InteractiveFunction.svelte generated by Svelte v3.12.1 */ function add_css$2() { var style = element("style"); style.id = 'svelte-khot71-style'; style.textContent = ".move.svelte-khot71{cursor:pointer;margin-left:10px;color:#666}.move.svelte-khot71:hover{color:#333}.move.active.svelte-khot71{color:#111;font-weight:bold}.arg-field.svelte-khot71{outline:none;font-family:monospace}"; append(document.head, style); } function create_fragment$2(ctx) { var div, t0, t1, span_1, t2, dispose; return { c() { div = element("div"); t0 = text(ctx.name); t1 = text("("); span_1 = element("span"); t2 = text(")"); attr(span_1, "class", "arg-field svelte-khot71"); attr(span_1, "contenteditable", ""); attr(div, "class", "move svelte-khot71"); toggle_class(div, "active", ctx.active); dispose = [ listen(span_1, "blur", ctx.Deactivate), listen(span_1, "keydown", ctx.OnKeyDown), listen(div, "click", ctx.Activate) ]; }, m(target, anchor) { insert(target, div, anchor); append(div, t0); append(div, t1); append(div, span_1); ctx.span_1_binding(span_1); append(div, t2); }, p(changed, ctx) { if (changed.name) { set_data(t0, ctx.name); } if (changed.active) { toggle_class(div, "active", ctx.active); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div); } ctx.span_1_binding(null); run_all(dispose); } }; } function instance$2($$self, $$props, $$invalidate) { let { Activate, Deactivate, name, 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('span', 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 span_1_binding($$value) { binding_callbacks[$$value ? 'unshift' : 'push'](() => { $$invalidate('span', span = $$value); }); } $$self.$set = $$props => { if ('Activate' in $$props) $$invalidate('Activate', Activate = $$props.Activate); if ('Deactivate' in $$props) $$invalidate('Deactivate', Deactivate = $$props.Deactivate); if ('name' in $$props) $$invalidate('name', name = $$props.name); if ('active' in $$props) $$invalidate('active', active = $$props.active); }; return { Activate, Deactivate, name, active, span, OnKeyDown, span_1_binding }; } class InteractiveFunction extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-khot71-style")) add_css$2(); init(this, options, instance$2, create_fragment$2, safe_not_equal, ["Activate", "Deactivate", "name", "active"]); } } /* src/client/debug/main/Move.svelte generated by Svelte v3.12.1 */ function add_css$3() { var style = element("style"); style.id = 'svelte-smqssc-style'; style.textContent = ".move-error.svelte-smqssc{color:#a00;font-weight:bold}.wrapper.svelte-smqssc{display:flex;flex-direction:row;align-items:center}"; append(document.head, style); } // (65:2) {#if error} function create_if_block$1(ctx) { var span, t; return { c() { span = element("span"); t = text(ctx.error); attr(span, "class", "move-error svelte-smqssc"); }, m(target, anchor) { insert(target, span, anchor); append(span, t); }, p(changed, ctx) { if (changed.error) { set_data(t, ctx.error); } }, d(detaching) { if (detaching) { detach(span); } } }; } function create_fragment$3(ctx) { var div1, div0, t0, t1, current; var hotkey = new Hotkey({ props: { value: ctx.shortcut, onPress: ctx.Activate } }); var interactivefunction = new InteractiveFunction({ props: { Activate: ctx.Activate, Deactivate: ctx.Deactivate, name: ctx.name, active: ctx.active } }); interactivefunction.$on("submit", ctx.Submit); interactivefunction.$on("error", ctx.Error); var if_block = (ctx.error) && create_if_block$1(ctx); return { c() { div1 = element("div"); div0 = element("div"); hotkey.$$.fragment.c(); t0 = space(); interactivefunction.$$.fragment.c(); 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(changed, ctx) { var hotkey_changes = {}; if (changed.shortcut) hotkey_changes.value = ctx.shortcut; hotkey.$set(hotkey_changes); var interactivefunction_changes = {}; if (changed.name) interactivefunction_changes.name = ctx.name; if (changed.active) interactivefunction_changes.active = ctx.active; interactivefunction.$set(interactivefunction_changes); if (ctx.error) { if (if_block) { if_block.p(changed, ctx); } else { if_block = create_if_block$1(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$3($$self, $$props, $$invalidate) { let { shortcut, name, fn } = $$props; const {disableHotkeys} = getContext('hotkeys'); let error$1 = ''; let active = false; function Activate() { disableHotkeys.set(true); $$invalidate('active', active = true); } function Deactivate() { disableHotkeys.set(false); $$invalidate('error', error$1 = ''); $$invalidate('active', active = false); } function Submit(e) { $$invalidate('error', error$1 = ''); Deactivate(); fn.apply(this, e.detail); } function Error(e) { $$invalidate('error', error$1 = e.detail); error(e.detail); } $$self.$set = $$props => { if ('shortcut' in $$props) $$invalidate('shortcut', shortcut = $$props.shortcut); if ('name' in $$props) $$invalidate('name', name = $$props.name); if ('fn' in $$props) $$invalidate('fn', fn = $$props.fn); }; return { shortcut, name, fn, error: error$1, active, Activate, Deactivate, Submit, Error }; } class Move extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-smqssc-style")) add_css$3(); init(this, options, instance$3, create_fragment$3, safe_not_equal, ["shortcut", "name", "fn"]); } } /* src/client/debug/main/Controls.svelte generated by Svelte v3.12.1 */ function add_css$4() { var style = element("style"); style.id = 'svelte-1x2w9i0-style'; style.textContent = "li.svelte-1x2w9i0{list-style:none;margin:none;margin-bottom:5px}"; append(document.head, style); } function create_fragment$4(ctx) { var section, li0, t0, li1, t1, li2, t2, li3, current; var hotkey0 = new Hotkey({ props: { value: "1", onPress: ctx.client.reset, label: "reset" } }); var hotkey1 = new Hotkey({ props: { value: "2", onPress: ctx.Save, label: "save" } }); var hotkey2 = new Hotkey({ props: { value: "3", onPress: ctx.Restore, label: "restore" } }); var hotkey3 = new Hotkey({ props: { value: ".", disable: true, label: "hide" } }); return { c() { section = element("section"); li0 = element("li"); hotkey0.$$.fragment.c(); t0 = space(); li1 = element("li"); hotkey1.$$.fragment.c(); t1 = space(); li2 = element("li"); hotkey2.$$.fragment.c(); t2 = space(); li3 = element("li"); hotkey3.$$.fragment.c(); attr(li0, "class", "svelte-1x2w9i0"); attr(li1, "class", "svelte-1x2w9i0"); attr(li2, "class", "svelte-1x2w9i0"); attr(li3, "class", "svelte-1x2w9i0"); attr(section, "id", "debug-controls"); attr(section, "class", "controls"); }, m(target, anchor) { insert(target, section, anchor); append(section, li0); mount_component(hotkey0, li0, null); append(section, t0); append(section, li1); mount_component(hotkey1, li1, null); append(section, t1); append(section, li2); mount_component(hotkey2, li2, null); append(section, t2); append(section, li3); mount_component(hotkey3, li3, null); current = true; }, p(changed, ctx) { var hotkey0_changes = {}; if (changed.client) hotkey0_changes.onPress = ctx.client.reset; hotkey0.$set(hotkey0_changes); }, i(local) { if (current) return; transition_in(hotkey0.$$.fragment, local); transition_in(hotkey1.$$.fragment, local); transition_in(hotkey2.$$.fragment, local); transition_in(hotkey3.$$.fragment, local); current = true; }, o(local) { transition_out(hotkey0.$$.fragment, local); transition_out(hotkey1.$$.fragment, local); transition_out(hotkey2.$$.fragment, local); transition_out(hotkey3.$$.fragment, local); current = false; }, d(detaching) { if (detaching) { detach(section); } destroy_component(hotkey0); destroy_component(hotkey1); destroy_component(hotkey2); destroy_component(hotkey3); } }; } function instance$4($$self, $$props, $$invalidate) { let { client } = $$props; function Save() { const { G, ctx } = client.getState(); const json = stringify({ G, ctx }); window.localStorage.setItem('gamestate', json); } function Restore() { const gamestateJSON = window.localStorage.getItem('gamestate'); if (gamestateJSON !== null) { const gamestate = parse(gamestateJSON); client.store.dispatch(sync(gamestate)); } } $$self.$set = $$props => { if ('client' in $$props) $$invalidate('client', client = $$props.client); }; return { client, Save, Restore }; } class Controls extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1x2w9i0-style")) add_css$4(); init(this, options, instance$4, create_fragment$4, safe_not_equal, ["client"]); } } /* src/client/debug/main/PlayerInfo.svelte generated by Svelte v3.12.1 */ function add_css$5() { var style = element("style"); style.id = 'svelte-6sf87x-style'; style.textContent = ".player-box.svelte-6sf87x{display:flex;flex-direction:row}.player.svelte-6sf87x{cursor:pointer;text-align:center;width:30px;height:30px;line-height:30px;background:#eee;border:3px solid #fefefe;box-sizing:content-box}.player.current.svelte-6sf87x{background:#555;color:#eee;font-weight:bold}.player.active.svelte-6sf87x{border:3px solid #ff7f50}"; append(document.head, style); } function get_each_context$1(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.player = list[i]; return child_ctx; } // (49:2) {#each players as player} function create_each_block$1(ctx) { var div, t0_value = ctx.player + "", t0, t1, dispose; function click_handler() { return ctx.click_handler(ctx); } return { c() { div = element("div"); t0 = text(t0_value); t1 = space(); attr(div, "class", "player svelte-6sf87x"); toggle_class(div, "current", ctx.player == ctx.ctx.currentPlayer); toggle_class(div, "active", ctx.player == ctx.playerID); dispose = listen(div, "click", click_handler); }, m(target, anchor) { insert(target, div, anchor); append(div, t0); append(div, t1); }, p(changed, new_ctx) { ctx = new_ctx; if ((changed.players) && t0_value !== (t0_value = ctx.player + "")) { set_data(t0, t0_value); } if ((changed.players || changed.ctx)) { toggle_class(div, "current", ctx.player == ctx.ctx.currentPlayer); } if ((changed.players || changed.playerID)) { toggle_class(div, "active", ctx.player == ctx.playerID); } }, d(detaching) { if (detaching) { detach(div); } dispose(); } }; } function create_fragment$5(ctx) { var div; let each_value = ctx.players; 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)); } 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-6sf87x"); }, m(target, anchor) { insert(target, div, anchor); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(div, null); } }, p(changed, ctx) { if (changed.players || changed.ctx || changed.playerID) { each_value = ctx.players; 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(changed, child_ctx); } else { each_blocks[i] = create_each_block$1(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$5($$self, $$props, $$invalidate) { let { ctx, playerID } = $$props; const dispatch = createEventDispatcher(); function OnClick(player) { if (player == playerID) { dispatch("change", { playerID: null }); } else { dispatch("change", { playerID: player }); } } let players; const click_handler = ({ player }) => OnClick(player); $$self.$set = $$props => { if ('ctx' in $$props) $$invalidate('ctx', ctx = $$props.ctx); if ('playerID' in $$props) $$invalidate('playerID', playerID = $$props.playerID); }; $$self.$$.update = ($$dirty = { ctx: 1 }) => { if ($$dirty.ctx) { $$invalidate('players', players = ctx ? [...Array(ctx.numPlayers).keys()].map(i => i.toString()) : []); } }; return { ctx, playerID, OnClick, players, click_handler }; } class PlayerInfo extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-6sf87x-style")) add_css$5(); init(this, options, instance$5, create_fragment$5, safe_not_equal, ["ctx", "playerID"]); } } /* * 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, eventNames, blacklist) { var shortcuts = {}; var events = {}; for (var name in moveNames) { events[name] = name; } for (var _name in eventNames) { events[_name] = _name; } var taken = {}; for (var i = 0; i < blacklist.length; i++) { var c = blacklist[i]; taken[c] = true; } // Try assigning the first char of each move as the shortcut. var t = taken; var canUseFirstChar = true; for (var _name2 in events) { var shortcut = _name2[0]; if (t[shortcut]) { canUseFirstChar = false; break; } t[shortcut] = true; shortcuts[_name2] = shortcut; } if (canUseFirstChar) { return shortcuts; } // If those aren't unique, use a-z. t = taken; var next = 97; shortcuts = {}; for (var _name3 in events) { var _shortcut = String.fromCharCode(next); while (t[_shortcut]) { next++; _shortcut = String.fromCharCode(next); } t[_shortcut] = true; shortcuts[_name3] = _shortcut; } return shortcuts; } /* src/client/debug/main/Main.svelte generated by Svelte v3.12.1 */ function add_css$6() { var style = element("style"); style.id = 'svelte-1vg2l2b-style'; style.textContent = ".json.svelte-1vg2l2b{font-family:monospace;color:#888}label.svelte-1vg2l2b{font-weight:bold;font-size:1.1em;display:inline}h3.svelte-1vg2l2b{text-transform:uppercase}li.svelte-1vg2l2b{list-style:none;margin:none;margin-bottom:5px}.events.svelte-1vg2l2b{display:flex;flex-direction:column}.events.svelte-1vg2l2b button.svelte-1vg2l2b{width:100px}.events.svelte-1vg2l2b button.svelte-1vg2l2b:not(:last-child){margin-bottom:10px}"; append(document.head, style); } function get_each_context$2(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.name = list[i][0]; child_ctx.fn = list[i][1]; return child_ctx; } // (85:2) {#each Object.entries(client.moves) as [name, fn]} function create_each_block$2(ctx) { var li, t, current; var move = new Move({ props: { shortcut: ctx.shortcuts[ctx.name], fn: ctx.fn, name: ctx.name } }); return { c() { li = element("li"); move.$$.fragment.c(); t = space(); attr(li, "class", "svelte-1vg2l2b"); }, m(target, anchor) { insert(target, li, anchor); mount_component(move, li, null); append(li, t); current = true; }, p(changed, ctx) { var move_changes = {}; if (changed.client) move_changes.shortcut = ctx.shortcuts[ctx.name]; if (changed.client) move_changes.fn = ctx.fn; if (changed.client) move_changes.name = ctx.name; 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); } }; } // (96:2) {#if client.events.endTurn} function create_if_block_2(ctx) { var button, dispose; return { c() { button = element("button"); button.textContent = "End Turn"; attr(button, "class", "svelte-1vg2l2b"); dispose = listen(button, "click", ctx.click_handler); }, m(target, anchor) { insert(target, button, anchor); }, d(detaching) { if (detaching) { detach(button); } dispose(); } }; } // (99:2) {#if ctx.phase && client.events.endPhase} function create_if_block_1(ctx) { var button, dispose; return { c() { button = element("button"); button.textContent = "End Phase"; attr(button, "class", "svelte-1vg2l2b"); dispose = listen(button, "click", ctx.click_handler_1); }, m(target, anchor) { insert(target, button, anchor); }, d(detaching) { if (detaching) { detach(button); } dispose(); } }; } // (102:2) {#if ctx.activePlayers && client.events.endStage} function create_if_block$2(ctx) { var button, dispose; return { c() { button = element("button"); button.textContent = "End Stage"; attr(button, "class", "svelte-1vg2l2b"); dispose = listen(button, "click", ctx.click_handler_2); }, m(target, anchor) { insert(target, button, anchor); }, d(detaching) { if (detaching) { detach(button); } dispose(); } }; } function create_fragment$6(ctx) { var section0, h30, t1, t2, section1, h31, t4, t5, section2, h32, t7, t8, section3, h33, t10, div, t11, t12, t13, section4, label0, t15, pre0, t16_value = JSON.stringify(ctx.G, null, 2) + "", t16, t17, section5, label1, t19, pre1, t20_value = JSON.stringify(SanitizeCtx(ctx.ctx), null, 2) + "", t20, current; var controls = new Controls({ props: { client: ctx.client } }); var playerinfo = new PlayerInfo({ props: { ctx: ctx.ctx, playerID: ctx.playerID } }); playerinfo.$on("change", ctx.change_handler); let each_value = Object.entries(ctx.client.moves); 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)); } const out = i => transition_out(each_blocks[i], 1, 1, () => { each_blocks[i] = null; }); var if_block0 = (ctx.client.events.endTurn) && create_if_block_2(ctx); var if_block1 = (ctx.ctx.phase && ctx.client.events.endPhase) && create_if_block_1(ctx); var if_block2 = (ctx.ctx.activePlayers && ctx.client.events.endStage) && create_if_block$2(ctx); return { c() { section0 = element("section"); h30 = element("h3"); h30.textContent = "Controls"; t1 = space(); controls.$$.fragment.c(); t2 = space(); section1 = element("section"); h31 = element("h3"); h31.textContent = "Players"; t4 = space(); playerinfo.$$.fragment.c(); t5 = space(); section2 = element("section"); h32 = element("h3"); h32.textContent = "Moves"; t7 = space(); 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(); div = element("div"); 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"); label0 = element("label"); label0.textContent = "G"; t15 = space(); pre0 = element("pre"); t16 = text(t16_value); t17 = space(); section5 = element("section"); label1 = element("label"); label1.textContent = "ctx"; t19 = space(); pre1 = element("pre"); t20 = text(t20_value); attr(h30, "class", "svelte-1vg2l2b"); attr(h31, "class", "svelte-1vg2l2b"); attr(h32, "class", "svelte-1vg2l2b"); attr(h33, "class", "svelte-1vg2l2b"); attr(div, "class", "events svelte-1vg2l2b"); attr(label0, "class", "svelte-1vg2l2b"); attr(pre0, "class", "json svelte-1vg2l2b"); attr(label1, "class", "svelte-1vg2l2b"); attr(pre1, "class", "json svelte-1vg2l2b"); }, 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); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(section2, null); } insert(target, t8, anchor); insert(target, section3, anchor); append(section3, h33); append(section3, t10); append(section3, div); if (if_block0) if_block0.m(div, null); append(div, t11); if (if_block1) if_block1.m(div, null); append(div, t12); if (if_block2) if_block2.m(div, null); insert(target, t13, anchor); insert(target, section4, anchor); append(section4, label0); append(section4, t15); append(section4, pre0); append(pre0, t16); insert(target, t17, anchor); insert(target, section5, anchor); append(section5, label1); append(section5, t19); append(section5, pre1); append(pre1, t20); current = true; }, p(changed, ctx) { var controls_changes = {}; if (changed.client) controls_changes.client = ctx.client; controls.$set(controls_changes); var playerinfo_changes = {}; if (changed.ctx) playerinfo_changes.ctx = ctx.ctx; if (changed.playerID) playerinfo_changes.playerID = ctx.playerID; playerinfo.$set(playerinfo_changes); if (changed.shortcuts || changed.client) { each_value = Object.entries(ctx.client.moves); 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(changed, child_ctx); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$2(child_ctx); each_blocks[i].c(); transition_in(each_blocks[i], 1); each_blocks[i].m(section2, null); } } group_outros(); for (i = each_value.length; i < each_blocks.length; i += 1) { out(i); } check_outros(); } if (ctx.client.events.endTurn) { if (!if_block0) { if_block0 = create_if_block_2(ctx); if_block0.c(); if_block0.m(div, t11); } } else if (if_block0) { if_block0.d(1); if_block0 = null; } if (ctx.ctx.phase && ctx.client.events.endPhase) { if (!if_block1) { if_block1 = create_if_block_1(ctx); if_block1.c(); if_block1.m(div, t12); } } else if (if_block1) { if_block1.d(1); if_block1 = null; } if (ctx.ctx.activePlayers && ctx.client.events.endStage) { if (!if_block2) { if_block2 = create_if_block$2(ctx); if_block2.c(); if_block2.m(div, null); } } else if (if_block2) { if_block2.d(1); if_block2 = null; } if ((!current || changed.G) && t16_value !== (t16_value = JSON.stringify(ctx.G, null, 2) + "")) { set_data(t16, t16_value); } if ((!current || changed.ctx) && t20_value !== (t20_value = JSON.stringify(SanitizeCtx(ctx.ctx), null, 2) + "")) { set_data(t20, t20_value); } }, 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]); } 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]); } current = false; }, d(detaching) { if (detaching) { detach(section0); } destroy_component(controls); if (detaching) { detach(t2); detach(section1); } destroy_component(playerinfo); if (detaching) { detach(t5); detach(section2); } destroy_each(each_blocks, detaching); if (detaching) { detach(t8); detach(section3); } if (if_block0) if_block0.d(); if (if_block1) if_block1.d(); if (if_block2) if_block2.d(); if (detaching) { detach(t13); detach(section4); detach(t17); detach(section5); } } }; } function SanitizeCtx(ctx) { let r = {}; for (const key in ctx) { if (!key.startsWith('_')) { r[key] = ctx[key]; } } return r; } function instance$6($$self, $$props, $$invalidate) { let { client } = $$props; const shortcuts = AssignShortcuts(client.moves, client.events, 'mlia'); let playerID = client.playerID; let ctx = {}; let G = {}; client.subscribe((state) => { if (state) { $$invalidate('G', G = state.G); $$invalidate('ctx', ctx = state.ctx); } $$invalidate('playerID', playerID = client.playerID); }); const change_handler = (e) => client.updatePlayerID(e.detail.playerID); const click_handler = () => client.events.endTurn(); const click_handler_1 = () => client.events.endPhase(); const click_handler_2 = () => client.events.endStage(); $$self.$set = $$props => { if ('client' in $$props) $$invalidate('client', client = $$props.client); }; return { client, shortcuts, playerID, ctx, G, change_handler, click_handler, click_handler_1, click_handler_2 }; } class Main extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1vg2l2b-style")) add_css$6(); init(this, options, instance$6, create_fragment$6, safe_not_equal, ["client"]); } } /* src/client/debug/info/Item.svelte generated by Svelte v3.12.1 */ function add_css$7() { var style = element("style"); style.id = 'svelte-13qih23-style'; style.textContent = ".item.svelte-13qih23{padding:10px}.item.svelte-13qih23:not(:first-child){border-top:1px dashed #aaa}.item.svelte-13qih23 div.svelte-13qih23{float:right;text-align:right}"; append(document.head, style); } function create_fragment$7(ctx) { var div1, strong, t0, t1, div0, t2_value = JSON.stringify(ctx.value) + "", t2; return { c() { div1 = element("div"); strong = element("strong"); t0 = text(ctx.name); 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(changed, ctx) { if (changed.name) { set_data(t0, ctx.name); } if ((changed.value) && t2_value !== (t2_value = JSON.stringify(ctx.value) + "")) { set_data(t2, t2_value); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div1); } } }; } function instance$7($$self, $$props, $$invalidate) { let { name, value } = $$props; $$self.$set = $$props => { if ('name' in $$props) $$invalidate('name', name = $$props.name); if ('value' in $$props) $$invalidate('value', value = $$props.value); }; return { name, value }; } class Item extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-13qih23-style")) add_css$7(); init(this, options, instance$7, create_fragment$7, safe_not_equal, ["name", "value"]); } } /* src/client/debug/info/Info.svelte generated by Svelte v3.12.1 */ function add_css$8() { var style = element("style"); style.id = 'svelte-1yzq5o8-style'; style.textContent = ".gameinfo.svelte-1yzq5o8{padding:10px}"; append(document.head, style); } // (17:2) {#if $client.isMultiplayer} function create_if_block$3(ctx) { var span, t, current; var item0 = new Item({ props: { name: "isConnected", value: ctx.$client.isConnected } }); var item1 = new Item({ props: { name: "isMultiplayer", value: ctx.$client.isMultiplayer } }); return { c() { span = element("span"); item0.$$.fragment.c(); t = space(); item1.$$.fragment.c(); }, m(target, anchor) { insert(target, span, anchor); mount_component(item0, span, null); append(span, t); mount_component(item1, span, null); current = true; }, p(changed, ctx) { var item0_changes = {}; if (changed.$client) item0_changes.value = ctx.$client.isConnected; item0.$set(item0_changes); var item1_changes = {}; if (changed.$client) item1_changes.value = ctx.$client.isMultiplayer; item1.$set(item1_changes); }, i(local) { if (current) return; transition_in(item0.$$.fragment, local); transition_in(item1.$$.fragment, local); current = true; }, o(local) { transition_out(item0.$$.fragment, local); transition_out(item1.$$.fragment, local); current = false; }, d(detaching) { if (detaching) { detach(span); } destroy_component(item0); destroy_component(item1); } }; } function create_fragment$8(ctx) { var section, t0, t1, t2, current; var item0 = new Item({ props: { name: "gameID", value: ctx.client.gameID } }); var item1 = new Item({ props: { name: "playerID", value: ctx.client.playerID } }); var item2 = new Item({ props: { name: "isActive", value: ctx.$client.isActive } }); var if_block = (ctx.$client.isMultiplayer) && create_if_block$3(ctx); return { c() { section = element("section"); item0.$$.fragment.c(); t0 = space(); item1.$$.fragment.c(); t1 = space(); item2.$$.fragment.c(); 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(changed, ctx) { var item0_changes = {}; if (changed.client) item0_changes.value = ctx.client.gameID; item0.$set(item0_changes); var item1_changes = {}; if (changed.client) item1_changes.value = ctx.client.playerID; item1.$set(item1_changes); var item2_changes = {}; if (changed.$client) item2_changes.value = ctx.$client.isActive; item2.$set(item2_changes); if (ctx.$client.isMultiplayer) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block$3(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$8($$self, $$props, $$invalidate) { let $client; let { client } = $$props; component_subscribe($$self, client, $$value => { $client = $$value; $$invalidate('$client', $client); }); $$self.$set = $$props => { if ('client' in $$props) $$invalidate('client', client = $$props.client); }; return { client, $client }; } class Info extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1yzq5o8-style")) add_css$8(); init(this, options, instance$8, create_fragment$8, safe_not_equal, ["client"]); } } /* src/client/debug/log/TurnMarker.svelte generated by Svelte v3.12.1 */ function add_css$9() { var style = element("style"); style.id = 'svelte-6eza86-style'; style.textContent = ".turn-marker.svelte-6eza86{display:flex;justify-content:center;align-items:center;grid-column:1;background:#555;color:#eee;text-align:center;font-weight:bold;border:1px solid #888}"; append(document.head, style); } function create_fragment$9(ctx) { var div, t; return { c() { div = element("div"); t = text(ctx.turn); attr(div, "class", "turn-marker svelte-6eza86"); attr(div, "style", ctx.style); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p(changed, ctx) { if (changed.turn) { set_data(t, ctx.turn); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div); } } }; } function instance$9($$self, $$props, $$invalidate) { let { turn, numEvents } = $$props; const style = `grid-row: span ${numEvents}`; $$self.$set = $$props => { if ('turn' in $$props) $$invalidate('turn', turn = $$props.turn); if ('numEvents' in $$props) $$invalidate('numEvents', numEvents = $$props.numEvents); }; return { turn, numEvents, style }; } class TurnMarker extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-6eza86-style")) add_css$9(); init(this, options, instance$9, create_fragment$9, safe_not_equal, ["turn", "numEvents"]); } } /* src/client/debug/log/PhaseMarker.svelte generated by Svelte v3.12.1 */ function add_css$a() { var style = element("style"); style.id = 'svelte-1t4xap-style'; style.textContent = ".phase-marker.svelte-1t4xap{grid-column:3;background:#555;border:1px solid #888;color:#eee;text-align:center;font-weight:bold;padding-top:10px;padding-bottom:10px;text-orientation:sideways;writing-mode:vertical-rl;line-height:30px;width:100%}"; append(document.head, style); } function create_fragment$a(ctx) { var div, t_value = ctx.phase || '' + "", t; return { c() { div = element("div"); t = text(t_value); attr(div, "class", "phase-marker svelte-1t4xap"); attr(div, "style", ctx.style); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p(changed, ctx) { if ((changed.phase) && t_value !== (t_value = ctx.phase || '' + "")) { set_data(t, t_value); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div); } } }; } function instance$a($$self, $$props, $$invalidate) { let { phase, numEvents } = $$props; const style = `grid-row: span ${numEvents}`; $$self.$set = $$props => { if ('phase' in $$props) $$invalidate('phase', phase = $$props.phase); if ('numEvents' in $$props) $$invalidate('numEvents', numEvents = $$props.numEvents); }; return { phase, numEvents, style }; } class PhaseMarker extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1t4xap-style")) add_css$a(); init(this, options, instance$a, create_fragment$a, safe_not_equal, ["phase", "numEvents"]); } } /* src/client/debug/log/CustomPayload.svelte generated by Svelte v3.12.1 */ function create_fragment$b(ctx) { var div, t; return { c() { div = element("div"); t = text(ctx.custompayload); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p: noop, i: noop, o: noop, d(detaching) { if (detaching) { detach(div); } } }; } function instance$b($$self, $$props, $$invalidate) { let { payload } = $$props; const custompayload = payload !== undefined ? JSON.stringify(payload, null, 4) : ''; $$self.$set = $$props => { if ('payload' in $$props) $$invalidate('payload', payload = $$props.payload); }; return { payload, custompayload }; } class CustomPayload extends SvelteComponent { constructor(options) { super(); init(this, options, instance$b, create_fragment$b, safe_not_equal, ["payload"]); } } /* src/client/debug/log/LogEvent.svelte generated by Svelte v3.12.1 */ function add_css$b() { var style = element("style"); style.id = 'svelte-10wdo7v-style'; style.textContent = ".log-event.svelte-10wdo7v{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:#888;font-size:14px;min-height:25px;line-height:25px}.log-event.svelte-10wdo7v:hover{border-style:solid;background:#eee}.log-event.pinned.svelte-10wdo7v{border-style:solid;background:#eee;opacity:1}.player0.svelte-10wdo7v{border-left-color:#ff851b}.player1.svelte-10wdo7v{border-left-color:#7fdbff}.player2.svelte-10wdo7v{border-left-color:#0074d9}.player3.svelte-10wdo7v{border-left-color:#39cccc}.player4.svelte-10wdo7v{border-left-color:#3d9970}.player5.svelte-10wdo7v{border-left-color:#2ecc40}.player6.svelte-10wdo7v{border-left-color:#01ff70}.player7.svelte-10wdo7v{border-left-color:#ffdc00}.player8.svelte-10wdo7v{border-left-color:#001f3f}.player9.svelte-10wdo7v{border-left-color:#ff4136}.player10.svelte-10wdo7v{border-left-color:#85144b}.player11.svelte-10wdo7v{border-left-color:#f012be}.player12.svelte-10wdo7v{border-left-color:#b10dc9}.player13.svelte-10wdo7v{border-left-color:#111111}.player14.svelte-10wdo7v{border-left-color:#aaaaaa}.player15.svelte-10wdo7v{border-left-color:#dddddd}"; append(document.head, style); } // (122:2) {:else} function create_else_block(ctx) { var current; var custompayload = new CustomPayload({ props: { payload: ctx.payload } }); return { c() { custompayload.$$.fragment.c(); }, m(target, anchor) { mount_component(custompayload, target, anchor); current = true; }, p(changed, ctx) { var custompayload_changes = {}; if (changed.payload) custompayload_changes.payload = ctx.payload; custompayload.$set(custompayload_changes); }, i(local) { if (current) return; transition_in(custompayload.$$.fragment, local); current = true; }, o(local) { transition_out(custompayload.$$.fragment, local); current = false; }, d(detaching) { destroy_component(custompayload, detaching); } }; } // (120:2) {#if payloadComponent} function create_if_block$4(ctx) { var switch_instance_anchor, current; var switch_value = ctx.payloadComponent; function switch_props(ctx) { return { props: { payload: ctx.payload } }; } if (switch_value) { var switch_instance = new switch_value(switch_props(ctx)); } return { c() { if (switch_instance) switch_instance.$$.fragment.c(); 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(changed, ctx) { var switch_instance_changes = {}; if (changed.payload) switch_instance_changes.payload = ctx.payload; if (switch_value !== (switch_value = ctx.payloadComponent)) { 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)); switch_instance.$$.fragment.c(); 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$c(ctx) { var div1, div0, t0_value = ctx.action.payload.type + "", t0, t1, t2_value = ctx.args.join(',') + "", t2, t3, t4, current_block_type_index, if_block, current, dispose; var if_block_creators = [ create_if_block$4, create_else_block ]; var if_blocks = []; function select_block_type(changed, ctx) { if (ctx.payloadComponent) return 0; return 1; } current_block_type_index = select_block_type(null, ctx); if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); return { c() { div1 = element("div"); div0 = element("div"); t0 = text(t0_value); t1 = text("("); t2 = text(t2_value); t3 = text(")"); t4 = space(); if_block.c(); attr(div1, "class", "log-event player" + ctx.playerID + " svelte-10wdo7v"); toggle_class(div1, "pinned", ctx.pinned); dispose = [ listen(div1, "click", ctx.click_handler), listen(div1, "mouseenter", ctx.mouseenter_handler), listen(div1, "mouseleave", ctx.mouseleave_handler) ]; }, m(target, anchor) { insert(target, div1, anchor); append(div1, div0); append(div0, t0); append(div0, t1); append(div0, t2); append(div0, t3); append(div1, t4); if_blocks[current_block_type_index].m(div1, null); current = true; }, p(changed, ctx) { if ((!current || changed.action) && t0_value !== (t0_value = ctx.action.payload.type + "")) { set_data(t0, t0_value); } var previous_block_index = current_block_type_index; current_block_type_index = select_block_type(changed, ctx); if (current_block_type_index === previous_block_index) { if_blocks[current_block_type_index].p(changed, ctx); } else { group_outros(); transition_out(if_blocks[previous_block_index], 1, 1, () => { if_blocks[previous_block_index] = null; }); check_outros(); if_block = if_blocks[current_block_type_index]; if (!if_block) { if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); if_block.c(); } transition_in(if_block, 1); if_block.m(div1, null); } if (changed.pinned) { toggle_class(div1, "pinned", ctx.pinned); } }, i(local) { if (current) return; transition_in(if_block); current = true; }, o(local) { transition_out(if_block); current = false; }, d(detaching) { if (detaching) { detach(div1); } if_blocks[current_block_type_index].d(); run_all(dispose); } }; } function instance$c($$self, $$props, $$invalidate) { let { logIndex, action, pinned, payload, payloadComponent } = $$props; const dispatch = createEventDispatcher(); const args = action.payload.args || []; const playerID = action.payload.playerID; const click_handler = () => dispatch('click', { logIndex }); const mouseenter_handler = () => dispatch('mouseenter', { logIndex }); const mouseleave_handler = () => dispatch('mouseleave'); $$self.$set = $$props => { if ('logIndex' in $$props) $$invalidate('logIndex', logIndex = $$props.logIndex); if ('action' in $$props) $$invalidate('action', action = $$props.action); if ('pinned' in $$props) $$invalidate('pinned', pinned = $$props.pinned); if ('payload' in $$props) $$invalidate('payload', payload = $$props.payload); if ('payloadComponent' in $$props) $$invalidate('payloadComponent', payloadComponent = $$props.payloadComponent); }; return { logIndex, action, pinned, payload, payloadComponent, dispatch, args, playerID, click_handler, mouseenter_handler, mouseleave_handler }; } class LogEvent extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-10wdo7v-style")) add_css$b(); init(this, options, instance$c, create_fragment$c, safe_not_equal, ["logIndex", "action", "pinned", "payload", "payloadComponent"]); } } /* node_modules/svelte-icons/components/IconBase.svelte generated by Svelte v3.12.1 */ function add_css$c() { var style = element("style"); style.id = 'svelte-c8tyih-style'; style.textContent = "svg.svelte-c8tyih{stroke:currentColor;fill:currentColor;stroke-width:0;width:100%;height:auto;max-height:100%}"; append(document.head, style); } // (18:2) {#if title} function create_if_block$5(ctx) { var title_1, t; return { c() { title_1 = svg_element("title"); t = text(ctx.title); }, m(target, anchor) { insert(target, title_1, anchor); append(title_1, t); }, p(changed, ctx) { if (changed.title) { set_data(t, ctx.title); } }, d(detaching) { if (detaching) { detach(title_1); } } }; } function create_fragment$d(ctx) { var svg, if_block_anchor, current; var if_block = (ctx.title) && create_if_block$5(ctx); const default_slot_template = ctx.$$slots.default; const default_slot = create_slot(default_slot_template, ctx, 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", ctx.viewBox); attr(svg, "class", "svelte-c8tyih"); }, l(nodes) { if (default_slot) default_slot.l(svg_nodes); }, 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(changed, ctx) { if (ctx.title) { if (if_block) { if_block.p(changed, ctx); } else { if_block = create_if_block$5(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 && default_slot.p && changed.$$scope) { default_slot.p( get_slot_changes(default_slot_template, ctx, changed, null), get_slot_context(default_slot_template, ctx, null) ); } if (!current || changed.viewBox) { attr(svg, "viewBox", ctx.viewBox); } }, 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$d($$self, $$props, $$invalidate) { let { title = null, viewBox } = $$props; let { $$slots = {}, $$scope } = $$props; $$self.$set = $$props => { if ('title' in $$props) $$invalidate('title', title = $$props.title); if ('viewBox' in $$props) $$invalidate('viewBox', viewBox = $$props.viewBox); if ('$$scope' in $$props) $$invalidate('$$scope', $$scope = $$props.$$scope); }; return { title, viewBox, $$slots, $$scope }; } class IconBase extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-c8tyih-style")) add_css$c(); init(this, options, instance$d, create_fragment$d, safe_not_equal, ["title", "viewBox"]); } } /* node_modules/svelte-icons/fa/FaArrowAltCircleDown.svelte generated by Svelte v3.12.1 */ // (4:8) <IconBase viewBox="0 0 512 512" {...$$props}> function create_default_slot(ctx) { var 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$e(ctx) { var current; var iconbase_spread_levels = [ { viewBox: "0 0 512 512" }, ctx.$$props ]; let iconbase_props = { $$slots: { default: [create_default_slot] }, $$scope: { ctx } }; for (var i = 0; i < iconbase_spread_levels.length; i += 1) { iconbase_props = assign(iconbase_props, iconbase_spread_levels[i]); } var iconbase = new IconBase({ props: iconbase_props }); return { c() { iconbase.$$.fragment.c(); }, m(target, anchor) { mount_component(iconbase, target, anchor); current = true; }, p(changed, ctx) { var iconbase_changes = (changed.$$props) ? get_spread_update(iconbase_spread_levels, [ iconbase_spread_levels[0], get_spread_object(ctx.$$props) ]) : {}; if (changed.$$scope) iconbase_changes.$$scope = { changed, 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$e($$self, $$props, $$invalidate) { $$self.$set = $$new_props => { $$invalidate('$$props', $$props = assign(assign({}, $$props), $$new_props)); }; return { $$props, $$props: $$props = exclude_internal_props($$props) }; } class FaArrowAltCircleDown extends SvelteComponent { constructor(options) { super(); init(this, options, instance$e, create_fragment$e, safe_not_equal, []); } } /* src/client/debug/mcts/Action.svelte generated by Svelte v3.12.1 */ function add_css$d() { var style = element("style"); style.id = 'svelte-1a7time-style'; style.textContent = "div.svelte-1a7time{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;max-width:500px}"; append(document.head, style); } function create_fragment$f(ctx) { var div, t; return { c() { div = element("div"); t = text(ctx.text); attr(div, "alt", ctx.text); attr(div, "class", "svelte-1a7time"); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p(changed, ctx) { if (changed.text) { set_data(t, ctx.text); attr(div, "alt", ctx.text); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div); } } }; } function instance$f($$self, $$props, $$invalidate) { let { action } = $$props; let text; $$self.$set = $$props => { if ('action' in $$props) $$invalidate('action', action = $$props.action); }; $$self.$$.update = ($$dirty = { action: 1 }) => { if ($$dirty.action) { { const { type, args } = action.payload; const argsFormatted = (args || []).join(','); $$invalidate('text', text = `${type}(${argsFormatted})`); } } }; return { action, text }; } class Action extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1a7time-style")) add_css$d(); init(this, options, instance$f, create_fragment$f, safe_not_equal, ["action"]); } } /* src/client/debug/mcts/Table.svelte generated by Svelte v3.12.1 */ function add_css$e() { var style = element("style"); style.id = 'svelte-ztcwsu-style'; style.textContent = "table.svelte-ztcwsu{font-size:12px;border-collapse:collapse;border:1px solid #ddd;padding:0}tr.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{padding:10px;height:10px;line-height:10px;font-size:12px;border:none}th.svelte-ztcwsu{background:#888;color:#fff;padding:10px;text-align:center}"; append(document.head, style); } function get_each_context$3(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.child = list[i]; child_ctx.i = i; return child_ctx; } // (86:2) {#each children as child, i} function create_each_block$3(ctx) { var tr, td0, t0_value = ctx.child.value + "", t0, t1, td1, t2_value = ctx.child.visits + "", t2, t3, td2, t4, current, dispose; var action = new Action({ props: { action: ctx.child.parentAction } }); function click_handler() { return ctx.click_handler(ctx); } function mouseout_handler() { return ctx.mouseout_handler(ctx); } function mouseover_handler() { return ctx.mouseover_handler(ctx); } 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"); action.$$.fragment.c(); 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", ctx.children.length > 0); toggle_class(tr, "selected", ctx.i === ctx.selectedIndex); dispose = [ listen(tr, "click", click_handler), listen(tr, "mouseout", mouseout_handler), listen(tr, "mouseover", mouseover_handler) ]; }, 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; }, p(changed, new_ctx) { ctx = new_ctx; if ((!current || changed.children) && t0_value !== (t0_value = ctx.child.value + "")) { set_data(t0, t0_value); } if ((!current || changed.children) && t2_value !== (t2_value = ctx.child.visits + "")) { set_data(t2, t2_value); } var action_changes = {}; if (changed.children) action_changes.action = ctx.child.parentAction; action.$set(action_changes); if (changed.children) { toggle_class(tr, "clickable", ctx.children.length > 0); } if (changed.selectedIndex) { toggle_class(tr, "selected", ctx.i === ctx.selectedIndex); } }, 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); run_all(dispose); } }; } function create_fragment$g(ctx) { var table, thead, t_5, tbody, current; let each_value = ctx.children; 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)); } 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>`; t_5 = 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, t_5); append(table, tbody); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(tbody, null); } current = true; }, p(changed, ctx) { if (changed.children || changed.selectedIndex) { each_value = ctx.children; 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(changed, child_ctx); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$3(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$g($$self, $$props, $$invalidate) { let { root, 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('root', root = $$props.root); if ('selectedIndex' in $$props) $$invalidate('selectedIndex', selectedIndex = $$props.selectedIndex); }; $$self.$$.update = ($$dirty = { root: 1, parents: 1 }) => { if ($$dirty.root || $$dirty.parents) { { let t = root; $$invalidate('parents', 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('children', children = [...root.children] .sort((a, b) => (a.visits < b.visits ? 1 : -1)) .slice(0, 50)); } } }; return { root, selectedIndex, children, Select, Preview, click_handler, mouseout_handler, mouseover_handler }; } class Table extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-ztcwsu-style")) add_css$e(); init(this, options, instance$g, create_fragment$g, safe_not_equal, ["root", "selectedIndex"]); } } /* src/client/debug/mcts/MCTS.svelte generated by Svelte v3.12.1 */ function add_css$f() { var style = element("style"); style.id = 'svelte-1f0amz4-style'; style.textContent = ".visualizer.svelte-1f0amz4{display:flex;flex-direction:column;align-items:center;padding:50px}.preview.svelte-1f0amz4{opacity:0.5}.icon.svelte-1f0amz4{color:#777;width:32px;height:32px;margin-bottom:20px}"; append(document.head, style); } function get_each_context$4(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.node = list[i].node; child_ctx.selectedIndex = list[i].selectedIndex; child_ctx.i = i; return child_ctx; } // (50:4) {#if i !== 0} function create_if_block_2$1(ctx) { var div, current; var arrow = new FaArrowAltCircleDown({}); return { c() { div = element("div"); arrow.$$.fragment.c(); 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$1(ctx) { var current; function select_handler_1(...args) { return ctx.select_handler_1(ctx, ...args); } var table = new Table({ props: { root: ctx.node, selectedIndex: ctx.selectedIndex } }); table.$on("select", select_handler_1); return { c() { table.$$.fragment.c(); }, m(target, anchor) { mount_component(table, target, anchor); current = true; }, p(changed, new_ctx) { ctx = new_ctx; var table_changes = {}; if (changed.nodes) table_changes.root = ctx.node; if (changed.nodes) table_changes.selectedIndex = ctx.selectedIndex; 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$1(ctx) { var current; function select_handler(...args) { return ctx.select_handler(ctx, ...args); } function preview_handler(...args) { return ctx.preview_handler(ctx, ...args); } var table = new Table({ props: { root: ctx.node } }); table.$on("select", select_handler); table.$on("preview", preview_handler); return { c() { table.$$.fragment.c(); }, m(target, anchor) { mount_component(table, target, anchor); current = true; }, p(changed, new_ctx) { ctx = new_ctx; var table_changes = {}; if (changed.nodes) table_changes.root = ctx.node; 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$4(ctx) { var t, section, current_block_type_index, if_block1, current; var if_block0 = (ctx.i !== 0) && create_if_block_2$1(); var if_block_creators = [ create_if_block_1$1, create_else_block$1 ]; var if_blocks = []; function select_block_type(changed, ctx) { if (ctx.i === ctx.nodes.length - 1) return 0; return 1; } current_block_type_index = select_block_type(null, 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(changed, ctx) { var previous_block_index = current_block_type_index; current_block_type_index = select_block_type(changed, ctx); if (current_block_type_index === previous_block_index) { if_blocks[current_block_type_index].p(changed, ctx); } else { group_outros(); transition_out(if_blocks[previous_block_index], 1, 1, () => { if_blocks[previous_block_index] = null; }); check_outros(); if_block1 = if_blocks[current_block_type_index]; if (!if_block1) { if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); if_block1.c(); } transition_in(if_block1, 1); if_block1.m(section, null); } }, i(local) { if (current) return; transition_in(if_block0); transition_in(if_block1); current = true; }, o(local) { transition_out(if_block0); transition_out(if_block1); current = false; }, d(detaching) { if (if_block0) if_block0.d(detaching); if (detaching) { detach(t); detach(section); } if_blocks[current_block_type_index].d(); } }; } // (69:2) {#if preview} function create_if_block$6(ctx) { var div, t, section, current; var arrow = new FaArrowAltCircleDown({}); var table = new Table({ props: { root: ctx.preview } }); return { c() { div = element("div"); arrow.$$.fragment.c(); t = space(); section = element("section"); table.$$.fragment.c(); 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(changed, ctx) { var table_changes = {}; if (changed.preview) table_changes.root = ctx.preview; 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); detach(section); } destroy_component(table); } }; } function create_fragment$h(ctx) { var div, t, current; let each_value = ctx.nodes; 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)); } const out = i => transition_out(each_blocks[i], 1, 1, () => { each_blocks[i] = null; }); var if_block = (ctx.preview) && create_if_block$6(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(changed, ctx) { if (changed.nodes) { each_value = ctx.nodes; 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(changed, child_ctx); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$4(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 (ctx.preview) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block$6(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$h($$self, $$props, $$invalidate) { let { metadata } = $$props; let nodes = []; let preview = null; function SelectNode({ node, selectedIndex }, i) { $$invalidate('preview', preview = null); $$invalidate('nodes', nodes[i].selectedIndex = selectedIndex, nodes); $$invalidate('nodes', nodes = [...nodes.slice(0, i + 1), { node }]); } function PreviewNode({ node }, i) { $$invalidate('preview', 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('metadata', metadata = $$props.metadata); }; $$self.$$.update = ($$dirty = { metadata: 1 }) => { if ($$dirty.metadata) { { $$invalidate('nodes', nodes = [{ node: metadata }]); } } }; return { metadata, nodes, preview, SelectNode, PreviewNode, select_handler, preview_handler, select_handler_1 }; } class MCTS extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1f0amz4-style")) add_css$f(); init(this, options, instance$h, create_fragment$h, safe_not_equal, ["metadata"]); } } /* src/client/debug/log/Log.svelte generated by Svelte v3.12.1 */ function add_css$g() { var style = element("style"); style.id = 'svelte-1pq5e4b-style'; style.textContent = ".gamelog.svelte-1pq5e4b{display:grid;grid-template-columns:30px 1fr 30px;grid-auto-rows:auto;grid-auto-flow:column}"; append(document.head, style); } function get_each_context$5(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.phase = list[i].phase; child_ctx.i = i; return child_ctx; } function get_each_context_1(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.action = list[i].action; child_ctx.payload = list[i].payload; child_ctx.i = i; return child_ctx; } function get_each_context_2(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.turn = list[i].turn; child_ctx.i = i; return child_ctx; } // (137:4) {#if i in turnBoundaries} function create_if_block_1$2(ctx) { var current; var turnmarker = new TurnMarker({ props: { turn: ctx.turn, numEvents: ctx.turnBoundaries[ctx.i] } }); return { c() { turnmarker.$$.fragment.c(); }, m(target, anchor) { mount_component(turnmarker, target, anchor); current = true; }, p(changed, ctx) { var turnmarker_changes = {}; if (changed.renderedLogEntries) turnmarker_changes.turn = ctx.turn; if (changed.turnBoundaries) turnmarker_changes.numEvents = ctx.turnBoundaries[ctx.i]; 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); } }; } // (136:2) {#each renderedLogEntries as { turn } function create_each_block_2(ctx) { var if_block_anchor, current; var if_block = (ctx.i in ctx.turnBoundaries) && create_if_block_1$2(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(changed, ctx) { if (ctx.i in ctx.turnBoundaries) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block_1$2(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); } } }; } // (142:2) {#each renderedLogEntries as { action, payload } function create_each_block_1(ctx) { var current; var logevent = new LogEvent({ props: { pinned: ctx.i === ctx.pinned, logIndex: ctx.i, action: ctx.action, payload: ctx.payload } }); logevent.$on("click", ctx.OnLogClick); logevent.$on("mouseenter", ctx.OnMouseEnter); logevent.$on("mouseleave", ctx.OnMouseLeave); return { c() { logevent.$$.fragment.c(); }, m(target, anchor) { mount_component(logevent, target, anchor); current = true; }, p(changed, ctx) { var logevent_changes = {}; if (changed.pinned) logevent_changes.pinned = ctx.i === ctx.pinned; if (changed.renderedLogEntries) logevent_changes.action = ctx.action; if (changed.renderedLogEntries) logevent_changes.payload = ctx.payload; 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); } }; } // (154:4) {#if i in phaseBoundaries} function create_if_block$7(ctx) { var current; var phasemarker = new PhaseMarker({ props: { phase: ctx.phase, numEvents: ctx.phaseBoundaries[ctx.i] } }); return { c() { phasemarker.$$.fragment.c(); }, m(target, anchor) { mount_component(phasemarker, target, anchor); current = true; }, p(changed, ctx) { var phasemarker_changes = {}; if (changed.renderedLogEntries) phasemarker_changes.phase = ctx.phase; if (changed.phaseBoundaries) phasemarker_changes.numEvents = ctx.phaseBoundaries[ctx.i]; 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); } }; } // (153:2) {#each renderedLogEntries as { phase } function create_each_block$5(ctx) { var if_block_anchor, current; var if_block = (ctx.i in ctx.phaseBoundaries) && create_if_block$7(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(changed, ctx) { if (ctx.i in ctx.phaseBoundaries) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block$7(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$i(ctx) { var div, t0, t1, current, dispose; let each_value_2 = ctx.renderedLogEntries; 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 = ctx.renderedLogEntries; 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 = ctx.renderedLogEntries; 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_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", ctx.pinned); dispose = listen(window, "keydown", ctx.OnKeyDown); }, 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; }, p(changed, ctx) { if (changed.turnBoundaries || changed.renderedLogEntries) { each_value_2 = ctx.renderedLogEntries; 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(changed, child_ctx); 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 (changed.pinned || changed.renderedLogEntries) { each_value_1 = ctx.renderedLogEntries; 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(changed, child_ctx); 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 (changed.phaseBoundaries || changed.renderedLogEntries) { each_value = ctx.renderedLogEntries; 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(changed, child_ctx); 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(div, null); } } group_outros(); for (i = each_value.length; i < each_blocks.length; i += 1) { out_2(i); } check_outros(); } if (changed.pinned) { toggle_class(div, "pinned", ctx.pinned); } }, 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); dispose(); } }; } function instance$i($$self, $$props, $$invalidate) { let $client; let { client } = $$props; component_subscribe($$self, client, $$value => { $client = $$value; $$invalidate('$client', $client); }); const { secondaryPane } = getContext('secondaryPane'); 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 = client.reducer(state, action); } if (action.type == MAKE_MOVE) { if (logIndex == 0) { break; } logIndex--; } } return { G: state.G, ctx: state.ctx }; } function OnLogClick(e) { const { logIndex } = e.detail; const state = rewind(logIndex); const renderedLogEntries = log.filter(e => e.action.type == MAKE_MOVE); client.overrideGameState(state); if (pinned == logIndex) { $$invalidate('pinned', pinned = null); secondaryPane.set(null); } else { $$invalidate('pinned', 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('pinned', 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) $$invalidate('client', client = $$props.client); }; $$self.$$.update = ($$dirty = { $client: 1, log: 1, renderedLogEntries: 1 }) => { if ($$dirty.$client || $$dirty.log || $$dirty.renderedLogEntries) { { $$invalidate('log', log = $client.log); $$invalidate('renderedLogEntries', renderedLogEntries = log.filter(e => e.action.type == MAKE_MOVE)); let eventsInCurrentPhase = 0; let eventsInCurrentTurn = 0; $$invalidate('turnBoundaries', turnBoundaries = {}); $$invalidate('phaseBoundaries', 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('turnBoundaries', turnBoundaries[i] = eventsInCurrentTurn, turnBoundaries); eventsInCurrentTurn = 0; } if ( i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].phase != phase ) { $$invalidate('phaseBoundaries', phaseBoundaries[i] = eventsInCurrentPhase, phaseBoundaries); eventsInCurrentPhase = 0; } } } } }; return { client, pinned, OnLogClick, OnMouseEnter, OnMouseLeave, OnKeyDown, renderedLogEntries, turnBoundaries, phaseBoundaries }; } class Log extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1pq5e4b-style")) add_css$g(); init(this, options, instance$i, create_fragment$i, safe_not_equal, ["client"]); } } /* src/client/debug/ai/Options.svelte generated by Svelte v3.12.1 */ const { Object: Object_1 } = globals; function add_css$h() { var style = element("style"); style.id = 'svelte-7cel4i-style'; style.textContent = "label.svelte-7cel4i{font-weight:bold;color:#999}.option.svelte-7cel4i{margin-bottom:20px}.value.svelte-7cel4i{font-weight:bold}input[type='checkbox'].svelte-7cel4i{vertical-align:middle}"; append(document.head, style); } function get_each_context$6(ctx, list, i) { const child_ctx = Object_1.create(ctx); child_ctx.key = list[i][0]; child_ctx.value = list[i][1]; return child_ctx; } // (39:4) {#if value.range} function create_if_block_1$3(ctx) { var span, t0_value = ctx.values[ctx.key] + "", t0, t1, input, input_min_value, input_max_value, dispose; function input_change_input_handler() { ctx.input_change_input_handler.call(input, ctx); } return { c() { span = element("span"); t0 = text(t0_value); t1 = space(); input = element("input"); attr(span, "class", "value svelte-7cel4i"); attr(input, "type", "range"); attr(input, "min", input_min_value = ctx.value.range.min); attr(input, "max", input_max_value = ctx.value.range.max); dispose = [ listen(input, "change", input_change_input_handler), listen(input, "input", input_change_input_handler), listen(input, "change", ctx.OnChange) ]; }, m(target, anchor) { insert(target, span, anchor); append(span, t0); insert(target, t1, anchor); insert(target, input, anchor); set_input_value(input, ctx.values[ctx.key]); }, p(changed, new_ctx) { ctx = new_ctx; if ((changed.values || changed.bot) && t0_value !== (t0_value = ctx.values[ctx.key] + "")) { set_data(t0, t0_value); } if ((changed.values || changed.Object || changed.bot)) set_input_value(input, ctx.values[ctx.key]); if ((changed.bot) && input_min_value !== (input_min_value = ctx.value.range.min)) { attr(input, "min", input_min_value); } if ((changed.bot) && input_max_value !== (input_max_value = ctx.value.range.max)) { attr(input, "max", input_max_value); } }, d(detaching) { if (detaching) { detach(span); detach(t1); detach(input); } run_all(dispose); } }; } // (44:4) {#if typeof value.value === 'boolean'} function create_if_block$8(ctx) { var input, dispose; function input_change_handler() { ctx.input_change_handler.call(input, ctx); } return { c() { input = element("input"); attr(input, "type", "checkbox"); attr(input, "class", "svelte-7cel4i"); dispose = [ listen(input, "change", input_change_handler), listen(input, "change", ctx.OnChange) ]; }, m(target, anchor) { insert(target, input, anchor); input.checked = ctx.values[ctx.key]; }, p(changed, new_ctx) { ctx = new_ctx; if ((changed.values || changed.Object || changed.bot)) input.checked = ctx.values[ctx.key]; }, d(detaching) { if (detaching) { detach(input); } run_all(dispose); } }; } // (35:0) {#each Object.entries(bot.opts()) as [key, value]} function create_each_block$6(ctx) { var div, label, t0_value = ctx.key + "", t0, t1, t2, t3; var if_block0 = (ctx.value.range) && create_if_block_1$3(ctx); var if_block1 = (typeof ctx.value.value === 'boolean') && create_if_block$8(ctx); return { c() { div = element("div"); label = element("label"); t0 = text(t0_value); t1 = space(); if (if_block0) if_block0.c(); t2 = space(); if (if_block1) if_block1.c(); t3 = space(); attr(label, "class", "svelte-7cel4i"); attr(div, "class", "option svelte-7cel4i"); }, m(target, anchor) { insert(target, div, anchor); append(div, label); append(label, t0); append(div, t1); if (if_block0) if_block0.m(div, null); append(div, t2); if (if_block1) if_block1.m(div, null); append(div, t3); }, p(changed, ctx) { if ((changed.bot) && t0_value !== (t0_value = ctx.key + "")) { set_data(t0, t0_value); } if (ctx.value.range) { if (if_block0) { if_block0.p(changed, ctx); } else { if_block0 = create_if_block_1$3(ctx); if_block0.c(); if_block0.m(div, t2); } } else if (if_block0) { if_block0.d(1); if_block0 = null; } if (typeof ctx.value.value === 'boolean') { if (if_block1) { if_block1.p(changed, ctx); } else { if_block1 = create_if_block$8(ctx); if_block1.c(); if_block1.m(div, t3); } } else if (if_block1) { if_block1.d(1); if_block1 = null; } }, d(detaching) { if (detaching) { detach(div); } if (if_block0) if_block0.d(); if (if_block1) if_block1.d(); } }; } function create_fragment$j(ctx) { var each_1_anchor; let each_value = ctx.Object.entries(ctx.bot.opts()); 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)); } 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(changed, ctx) { if (changed.Object || changed.bot || changed.values) { each_value = ctx.Object.entries(ctx.bot.opts()); 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(changed, child_ctx); } else { each_blocks[i] = create_each_block$6(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$j($$self, $$props, $$invalidate) { let { bot } = $$props; let values = {}; for (let [key, value] of Object.entries(bot.opts())) { $$invalidate('values', values[key] = value.value, values); } function OnChange() { for (let [key, value] of Object.entries(values)) { bot.setOpt(key, value); } } function input_change_input_handler({ key }) { values[key] = to_number(this.value); $$invalidate('values', values); $$invalidate('Object', Object); $$invalidate('bot', bot); } function input_change_handler({ key }) { values[key] = this.checked; $$invalidate('values', values); $$invalidate('Object', Object); $$invalidate('bot', bot); } $$self.$set = $$props => { if ('bot' in $$props) $$invalidate('bot', bot = $$props.bot); }; return { bot, values, OnChange, Object, input_change_input_handler, input_change_handler }; } class Options extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-7cel4i-style")) add_css$h(); init(this, options, instance$j, create_fragment$j, safe_not_equal, ["bot"]); } } /* * 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. */ /** * 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; }; /** * 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'; /** * CreateGameReducer * * Creates the main game state reducer. */ function CreateGameReducer({ game, isClient, }) { game = ProcessGameConfig(game); /** * GameReducer * * Redux reducer that maintains the overall game state. * @param {object} state - The state before the action. * @param {object} action - A Redux action. */ return (state = null, action) => { switch (action.type) { case GAME_EVENT: { state = { ...state, deltalog: [] }; // Process game events only on the server. // These events like `endTurn` typically // contain code that may rely on secret state // and cannot be computed on the client. if (isClient) { return state; } // Disallow events once the game is over. if (state.ctx.gameover !== undefined) { error(`cannot call event after game end`); return state; } // Ignore the event if the player isn't active. if (action.payload.playerID !== null && action.payload.playerID !== undefined && !game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) { error(`disallowed event: ${action.payload.type}`); return state; } // Execute plugins. state = Enhance(state, { game, isClient: false, playerID: action.payload.playerID, }); // Process event. let newState = game.flow.processEvent(state, action); // Execute plugins. newState = Flush(newState, { game, isClient: false }); return { ...newState, _stateID: state._stateID + 1 }; } case MAKE_MOVE: { state = { ...state, deltalog: [] }; // Check whether the move is allowed at this time. const move = game.flow.getMove(state.ctx, action.payload.type, action.payload.playerID || state.ctx.currentPlayer); if (move === null) { error(`disallowed move: ${action.payload.type}`); return state; } // Don't run move on client if move says so. if (isClient && move.client === false) { return state; } // Disallow moves once the game is over. if (state.ctx.gameover !== undefined) { error(`cannot make move after game end`); return state; } // Ignore the move if the player isn't active. if (action.payload.playerID !== null && action.payload.playerID !== undefined && !game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) { error(`disallowed move: ${action.payload.type}`); return state; } // Execute plugins. state = Enhance(state, { game, isClient, playerID: action.payload.playerID, }); // Process the move. let G = game.processMove(state, action.payload); // The game declared the move as invalid. if (G === INVALID_MOVE) { error(`invalid move: ${action.payload.type} args: ${action.payload.args}`); return state; } // Create a log entry for this move. let logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (move.redact === true) { logEntry.redact = true; } const newState = { ...state, G, deltalog: [logEntry], _stateID: state._stateID + 1, }; // Some plugin indicated that it is not suitable to be // materialized on the client (and must wait for the server // response instead). if (isClient && NoClient(newState, { game })) { return state; } state = newState; // If we're on the client, just process the move // and no triggers in multiplayer mode. // These will be processed on the server, which // will send back a state update. if (isClient) { state = Flush(state, { game, isClient: true, }); return state; } // Allow the flow reducer to process any triggers that happen after moves. state = game.flow.processMove(state, action.payload); state = Flush(state, { game }); return state; } case RESET: case UPDATE: case SYNC: { return action.state; } case UNDO: { const { _undo, _redo } = state; if (_undo.length < 2) { return state; } const last = _undo[_undo.length - 1]; const restore = _undo[_undo.length - 2]; // Only allow undoable moves to be undone. const lastMove = game.flow.getMove(state.ctx, last.moveType, state.ctx.currentPlayer); if (!CanUndoMove(state.G, state.ctx, lastMove)) { return state; } return { ...state, G: restore.G, ctx: restore.ctx, _undo: _undo.slice(0, _undo.length - 1), _redo: [last, ..._redo], }; } case REDO: { const { _undo, _redo } = state; if (_redo.length == 0) { return state; } const first = _redo[0]; return { ...state, G: first.G, ctx: first.ctx, _undo: [..._undo, first], _redo: _redo.slice(1), }; } case PLUGIN: { return ProcessAction(state, action, { game }); } default: { return state; } } }; } /** * Base class that bots can extend. */ var Bot = /*#__PURE__*/ function () { function Bot(_ref) { var _this = this; var enumerate = _ref.enumerate, seed = _ref.seed; _classCallCheck(this, Bot); _defineProperty(this, "enumerate", function (G, ctx, playerID) { var actions = _this.enumerateFn(G, ctx, playerID); return actions.map(function (a) { if (a.payload !== undefined) { return a; } if (a.move !== undefined) { return makeMove(a.move, a.args, playerID); } if (a.event !== undefined) { return gameEvent(a.event, a.args, playerID); } }); }); this.enumerateFn = enumerate; this.seed = seed; this.iterationCounter = 0; this._opts = {}; } _createClass(Bot, [{ key: "addOpt", value: function addOpt(_ref2) { var key = _ref2.key, range = _ref2.range, initial = _ref2.initial; this._opts[key] = { range: range, value: initial }; } }, { key: "getOpt", value: function getOpt(key) { return this._opts[key].value; } }, { key: "setOpt", value: function setOpt(key, value) { if (key in this._opts) { this._opts[key].value = value; } } }, { key: "opts", value: function opts() { return this._opts; } }, { key: "random", value: function random(arg) { var number; if (this.seed !== undefined) { var r = null; if (this.prngstate) { r = new alea('', { state: this.prngstate }); } else { r = new alea(this.seed, { state: true }); } number = r(); this.prngstate = r.state(); } else { number = Math.random(); } if (arg) { // eslint-disable-next-line unicorn/explicit-length-check if (arg.length) { var id = Math.floor(number * arg.length); return arg[id]; } else { return Math.floor(number * arg); } } return number; } }]); return Bot; }(); /** * The number of iterations to run before yielding to * the JS event loop (in async mode). */ var CHUNK_SIZE = 25; /** * Bot that uses Monte-Carlo Tree Search to find promising moves. */ var MCTSBot = /*#__PURE__*/ function (_Bot) { _inherits(MCTSBot, _Bot); function MCTSBot(_ref) { var _this; var enumerate = _ref.enumerate, seed = _ref.seed, objectives = _ref.objectives, game = _ref.game, iterations = _ref.iterations, playoutDepth = _ref.playoutDepth, iterationCallback = _ref.iterationCallback; _classCallCheck(this, MCTSBot); _this = _possibleConstructorReturn(this, _getPrototypeOf(MCTSBot).call(this, { enumerate: enumerate, seed: seed })); if (objectives === undefined) { objectives = function objectives() { return {}; }; } _this.objectives = objectives; _this.iterationCallback = iterationCallback || function () {}; _this.reducer = CreateGameReducer({ game: 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 } }); return _this; } _createClass(MCTSBot, [{ key: "createNode", value: function createNode(_ref2) { var state = _ref2.state, parentAction = _ref2.parentAction, parent = _ref2.parent, playerID = _ref2.playerID; var G = state.G, ctx = state.ctx; var actions = []; var objectives = []; if (playerID !== undefined) { actions = this.enumerate(G, ctx, playerID); objectives = this.objectives(G, ctx, playerID); } else if (ctx.activePlayers) { for (var _playerID in ctx.activePlayers) { actions = actions.concat(this.enumerate(G, ctx, _playerID)); objectives = objectives.concat(this.objectives(G, ctx, _playerID)); } } else { actions = actions.concat(this.enumerate(G, ctx, ctx.currentPlayer)); objectives = objectives.concat(this.objectives(G, ctx, ctx.currentPlayer)); } return { // Game state at this node. state: state, // Parent of the node. parent: parent, // Move used to get to this node. parentAction: parentAction, // Unexplored actions. actions: actions, // Current objectives. objectives: objectives, // Children of the node. children: [], // Number of simulations that pass through this node. visits: 0, // Number of wins for this node. value: 0 }; } }, { key: "select", value: function 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; } var selectedChild = null; var best = 0.0; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = node.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var child = _step.value; var childVisits = child.visits + Number.EPSILON; var uct = child.value / childVisits + Math.sqrt(2 * Math.log(node.visits) / childVisits); if (selectedChild == null || uct > best) { best = uct; selectedChild = child; } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"] != null) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return this.select(selectedChild); } }, { key: "expand", value: function expand(node) { var actions = node.actions; if (actions.length == 0 || node.state.ctx.gameover !== undefined) { return node; } var id = this.random(actions.length); var action = actions[id]; node.actions.splice(id, 1); var childState = this.reducer(node.state, action); var childNode = this.createNode({ state: childState, parentAction: action, parent: node }); node.children.push(childNode); return childNode; } }, { key: "playout", value: function playout(node) { var _this2 = this; var state = node.state; var playoutDepth = this.getOpt('playoutDepth'); if (typeof this.playoutDepth === 'function') { playoutDepth = this.playoutDepth(state.G, state.ctx); } var _loop = function _loop(i) { var _state = state, G = _state.G, ctx = _state.ctx; var playerID = ctx.currentPlayer; if (ctx.activePlayers) { playerID = Object.keys(ctx.activePlayers)[0]; } var moves = _this2.enumerate(G, ctx, playerID); // Check if any objectives are met. var objectives = _this2.objectives(G, ctx); var score = Object.keys(objectives).reduce(function (score, key) { var objective = objectives[key]; if (objective.checker(G, ctx)) { return score + objective.weight; } return score; }, 0.0); // If so, stop and return the score. if (score > 0) { return { v: { score: score } }; } if (!moves || moves.length == 0) { return { v: undefined }; } var id = _this2.random(moves.length); var childState = _this2.reducer(state, moves[id]); state = childState; }; for (var i = 0; i < playoutDepth && state.ctx.gameover === undefined; i++) { var _ret = _loop(); if (_typeof(_ret) === "object") return _ret.v; } return state.ctx.gameover; } }, { key: "backpropagate", value: function backpropagate(node) { var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; 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); } } }, { key: "play", value: function play(state, playerID) { var _this3 = this; var root = this.createNode({ state: state, playerID: playerID }); var numIterations = this.getOpt('iterations'); if (typeof this.iterations === 'function') { numIterations = this.iterations(state.G, state.ctx); } var getResult = function getResult() { var selectedChild = null; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = root.children[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var child = _step2.value; if (selectedChild == null || child.visits > selectedChild.visits) { selectedChild = child; } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { _iterator2["return"](); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } var action = selectedChild && selectedChild.parentAction; var metadata = root; return { action: action, metadata: metadata }; }; return new Promise(function (resolve) { var iteration = function iteration() { for (var i = 0; i < CHUNK_SIZE && _this3.iterationCounter < numIterations; i++) { var leaf = _this3.select(root); var child = _this3.expand(leaf); var result = _this3.playout(child); _this3.backpropagate(child, result); _this3.iterationCounter++; } _this3.iterationCallback({ iterationCounter: _this3.iterationCounter, numIterations: numIterations, metadata: root }); }; _this3.iterationCounter = 0; if (_this3.getOpt('async')) { var asyncIteration = function asyncIteration() { if (_this3.iterationCounter < numIterations) { iteration(); setTimeout(asyncIteration, 0); } else { resolve(getResult()); } }; asyncIteration(); } else { while (_this3.iterationCounter < numIterations) { iteration(); } resolve(getResult()); } }); } }]); return MCTSBot; }(Bot); /** * Bot that picks a move at random. */ var RandomBot = /*#__PURE__*/ function (_Bot) { _inherits(RandomBot, _Bot); function RandomBot() { _classCallCheck(this, RandomBot); return _possibleConstructorReturn(this, _getPrototypeOf(RandomBot).apply(this, arguments)); } _createClass(RandomBot, [{ key: "play", value: function play(_ref, playerID) { var G = _ref.G, ctx = _ref.ctx; var moves = this.enumerate(G, ctx, playerID); return Promise.resolve({ action: this.random(moves) }); } }]); return RandomBot; }(Bot); /* * 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) { var state = client.store.getState(); var playerID = state.ctx.currentPlayer; if (state.ctx.activePlayers) { playerID = Object.keys(state.ctx.activePlayers)[0]; } var _ref = await bot.play(state, playerID), action = _ref.action, metadata = _ref.metadata; if (action) { action.payload.metadata = metadata; client.store.dispatch(action); } return action; } /** * 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(_ref2) { var game = _ref2.game, bots = _ref2.bots, state = _ref2.state, depth = _ref2.depth; if (depth === undefined) depth = 10000; var reducer = CreateGameReducer({ game: game, numPlayers: state.ctx.numPlayers }); var metadata = null; var iter = 0; while (state.ctx.gameover === undefined && iter < depth) { var playerID = state.ctx.currentPlayer; if (state.ctx.activePlayers) { playerID = Object.keys(state.ctx.activePlayers)[0]; } var bot = bots instanceof Bot ? bots : bots[playerID]; var t = await bot.play(state, playerID); if (!t.action) { break; } metadata = t.metadata; state = reducer(state, t.action); iter++; } return { state: state, metadata: metadata }; } /* src/client/debug/ai/AI.svelte generated by Svelte v3.12.1 */ function add_css$i() { var style = element("style"); style.id = 'svelte-hsd9fq-style'; style.textContent = "li.svelte-hsd9fq{list-style:none;margin:none;margin-bottom:5px}h3.svelte-hsd9fq{text-transform:uppercase}label.svelte-hsd9fq{font-weight:bold;color:#999}input[type='checkbox'].svelte-hsd9fq{vertical-align:middle}"; append(document.head, style); } function get_each_context$7(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.bot = list[i]; return child_ctx; } // (193:4) {:else} function create_else_block$2(ctx) { var p0, t_1, p1; return { c() { p0 = element("p"); p0.textContent = "No bots available."; t_1 = 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, t_1, anchor); insert(target, p1, anchor); }, p: noop, i: noop, o: noop, d(detaching) { if (detaching) { detach(p0); detach(t_1); detach(p1); } } }; } // (191:4) {#if client.multiplayer} function create_if_block_5(ctx) { var 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); } } }; } // (145:2) {#if client.game.ai && !client.multiplayer} function create_if_block$9(ctx) { var section0, h30, t1, li0, t2, li1, t3, li2, t4, section1, h31, t6, select, t7, show_if = Object.keys(ctx.bot.opts()).length, t8, if_block1_anchor, current, dispose; var hotkey0 = new Hotkey({ props: { value: "1", onPress: ctx.Reset, label: "reset" } }); var hotkey1 = new Hotkey({ props: { value: "2", onPress: ctx.Step, label: "play" } }); var hotkey2 = new Hotkey({ props: { value: "3", onPress: ctx.Simulate, label: "simulate" } }); let each_value = Object.keys(ctx.bots); 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)); } var if_block0 = (show_if) && create_if_block_4(ctx); var if_block1 = (ctx.botAction || ctx.iterationCounter) && create_if_block_1$4(ctx); return { c() { section0 = element("section"); h30 = element("h3"); h30.textContent = "Controls"; t1 = space(); li0 = element("li"); hotkey0.$$.fragment.c(); t2 = space(); li1 = element("li"); hotkey1.$$.fragment.c(); t3 = space(); li2 = element("li"); hotkey2.$$.fragment.c(); 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-hsd9fq"); attr(li0, "class", "svelte-hsd9fq"); attr(li1, "class", "svelte-hsd9fq"); attr(li2, "class", "svelte-hsd9fq"); attr(h31, "class", "svelte-hsd9fq"); if (ctx.selectedBot === void 0) add_render_callback(() => ctx.select_change_handler.call(select)); dispose = [ listen(select, "change", ctx.select_change_handler), listen(select, "change", ctx.ChangeBot) ]; }, m(target, anchor) { insert(target, section0, anchor); append(section0, h30); append(section0, t1); append(section0, li0); mount_component(hotkey0, li0, null); append(section0, t2); append(section0, li1); mount_component(hotkey1, li1, null); append(section0, t3); append(section0, 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, ctx.selectedBot); 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; }, p(changed, ctx) { if (changed.bots) { each_value = Object.keys(ctx.bots); 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(changed, child_ctx); } else { each_blocks[i] = create_each_block$7(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 (changed.selectedBot) select_option(select, ctx.selectedBot); if (changed.bot) show_if = Object.keys(ctx.bot.opts()).length; if (show_if) { if (if_block0) { if_block0.p(changed, ctx); 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 (ctx.botAction || ctx.iterationCounter) { if (if_block1) { if_block1.p(changed, ctx); } else { if_block1 = create_if_block_1$4(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); 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); } run_all(dispose); } }; } // (162:8) {#each Object.keys(bots) as bot} function create_each_block$7(ctx) { var option, t_value = ctx.bot + "", t; return { c() { option = element("option"); t = text(t_value); option.__value = ctx.bot; option.value = option.__value; }, m(target, anchor) { insert(target, option, anchor); append(option, t); }, p: noop, d(detaching) { if (detaching) { detach(option); } } }; } // (168:4) {#if Object.keys(bot.opts()).length} function create_if_block_4(ctx) { var section, h3, t1, label, t3, input, t4, current, dispose; var options = new Options({ props: { bot: ctx.bot } }); 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(); options.$$.fragment.c(); attr(h3, "class", "svelte-hsd9fq"); attr(label, "class", "svelte-hsd9fq"); attr(input, "type", "checkbox"); attr(input, "class", "svelte-hsd9fq"); dispose = [ listen(input, "change", ctx.input_change_handler), listen(input, "change", ctx.OnDebug) ]; }, m(target, anchor) { insert(target, section, anchor); append(section, h3); append(section, t1); append(section, label); append(section, t3); append(section, input); input.checked = ctx.debug; append(section, t4); mount_component(options, section, null); current = true; }, p(changed, ctx) { if (changed.debug) input.checked = ctx.debug; var options_changes = {}; if (changed.bot) options_changes.bot = ctx.bot; 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); run_all(dispose); } }; } // (177:4) {#if botAction || iterationCounter} function create_if_block_1$4(ctx) { var section, h3, t1, t2; var if_block0 = (ctx.progress && ctx.progress < 1.0) && create_if_block_3(ctx); var if_block1 = (ctx.botAction) && create_if_block_2$2(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-hsd9fq"); }, 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(changed, ctx) { if (ctx.progress && ctx.progress < 1.0) { if (if_block0) { if_block0.p(changed, ctx); } else { if_block0 = create_if_block_3(ctx); if_block0.c(); if_block0.m(section, t2); } } else if (if_block0) { if_block0.d(1); if_block0 = null; } if (ctx.botAction) { if (if_block1) { if_block1.p(changed, ctx); } else { if_block1 = create_if_block_2$2(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(); } }; } // (180:6) {#if progress && progress < 1.0} function create_if_block_3(ctx) { var progress_1; return { c() { progress_1 = element("progress"); progress_1.value = ctx.progress; }, m(target, anchor) { insert(target, progress_1, anchor); }, p(changed, ctx) { if (changed.progress) { progress_1.value = ctx.progress; } }, d(detaching) { if (detaching) { detach(progress_1); } } }; } // (184:6) {#if botAction} function create_if_block_2$2(ctx) { var li0, t0, t1, t2, li1, t3, t4_value = JSON.stringify(ctx.botActionArgs) + "", t4; return { c() { li0 = element("li"); t0 = text("Action: "); t1 = text(ctx.botAction); t2 = space(); li1 = element("li"); t3 = text("Args: "); t4 = text(t4_value); attr(li0, "class", "svelte-hsd9fq"); attr(li1, "class", "svelte-hsd9fq"); }, m(target, anchor) { insert(target, li0, anchor); append(li0, t0); append(li0, t1); insert(target, t2, anchor); insert(target, li1, anchor); append(li1, t3); append(li1, t4); }, p(changed, ctx) { if (changed.botAction) { set_data(t1, ctx.botAction); } if ((changed.botActionArgs) && t4_value !== (t4_value = JSON.stringify(ctx.botActionArgs) + "")) { set_data(t4, t4_value); } }, d(detaching) { if (detaching) { detach(li0); detach(t2); detach(li1); } } }; } function create_fragment$k(ctx) { var section, current_block_type_index, if_block, current, dispose; var if_block_creators = [ create_if_block$9, create_if_block_5, create_else_block$2 ]; var if_blocks = []; function select_block_type(changed, ctx) { if (ctx.client.game.ai && !ctx.client.multiplayer) return 0; if (ctx.client.multiplayer) return 1; return 2; } current_block_type_index = select_block_type(null, 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(); dispose = listen(window, "keydown", ctx.OnKeyDown); }, m(target, anchor) { insert(target, section, anchor); if_blocks[current_block_type_index].m(section, null); current = true; }, p(changed, ctx) { var previous_block_index = current_block_type_index; current_block_type_index = select_block_type(changed, ctx); if (current_block_type_index === previous_block_index) { if_blocks[current_block_type_index].p(changed, ctx); } else { group_outros(); transition_out(if_blocks[previous_block_index], 1, 1, () => { if_blocks[previous_block_index] = null; }); check_outros(); if_block = if_blocks[current_block_type_index]; if (!if_block) { if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); if_block.c(); } transition_in(if_block, 1); if_block.m(section, null); } }, i(local) { if (current) return; transition_in(if_block); current = true; }, o(local) { transition_out(if_block); current = false; }, d(detaching) { if (detaching) { detach(section); } if_blocks[current_block_type_index].d(); dispose(); } }; } function instance$k($$self, $$props, $$invalidate) { let { client } = $$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('iterationCounter', iterationCounter = c); $$invalidate('progress', 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) { $$invalidate('bot', 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('bot', bot = new botConstructor({ game: client.game, enumerate: client.game.ai.enumerate, iterationCallback, })); bot.setOpt('async', true); $$invalidate('botAction', botAction = null); metadata = null; secondaryPane.set(null); $$invalidate('iterationCounter', iterationCounter = 0); } async function Step$1() { $$invalidate('botAction', botAction = null); metadata = null; $$invalidate('iterationCounter', iterationCounter = 0); const t = await Step(client, bot); if (t) { $$invalidate('botAction', botAction = t.payload.type); $$invalidate('botActionArgs', botActionArgs = t.payload.args); } } function Simulate(iterations = 10000, sleepTimeout = 100) { $$invalidate('botAction', botAction = null); metadata = null; $$invalidate('iterationCounter', 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('debug', debug = false); } function Reset() { client.reset(); $$invalidate('botAction', botAction = null); metadata = null; $$invalidate('iterationCounter', iterationCounter = 0); Exit(); } function OnKeyDown(e) { // ESC. if (e.keyCode == 27) { Exit(); } } onDestroy(Exit); function select_change_handler() { selectedBot = select_value(this); $$invalidate('selectedBot', selectedBot); $$invalidate('bots', bots); } function input_change_handler() { debug = this.checked; $$invalidate('debug', debug); } $$self.$set = $$props => { if ('client' in $$props) $$invalidate('client', client = $$props.client); }; return { client, bots, debug, progress, iterationCounter, OnDebug, bot, selectedBot, botAction, botActionArgs, ChangeBot, Step: Step$1, Simulate, Reset, OnKeyDown, select_change_handler, input_change_handler }; } class AI extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-hsd9fq-style")) add_css$i(); init(this, options, instance$k, create_fragment$k, safe_not_equal, ["client"]); } } /* src/client/debug/Debug.svelte generated by Svelte v3.12.1 */ function add_css$j() { var style = element("style"); style.id = 'svelte-1h5kecx-style'; style.textContent = ".debug-panel.svelte-1h5kecx{position:fixed;color:#555;font-family:monospace;display:flex;flex-direction:row;text-align:left;right:0;top:0;height:100%;font-size:14px;box-sizing:border-box;opacity:0.9}.pane.svelte-1h5kecx{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-1h5kecx{background:#fefefe;overflow-y:scroll}.debug-panel.svelte-1h5kecx button, select{cursor:pointer;outline:none;background:#eee;border:1px solid #bbb;color:#555;padding:3px;border-radius:3px}.debug-panel.svelte-1h5kecx button{padding-left:10px;padding-right:10px}.debug-panel.svelte-1h5kecx button:hover{background:#ddd}.debug-panel.svelte-1h5kecx button:active{background:#888;color:#fff}.debug-panel.svelte-1h5kecx section{margin-bottom:20px}"; append(document.head, style); } // (109:0) {#if visible} function create_if_block$a(ctx) { var div1, t0, div0, t1, div1_transition, current; var menu = new Menu({ props: { panes: ctx.panes, pane: ctx.pane } }); menu.$on("change", ctx.MenuChange); var switch_value = ctx.panes[ctx.pane].component; function switch_props(ctx) { return { props: { client: ctx.client } }; } if (switch_value) { var switch_instance = new switch_value(switch_props(ctx)); } var if_block = (ctx.$secondaryPane) && create_if_block_1$5(ctx); return { c() { div1 = element("div"); menu.$$.fragment.c(); t0 = space(); div0 = element("div"); if (switch_instance) switch_instance.$$.fragment.c(); t1 = space(); if (if_block) if_block.c(); attr(div0, "class", "pane svelte-1h5kecx"); attr(div1, "class", "debug-panel svelte-1h5kecx"); }, m(target, anchor) { insert(target, div1, anchor); mount_component(menu, div1, null); append(div1, t0); append(div1, div0); if (switch_instance) { mount_component(switch_instance, div0, null); } append(div1, t1); if (if_block) if_block.m(div1, null); current = true; }, p(changed, ctx) { var menu_changes = {}; if (changed.pane) menu_changes.pane = ctx.pane; menu.$set(menu_changes); var switch_instance_changes = {}; if (changed.client) switch_instance_changes.client = ctx.client; if (switch_value !== (switch_value = ctx.panes[ctx.pane].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)); switch_instance.$$.fragment.c(); 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 (ctx.$secondaryPane) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block_1$5(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(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 }, true); div1_transition.run(1); }); current = true; }, o(local) { transition_out(menu.$$.fragment, local); if (switch_instance) transition_out(switch_instance.$$.fragment, local); transition_out(if_block); if (!div1_transition) div1_transition = create_bidirectional_transition(div1, fly, { x: 400 }, false); div1_transition.run(0); current = false; }, d(detaching) { if (detaching) { detach(div1); } destroy_component(menu); if (switch_instance) destroy_component(switch_instance); if (if_block) if_block.d(); if (detaching) { if (div1_transition) div1_transition.end(); } } }; } // (115:4) {#if $secondaryPane} function create_if_block_1$5(ctx) { var div, current; var switch_value = ctx.$secondaryPane.component; function switch_props(ctx) { return { props: { metadata: ctx.$secondaryPane.metadata } }; } if (switch_value) { var switch_instance = new switch_value(switch_props(ctx)); } return { c() { div = element("div"); if (switch_instance) switch_instance.$$.fragment.c(); attr(div, "class", "secondary-pane svelte-1h5kecx"); }, m(target, anchor) { insert(target, div, anchor); if (switch_instance) { mount_component(switch_instance, div, null); } current = true; }, p(changed, ctx) { var switch_instance_changes = {}; if (changed.$secondaryPane) switch_instance_changes.metadata = ctx.$secondaryPane.metadata; if (switch_value !== (switch_value = ctx.$secondaryPane.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)); switch_instance.$$.fragment.c(); 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$l(ctx) { var if_block_anchor, current, dispose; var if_block = (ctx.visible) && create_if_block$a(ctx); return { c() { if (if_block) if_block.c(); if_block_anchor = empty(); dispose = listen(window, "keypress", ctx.Keypress); }, m(target, anchor) { if (if_block) if_block.m(target, anchor); insert(target, if_block_anchor, anchor); current = true; }, p(changed, ctx) { if (ctx.visible) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block$a(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); } dispose(); } }; } function instance$l($$self, $$props, $$invalidate) { let $secondaryPane; let { client } = $$props; 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 => { $secondaryPane = $$value; $$invalidate('$secondaryPane', $secondaryPane); }); setContext('hotkeys', { disableHotkeys }); setContext('secondaryPane', { secondaryPane }); let pane = 'main'; function MenuChange(e) { $$invalidate('pane', pane = e.detail); } let visible = true; function Keypress(e) { if (e.key == '.') { $$invalidate('visible', visible = !visible); return; } Object.entries(panes).forEach(([key, { shortcut }]) => { if (e.key == shortcut) { $$invalidate('pane', pane = key); } }); } $$self.$set = $$props => { if ('client' in $$props) $$invalidate('client', client = $$props.client); }; return { client, panes, secondaryPane, pane, MenuChange, visible, Keypress, $secondaryPane }; } class Debug extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1h5kecx-style")) add_css$j(); init(this, options, instance$l, create_fragment$l, safe_not_equal, ["client"]); } } /* * 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; } let ctx = game.flow.ctx(numPlayers); let state = { // User managed state. G: {}, // Framework managed state. ctx, // Plugin related state. plugins: {}, }; // Run plugins over initial state. state = Setup(state, { game }); state = Enhance(state, { game, playerID: undefined }); const enhancedCtx = EnhanceCtx(state); state.G = game.setup(enhancedCtx, setupData); let initial = { ...state, // List of {G, ctx} pairs that can be undone. _undo: [], // List of {G, ctx} pairs that can be redone. _redo: [], // A monotonically non-decreasing ID to ensure that // state updates are only allowed from clients that // are at the same version that the server. _stateID: 0, }; initial = game.flow.init(initial); initial = Flush(initial, { game }); return initial; } /** * createDispatchers * * Create action dispatcher wrappers with bound playerID and credentials */ function createDispatchers(storeActionType, innerActionNames, store, playerID, credentials, multiplayer) { return innerActionNames.reduce(function (dispatchers, name) { dispatchers[name] = function () { var assumedPlayerID = playerID; // 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)) { var state = store.getState(); assumedPlayerID = state.ctx.currentPlayer; } for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } store.dispatch(ActionCreators[storeActionType](name, args, assumedPlayerID, credentials)); }; return dispatchers; }, {}); } // Creates a set of dispatchers to make moves. var createMoveDispatchers = createDispatchers.bind(null, 'makeMove'); // Creates a set of dispatchers to dispatch game flow events. var createEventDispatchers = createDispatchers.bind(null, 'gameEvent'); // Creates a set of dispatchers to dispatch actions to plugins. var createPluginDispatchers = createDispatchers.bind(null, 'plugin'); /** * Implementation of Client (see below). */ var _ClientImpl = /*#__PURE__*/ function () { function _ClientImpl(_ref) { var _this = this; var game = _ref.game, debug = _ref.debug, numPlayers = _ref.numPlayers, multiplayer = _ref.multiplayer, gameID = _ref.gameID, playerID = _ref.playerID, credentials = _ref.credentials, enhancer = _ref.enhancer; _classCallCheck(this, _ClientImpl); this.game = ProcessGameConfig(game); this.playerID = playerID; this.gameID = gameID; this.credentials = credentials; this.multiplayer = multiplayer; this.debug = debug; this.gameStateOverride = null; this.subscribers = {}; this._running = false; this.reducer = CreateGameReducer({ game: this.game, isClient: multiplayer !== undefined, numPlayers: numPlayers }); this.initialState = null; if (!multiplayer) { this.initialState = InitializeGame({ game: this.game, numPlayers: numPlayers }); } this.reset = function () { _this.store.dispatch(reset(_this.initialState)); }; this.undo = function () { _this.store.dispatch(undo(playerID, credentials)); }; this.redo = function () { _this.store.dispatch(redo(playerID, credentials)); }; this.store = null; 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. */ var LogMiddleware = function LogMiddleware(store) { return function (next) { return function (action) { var result = next(action); var state = store.getState(); switch (action.type) { case MAKE_MOVE: case GAME_EVENT: { var deltalog = state.deltalog; _this.log = [].concat(_toConsumableArray(_this.log), _toConsumableArray(deltalog)); break; } case RESET: { _this.log = []; break; } case UPDATE: { var id = -1; if (_this.log.length > 0) { id = _this.log[_this.log.length - 1]._stateID; } var _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(function (l) { return l._stateID > id; }); _this.log = [].concat(_toConsumableArray(_this.log), _toConsumableArray(_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. */ var TransportMiddleware = function TransportMiddleware(store) { return function (next) { return function (action) { var baseState = store.getState(); var result = next(action); if (action.clientOnly != true) { _this.transport.onAction(baseState, action); } return result; }; }; }; /** * Middleware that intercepts actions and invokes the subscription callback. */ var SubscriptionMiddleware = function SubscriptionMiddleware() { return function (next) { return function (action) { var result = next(action); _this.notifySubscribers(); return result; }; }; }; if (enhancer !== undefined) { enhancer = compose(applyMiddleware(SubscriptionMiddleware, TransportMiddleware, LogMiddleware), enhancer); } else { enhancer = applyMiddleware(SubscriptionMiddleware, TransportMiddleware, LogMiddleware); } this.store = createStore(this.reducer, this.initialState, enhancer); this.transport = { isConnected: true, onAction: function onAction() {}, subscribe: function subscribe() {}, subscribeGameMetadata: function subscribeGameMetadata(_metadata) {}, // eslint-disable-line no-unused-vars connect: function connect() {}, disconnect: function disconnect() {}, updateGameID: function updateGameID() {}, updatePlayerID: function updatePlayerID() {} }; if (multiplayer) { // typeof multiplayer is 'function' this.transport = multiplayer({ gameKey: game, game: this.game, store: this.store, gameID: gameID, playerID: playerID, gameName: this.game.name, numPlayers: numPlayers }); } this.createDispatchers(); this.transport.subscribeGameMetadata(function (metadata) { _this.gameMetadata = metadata; }); this._debugPanel = null; } _createClass(_ClientImpl, [{ key: "notifySubscribers", value: function notifySubscribers() { var _this2 = this; Object.values(this.subscribers).forEach(function (fn) { return fn(_this2.getState()); }); } }, { key: "overrideGameState", value: function overrideGameState(state) { this.gameStateOverride = state; this.notifySubscribers(); } }, { key: "start", value: function start() { this.transport.connect(); this._running = true; var debugImpl = null; if (process.env.NODE_ENV !== 'production') { debugImpl = Debug; } if (this.debug && this.debug.impl) { debugImpl = this.debug.impl; } if (debugImpl !== null && this.debug !== false && this._debugPanel == null && typeof document !== 'undefined') { var target = document.body; if (this.debug && this.debug.target !== undefined) { target = this.debug.target; } if (target) { this._debugPanel = new debugImpl({ target: target, props: { client: this } }); } } } }, { key: "stop", value: function stop() { this.transport.disconnect(); this._running = false; if (this._debugPanel != null) { this._debugPanel.$destroy(); this._debugPanel = null; } } }, { key: "subscribe", value: function subscribe(fn) { var _this3 = this; var id = Object.keys(this.subscribers).length; this.subscribers[id] = fn; this.transport.subscribe(function () { return _this3.notifySubscribers(); }); if (this._running || !this.multiplayer) { fn(this.getState()); } // Return a handle that allows the caller to unsubscribe. return function () { delete _this3.subscribers[id]; }; } }, { key: "getInitialState", value: function getInitialState() { return this.initialState; } }, { key: "getState", value: function getState() { var 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. var isActive = true; var 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. var G = this.game.playerView(state.G, state.ctx, this.playerID); // Combine into return value. var ret = _objectSpread2({}, state, { isActive: isActive, G: G, log: this.log }); var isConnected = this.transport.isConnected; ret = _objectSpread2({}, ret, { isConnected: isConnected }); return ret; } }, { key: "createDispatchers", value: function 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); } }, { key: "updatePlayerID", value: function updatePlayerID(playerID) { this.playerID = playerID; this.createDispatchers(); this.transport.updatePlayerID(playerID); this.notifySubscribers(); } }, { key: "updateGameID", value: function updateGameID(gameID) { this.gameID = gameID; this.createDispatchers(); this.transport.updateGameID(gameID); this.notifySubscribers(); } }, { key: "updateCredentials", value: function updateCredentials(credentials) { this.credentials = credentials; this.createDispatchers(); this.notifySubscribers(); } }]); return _ClientImpl; }(); /** * 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} gameID - The gameID 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); } /** * 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 _class, _temp; var game = opts.game, numPlayers = opts.numPlayers, loading = opts.loading, board = opts.board, multiplayer = opts.multiplayer, enhancer = opts.enhancer, debug = opts.debug; // Component that is displayed before the client has synced // with the game master. if (loading === undefined) { var Loading = function Loading() { return React.createElement("div", { className: "bgio-loading" }, "connecting..."); }; loading = Loading; } /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _temp = _class = /*#__PURE__*/ function (_React$Component) { _inherits(WrappedBoard, _React$Component); function WrappedBoard(props) { var _this; _classCallCheck(this, WrappedBoard); _this = _possibleConstructorReturn(this, _getPrototypeOf(WrappedBoard).call(this, props)); if (debug === undefined) { debug = props.debug; } _this.client = Client({ game: game, debug: debug, numPlayers: numPlayers, multiplayer: multiplayer, gameID: props.gameID, playerID: props.playerID, credentials: props.credentials, enhancer: enhancer }); return _this; } _createClass(WrappedBoard, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; this.unsubscribe = this.client.subscribe(function () { return _this2.forceUpdate(); }); this.client.start(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.client.stop(); this.unsubscribe(); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props.gameID != prevProps.gameID) { this.client.updateGameID(this.props.gameID); } if (this.props.playerID != prevProps.playerID) { this.client.updatePlayerID(this.props.playerID); } if (this.props.credentials != prevProps.credentials) { this.client.updateCredentials(this.props.credentials); } } }, { key: "render", value: function render() { var state = this.client.getState(); if (state === null) { return React.createElement(loading); } var _board = null; if (board) { _board = React.createElement(board, _objectSpread2({}, state, {}, this.props, { isMultiplayer: !!multiplayer, moves: this.client.moves, events: this.client.events, gameID: this.client.gameID, playerID: this.client.playerID, reset: this.client.reset, undo: this.client.undo, redo: this.client.redo, gameMetadata: this.client.gameMetadata })); } return React.createElement("div", { className: "bgio-client" }, _board); } }]); return WrappedBoard; }(React.Component), _defineProperty(_class, "propTypes", { // The ID of a game to connect to. // Only relevant in multiplayer. gameID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string, // Enable / disable the Debug UI. debug: PropTypes.any }), _defineProperty(_class, "defaultProps", { gameID: 'default', playerID: null, credentials: null, debug: true }), _temp; } /** * Client * * boardgame.io React Native client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React Native component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE. */ function Client$2(opts) { var _class, _temp; var game = opts.game, numPlayers = opts.numPlayers, board = opts.board, multiplayer = opts.multiplayer, enhancer = opts.enhancer; /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _temp = _class = /*#__PURE__*/ function (_React$Component) { _inherits(WrappedBoard, _React$Component); function WrappedBoard(props) { var _this; _classCallCheck(this, WrappedBoard); _this = _possibleConstructorReturn(this, _getPrototypeOf(WrappedBoard).call(this, props)); _this.client = Client({ game: game, numPlayers: numPlayers, multiplayer: multiplayer, gameID: props.gameID, 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.gameID != this.props.gameID) { this.client.updateGameID(this.props.gameID); } if (prevProps.playerID != this.props.playerID) { this.client.updatePlayerID(this.props.playerID); } if (prevProps.credentials != this.props.credentials) { this.client.updateCredentials(this.props.credentials); } } }, { key: "render", value: function render() { var _board = null; var state = this.client.getState(); var _this$props = this.props, gameID = _this$props.gameID, playerID = _this$props.playerID, rest = _objectWithoutProperties(_this$props, ["gameID", "playerID"]); if (board) { _board = React.createElement(board, _objectSpread2({}, state, {}, rest, { gameID: gameID, 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, gameMetadata: this.client.gameMetadata })); } return _board; } }]); return WrappedBoard; }(React.Component), _defineProperty(_class, "propTypes", { // The ID of a game to connect to. // Only relevant in multiplayer. gameID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string }), _defineProperty(_class, "defaultProps", { gameID: 'default', playerID: null, credentials: null }), _temp; } var Type; (function (Type) { Type[Type["SYNC"] = 0] = "SYNC"; Type[Type["ASYNC"] = 1] = "ASYNC"; })(Type || (Type = {})); class Sync { type() { return Type.SYNC; } /** * Connect. */ connect() { return; } } /* * 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 game. */ createGame(gameID, opts) { this.initial.set(gameID, opts.initialState); this.setState(gameID, opts.initialState); this.setMetadata(gameID, opts.metadata); } /** * Write the game metadata to the in-memory object. */ setMetadata(gameID, metadata) { this.metadata.set(gameID, metadata); } /** * Write the game state to the in-memory object. */ setState(gameID, state, deltalog) { if (deltalog && deltalog.length > 0) { const log = this.log.get(gameID) || []; this.log.set(gameID, log.concat(deltalog)); } this.state.set(gameID, state); } /** * Fetches state for a particular gameID. */ fetch(gameID, opts) { let result = {}; if (opts.state) { result.state = this.state.get(gameID); } if (opts.metadata) { result.metadata = this.metadata.get(gameID); } if (opts.log) { result.log = this.log.get(gameID) || []; } if (opts.initialState) { result.initialState = this.initial.get(gameID); } return result; } /** * Remove the game state from the in-memory object. */ wipe(gameID) { this.state.delete(gameID); this.metadata.delete(gameID); } /** * Return all keys. */ listGames(opts) { if (opts && opts.gameName !== undefined) { let gameIDs = []; this.metadata.forEach((metadata, gameID) => { if (metadata.gameName === opts.gameName) { gameIDs.push(gameID); } }); return gameIDs; } return [...this.metadata.keys()]; } } /* * 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 getPlayerMetadata = (gameMetadata, playerID) => { if (gameMetadata && gameMetadata.players) { return gameMetadata.players[playerID]; } }; function IsSynchronous(storageAPI) { return storageAPI.type() === Type.SYNC; } /** * 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 }, }; /* eslint-disable-next-line no-unused-vars */ const { redact, ...remaining } = filteredEvent; return remaining; }); } /** * Verifies that the game has metadata and is using credentials. */ const doesGameRequireAuthentication = (gameMetadata) => { if (!gameMetadata) return false; const { players } = gameMetadata; const hasCredentials = Object.keys(players).some(key => { return !!(players[key] && players[key].credentials); }); return hasCredentials; }; /** * Verifies that the move came from a player with the correct credentials. */ const isActionFromAuthenticPlayer = (actionCredentials, playerMetadata) => { if (!actionCredentials) return false; if (!playerMetadata) return false; return actionCredentials === playerMetadata.credentials; }; /** * Remove player credentials from action payload */ const stripCredentialsFromAction = (action) => { // eslint-disable-next-line no-unused-vars 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.auth = null; this.subscribeCallback = () => { }; this.shouldAuth = () => false; if (auth === true) { this.auth = isActionFromAuthenticPlayer; this.shouldAuth = doesGameRequireAuthentication; } else if (typeof auth === 'function') { this.auth = auth; this.shouldAuth = () => true; } } 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, gameID, playerID) { let isActionAuthentic; const credentials = credAction.payload.credentials; if (IsSynchronous(this.storageAPI)) { const { metadata } = this.storageAPI.fetch(gameID, { metadata: true }); const playerMetadata = getPlayerMetadata(metadata, playerID); isActionAuthentic = this.shouldAuth(metadata) ? this.auth(credentials, playerMetadata) : true; } else { const { metadata } = await this.storageAPI.fetch(gameID, { metadata: true, }); const playerMetadata = getPlayerMetadata(metadata, playerID); isActionAuthentic = this.shouldAuth(metadata) ? await this.auth(credentials, playerMetadata) : true; } if (!isActionAuthentic) { return { error: 'unauthorized action' }; } let action = stripCredentialsFromAction(credAction); const key = gameID; let state; let result; if (IsSynchronous(this.storageAPI)) { result = this.storageAPI.fetch(key, { state: true }); } else { result = await this.storageAPI.fetch(key, { state: true }); } state = result.state; if (state === undefined) { error(`game not found, gameID=[${key}]`); return { error: 'game not found' }; } if (state.ctx.gameover !== undefined) { error(`game over - gameID=[${key}]`); return; } const reducer = CreateGameReducer({ game: this.game, }); const store = createStore(reducer, state); // Only allow UNDO / REDO if there is exactly one player // that can make moves right now and the person doing the // action is that player. if (action.type == UNDO || action.type == REDO) { if (state.ctx.currentPlayer !== playerID || state.ctx.activePlayers !== null) { 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}]`); return; } // Check whether the player is allowed to make the move. if (action.type == MAKE_MOVE && !this.game.flow.getMove(state.ctx, action.payload.type, playerID)) { error(`move not processed - canPlayerMakeMove=false, playerID=[${playerID}]`); return; } if (state._stateID !== stateID) { error(`invalid stateID, was=[${stateID}], expected=[${state._stateID}]`); return; } // Update server's version of the store. store.dispatch(action); state = store.getState(); this.subscribeCallback({ state, action, gameID, }); this.transportAPI.sendAll((playerID) => { const filteredState = { ...state, G: this.game.playerView(state.G, state.ctx, playerID), deltalog: undefined, _undo: [], _redo: [], }; const log = redactLog(state.deltalog, playerID); return { type: 'update', args: [gameID, filteredState, log], }; }); const { deltalog, ...stateWithoutDeltalog } = state; if (IsSynchronous(this.storageAPI)) { this.storageAPI.setState(key, stateWithoutDeltalog, deltalog); } else { await this.storageAPI.setState(key, stateWithoutDeltalog, deltalog); } } /** * Called when the client connects / reconnects. * Returns the latest game state and the entire log. */ async onSync(gameID, playerID, numPlayers) { const key = gameID; let state; let initialState; let log; let gameMetadata; let filteredMetadata; let result; if (IsSynchronous(this.storageAPI)) { const api = this.storageAPI; result = api.fetch(key, { state: true, metadata: true, log: true, initialState: true, }); } else { result = await this.storageAPI.fetch(key, { state: true, metadata: true, log: true, initialState: true, }); } state = result.state; initialState = result.initialState; log = result.log; gameMetadata = result.metadata; if (gameMetadata) { filteredMetadata = Object.values(gameMetadata.players).map(player => { return { id: player.id, name: player.name }; }); } // If the game doesn't exist, then create one on demand. // TODO: Move this out of the sync call. if (state === undefined) { initialState = state = InitializeGame({ game: this.game, numPlayers }); this.subscribeCallback({ state, gameID, }); if (IsSynchronous(this.storageAPI)) { const api = this.storageAPI; api.setState(key, state); } else { await this.storageAPI.setState(key, state); } } const filteredState = { ...state, G: this.game.playerView(state.G, state.ctx, playerID), deltalog: undefined, _undo: [], _redo: [], }; log = redactLog(log, playerID); const syncInfo = { state: filteredState, log, filteredMetadata, initialState, }; this.transportAPI.send({ playerID, type: 'sync', args: [gameID, syncInfo], }); return; } } /* * 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 Transport = function Transport(_ref) { var store = _ref.store, gameName = _ref.gameName, playerID = _ref.playerID, gameID = _ref.gameID, numPlayers = _ref.numPlayers; _classCallCheck(this, Transport); this.store = store; this.gameName = gameName || 'default'; this.playerID = playerID || null; this.gameID = gameID || 'default'; this.numPlayers = numPlayers || 2; }; /** * 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.stage) { for (var _i = 0, _Object$keys = Object.keys(bots); _i < _Object$keys.length; _i++) { var key = _Object$keys[_i]; if (key in state.ctx.stage) { 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. */ function LocalMaster(_ref) { var game = _ref.game, bots = _ref.bots; var clientCallbacks = {}; var initializedBots = {}; if (game && game.ai && bots) { for (var playerID in bots) { var bot = bots[playerID]; initializedBots[playerID] = new bot({ game: game, enumerate: game.ai.enumerate, seed: game.seed }); } } var send = function send(_ref2) { var type = _ref2.type, playerID = _ref2.playerID, args = _ref2.args; var callback = clientCallbacks[playerID]; if (callback !== undefined) { callback.apply(null, [type].concat(_toConsumableArray(args))); } }; var sendAll = function sendAll(arg) { for (var _playerID in clientCallbacks) { var _arg = arg(_playerID), type = _arg.type, args = _arg.args; send({ type: type, playerID: _playerID, args: args }); } }; var master = new Master(game, new InMemory(), { send: send, sendAll: sendAll }, false); master.connect = function (gameID, playerID, callback) { clientCallbacks[playerID] = callback; }; master.subscribe(function (_ref3) { var state = _ref3.state, gameID = _ref3.gameID; if (!bots) { return; } var botPlayer = GetBotPlayer(state, initializedBots); if (botPlayer !== null) { setTimeout(async function () { var botAction = await initializedBots[botPlayer].play(state, botPlayer); await master.onUpdate(botAction.action, state._stateID, gameID, botAction.action.payload.playerID); }, 100); } }); return master; } /** * Local * * Transport interface that embeds a GameMaster within it * that you can connect multiple clients to. */ var LocalTransport = /*#__PURE__*/ function (_Transport) { _inherits(LocalTransport, _Transport); /** * Creates a new Mutiplayer instance. * @param {object} socket - Override for unit tests. * @param {object} socketOpts - Options to pass to socket.io. * @param {string} gameID - The game ID to connect to. * @param {string} playerID - The player ID associated with this client. * @param {string} gameName - The game type (the `name` field in `Game`). * @param {string} numPlayers - The number of players. * @param {string} server - The game server in the form of 'hostname:port'. Defaults to the server serving the client if not provided. */ function LocalTransport(_ref4) { var _this; var master = _ref4.master, game = _ref4.game, store = _ref4.store, gameID = _ref4.gameID, playerID = _ref4.playerID, gameName = _ref4.gameName, numPlayers = _ref4.numPlayers; _classCallCheck(this, LocalTransport); _this = _possibleConstructorReturn(this, _getPrototypeOf(LocalTransport).call(this, { store: store, gameName: gameName, playerID: playerID, gameID: gameID, numPlayers: numPlayers })); _this.master = master; _this.game = game; _this.isConnected = true; return _this; } /** * Called when another player makes a move and the * master broadcasts the update to other clients (including * this one). */ _createClass(LocalTransport, [{ key: "onUpdate", value: async function onUpdate(gameID, state, deltalog) { var currentState = this.store.getState(); if (gameID == this.gameID && state._stateID >= currentState._stateID) { var action = update(state, deltalog); this.store.dispatch(action); } } /** * Called when the client first connects to the master * and requests the current game state. */ }, { key: "onSync", value: function onSync(gameID, syncInfo) { if (gameID == this.gameID) { var action = sync(syncInfo); this.store.dispatch(action); } } /** * Called when an action that has to be relayed to the * game master is made. */ }, { key: "onAction", value: function onAction(state, action) { this.master.onUpdate(action, state._stateID, this.gameID, this.playerID); } /** * Connect to the master. */ }, { key: "connect", value: function connect() { var _this2 = this; this.master.connect(this.gameID, this.playerID, function (type) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (type == 'sync') { _this2.onSync.apply(_this2, args); } if (type == 'update') { _this2.onUpdate.apply(_this2, args); } }); this.master.onSync(this.gameID, this.playerID, this.numPlayers); } /** * Disconnect from the master. */ }, { key: "disconnect", value: function disconnect() {} /** * Subscribe to connection state changes. */ }, { key: "subscribe", value: function subscribe() {} }, { key: "subscribeGameMetadata", value: function subscribeGameMetadata(_metadata) {} // eslint-disable-line no-unused-vars /** * Updates the game id. * @param {string} id - The new game id. */ }, { key: "updateGameID", value: function updateGameID(id) { this.gameID = id; var action = reset(null); this.store.dispatch(action); this.connect(); } /** * Updates the player associated with this client. * @param {string} id - The new player id. */ }, { key: "updatePlayerID", value: function updatePlayerID(id) { this.playerID = id; var action = reset(null); this.store.dispatch(action); this.connect(); } }]); return LocalTransport; }(Transport); var localMasters = new Map(); function Local(opts) { return function (transportOpts) { var master; if (localMasters.has(transportOpts.gameKey) & !opts) { master = localMasters.get(transportOpts.gameKey); } else { master = new LocalMaster({ game: transportOpts.game, bots: opts && opts.bots }); localMasters.set(transportOpts.gameKey, master); } return new LocalTransport(_objectSpread2({ master: master }, transportOpts)); }; } /** * SocketIO * * Transport interface that interacts with the Master via socket.io. */ var SocketIOTransport = /*#__PURE__*/ function (_Transport) { _inherits(SocketIOTransport, _Transport); /** * Creates a new Mutiplayer instance. * @param {object} socket - Override for unit tests. * @param {object} socketOpts - Options to pass to socket.io. * @param {string} gameID - The game ID to connect to. * @param {string} playerID - The player ID associated with this client. * @param {string} gameName - The game type (the `name` field in `Game`). * @param {string} numPlayers - The number of players. * @param {string} server - The game server in the form of 'hostname:port'. Defaults to the server serving the client if not provided. */ function SocketIOTransport() { var _this; var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, socket = _ref.socket, socketOpts = _ref.socketOpts, store = _ref.store, gameID = _ref.gameID, playerID = _ref.playerID, gameName = _ref.gameName, numPlayers = _ref.numPlayers, server = _ref.server; _classCallCheck(this, SocketIOTransport); _this = _possibleConstructorReturn(this, _getPrototypeOf(SocketIOTransport).call(this, { store: store, gameName: gameName, playerID: playerID, gameID: gameID, numPlayers: numPlayers })); _this.server = server; _this.socket = socket; _this.socketOpts = socketOpts; _this.isConnected = false; _this.callback = function () {}; _this.gameMetadataCallback = function () {}; return _this; } /** * Called when an action that has to be relayed to the * game master is made. */ _createClass(SocketIOTransport, [{ key: "onAction", value: function onAction(state, action) { this.socket.emit('update', action, state._stateID, this.gameID, this.playerID); } /** * Connect to the server. */ }, { key: "connect", value: function connect() { var _this2 = this; if (!this.socket) { if (this.server) { var server = this.server; if (server.search(/^https?:\/\//) == -1) { server = 'http://' + this.server; } if (server.substr(-1) != '/') { // add trailing slash if not already present server = server + '/'; } this.socket = io(server + this.gameName, this.socketOpts); } else { this.socket = io('/' + this.gameName, this.socketOpts); } } // Called when another player makes a move and the // master broadcasts the update to other clients (including // this one). this.socket.on('update', function (gameID, state, deltalog) { var currentState = _this2.store.getState(); if (gameID == _this2.gameID && state._stateID >= currentState._stateID) { var action = update(state, deltalog); _this2.store.dispatch(action); } }); // Called when the client first connects to the master // and requests the current game state. this.socket.on('sync', function (gameID, syncInfo) { if (gameID == _this2.gameID) { var action = sync(syncInfo); _this2.gameMetadataCallback(syncInfo.filteredMetadata); _this2.store.dispatch(action); } }); // Initial sync to get game state. this.socket.emit('sync', this.gameID, this.playerID, this.numPlayers); // Keep track of connection status. this.socket.on('connect', function () { _this2.isConnected = true; _this2.callback(); }); this.socket.on('disconnect', function () { _this2.isConnected = false; _this2.callback(); }); } /** * Disconnect from the server. */ }, { key: "disconnect", value: function disconnect() { this.socket.close(); this.socket = null; this.isConnected = false; this.callback(); } /** * Subscribe to connection state changes. */ }, { key: "subscribe", value: function subscribe(fn) { this.callback = fn; } }, { key: "subscribeGameMetadata", value: function subscribeGameMetadata(fn) { this.gameMetadataCallback = fn; } /** * Updates the game id. * @param {string} id - The new game id. */ }, { key: "updateGameID", value: function updateGameID(id) { this.gameID = id; var action = reset(null); this.store.dispatch(action); if (this.socket) { this.socket.emit('sync', this.gameID, this.playerID, this.numPlayers); } } /** * Updates the player associated with this client. * @param {string} id - The new player id. */ }, { key: "updatePlayerID", value: function updatePlayerID(id) { this.playerID = id; var action = reset(null); this.store.dispatch(action); if (this.socket) { this.socket.emit('sync', this.gameID, this.playerID, this.numPlayers); } } }]); return SocketIOTransport; }(Transport); function SocketIO() { var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, server = _ref2.server, socketOpts = _ref2.socketOpts; return function (transportOpts) { return new SocketIOTransport(_objectSpread2({ server: server, socketOpts: 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/esm/ButtonBase/TouchRipple.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import { TransitionGroup } from 'react-transition-group'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import Ripple from './Ripple'; var DURATION = 550; export var DELAY_RIPPLE = 80; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { overflow: 'hidden', pointerEvents: 'none', position: 'absolute', zIndex: 0, top: 0, right: 0, bottom: 0, left: 0, borderRadius: 'inherit' }, /* Styles applied to the internal `Ripple` components `ripple` class. */ ripple: { opacity: 0, position: 'absolute' }, /* Styles applied to the internal `Ripple` components `rippleVisible` class. */ rippleVisible: { opacity: 0.3, transform: 'scale(1)', animation: "$enter ".concat(DURATION, "ms ").concat(theme.transitions.easing.easeInOut) }, /* Styles applied to the internal `Ripple` components `ripplePulsate` class. */ ripplePulsate: { animationDuration: "".concat(theme.transitions.duration.shorter, "ms") }, /* Styles applied to the internal `Ripple` components `child` class. */ child: { opacity: 1, display: 'block', width: '100%', height: '100%', borderRadius: '50%', backgroundColor: 'currentColor' }, /* Styles applied to the internal `Ripple` components `childLeaving` class. */ childLeaving: { opacity: 0, animation: "$exit ".concat(DURATION, "ms ").concat(theme.transitions.easing.easeInOut) }, /* Styles applied to the internal `Ripple` components `childPulsate` class. */ childPulsate: { position: 'absolute', left: 0, top: 0, animation: "$pulsate 2500ms ".concat(theme.transitions.easing.easeInOut, " 200ms infinite") }, '@keyframes enter': { '0%': { transform: 'scale(0)', opacity: 0.1 }, '100%': { transform: 'scale(1)', opacity: 0.3 } }, '@keyframes exit': { '0%': { opacity: 1 }, '100%': { opacity: 0 } }, '@keyframes pulsate': { '0%': { transform: 'scale(1)' }, '50%': { transform: 'scale(0.92)' }, '100%': { transform: 'scale(1)' } } }; }; /** * @ignore - internal component. * * TODO v5: Make private */ var TouchRipple = React.forwardRef(function TouchRipple(props, ref) { var _props$center = props.center, centerProp = _props$center === void 0 ? false : _props$center, classes = props.classes, className = props.className, other = _objectWithoutProperties(props, ["center", "classes", "className"]); var _React$useState = React.useState([]), ripples = _React$useState[0], setRipples = _React$useState[1]; var nextKey = React.useRef(0); var rippleCallback = React.useRef(null); React.useEffect(function () { if (rippleCallback.current) { rippleCallback.current(); rippleCallback.current = null; } }, [ripples]); // Used to filter out mouse emulated events on mobile. var ignoringMouseDown = React.useRef(false); // We use a timer in order to only show the ripples for touch "click" like events. // We don't want to display the ripple for touch scroll events. var startTimer = React.useRef(null); // This is the hook called once the previous timeout is ready. var startTimerCommit = React.useRef(null); var container = React.useRef(null); React.useEffect(function () { return function () { clearTimeout(startTimer.current); }; }, []); var startCommit = React.useCallback(function (params) { var pulsate = params.pulsate, rippleX = params.rippleX, rippleY = params.rippleY, rippleSize = params.rippleSize, cb = params.cb; setRipples(function (oldRipples) { return [].concat(_toConsumableArray(oldRipples), [React.createElement(Ripple, { key: nextKey.current, classes: classes, timeout: DURATION, pulsate: pulsate, rippleX: rippleX, rippleY: rippleY, rippleSize: rippleSize })]); }); nextKey.current += 1; rippleCallback.current = cb; }, [classes]); var start = React.useCallback(function () { var event = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var cb = arguments.length > 2 ? arguments[2] : undefined; var _options$pulsate = options.pulsate, pulsate = _options$pulsate === void 0 ? false : _options$pulsate, _options$center = options.center, center = _options$center === void 0 ? centerProp || options.pulsate : _options$center, _options$fakeElement = options.fakeElement, fakeElement = _options$fakeElement === void 0 ? false : _options$fakeElement; if (event.type === 'mousedown' && ignoringMouseDown.current) { ignoringMouseDown.current = false; return; } if (event.type === 'touchstart') { ignoringMouseDown.current = true; } var element = fakeElement ? null : container.current; var rect = element ? element.getBoundingClientRect() : { width: 0, height: 0, left: 0, top: 0 }; // Get the size of the ripple var rippleX; var rippleY; var rippleSize; if (center || event.clientX === 0 && event.clientY === 0 || !event.clientX && !event.touches) { rippleX = Math.round(rect.width / 2); rippleY = Math.round(rect.height / 2); } else { var clientX = event.clientX ? event.clientX : event.touches[0].clientX; var clientY = event.clientY ? event.clientY : event.touches[0].clientY; rippleX = Math.round(clientX - rect.left); rippleY = Math.round(clientY - rect.top); } if (center) { rippleSize = Math.sqrt((2 * Math.pow(rect.width, 2) + Math.pow(rect.height, 2)) / 3); // For some reason the animation is broken on Mobile Chrome if the size if even. if (rippleSize % 2 === 0) { rippleSize += 1; } } else { var sizeX = Math.max(Math.abs((element ? element.clientWidth : 0) - rippleX), rippleX) * 2 + 2; var sizeY = Math.max(Math.abs((element ? element.clientHeight : 0) - rippleY), rippleY) * 2 + 2; rippleSize = Math.sqrt(Math.pow(sizeX, 2) + Math.pow(sizeY, 2)); } // Touche devices if (event.touches) { // check that this isn't another touchstart due to multitouch // otherwise we will only clear a single timer when unmounting while two // are running if (startTimerCommit.current === null) { // Prepare the ripple effect. startTimerCommit.current = function () { startCommit({ pulsate: pulsate, rippleX: rippleX, rippleY: rippleY, rippleSize: rippleSize, cb: cb }); }; // Delay the execution of the ripple effect. startTimer.current = setTimeout(function () { if (startTimerCommit.current) { startTimerCommit.current(); startTimerCommit.current = null; } }, DELAY_RIPPLE); // We have to make a tradeoff with this value. } } else { startCommit({ pulsate: pulsate, rippleX: rippleX, rippleY: rippleY, rippleSize: rippleSize, cb: cb }); } }, [centerProp, startCommit]); var pulsate = React.useCallback(function () { start({}, { pulsate: true }); }, [start]); var stop = React.useCallback(function (event, cb) { clearTimeout(startTimer.current); // The touch interaction occurs too quickly. // We still want to show ripple effect. if (event.type === 'touchend' && startTimerCommit.current) { event.persist(); startTimerCommit.current(); startTimerCommit.current = null; startTimer.current = setTimeout(function () { stop(event, cb); }); return; } startTimerCommit.current = null; setRipples(function (oldRipples) { if (oldRipples.length > 0) { return oldRipples.slice(1); } return oldRipples; }); rippleCallback.current = cb; }, []); React.useImperativeHandle(ref, function () { return { pulsate: pulsate, start: start, stop: stop }; }, [pulsate, start, stop]); return React.createElement("span", _extends({ className: clsx(classes.root, className), ref: container }, other), React.createElement(TransitionGroup, { component: null, exit: true }, ripples)); }); process.env.NODE_ENV !== "production" ? TouchRipple.propTypes = { /** * If `true`, the ripple starts at the center of the component * rather than at the point of interaction. */ center: 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 } : void 0; export default withStyles(styles, { flip: false, name: 'MuiTouchRipple' })(React.memo(TouchRipple));
ajax/libs/react-native-web/0.12.3/exports/Image/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 _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 createElement from '../createElement'; import css from '../StyleSheet/css'; import { getAssetByID } from '../../modules/AssetRegistry'; import resolveShadowValue from '../StyleSheet/resolveShadowValue'; import ImageLoader from '../../modules/ImageLoader'; import ImageUriCache from './ImageUriCache'; import PixelRatio from '../PixelRatio'; import StyleSheet from '../StyleSheet'; import TextAncestorContext from '../Text/TextAncestorContext'; import View from '../View'; import React from 'react'; var STATUS_ERRORED = 'ERRORED'; var STATUS_LOADED = 'LOADED'; var STATUS_LOADING = 'LOADING'; var STATUS_PENDING = 'PENDING'; var STATUS_IDLE = 'IDLE'; var getImageState = function getImageState(uri, shouldDisplaySource) { return shouldDisplaySource ? STATUS_LOADED : uri ? STATUS_PENDING : STATUS_IDLE; }; var resolveAssetDimensions = function resolveAssetDimensions(source) { if (typeof source === 'number') { var _getAssetByID = getAssetByID(source), height = _getAssetByID.height, width = _getAssetByID.width; return { height: height, width: width }; } else if (typeof source === 'object') { var _height = source.height, _width = source.width; return { height: _height, width: _width }; } }; var svgDataUriPattern = /^(data:image\/svg\+xml;utf8,)(.*)/; var resolveAssetUri = function resolveAssetUri(source) { var uri = ''; if (typeof source === 'number') { // get the URI from the packager var asset = getAssetByID(source); var scale = asset.scales[0]; if (asset.scales.length > 1) { var preferredScale = PixelRatio.get(); // Get the scale which is closest to the preferred scale scale = asset.scales.reduce(function (prev, curr) { return Math.abs(curr - preferredScale) < Math.abs(prev - preferredScale) ? curr : prev; }); } var scaleSuffix = scale !== 1 ? "@" + scale + "x" : ''; uri = asset ? asset.httpServerLocation + "/" + asset.name + scaleSuffix + "." + asset.type : ''; } else if (typeof source === 'string') { uri = source; } else if (source && typeof source.uri === 'string') { uri = source.uri; } if (uri) { var match = uri.match(svgDataUriPattern); // inline SVG markup may contain characters (e.g., #, ") that need to be escaped if (match) { var prefix = match[1], svg = match[2]; var encodedSvg = encodeURIComponent(svg); return "" + prefix + encodedSvg; } } return uri; }; var filterId = 0; var createTintColorSVG = function createTintColorSVG(tintColor, id) { return tintColor && id != null ? React.createElement("svg", { style: { position: 'absolute', height: 0, visibility: 'hidden', width: 0 } }, React.createElement("defs", null, React.createElement("filter", { id: "tint-" + id }, React.createElement("feFlood", { floodColor: "" + tintColor }), React.createElement("feComposite", { in2: "SourceAlpha", operator: "atop" })))) : null; }; var Image = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Image, _React$Component); Image.getSize = function getSize(uri, success, failure) { ImageLoader.getSize(uri, success, failure); }; Image.prefetch = function prefetch(uri) { return ImageLoader.prefetch(uri).then(function () { // Add the uri to the cache so it can be immediately displayed when used // but also immediately remove it to correctly reflect that it has no active references ImageUriCache.add(uri); ImageUriCache.remove(uri); }); }; Image.queryCache = function queryCache(uris) { var result = {}; uris.forEach(function (u) { if (ImageUriCache.has(u)) { result[u] = 'disk/memory'; } }); return Promise.resolve(result); }; function Image(props, context) { var _this; _this = _React$Component.call(this, props, context) || this; // If an image has been loaded before, render it immediately _this._filterId = 0; _this._imageRef = null; _this._imageRequestId = null; _this._imageState = null; _this._isMounted = false; _this._createLayoutHandler = function (resizeMode) { var onLayout = _this.props.onLayout; if (resizeMode === 'center' || resizeMode === 'repeat' || onLayout) { return function (e) { var layout = e.nativeEvent.layout; onLayout && onLayout(e); _this.setState(function () { return { layout: layout }; }); }; } }; _this._getBackgroundSize = function (resizeMode) { if (_this._imageRef && (resizeMode === 'center' || resizeMode === 'repeat')) { var _this$_imageRef = _this._imageRef, naturalHeight = _this$_imageRef.naturalHeight, naturalWidth = _this$_imageRef.naturalWidth; var _this$state$layout = _this.state.layout, height = _this$state$layout.height, width = _this$state$layout.width; if (naturalHeight && naturalWidth && height && width) { var scaleFactor = Math.min(1, width / naturalWidth, height / naturalHeight); var x = Math.ceil(scaleFactor * naturalWidth); var y = Math.ceil(scaleFactor * naturalHeight); return { backgroundSize: x + "px " + y + "px" }; } } }; _this._onError = function () { var _this$props = _this.props, onError = _this$props.onError, source = _this$props.source; _this._updateImageState(STATUS_ERRORED); if (onError) { onError({ nativeEvent: { error: "Failed to load resource " + resolveAssetUri(source) + " (404)" } }); } _this._onLoadEnd(); }; _this._onLoad = function (e) { var _this$props2 = _this.props, onLoad = _this$props2.onLoad, source = _this$props2.source; var event = { nativeEvent: e }; ImageUriCache.add(resolveAssetUri(source)); _this._updateImageState(STATUS_LOADED); if (onLoad) { onLoad(event); } _this._onLoadEnd(); }; _this._setImageRef = function (ref) { _this._imageRef = ref; }; var uri = resolveAssetUri(props.source); var shouldDisplaySource = ImageUriCache.has(uri); _this.state = { layout: {}, shouldDisplaySource: shouldDisplaySource }; _this._imageState = getImageState(uri, shouldDisplaySource); _this._filterId = filterId; filterId++; return _this; } var _proto = Image.prototype; _proto.componentDidMount = function componentDidMount() { this._isMounted = true; if (this._imageState === STATUS_PENDING) { this._createImageLoader(); } else if (this._imageState === STATUS_LOADED) { this._onLoad({ target: this._imageRef }); } }; _proto.componentDidUpdate = function componentDidUpdate(prevProps) { var prevUri = resolveAssetUri(prevProps.source); var uri = resolveAssetUri(this.props.source); var hasDefaultSource = this.props.defaultSource != null; if (prevUri !== uri) { ImageUriCache.remove(prevUri); var isPreviouslyLoaded = ImageUriCache.has(uri); isPreviouslyLoaded && ImageUriCache.add(uri); this._updateImageState(getImageState(uri, isPreviouslyLoaded), hasDefaultSource); } else if (hasDefaultSource && prevProps.defaultSource !== this.props.defaultSource) { this._updateImageState(this._imageState, hasDefaultSource); } if (this._imageState === STATUS_PENDING) { this._createImageLoader(); } }; _proto.componentWillUnmount = function componentWillUnmount() { var uri = resolveAssetUri(this.props.source); ImageUriCache.remove(uri); this._destroyImageLoader(); this._isMounted = false; }; _proto.renderImage = function renderImage(hasTextAncestor) { var shouldDisplaySource = this.state.shouldDisplaySource; var _this$props3 = this.props, accessibilityLabel = _this$props3.accessibilityLabel, accessibilityRelationship = _this$props3.accessibilityRelationship, accessibilityRole = _this$props3.accessibilityRole, accessibilityState = _this$props3.accessibilityState, accessible = _this$props3.accessible, blurRadius = _this$props3.blurRadius, defaultSource = _this$props3.defaultSource, draggable = _this$props3.draggable, importantForAccessibility = _this$props3.importantForAccessibility, nativeID = _this$props3.nativeID, pointerEvents = _this$props3.pointerEvents, resizeMode = _this$props3.resizeMode, source = _this$props3.source, testID = _this$props3.testID; if (process.env.NODE_ENV !== 'production') { if (this.props.children) { throw new Error('The <Image> component cannot contain children. If you want to render content on top of the image, consider using the <ImageBackground> component or absolute positioning.'); } } var selectedSource = shouldDisplaySource ? source : defaultSource; var displayImageUri = resolveAssetUri(selectedSource); var imageSizeStyle = resolveAssetDimensions(selectedSource); var backgroundImage = displayImageUri ? "url(\"" + displayImageUri + "\")" : null; var flatStyle = _objectSpread({}, StyleSheet.flatten(this.props.style)); var finalResizeMode = resizeMode || flatStyle.resizeMode || 'cover'; // CSS filters var filters = []; var tintColor = flatStyle.tintColor; if (flatStyle.filter) { filters.push(flatStyle.filter); } if (blurRadius) { filters.push("blur(" + blurRadius + "px)"); } if (flatStyle.shadowOffset) { var shadowString = resolveShadowValue(flatStyle); if (shadowString) { filters.push("drop-shadow(" + shadowString + ")"); } } if (flatStyle.tintColor) { filters.push("url(#tint-" + this._filterId + ")"); } // these styles were converted to filters delete flatStyle.shadowColor; delete flatStyle.shadowOpacity; delete flatStyle.shadowOffset; delete flatStyle.shadowRadius; delete flatStyle.tintColor; // these styles are not supported on View delete flatStyle.overlayColor; delete flatStyle.resizeMode; // Accessibility image allows users to trigger the browser's image context menu var hiddenImage = displayImageUri ? createElement('img', { alt: accessibilityLabel || '', classList: [classes.accessibilityImage], draggable: draggable || false, ref: this._setImageRef, src: displayImageUri }) : null; return React.createElement(View, { accessibilityLabel: accessibilityLabel, accessibilityRelationship: accessibilityRelationship, accessibilityRole: accessibilityRole, accessibilityState: accessibilityState, accessible: accessible, importantForAccessibility: importantForAccessibility, nativeID: nativeID, onLayout: this._createLayoutHandler(finalResizeMode), pointerEvents: pointerEvents, style: [styles.root, hasTextAncestor && styles.inline, imageSizeStyle, flatStyle], testID: testID }, React.createElement(View, { style: [styles.image, resizeModeStyles[finalResizeMode], this._getBackgroundSize(finalResizeMode), backgroundImage && { backgroundImage: backgroundImage }, filters.length > 0 && { filter: filters.join(' ') }] }), hiddenImage, createTintColorSVG(tintColor, this._filterId)); }; _proto.render = function render() { var _this2 = this; return React.createElement(TextAncestorContext.Consumer, null, function (hasTextAncestor) { return _this2.renderImage(hasTextAncestor); }); }; _proto._createImageLoader = function _createImageLoader() { var source = this.props.source; this._destroyImageLoader(); var uri = resolveAssetUri(source); this._imageRequestId = ImageLoader.load(uri, this._onLoad, this._onError); this._onLoadStart(); }; _proto._destroyImageLoader = function _destroyImageLoader() { if (this._imageRequestId) { ImageLoader.abort(this._imageRequestId); this._imageRequestId = null; } }; _proto._onLoadEnd = function _onLoadEnd() { var onLoadEnd = this.props.onLoadEnd; if (onLoadEnd) { onLoadEnd(); } }; _proto._onLoadStart = function _onLoadStart() { var _this$props4 = this.props, defaultSource = _this$props4.defaultSource, onLoadStart = _this$props4.onLoadStart; this._updateImageState(STATUS_LOADING, defaultSource != null); if (onLoadStart) { onLoadStart(); } }; _proto._updateImageState = function _updateImageState(status, hasDefaultSource) { if (hasDefaultSource === void 0) { hasDefaultSource = false; } this._imageState = status; var shouldDisplaySource = this._imageState === STATUS_LOADED || this._imageState === STATUS_LOADING && !hasDefaultSource; // only triggers a re-render when the image is loading and has no default image (to support PJPEG), loaded, or failed if (shouldDisplaySource !== this.state.shouldDisplaySource) { if (this._isMounted) { this.setState(function () { return { shouldDisplaySource: shouldDisplaySource }; }); } } }; return Image; }(React.Component); Image.displayName = 'Image'; var classes = css.create({ accessibilityImage: _objectSpread({}, StyleSheet.absoluteFillObject, { height: '100%', opacity: 0, width: '100%', zIndex: -1 }) }); var styles = StyleSheet.create({ root: { flexBasis: 'auto', overflow: 'hidden', zIndex: 0 }, inline: { display: 'inline-flex' }, image: _objectSpread({}, StyleSheet.absoluteFillObject, { backgroundColor: 'transparent', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', backgroundSize: 'cover', height: '100%', width: '100%', zIndex: -1 }) }); var resizeModeStyles = StyleSheet.create({ center: { backgroundSize: 'auto' }, contain: { backgroundSize: 'contain' }, cover: { backgroundSize: 'cover' }, none: { backgroundPosition: '0 0', backgroundSize: 'auto' }, repeat: { backgroundPosition: '0 0', backgroundRepeat: 'repeat', backgroundSize: 'auto' }, stretch: { backgroundSize: '100% 100%' } }); export default applyNativeMethods(Image);
ajax/libs/material-ui/4.11.3-deprecations.0/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'; var warnedOnce = 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> * ); * } * ``` * * @deprecated */ 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() { if (process.env.NODE_ENV !== 'production') { if (!warnedOnce) { warnedOnce = true; console.warn(['Material-UI: The RootRef component is deprecated.', 'The component relies on the ReactDOM.findDOMNode API which is deprecated in React.StrictMode.', 'Instead, you can get a reference to the underlying DOM node of the components via the `ref` prop.'].join('/n')); } } 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/CheckBox.js
cdnjs/cdnjs
import React from 'react'; import createSvgIcon from './createSvgIcon'; /** * @ignore - internal component. */ export default createSvgIcon(React.createElement("path", { d: "M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" }), 'CheckBox');
ajax/libs/primereact/7.0.1/listbox/listbox.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { FilterService } from 'primereact/api'; import { DomHandler, classNames, ObjectUtils } from 'primereact/utils'; import { Ripple } from 'primereact/ripple'; import { InputText } from 'primereact/inputtext'; import { tip } from 'primereact/tooltip'; import { VirtualScroller } from 'primereact/virtualscroller'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _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$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 ListBoxItem = /*#__PURE__*/function (_Component) { _inherits(ListBoxItem, _Component); var _super = _createSuper$2(ListBoxItem); function ListBoxItem(props) { var _this; _classCallCheck(this, ListBoxItem); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(ListBoxItem, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, option: this.props.option }); } event.preventDefault(); } }, { key: "onTouchEnd", value: function onTouchEnd(event) { if (this.props.onTouchEnd) { this.props.onTouchEnd({ originalEvent: event, option: this.props.option }); } } }, { key: "onKeyDown", value: function onKeyDown(event) { var item = event.currentTarget; switch (event.which) { //down case 40: var nextItem = this.findNextItem(item); if (nextItem) { nextItem.focus(); } event.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(item); if (prevItem) { prevItem.focus(); } event.preventDefault(); break; //enter case 13: this.onClick(event); event.preventDefault(); break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return DomHandler.hasClass(nextItem, 'p-disabled') || DomHandler.hasClass(nextItem, 'p-listbox-item-group') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return DomHandler.hasClass(prevItem, 'p-disabled') || DomHandler.hasClass(prevItem, 'p-listbox-item-group') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "render", value: function render() { var className = classNames('p-listbox-item', { 'p-highlight': this.props.selected, 'p-disabled': this.props.disabled }, this.props.option.className); var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props.option) : this.props.label; return /*#__PURE__*/React.createElement("li", { className: className, onClick: this.onClick, onTouchEnd: this.onTouchEnd, onKeyDown: this.onKeyDown, tabIndex: this.props.tabIndex, "aria-label": this.props.label, key: this.props.label, role: "option", "aria-selected": this.props.selected }, content, /*#__PURE__*/React.createElement(Ripple, null)); } }]); return ListBoxItem; }(Component); _defineProperty(ListBoxItem, "defaultProps", { option: null, label: null, selected: false, disabled: false, tabIndex: null, onClick: null, onTouchEnd: null, 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 ListBoxHeader = /*#__PURE__*/function (_Component) { _inherits(ListBoxHeader, _Component); var _super = _createSuper$1(ListBoxHeader); function ListBoxHeader(props) { var _this; _classCallCheck(this, ListBoxHeader); _this = _super.call(this, props); _this.onFilter = _this.onFilter.bind(_assertThisInitialized(_this)); return _this; } _createClass(ListBoxHeader, [{ key: "onFilter", value: function onFilter(event) { if (this.props.onFilter) { this.props.onFilter({ originalEvent: event, value: event.target.value }); } } }, { key: "render", value: function render() { return /*#__PURE__*/React.createElement("div", { className: "p-listbox-header" }, /*#__PURE__*/React.createElement("div", { className: "p-listbox-filter-container" }, /*#__PURE__*/React.createElement(InputText, { type: "text", value: this.props.filter, onChange: this.onFilter, className: "p-listbox-filter", disabled: this.props.disabled, placeholder: this.props.filterPlaceholder }), /*#__PURE__*/React.createElement("span", { className: "p-listbox-filter-icon pi pi-search" }))); } }]); return ListBoxHeader; }(Component); _defineProperty(ListBoxHeader, "defaultProps", { filter: null, filterPlaceholder: null, disabled: false, onFilter: null }); function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var ListBox = /*#__PURE__*/function (_Component) { _inherits(ListBox, _Component); var _super = _createSuper(ListBox); function ListBox(props) { var _this; _classCallCheck(this, ListBox); _this = _super.call(this, props); _this.state = {}; if (!_this.props.onFilterValueChange) { _this.state.filterValue = ''; } _this.onFilter = _this.onFilter.bind(_assertThisInitialized(_this)); _this.onOptionSelect = _this.onOptionSelect.bind(_assertThisInitialized(_this)); _this.onOptionTouchEnd = _this.onOptionTouchEnd.bind(_assertThisInitialized(_this)); return _this; } _createClass(ListBox, [{ 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: "getFilterValue", value: function getFilterValue() { return (this.props.onFilterValueChange ? this.props.filterValue : this.state.filterValue) || ''; } }, { key: "onOptionSelect", value: function onOptionSelect(event) { var option = event.option; if (this.props.disabled || this.isOptionDisabled(option)) { return; } if (this.props.multiple) this.onOptionSelectMultiple(event.originalEvent, option);else this.onOptionSelectSingle(event.originalEvent, option); this.optionTouched = false; } }, { key: "onOptionTouchEnd", value: function onOptionTouchEnd() { if (this.props.disabled) { return; } this.optionTouched = true; } }, { key: "onOptionSelectSingle", value: function onOptionSelectSingle(event, option) { var selected = this.isSelected(option); var valueChanged = false; var value = null; var metaSelection = this.optionTouched ? false : this.props.metaKeySelection; if (metaSelection) { var metaKey = event.metaKey || event.ctrlKey; if (selected) { if (metaKey) { value = null; valueChanged = true; } } else { value = this.getOptionValue(option); valueChanged = true; } } else { value = selected ? null : this.getOptionValue(option); valueChanged = true; } if (valueChanged) { this.updateModel(event, value); } } }, { key: "onOptionSelectMultiple", value: function onOptionSelectMultiple(event, option) { var selected = this.isSelected(option); var valueChanged = false; var value = null; var metaSelection = this.optionTouched ? false : this.props.metaKeySelection; if (metaSelection) { var metaKey = event.metaKey || event.ctrlKey; if (selected) { if (metaKey) value = this.removeOption(option);else value = [this.getOptionValue(option)]; valueChanged = true; } else { value = metaKey ? this.props.value || [] : []; value = [].concat(_toConsumableArray(value), [this.getOptionValue(option)]); valueChanged = true; } } else { if (selected) value = this.removeOption(option);else value = [].concat(_toConsumableArray(this.props.value || []), [this.getOptionValue(option)]); valueChanged = true; } if (valueChanged) { this.props.onChange({ originalEvent: event, value: value, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: value } }); } } }, { key: "onFilter", value: function onFilter(event) { var originalEvent = event.originalEvent, value = event.value; if (this.props.onFilterValueChange) { this.props.onFilterValueChange({ originalEvent: originalEvent, value: value }); } else { this.setState({ filterValue: value }); } } }, { key: "updateModel", value: function updateModel(event, value) { if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: value, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: value } }); } } }, { key: "removeOption", value: function removeOption(option) { var _this2 = this; return this.props.value.filter(function (val) { return !ObjectUtils.equals(val, _this2.getOptionValue(option), _this2.props.dataKey); }); } }, { key: "isSelected", value: function isSelected(option) { var selected = false; var optionValue = this.getOptionValue(option); if (this.props.multiple) { if (this.props.value) { 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: "filter", value: function filter(option) { var filterValue = this.getFilterValue().trim().toLocaleLowerCase(this.props.filterLocale); var optionLabel = this.getOptionLabel(option).toLocaleLowerCase(this.props.filterLocale); return optionLabel.indexOf(filterValue) > -1; } }, { key: "hasFilter", value: function hasFilter() { var filter = this.getFilterValue(); return filter && filter.trim().length > 0; } }, { 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: "getOptionRenderKey", value: function getOptionRenderKey(option) { return this.props.dataKey ? ObjectUtils.resolveFieldData(option, this.props.dataKey) : this.getOptionLabel(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: "getOptionGroupRenderKey", value: function getOptionGroupRenderKey(optionGroup) { return ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupLabel", value: function getOptionGroupLabel(optionGroup) { return ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupChildren", value: function getOptionGroupChildren(optionGroup) { return ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupChildren); } }, { key: "getVisibleOptions", value: function getVisibleOptions() { if (this.hasFilter()) { var filterValue = this.getFilterValue().trim().toLocaleLowerCase(this.props.filterLocale); var searchFields = this.props.filterBy ? this.props.filterBy.split(',') : [this.props.optionLabel || 'label']; if (this.props.optionGroupLabel) { var filteredGroups = []; var _iterator2 = _createForOfIteratorHelper(this.props.options), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var optgroup = _step2.value; var filteredSubOptions = FilterService.filter(this.getOptionGroupChildren(optgroup), searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); if (filteredSubOptions && filteredSubOptions.length) { filteredGroups.push(_objectSpread(_objectSpread({}, optgroup), { items: filteredSubOptions })); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return filteredGroups; } else { return FilterService.filter(this.props.options, searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); } } else { return this.props.options; } } }, { key: "renderGroupChildren", value: function renderGroupChildren(optionGroup) { var _this3 = this; var groupChildren = this.getOptionGroupChildren(optionGroup); return groupChildren.map(function (option, j) { var optionLabel = _this3.getOptionLabel(option); var optionKey = j + '_' + _this3.getOptionRenderKey(option); var disabled = _this3.isOptionDisabled(option); var tabIndex = disabled ? null : _this3.props.tabIndex || 0; return /*#__PURE__*/React.createElement(ListBoxItem, { key: optionKey, label: optionLabel, option: option, template: _this3.props.itemTemplate, selected: _this3.isSelected(option), onClick: _this3.onOptionSelect, onTouchEnd: _this3.onOptionTouchEnd, tabIndex: tabIndex, disabled: disabled }); }); } }, { key: "renderItem", value: function renderItem(option, index) { if (this.props.optionGroupLabel) { var groupContent = this.props.optionGroupTemplate ? ObjectUtils.getJSXElement(this.props.optionGroupTemplate, option, index) : this.getOptionGroupLabel(option); var groupChildrenContent = this.renderGroupChildren(option); var key = index + '_' + this.getOptionGroupRenderKey(option); return /*#__PURE__*/React.createElement(React.Fragment, { key: key }, /*#__PURE__*/React.createElement("li", { className: "p-listbox-item-group" }, groupContent), groupChildrenContent); } else { var optionLabel = this.getOptionLabel(option); var optionKey = index + '_' + this.getOptionRenderKey(option); var disabled = this.isOptionDisabled(option); var tabIndex = disabled ? null : this.props.tabIndex || 0; return /*#__PURE__*/React.createElement(ListBoxItem, { key: optionKey, label: optionLabel, option: option, template: this.props.itemTemplate, selected: this.isSelected(option), onClick: this.onOptionSelect, onTouchEnd: this.onOptionTouchEnd, tabIndex: tabIndex, disabled: disabled }); } } }, { key: "renderItems", value: function renderItems(visibleOptions) { var _this4 = this; if (visibleOptions && visibleOptions.length) { return visibleOptions.map(function (option, index) { return _this4.renderItem(option, index); }); } return null; } }, { key: "renderList", value: function renderList(visibleOptions) { var _this5 = this; if (this.props.virtualScrollerOptions) { var virtualScrollerProps = _objectSpread(_objectSpread({}, this.props.virtualScrollerOptions), { items: visibleOptions, onLazyLoad: function onLazyLoad(event) { return _this5.props.virtualScrollerOptions.onLazyLoad(_objectSpread(_objectSpread({}, event), { filter: _this5.getFilterValue() })); }, itemTemplate: function itemTemplate(item, options) { return item && _this5.renderItem(item, options.index); }, contentTemplate: function contentTemplate(options) { var className = classNames('p-listbox-list', options.className); return /*#__PURE__*/React.createElement("ul", { ref: options.contentRef, className: className, role: "listbox", "aria-multiselectable": _this5.props.multiple }, options.children); } }); return /*#__PURE__*/React.createElement(VirtualScroller, _extends({ ref: function ref(el) { return _this5.virtualScrollerRef = el; } }, virtualScrollerProps)); } else { var items = this.renderItems(visibleOptions); return /*#__PURE__*/React.createElement("ul", { className: "p-listbox-list", role: "listbox", "aria-multiselectable": this.props.multiple }, items); } } }, { key: "render", value: function render() { var _this6 = this; var className = classNames('p-listbox p-component', { 'p-disabled': this.props.disabled }, this.props.className); var listClassName = classNames('p-listbox-list-wrapper', this.props.listClassName); var visibleOptions = this.getVisibleOptions(); var list = this.renderList(visibleOptions); var header; if (this.props.filter) { header = /*#__PURE__*/React.createElement(ListBoxHeader, { filter: this.getFilterValue(), onFilter: this.onFilter, disabled: this.props.disabled, filterPlaceholder: this.props.filterPlaceholder }); } return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this6.element = el; }, id: this.props.id, className: className, style: this.props.style }, header, /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this6.wrapper = el; }, className: listClassName, style: this.props.listStyle }, list)); } }]); return ListBox; }(Component); _defineProperty(ListBox, "defaultProps", { id: null, value: null, options: null, optionLabel: null, optionValue: null, optionDisabled: null, optionGroupLabel: null, optionGroupChildren: null, optionGroupTemplate: null, itemTemplate: null, style: null, listStyle: null, listClassName: null, className: null, virtualScrollerOptions: null, disabled: null, dataKey: null, multiple: false, metaKeySelection: false, filter: false, filterBy: null, filterValue: null, filterMatchMode: 'contains', filterPlaceholder: null, filterLocale: undefined, tabIndex: 0, tooltip: null, tooltipOptions: null, ariaLabelledBy: null, onChange: null, onFilterValueChange: null }); export { ListBox };
ajax/libs/react-native-web/0.0.0-20f889ecc/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.2.0/listbox/listbox.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { FilterService } from 'primereact/api'; import { DomHandler, classNames, ObjectUtils } from 'primereact/utils'; import { Ripple } from 'primereact/ripple'; import { InputText } from 'primereact/inputtext'; import { tip } from 'primereact/tooltip'; import { VirtualScroller } from 'primereact/virtualscroller'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$1(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _createSuper$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 ListBoxItem = /*#__PURE__*/function (_Component) { _inherits(ListBoxItem, _Component); var _super = _createSuper$2(ListBoxItem); function ListBoxItem(props) { var _this; _classCallCheck(this, ListBoxItem); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(ListBoxItem, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, option: this.props.option }); } event.preventDefault(); } }, { key: "onTouchEnd", value: function onTouchEnd(event) { if (this.props.onTouchEnd) { this.props.onTouchEnd({ originalEvent: event, option: this.props.option }); } } }, { key: "onKeyDown", value: function onKeyDown(event) { var item = event.currentTarget; switch (event.which) { //down case 40: var nextItem = this.findNextItem(item); if (nextItem) { nextItem.focus(); } event.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(item); if (prevItem) { prevItem.focus(); } event.preventDefault(); break; //enter case 13: this.onClick(event); event.preventDefault(); break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return DomHandler.hasClass(nextItem, 'p-disabled') || DomHandler.hasClass(nextItem, 'p-listbox-item-group') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return DomHandler.hasClass(prevItem, 'p-disabled') || DomHandler.hasClass(prevItem, 'p-listbox-item-group') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "render", value: function render() { var className = classNames('p-listbox-item', { 'p-highlight': this.props.selected, 'p-disabled': this.props.disabled }, this.props.option.className); var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props.option) : this.props.label; return /*#__PURE__*/React.createElement("li", { className: className, onClick: this.onClick, onTouchEnd: this.onTouchEnd, onKeyDown: this.onKeyDown, tabIndex: this.props.tabIndex, "aria-label": this.props.label, key: this.props.label, role: "option", "aria-selected": this.props.selected }, content, /*#__PURE__*/React.createElement(Ripple, null)); } }]); return ListBoxItem; }(Component); _defineProperty(ListBoxItem, "defaultProps", { option: null, label: null, selected: false, disabled: false, tabIndex: null, onClick: null, onTouchEnd: null, 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 ListBoxHeader = /*#__PURE__*/function (_Component) { _inherits(ListBoxHeader, _Component); var _super = _createSuper$1(ListBoxHeader); function ListBoxHeader(props) { var _this; _classCallCheck(this, ListBoxHeader); _this = _super.call(this, props); _this.onFilter = _this.onFilter.bind(_assertThisInitialized(_this)); return _this; } _createClass(ListBoxHeader, [{ key: "onFilter", value: function onFilter(event) { if (this.props.onFilter) { this.props.onFilter({ originalEvent: event, value: event.target.value }); } } }, { key: "render", value: function render() { return /*#__PURE__*/React.createElement("div", { className: "p-listbox-header" }, /*#__PURE__*/React.createElement("div", { className: "p-listbox-filter-container" }, /*#__PURE__*/React.createElement(InputText, { type: "text", value: this.props.filter, onChange: this.onFilter, className: "p-listbox-filter", disabled: this.props.disabled, placeholder: this.props.filterPlaceholder }), /*#__PURE__*/React.createElement("span", { className: "p-listbox-filter-icon pi pi-search" }))); } }]); return ListBoxHeader; }(Component); _defineProperty(ListBoxHeader, "defaultProps", { filter: null, filterPlaceholder: null, disabled: false, onFilter: 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 ListBox = /*#__PURE__*/function (_Component) { _inherits(ListBox, _Component); var _super = _createSuper(ListBox); function ListBox(props) { var _this; _classCallCheck(this, ListBox); _this = _super.call(this, props); _this.state = {}; if (!_this.props.onFilterValueChange) { _this.state.filterValue = ''; } _this.onFilter = _this.onFilter.bind(_assertThisInitialized(_this)); _this.onOptionSelect = _this.onOptionSelect.bind(_assertThisInitialized(_this)); _this.onOptionTouchEnd = _this.onOptionTouchEnd.bind(_assertThisInitialized(_this)); return _this; } _createClass(ListBox, [{ 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: "getFilterValue", value: function getFilterValue() { return (this.props.onFilterValueChange ? this.props.filterValue : this.state.filterValue) || ''; } }, { key: "onOptionSelect", value: function onOptionSelect(event) { var option = event.option; if (this.props.disabled || this.isOptionDisabled(option)) { return; } if (this.props.multiple) this.onOptionSelectMultiple(event.originalEvent, option);else this.onOptionSelectSingle(event.originalEvent, option); this.optionTouched = false; } }, { key: "onOptionTouchEnd", value: function onOptionTouchEnd() { if (this.props.disabled) { return; } this.optionTouched = true; } }, { key: "onOptionSelectSingle", value: function onOptionSelectSingle(event, option) { var selected = this.isSelected(option); var valueChanged = false; var value = null; var metaSelection = this.optionTouched ? false : this.props.metaKeySelection; if (metaSelection) { var metaKey = event.metaKey || event.ctrlKey; if (selected) { if (metaKey) { value = null; valueChanged = true; } } else { value = this.getOptionValue(option); valueChanged = true; } } else { value = selected ? null : this.getOptionValue(option); valueChanged = true; } if (valueChanged) { this.updateModel(event, value); } } }, { key: "onOptionSelectMultiple", value: function onOptionSelectMultiple(event, option) { var selected = this.isSelected(option); var valueChanged = false; var value = null; var metaSelection = this.optionTouched ? false : this.props.metaKeySelection; if (metaSelection) { var metaKey = event.metaKey || event.ctrlKey; if (selected) { if (metaKey) value = this.removeOption(option);else value = [this.getOptionValue(option)]; valueChanged = true; } else { value = metaKey ? this.props.value || [] : []; value = [].concat(_toConsumableArray(value), [this.getOptionValue(option)]); valueChanged = true; } } else { if (selected) value = this.removeOption(option);else value = [].concat(_toConsumableArray(this.props.value || []), [this.getOptionValue(option)]); valueChanged = true; } if (valueChanged) { this.props.onChange({ originalEvent: event, value: value, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: value } }); } } }, { key: "onFilter", value: function onFilter(event) { var originalEvent = event.originalEvent, value = event.value; if (this.props.onFilterValueChange) { this.props.onFilterValueChange({ originalEvent: originalEvent, value: value }); } else { this.setState({ filterValue: value }); } } }, { key: "updateModel", value: function updateModel(event, value) { if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: value, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: value } }); } } }, { key: "removeOption", value: function removeOption(option) { var _this2 = this; return this.props.value.filter(function (val) { return !ObjectUtils.equals(val, _this2.getOptionValue(option), _this2.props.dataKey); }); } }, { key: "isSelected", value: function isSelected(option) { var selected = false; var optionValue = this.getOptionValue(option); if (this.props.multiple) { if (this.props.value) { 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: "filter", value: function filter(option) { var filterValue = this.getFilterValue().trim().toLocaleLowerCase(this.props.filterLocale); var optionLabel = this.getOptionLabel(option).toLocaleLowerCase(this.props.filterLocale); return optionLabel.indexOf(filterValue) > -1; } }, { key: "hasFilter", value: function hasFilter() { var filter = this.getFilterValue(); return filter && filter.trim().length > 0; } }, { 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: "getOptionRenderKey", value: function getOptionRenderKey(option) { return this.props.dataKey ? ObjectUtils.resolveFieldData(option, this.props.dataKey) : this.getOptionLabel(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: "getOptionGroupRenderKey", value: function getOptionGroupRenderKey(optionGroup) { return ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupLabel", value: function getOptionGroupLabel(optionGroup) { return ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupChildren", value: function getOptionGroupChildren(optionGroup) { return ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupChildren); } }, { key: "getVisibleOptions", value: function getVisibleOptions() { if (this.hasFilter()) { var filterValue = this.getFilterValue().trim().toLocaleLowerCase(this.props.filterLocale); var searchFields = this.props.filterBy ? this.props.filterBy.split(',') : [this.props.optionLabel || 'label']; if (this.props.optionGroupLabel) { var filteredGroups = []; var _iterator2 = _createForOfIteratorHelper(this.props.options), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var optgroup = _step2.value; var filteredSubOptions = FilterService.filter(this.getOptionGroupChildren(optgroup), searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); if (filteredSubOptions && filteredSubOptions.length) { filteredGroups.push(_objectSpread(_objectSpread({}, optgroup), { items: filteredSubOptions })); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return filteredGroups; } else { return FilterService.filter(this.props.options, searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); } } else { return this.props.options; } } }, { key: "renderGroupChildren", value: function renderGroupChildren(optionGroup) { var _this3 = this; var groupChildren = this.getOptionGroupChildren(optionGroup); return groupChildren.map(function (option, j) { var optionLabel = _this3.getOptionLabel(option); var optionKey = j + '_' + _this3.getOptionRenderKey(option); var disabled = _this3.isOptionDisabled(option); var tabIndex = disabled ? null : _this3.props.tabIndex || 0; return /*#__PURE__*/React.createElement(ListBoxItem, { key: optionKey, label: optionLabel, option: option, template: _this3.props.itemTemplate, selected: _this3.isSelected(option), onClick: _this3.onOptionSelect, onTouchEnd: _this3.onOptionTouchEnd, tabIndex: tabIndex, disabled: disabled }); }); } }, { key: "renderItem", value: function renderItem(option, index) { if (this.props.optionGroupLabel) { var groupContent = this.props.optionGroupTemplate ? ObjectUtils.getJSXElement(this.props.optionGroupTemplate, option, index) : this.getOptionGroupLabel(option); var groupChildrenContent = this.renderGroupChildren(option); var key = index + '_' + this.getOptionGroupRenderKey(option); return /*#__PURE__*/React.createElement(React.Fragment, { key: key }, /*#__PURE__*/React.createElement("li", { className: "p-listbox-item-group" }, groupContent), groupChildrenContent); } else { var optionLabel = this.getOptionLabel(option); var optionKey = index + '_' + this.getOptionRenderKey(option); var disabled = this.isOptionDisabled(option); var tabIndex = disabled ? null : this.props.tabIndex || 0; return /*#__PURE__*/React.createElement(ListBoxItem, { key: optionKey, label: optionLabel, option: option, template: this.props.itemTemplate, selected: this.isSelected(option), onClick: this.onOptionSelect, onTouchEnd: this.onOptionTouchEnd, tabIndex: tabIndex, disabled: disabled }); } } }, { key: "renderItems", value: function renderItems(visibleOptions) { var _this4 = this; if (visibleOptions && visibleOptions.length) { return visibleOptions.map(function (option, index) { return _this4.renderItem(option, index); }); } return null; } }, { key: "renderList", value: function renderList(visibleOptions) { var _this5 = this; if (this.props.virtualScrollerOptions) { var virtualScrollerProps = _objectSpread(_objectSpread({}, this.props.virtualScrollerOptions), { items: visibleOptions, onLazyLoad: function onLazyLoad(event) { return _this5.props.virtualScrollerOptions.onLazyLoad(_objectSpread(_objectSpread({}, event), { filter: _this5.getFilterValue() })); }, itemTemplate: function itemTemplate(item, options) { return item && _this5.renderItem(item, options.index); }, contentTemplate: function contentTemplate(options) { var className = classNames('p-listbox-list', options.className); return /*#__PURE__*/React.createElement("ul", { ref: options.contentRef, className: className, role: "listbox", "aria-multiselectable": _this5.props.multiple }, options.children); } }); return /*#__PURE__*/React.createElement(VirtualScroller, _extends({ ref: function ref(el) { return _this5.virtualScrollerRef = el; } }, virtualScrollerProps)); } else { var items = this.renderItems(visibleOptions); return /*#__PURE__*/React.createElement("ul", { className: "p-listbox-list", role: "listbox", "aria-multiselectable": this.props.multiple }, items); } } }, { key: "render", value: function render() { var _this6 = this; var className = classNames('p-listbox p-component', { 'p-disabled': this.props.disabled }, this.props.className); var listClassName = classNames('p-listbox-list-wrapper', this.props.listClassName); var visibleOptions = this.getVisibleOptions(); var list = this.renderList(visibleOptions); var header; if (this.props.filter) { header = /*#__PURE__*/React.createElement(ListBoxHeader, { filter: this.getFilterValue(), onFilter: this.onFilter, disabled: this.props.disabled, filterPlaceholder: this.props.filterPlaceholder }); } return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this6.element = el; }, id: this.props.id, className: className, style: this.props.style }, header, /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this6.wrapper = el; }, className: listClassName, style: this.props.listStyle }, list)); } }]); return ListBox; }(Component); _defineProperty(ListBox, "defaultProps", { id: null, value: null, options: null, optionLabel: null, optionValue: null, optionDisabled: null, optionGroupLabel: null, optionGroupChildren: null, optionGroupTemplate: null, itemTemplate: null, style: null, listStyle: null, listClassName: null, className: null, virtualScrollerOptions: null, disabled: null, dataKey: null, multiple: false, metaKeySelection: false, filter: false, filterBy: null, filterValue: null, filterMatchMode: 'contains', filterPlaceholder: null, filterLocale: undefined, tabIndex: 0, tooltip: null, tooltipOptions: null, ariaLabelledBy: null, onChange: null, onFilterValueChange: null }); export { ListBox };
ajax/libs/material-ui/4.9.3/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/esm/MobileStepper/MobileStepper.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray"; 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 Paper from '../Paper'; import capitalize from '../utils/capitalize'; import LinearProgress from '../LinearProgress'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', background: theme.palette.background.default, padding: 8 }, /* Styles applied to the root element if `position="bottom"`. */ positionBottom: { position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: theme.zIndex.mobileStepper }, /* Styles applied to the root element if `position="top"`. */ positionTop: { position: 'fixed', top: 0, left: 0, right: 0, zIndex: theme.zIndex.mobileStepper }, /* Styles applied to the root element if `position="static"`. */ positionStatic: {}, /* Styles applied to the dots container if `variant="dots"`. */ dots: { display: 'flex', flexDirection: 'row' }, /* Styles applied to each dot if `variant="dots"`. */ dot: { backgroundColor: theme.palette.action.disabled, borderRadius: '50%', width: 8, height: 8, margin: '0 2px' }, /* Styles applied to a dot if `variant="dots"` and this is the active step. */ dotActive: { backgroundColor: theme.palette.primary.main }, /* Styles applied to the Linear Progress component if `variant="progress"`. */ progress: { width: '50%' } }; }; var MobileStepper = React.forwardRef(function MobileStepper(props, ref) { var _props$activeStep = props.activeStep, activeStep = _props$activeStep === void 0 ? 0 : _props$activeStep, backButton = props.backButton, classes = props.classes, className = props.className, LinearProgressProps = props.LinearProgressProps, nextButton = props.nextButton, _props$position = props.position, position = _props$position === void 0 ? 'bottom' : _props$position, steps = props.steps, _props$variant = props.variant, variant = _props$variant === void 0 ? 'dots' : _props$variant, other = _objectWithoutProperties(props, ["activeStep", "backButton", "classes", "className", "LinearProgressProps", "nextButton", "position", "steps", "variant"]); return React.createElement(Paper, _extends({ square: true, elevation: 0, className: clsx(classes.root, classes["position".concat(capitalize(position))], className), ref: ref }, other), backButton, variant === 'text' && React.createElement(React.Fragment, null, activeStep + 1, " / ", steps), variant === 'dots' && React.createElement("div", { className: classes.dots }, _toConsumableArray(new Array(steps)).map(function (_, index) { return React.createElement("div", { key: index, className: clsx(classes.dot, index === activeStep && classes.dotActive) }); })), variant === 'progress' && React.createElement(LinearProgress, _extends({ className: classes.progress, variant: "determinate", value: Math.ceil(activeStep / (steps - 1) * 100) }, LinearProgressProps)), nextButton); }); process.env.NODE_ENV !== "production" ? MobileStepper.propTypes = { /** * Set the active step (zero based index). * Defines which dot is highlighted when the variant is 'dots'. */ activeStep: PropTypes.number, /** * A back button element. For instance, it can be a `Button` or an `IconButton`. */ backButton: 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, /** * Props applied to the `LinearProgress` element. */ LinearProgressProps: PropTypes.object, /** * A next button element. For instance, it can be a `Button` or an `IconButton`. */ nextButton: PropTypes.node, /** * Set the positioning type. */ position: PropTypes.oneOf(['bottom', 'top', 'static']), /** * The total steps. */ steps: PropTypes.number.isRequired, /** * The variant to use. */ variant: PropTypes.oneOf(['text', 'dots', 'progress']) } : void 0; export default withStyles(styles, { name: 'MuiMobileStepper' })(MobileStepper);
ajax/libs/material-ui/4.9.2/esm/test-utils/createMount.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck"; import _createClass from "@babel/runtime/helpers/esm/createClass"; import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn"; import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf"; import _inherits from "@babel/runtime/helpers/esm/inherits"; import React from 'react'; import ReactDOM from 'react-dom'; import * as PropTypes from 'prop-types'; import { mount as enzymeMount } from 'enzyme'; /** * Can't just mount <React.Fragment>{node}</React.Fragment> * because that swallows wrapper.setProps * * why class component: * https://github.com/airbnb/enzyme/issues/2043 */ // eslint-disable-next-line react/prefer-stateless-function var Mode = /*#__PURE__*/ function (_React$Component) { _inherits(Mode, _React$Component); function Mode() { _classCallCheck(this, Mode); return _possibleConstructorReturn(this, _getPrototypeOf(Mode).apply(this, arguments)); } _createClass(Mode, [{ key: "render", value: function render() { // Excess props will come from e.g. enzyme setProps var _this$props = this.props, __element = _this$props.__element, __strict = _this$props.__strict, other = _objectWithoutProperties(_this$props, ["__element", "__strict"]); var Component = __strict ? React.StrictMode : React.Fragment; return React.createElement(Component, null, React.cloneElement(__element, other)); } }]); return Mode; }(React.Component); // Generate an enhanced mount function. process.env.NODE_ENV !== "production" ? Mode.propTypes = { /** * this is essentially children. However we can't use children because then * using `wrapper.setProps({ children })` would work differently if this component * would be the root. */ __element: PropTypes.element.isRequired, __strict: PropTypes.bool.isRequired } : void 0; export default function createMount() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _options$mount = options.mount, mount = _options$mount === void 0 ? enzymeMount : _options$mount, globalStrict = options.strict, globalEnzymeOptions = _objectWithoutProperties(options, ["mount", "strict"]); var attachTo = document.createElement('div'); attachTo.className = 'app'; attachTo.setAttribute('id', 'app'); document.body.insertBefore(attachTo, document.body.firstChild); var mountWithContext = function mountWithContext(node) { var localOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _localOptions$disable = localOptions.disableUnnmount, disableUnnmount = _localOptions$disable === void 0 ? false : _localOptions$disable, _localOptions$strict = localOptions.strict, strict = _localOptions$strict === void 0 ? globalStrict : _localOptions$strict, localEnzymeOptions = _objectWithoutProperties(localOptions, ["disableUnnmount", "strict"]); if (!disableUnnmount) { ReactDOM.unmountComponentAtNode(attachTo); } // some tests require that no other components are in the tree // e.g. when doing .instance(), .state() etc. return mount(strict == null ? node : React.createElement(Mode, { __element: node, __strict: Boolean(strict) }), _extends({ attachTo: attachTo }, globalEnzymeOptions, {}, localEnzymeOptions)); }; mountWithContext.attachTo = attachTo; mountWithContext.cleanUp = function () { ReactDOM.unmountComponentAtNode(attachTo); attachTo.parentElement.removeChild(attachTo); }; return mountWithContext; }
ajax/libs/material-ui/4.9.3/esm/internal/svg-icons/RadioButtonChecked.js
cdnjs/cdnjs
import React from 'react'; import createSvgIcon from './createSvgIcon'; /** * @ignore - internal component. */ export default createSvgIcon(React.createElement("path", { d: "M8.465 8.465C9.37 7.56 10.62 7 12 7C14.76 7 17 9.24 17 12C17 13.38 16.44 14.63 15.535 15.535C14.63 16.44 13.38 17 12 17C9.24 17 7 14.76 7 12C7 10.62 7.56 9.37 8.465 8.465Z" }), 'RadioButtonChecked');
ajax/libs/material-ui/4.9.2/es/GridListTile/GridListTile.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 debounce from '../utils/debounce'; import withStyles from '../styles/withStyles'; import isMuiElement from '../utils/isMuiElement'; export const styles = { /* Styles applied to the root element. */ root: { boxSizing: 'border-box', flexShrink: 0 }, /* Styles applied to the `div` element that wraps the children. */ tile: { position: 'relative', display: 'block', // In case it's not rendered with a div. height: '100%', overflow: 'hidden' }, /* Styles applied to an `img` element child, if needed to ensure it covers the tile. */ imgFullHeight: { height: '100%', transform: 'translateX(-50%)', position: 'relative', left: '50%' }, /* Styles applied to an `img` element child, if needed to ensure it covers the tile. */ imgFullWidth: { width: '100%', position: 'relative', transform: 'translateY(-50%)', top: '50%' } }; const fit = (imgEl, classes) => { if (!imgEl || !imgEl.complete) { return; } if (imgEl.width / imgEl.height > imgEl.parentElement.offsetWidth / imgEl.parentElement.offsetHeight) { imgEl.classList.remove(...classes.imgFullWidth.split(' ')); imgEl.classList.add(...classes.imgFullHeight.split(' ')); } else { imgEl.classList.remove(...classes.imgFullHeight.split(' ')); imgEl.classList.add(...classes.imgFullWidth.split(' ')); } }; function ensureImageCover(imgEl, classes) { if (!imgEl) { return; } if (imgEl.complete) { fit(imgEl, classes); } else { imgEl.addEventListener('load', () => { fit(imgEl, classes); }); } } const GridListTile = React.forwardRef(function GridListTile(props, ref) { // cols rows default values are for docs only const { children, classes, className, // eslint-disable-next-line no-unused-vars cols = 1, component: Component = 'li', // eslint-disable-next-line no-unused-vars rows = 1 } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "cols", "component", "rows"]); const imgRef = React.useRef(null); React.useEffect(() => { ensureImageCover(imgRef.current, classes); }); React.useEffect(() => { const handleResize = debounce(() => { fit(imgRef.current, classes); }); window.addEventListener('resize', handleResize); return () => { handleResize.clear(); window.removeEventListener('resize', handleResize); }; }, [classes]); return React.createElement(Component, _extends({ className: clsx(classes.root, className), ref: ref }, other), React.createElement("div", { className: classes.tile }, React.Children.map(children, child => { if (!React.isValidElement(child)) { return null; } if (child.type === 'img' || isMuiElement(child, ['Image'])) { return React.cloneElement(child, { ref: imgRef }); } return child; }))); }); process.env.NODE_ENV !== "production" ? GridListTile.propTypes = { /** * Theoretically you can pass any node as children, but the main use case is to pass an img, * in which case GridListTile takes care of making the image "cover" available space * (similar to `background-size: cover` or to `object-fit: cover`). */ 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, /** * Width of the tile in number of grid cells. */ cols: PropTypes.number, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * Height of the tile in number of grid cells. */ rows: PropTypes.number } : void 0; export default withStyles(styles, { name: 'MuiGridListTile' })(GridListTile);
ajax/libs/primereact/6.6.0/timeline/timeline.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { ObjectUtils, classNames } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } 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 Timeline = /*#__PURE__*/function (_Component) { _inherits(Timeline, _Component); var _super = _createSuper(Timeline); function Timeline() { _classCallCheck(this, Timeline); return _super.apply(this, arguments); } _createClass(Timeline, [{ key: "getKey", value: function getKey(item, index) { return this.props.dataKey ? ObjectUtils.resolveFieldData(item, this.props.dataKey) : "pr_id__".concat(index); } }, { key: "renderEvents", value: function renderEvents() { var _this = this; return this.props.value && this.props.value.map(function (item, index) { var opposite = ObjectUtils.getJSXElement(_this.props.opposite, item, index); var marker = ObjectUtils.getJSXElement(_this.props.marker, item, index) || /*#__PURE__*/React.createElement("div", { className: "p-timeline-event-marker" }); var connector = index !== _this.props.value.length - 1 && /*#__PURE__*/React.createElement("div", { className: "p-timeline-event-connector" }); var content = ObjectUtils.getJSXElement(_this.props.content, item, index); return /*#__PURE__*/React.createElement("div", { key: _this.getKey(item, index), className: "p-timeline-event" }, /*#__PURE__*/React.createElement("div", { className: "p-timeline-event-opposite" }, opposite), /*#__PURE__*/React.createElement("div", { className: "p-timeline-event-separator" }, marker, connector), /*#__PURE__*/React.createElement("div", { className: "p-timeline-event-content" }, content)); }); } }, { key: "render", value: function render() { var _classNames; var containerClassName = classNames('p-timeline p-component', (_classNames = {}, _defineProperty(_classNames, "p-timeline-".concat(this.props.align), true), _defineProperty(_classNames, "p-timeline-".concat(this.props.layout), true), _classNames), this.props.className); var events = this.renderEvents(); return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: containerClassName, style: this.props.style }, events); } }]); return Timeline; }(Component); _defineProperty(Timeline, "defaultProps", { id: null, value: null, align: 'left', layout: 'vertical', dataKey: null, className: null, style: null, opposite: null, marker: null, content: null }); export { Timeline };
ajax/libs/react-instantsearch/5.7.0/Dom.js
cdnjs/cdnjs
/*! React InstantSearch 5.7.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 _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); } 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 global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } function nextTick(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; var title = 'browser'; var platform = 'browser'; var browser = true; var env = {}; var argv = []; var version = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; var config = {}; function noop() {} var on = noop; var addListener = noop; var once = noop; var off = noop; var removeListener = noop; var removeAllListeners = noop; var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); } function cwd () { return '/' } function chdir (dir) { throw new Error('process.chdir is not supported'); }function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function(){ return (new Date()).getTime() }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp){ var clocktime = performanceNow.call(performance)*1e-3; var seconds = Math.floor(clocktime); var nanoseconds = Math.floor((clocktime%1)*1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds<0) { seconds--; nanoseconds += 1e9; } } return [seconds,nanoseconds] } var startTime = new Date(); function uptime() { var currentTime = new Date(); var dif = currentTime - startTime; return dif / 1000; } var process = { nextTick: nextTick, title: title, browser: browser, env: env, argv: argv, version: version, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime }; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function commonjsRequire () { throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); } 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 _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; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } var _arrayMap = arrayMap; /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } var _listCacheClear = listCacheClear; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } var eq_1 = eq; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq_1(array[length][0], key)) { return length; } } return -1; } var _assocIndexOf = assocIndexOf; /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } var _listCacheDelete = listCacheDelete; /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = _assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } var _listCacheGet = listCacheGet; /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return _assocIndexOf(this.__data__, key) > -1; } var _listCacheHas = listCacheHas; /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } var _listCacheSet = listCacheSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = _listCacheClear; ListCache.prototype['delete'] = _listCacheDelete; ListCache.prototype.get = _listCacheGet; ListCache.prototype.has = _listCacheHas; ListCache.prototype.set = _listCacheSet; var _ListCache = ListCache; /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new _ListCache; this.size = 0; } var _stackClear = stackClear; /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } var _stackDelete = stackDelete; /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } var _stackGet = stackGet; /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } var _stackHas = stackHas; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var _freeGlobal = freeGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = _freeGlobal || freeSelf || Function('return this')(); var _root = root; /** Built-in value references. */ var Symbol$1 = _root.Symbol; var _Symbol = Symbol$1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty$1.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var _getRawTag = getRawTag; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$1.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } var _objectToString = objectToString; /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag$1 && symToStringTag$1 in Object(value)) ? _getRawTag(value) : _objectToString(value); } var _baseGetTag = baseGetTag; /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } var isObject_1 = isObject; /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject_1(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = _baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_1 = isFunction; /** Used to detect overreaching core-js shims. */ var coreJsData = _root['__core-js_shared__']; var _coreJsData = coreJsData; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } var _isMasked = isMasked; /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } var _toSource = toSource; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto$1 = Function.prototype, objectProto$2 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$1 = funcProto$1.toString; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$2.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject_1(value) || _isMasked(value)) { return false; } var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; return pattern.test(_toSource(value)); } var _baseIsNative = baseIsNative; /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } var _getValue = getValue; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = _getValue(object, key); return _baseIsNative(value) ? value : undefined; } var _getNative = getNative; /* Built-in method references that are verified to be native. */ var Map = _getNative(_root, 'Map'); var _Map = Map; /* Built-in method references that are verified to be native. */ var nativeCreate = _getNative(Object, 'create'); var _nativeCreate = nativeCreate; /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; this.size = 0; } var _hashClear = hashClear; /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } var _hashDelete = hashDelete; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$3.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (_nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty$3.call(data, key) ? data[key] : undefined; } var _hashGet = hashGet; /** Used for built-in method references. */ var objectProto$4 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$4 = objectProto$4.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$4.call(data, key); } var _hashHas = hashHas; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; return this; } var _hashSet = hashSet; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = _hashClear; Hash.prototype['delete'] = _hashDelete; Hash.prototype.get = _hashGet; Hash.prototype.has = _hashHas; Hash.prototype.set = _hashSet; var _Hash = Hash; /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new _Hash, 'map': new (_Map || _ListCache), 'string': new _Hash }; } var _mapCacheClear = mapCacheClear; /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } var _isKeyable = isKeyable; /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } var _getMapData = getMapData; /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = _getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } var _mapCacheDelete = mapCacheDelete; /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return _getMapData(this, key).get(key); } var _mapCacheGet = mapCacheGet; /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return _getMapData(this, key).has(key); } var _mapCacheHas = mapCacheHas; /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = _getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } var _mapCacheSet = mapCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = _mapCacheClear; MapCache.prototype['delete'] = _mapCacheDelete; MapCache.prototype.get = _mapCacheGet; MapCache.prototype.has = _mapCacheHas; MapCache.prototype.set = _mapCacheSet; var _MapCache = MapCache; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof _ListCache) { var pairs = data.__data__; if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new _MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } var _stackSet = stackSet; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new _ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = _stackClear; Stack.prototype['delete'] = _stackDelete; Stack.prototype.get = _stackGet; Stack.prototype.has = _stackHas; Stack.prototype.set = _stackSet; var _Stack = Stack; /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } var _arrayEach = arrayEach; var defineProperty = (function() { try { var func = _getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); var _defineProperty$1 = defineProperty; /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && _defineProperty$1) { _defineProperty$1(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } var _baseAssignValue = baseAssignValue; /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$5 = objectProto$5.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$5.call(object, key) && eq_1(objValue, value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignValue = assignValue; /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { _baseAssignValue(object, key, newValue); } else { _assignValue(object, key, newValue); } } return object; } var _copyObject = copyObject; /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } var _baseTimes = baseTimes; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } var isObjectLike_1 = isObjectLike; /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike_1(value) && _baseGetTag(value) == argsTag; } var _baseIsArguments = baseIsArguments; /** Used for built-in method references. */ var objectProto$6 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$6 = objectProto$6.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto$6.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { return isObjectLike_1(value) && hasOwnProperty$6.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; var isArguments_1 = isArguments; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; var isArray_1 = isArray; /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } var stubFalse_1 = stubFalse; var isBuffer_1 = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse_1; module.exports = isBuffer; }); /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } var _isIndex = isIndex; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; } var isLength_1 = isLength; /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag$1 = '[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$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; } var _baseIsTypedArray = baseIsTypedArray; /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } var _baseUnary = baseUnary; var _nodeUtil = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && _freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; }); /* Node.js helper references. */ var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; var isTypedArray_1 = isTypedArray; /** Used for built-in method references. */ var objectProto$7 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$7 = objectProto$7.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty$7.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. _isIndex(key, length) ))) { result.push(key); } } return result; } var _arrayLikeKeys = arrayLikeKeys; /** Used for built-in method references. */ var objectProto$8 = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$8; return value === proto; } var _isPrototype = isPrototype; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var _overArg = overArg; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = _overArg(Object.keys, Object); var _nativeKeys = nativeKeys; /** Used for built-in method references. */ var objectProto$9 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$8 = objectProto$9.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$8.call(object, key) && key != 'constructor') { result.push(key); } } return result; } var _baseKeys = baseKeys; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength_1(value.length) && !isFunction_1(value); } var isArrayLike_1 = isArrayLike; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); } var keys_1 = keys; /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && _copyObject(source, keys_1(source), object); } var _baseAssign = baseAssign; /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } var _nativeKeysIn = nativeKeysIn; /** Used for built-in method references. */ var objectProto$a = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$9 = objectProto$a.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject_1(object)) { return _nativeKeysIn(object); } var isProto = _isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty$9.call(object, key)))) { result.push(key); } } return result; } var _baseKeysIn = baseKeysIn; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn$1(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object); } var keysIn_1 = keysIn$1; /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && _copyObject(source, keysIn_1(source), object); } var _baseAssignIn = baseAssignIn; var _cloneBuffer = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; }); /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } var _copyArray = copyArray; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } var _arrayFilter = arrayFilter; /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } var stubArray_1 = stubArray; /** Used for built-in method references. */ var objectProto$b = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { if (object == null) { return []; } object = Object(object); return _arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable$1.call(object, symbol); }); }; var _getSymbols = getSymbols; /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return _copyObject(source, _getSymbols(source), object); } var _copySymbols = copySymbols; /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } var _arrayPush = arrayPush; /** Built-in value references. */ var getPrototype = _overArg(Object.getPrototypeOf, Object); var _getPrototype = getPrototype; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols$1 = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) { var result = []; while (object) { _arrayPush(result, _getSymbols(object)); object = _getPrototype(object); } return result; }; var _getSymbolsIn = getSymbolsIn; /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return _copyObject(source, _getSymbolsIn(source), object); } var _copySymbolsIn = copySymbolsIn; /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); } var _baseGetAllKeys = baseGetAllKeys; /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return _baseGetAllKeys(object, keys_1, _getSymbols); } var _getAllKeys = getAllKeys; /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn); } var _getAllKeysIn = getAllKeysIn; /* Built-in method references that are verified to be native. */ var DataView = _getNative(_root, 'DataView'); var _DataView = DataView; /* Built-in method references that are verified to be native. */ var Promise$1 = _getNative(_root, 'Promise'); var _Promise = Promise$1; /* Built-in method references that are verified to be native. */ var Set = _getNative(_root, 'Set'); var _Set = Set; /* Built-in method references that are verified to be native. */ var WeakMap = _getNative(_root, 'WeakMap'); var _WeakMap = WeakMap; /** `Object#toString` result references. */ var mapTag$1 = '[object Map]', objectTag$1 = '[object Object]', promiseTag = '[object Promise]', setTag$1 = '[object Set]', weakMapTag$1 = '[object WeakMap]'; var dataViewTag$1 = '[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$1) || (_Map && getTag(new _Map) != mapTag$1) || (_Promise && getTag(_Promise.resolve()) != promiseTag) || (_Set && getTag(new _Set) != setTag$1) || (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) { getTag = function(value) { var result = _baseGetTag(value), Ctor = result == objectTag$1 ? value.constructor : undefined, ctorString = Ctor ? _toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag$1; case mapCtorString: return mapTag$1; case promiseCtorString: return promiseTag; case setCtorString: return setTag$1; case weakMapCtorString: return weakMapTag$1; } } return result; }; } var _getTag = getTag; /** Used for built-in method references. */ var objectProto$c = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$a = objectProto$c.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty$a.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } var _initCloneArray = initCloneArray; /** Built-in value references. */ var Uint8Array = _root.Uint8Array; var _Uint8Array = Uint8Array; /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new _Uint8Array(result).set(new _Uint8Array(arrayBuffer)); return result; } var _cloneArrayBuffer = cloneArrayBuffer; /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } var _cloneDataView = cloneDataView; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } var _cloneRegExp = cloneRegExp; /** Used to convert symbols to primitives and strings. */ var symbolProto = _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)) : {}; } var _cloneSymbol = cloneSymbol; /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } var _cloneTypedArray = cloneTypedArray; /** `Object#toString` result references. */ var boolTag$1 = '[object Boolean]', dateTag$1 = '[object Date]', mapTag$2 = '[object Map]', numberTag$1 = '[object Number]', regexpTag$1 = '[object RegExp]', setTag$2 = '[object Set]', stringTag$1 = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag$1 = '[object ArrayBuffer]', dataViewTag$2 = '[object DataView]', float32Tag$1 = '[object Float32Array]', float64Tag$1 = '[object Float64Array]', int8Tag$1 = '[object Int8Array]', int16Tag$1 = '[object Int16Array]', int32Tag$1 = '[object Int32Array]', uint8Tag$1 = '[object Uint8Array]', uint8ClampedTag$1 = '[object Uint8ClampedArray]', uint16Tag$1 = '[object Uint16Array]', uint32Tag$1 = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag$1: return _cloneArrayBuffer(object); case boolTag$1: case dateTag$1: return new Ctor(+object); case dataViewTag$2: return _cloneDataView(object, isDeep); case float32Tag$1: case float64Tag$1: case int8Tag$1: case int16Tag$1: case int32Tag$1: case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: return _cloneTypedArray(object, isDeep); case mapTag$2: return new Ctor; case numberTag$1: case stringTag$1: return new Ctor(object); case regexpTag$1: return _cloneRegExp(object); case setTag$2: return new Ctor; case symbolTag: return _cloneSymbol(object); } } var _initCloneByTag = initCloneByTag; /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject_1(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); var _baseCreate = baseCreate; /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !_isPrototype(object)) ? _baseCreate(_getPrototype(object)) : {}; } var _initCloneObject = initCloneObject; /** `Object#toString` result references. */ var mapTag$3 = '[object Map]'; /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike_1(value) && _getTag(value) == mapTag$3; } var _baseIsMap = baseIsMap; /* Node.js helper references. */ var nodeIsMap = _nodeUtil && _nodeUtil.isMap; /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap; var isMap_1 = isMap; /** `Object#toString` result references. */ var setTag$3 = '[object Set]'; /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike_1(value) && _getTag(value) == setTag$3; } var _baseIsSet = baseIsSet; /* Node.js helper references. */ var nodeIsSet = _nodeUtil && _nodeUtil.isSet; /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet; var isSet_1 = isSet; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag$2 = '[object Arguments]', arrayTag$1 = '[object Array]', boolTag$2 = '[object Boolean]', dateTag$2 = '[object Date]', errorTag$1 = '[object Error]', funcTag$2 = '[object Function]', genTag$1 = '[object GeneratorFunction]', mapTag$4 = '[object Map]', numberTag$2 = '[object Number]', objectTag$2 = '[object Object]', regexpTag$2 = '[object RegExp]', setTag$4 = '[object Set]', stringTag$2 = '[object String]', symbolTag$1 = '[object Symbol]', weakMapTag$2 = '[object WeakMap]'; var arrayBufferTag$2 = '[object ArrayBuffer]', dataViewTag$3 = '[object DataView]', float32Tag$2 = '[object Float32Array]', float64Tag$2 = '[object Float64Array]', int8Tag$2 = '[object Int8Array]', int16Tag$2 = '[object Int16Array]', int32Tag$2 = '[object Int32Array]', uint8Tag$2 = '[object Uint8Array]', uint8ClampedTag$2 = '[object Uint8ClampedArray]', uint16Tag$2 = '[object Uint16Array]', uint32Tag$2 = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] = cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] = cloneableTags[boolTag$2] = cloneableTags[dateTag$2] = cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] = cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] = cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] = cloneableTags[numberTag$2] = cloneableTags[objectTag$2] = cloneableTags[regexpTag$2] = cloneableTags[setTag$4] = cloneableTags[stringTag$2] = cloneableTags[symbolTag$1] = cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] = cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true; cloneableTags[errorTag$1] = cloneableTags[funcTag$2] = cloneableTags[weakMapTag$2] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject_1(value)) { return value; } var isArr = isArray_1(value); if (isArr) { result = _initCloneArray(value); if (!isDeep) { return _copyArray(value, result); } } else { var tag = _getTag(value), isFunc = tag == funcTag$2 || tag == genTag$1; if (isBuffer_1(value)) { return _cloneBuffer(value, isDeep); } if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : _initCloneObject(value); if (!isDeep) { return isFlat ? _copySymbolsIn(value, _baseAssignIn(result, value)) : _copySymbols(value, _baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = _initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new _Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet_1(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); return result; } if (isMap_1(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var keysFunc = isFull ? (isFlat ? _getAllKeysIn : _getAllKeys) : (isFlat ? keysIn : keys_1); var props = isArr ? undefined : keysFunc(value); _arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var _baseClone = baseClone; /** `Object#toString` result references. */ var symbolTag$2 = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$2); } var isSymbol_1 = isSymbol; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray_1(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } var _isKey = isKey; /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || _MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = _MapCache; var memoize_1 = memoize; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize_1(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var _memoizeCapped = memoizeCapped; /** Used to match property names within property paths. */ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = _memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); var _stringToPath = stringToPath; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined, symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray_1(value)) { // Recursively convert values (susceptible to call stack limits). return _arrayMap(value, baseToString) + ''; } if (isSymbol_1(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } var _baseToString = baseToString; /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : _baseToString(value); } var toString_1 = toString; /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray_1(value)) { return value; } return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); } var _castPath = castPath; /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } var last_1 = last; /** Used as references for various `Number` constants. */ var INFINITY$1 = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol_1(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; } var _toKey = toKey; /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = _castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[_toKey(path[index++])]; } return (index && index == length) ? object : undefined; } var _baseGet = baseGet; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } var _baseSlice = baseSlice; /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1)); } var _parent = parent; /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = _castPath(path, object); object = _parent(object, path); return object == null || delete object[_toKey(last_1(path))]; } var _baseUnset = baseUnset; /** `Object#toString` result references. */ var objectTag$3 = '[object Object]'; /** Used for built-in method references. */ var funcProto$2 = Function.prototype, objectProto$d = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$2 = funcProto$2.toString; /** Used to check objects for own properties. */ var hasOwnProperty$b = objectProto$d.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString$2.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) { return false; } var proto = _getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$b.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString; } var isPlainObject_1 = isPlainObject; /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject_1(value) ? undefined : value; } var _customOmitClone = customOmitClone; /** Built-in value references. */ var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } var _isFlattenable = isFlattenable; /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = _isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { _arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } var _baseFlatten = baseFlatten; /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? _baseFlatten(array, 1) : []; } var flatten_1 = flatten; /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } var _apply = apply; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return _apply(func, this, otherArgs); }; } var _overRest = overRest; /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } var constant_1 = constant; /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } var identity_1 = identity; /** * The base implementation of `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$1 ? identity_1 : function(func, string) { return _defineProperty$1(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant_1(string), 'writable': true }); }; var _baseSetToString = baseSetToString; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } var _shortOut = shortOut; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = _shortOut(_baseSetToString); var _setToString = setToString; /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return _setToString(_overRest(func, undefined, flatten_1), func + ''); } var _flatRest = flatRest; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$1 = 1, CLONE_FLAT_FLAG$1 = 2, CLONE_SYMBOLS_FLAG$1 = 4; /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = _flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = _arrayMap(paths, function(path) { path = _castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); _copyObject(object, _getAllKeysIn(object), result); if (isDeep) { result = _baseClone(result, CLONE_DEEP_FLAG$1 | CLONE_FLAT_FLAG$1 | CLONE_SYMBOLS_FLAG$1, _customOmitClone); } var length = paths.length; while (length--) { _baseUnset(result, paths[length]); } return result; }); var omit_1 = omit; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED$2); return this; } var _setCacheAdd = setCacheAdd; /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } var _setCacheHas = setCacheHas; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new _MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; SetCache.prototype.has = _setCacheHas; var _SetCache = SetCache; /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } var _baseFindIndex = baseFindIndex; /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } var _baseIsNaN = baseIsNaN; /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } var _strictIndexOf = strictIndexOf; /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex); } var _baseIndexOf = baseIndexOf; /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && _baseIndexOf(array, value, 0) > -1; } var _arrayIncludes = arrayIncludes; /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } var _arrayIncludesWith = arrayIncludesWith; /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } var _cacheHas = cacheHas; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? _arrayIncludesWith : _arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = _arrayMap(array, _baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new _SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? _cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? _cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } var _baseIntersection = baseIntersection; /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return _setToString(_overRest(func, start, identity_1), func + ''); } var _baseRest = baseRest; /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike_1(value) && isArrayLike_1(value); } var isArrayLikeObject_1 = isArrayLikeObject; /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject_1(value) ? value : []; } var _castArrayLikeObject = castArrayLikeObject; /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = _baseRest(function(arrays) { var mapped = _arrayMap(arrays, _castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? _baseIntersection(mapped) : []; }); var intersection_1 = intersection; /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } var _createBaseFor = createBaseFor; /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = _createBaseFor(); var _baseFor = baseFor; /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && _baseFor(object, iteratee, keys_1); } var _baseForOwn = baseForOwn; /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity_1; } var _castFunction = castFunction; /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && _baseForOwn(object, _castFunction(iteratee)); } var forOwn_1 = forOwn; /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike_1(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } var _createBaseEach = createBaseEach; /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = _createBaseEach(_baseForOwn); var _baseEach = baseEach; /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray_1(collection) ? _arrayEach : _baseEach; return func(collection, _castFunction(iteratee)); } var forEach_1 = forEach; /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; _baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } var _baseFilter = baseFilter; /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } var _arraySome = arraySome; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!_arraySome(other, function(othValue, othIndex) { if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } var _equalArrays = equalArrays; /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } var _mapToArray = mapToArray; /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } var _setToArray = setToArray; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$1 = 1, COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ var boolTag$3 = '[object Boolean]', dateTag$3 = '[object Date]', errorTag$2 = '[object Error]', mapTag$5 = '[object Map]', numberTag$3 = '[object Number]', regexpTag$3 = '[object RegExp]', setTag$5 = '[object Set]', stringTag$3 = '[object String]', symbolTag$3 = '[object Symbol]'; var arrayBufferTag$3 = '[object ArrayBuffer]', dataViewTag$4 = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined, symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag$4: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag$3: if ((object.byteLength != other.byteLength) || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { return false; } return true; case boolTag$3: case dateTag$3: case numberTag$3: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq_1(+object, +other); case errorTag$2: return object.name == other.name && object.message == other.message; case regexpTag$3: case stringTag$3: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag$5: var convert = _mapToArray; case setTag$5: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; convert || (convert = _setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag$3: if (symbolValueOf$1) { return symbolValueOf$1.call(object) == symbolValueOf$1.call(other); } } return false; } var _equalByTag = equalByTag; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$2 = 1; /** Used for built-in method references. */ var objectProto$e = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$c = objectProto$e.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, objProps = _getAllKeys(object), objLength = objProps.length, othProps = _getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty$c.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } var _equalObjects = equalObjects; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$3 = 1; /** `Object#toString` result references. */ var argsTag$3 = '[object Arguments]', arrayTag$2 = '[object Array]', objectTag$4 = '[object Object]'; /** Used for built-in method references. */ var objectProto$f = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$d = objectProto$f.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray_1(object), othIsArr = isArray_1(other), objTag = objIsArr ? arrayTag$2 : _getTag(object), othTag = othIsArr ? arrayTag$2 : _getTag(other); objTag = objTag == argsTag$3 ? objectTag$4 : objTag; othTag = othTag == argsTag$3 ? objectTag$4 : othTag; var objIsObj = objTag == objectTag$4, othIsObj = othTag == objectTag$4, isSameTag = objTag == othTag; if (isSameTag && isBuffer_1(object)) { if (!isBuffer_1(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new _Stack); return (objIsArr || isTypedArray_1(object)) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { var objIsWrapped = objIsObj && hasOwnProperty$d.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty$d.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new _Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new _Stack); return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); } var _baseIsEqualDeep = baseIsEqualDeep; /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } var _baseIsEqual = baseIsEqual; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$4 = 1, COMPARE_UNORDERED_FLAG$2 = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result )) { return false; } } } return true; } var _baseIsMatch = baseIsMatch; /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject_1(value); } var _isStrictComparable = isStrictComparable; /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys_1(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, _isStrictComparable(value)]; } return result; } var _getMatchData = getMatchData; /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } var _matchesStrictComparable = matchesStrictComparable; /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = _getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return _matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || _baseIsMatch(object, source, matchData); }; } var _baseMatches = baseMatches; /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : _baseGet(object, path); return result === undefined ? defaultValue : result; } var get_1 = get; /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } var _baseHasIn = baseHasIn; /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = _castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = _toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); } var _hasPath = hasPath; /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && _hasPath(object, path, _baseHasIn); } var hasIn_1 = hasIn; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$5 = 1, COMPARE_UNORDERED_FLAG$3 = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (_isKey(path) && _isStrictComparable(srcValue)) { return _matchesStrictComparable(_toKey(path), srcValue); } return function(object) { var objValue = get_1(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); }; } var _baseMatchesProperty = baseMatchesProperty; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } var _baseProperty = baseProperty; /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return _baseGet(object, path); }; } var _basePropertyDeep = basePropertyDeep; /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); } var property_1 = property; /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity_1; } if (typeof value == 'object') { return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value); } return property_1(value); } var _baseIteratee = baseIteratee; /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray_1(collection) ? _arrayFilter : _baseFilter; return func(collection, _baseIteratee(predicate, 3)); } var filter_1 = filter; /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike_1(collection) ? Array(collection.length) : []; _baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } var _baseMap = baseMap; /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray_1(collection) ? _arrayMap : _baseMap; return func(collection, _baseIteratee(iteratee, 3)); } var map_1 = map; /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } var _arrayReduce = arrayReduce; /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } var _baseReduce = baseReduce; /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray_1(collection) ? _arrayReduce : _baseReduce, initAccum = arguments.length < 3; return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEach); } var reduce_1 = reduce; /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol_1(value)) { return NAN; } if (isObject_1(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject_1(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } var toNumber_1 = toNumber; /** Used as references for various `Number` constants. */ var INFINITY$2 = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber_1(value); if (value === INFINITY$2 || value === -INFINITY$2) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } var toFinite_1 = toFinite; /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite_1(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } var toInteger_1 = toInteger; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$1 = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$1(length + index, 0); } return _baseIndexOf(array, value, index); } var indexOf_1 = indexOf; /** `Object#toString` result references. */ var numberTag$4 = '[object Number]'; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike_1(value) && _baseGetTag(value) == numberTag$4); } var isNumber_1 = isNumber; /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN$1(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber_1(value) && value != +value; } var _isNaN = isNaN$1; /** `Object#toString` result references. */ var mapTag$6 = '[object Map]', setTag$6 = '[object Set]'; /** Used for built-in method references. */ var objectProto$g = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$e = objectProto$g.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike_1(value) && (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) { return !value.length; } var tag = _getTag(value); if (tag == mapTag$6 || tag == setTag$6) { return !value.size; } if (_isPrototype(value)) { return !_baseKeys(value).length; } for (var key in value) { if (hasOwnProperty$e.call(value, key)) { return false; } } return true; } var isEmpty_1 = isEmpty; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return _baseIsEqual(value, other); } var isEqual_1 = isEqual; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } var isUndefined_1 = isUndefined; /** `Object#toString` result references. */ var stringTag$4 = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$4); } var isString_1 = isString; /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike_1(collection)) { var iteratee = _baseIteratee(predicate, 3); collection = keys_1(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } var _createFind = createFind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$2 = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$2(length + index, 0); } return _baseFindIndex(array, _baseIteratee(predicate, 3), index); } var findIndex_1 = findIndex; /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = _createFind(findIndex_1); var find_1 = find; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : _baseSlice(array, start, end); } var _castSlice = castSlice; /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsEndIndex = charsEndIndex; /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsStartIndex = charsStartIndex; /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } var _asciiToArray = asciiToArray; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } var _hasUnicode = hasUnicode; /** Used to compose unicode character classes. */ var rsAstralRange$1 = '\\ud800-\\udfff', rsComboMarksRange$1 = '\\u0300-\\u036f', reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, rsVarRange$1 = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange$1 + ']', rsCombo = '[' + rsComboRange$1 + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange$1 + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsZWJ$1 = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange$1 + ']?', rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } var _unicodeToArray = unicodeToArray; /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return _hasUnicode(string) ? _unicodeToArray(string) : _asciiToArray(string); } var _stringToArray = stringToArray; /** Used to match leading and trailing whitespace. */ var reTrim$1 = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString_1(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim$1, ''); } if (!string || !(chars = _baseToString(chars))) { return string; } var strSymbols = _stringToArray(string), chrSymbols = _stringToArray(chars), start = _charsStartIndex(strSymbols, chrSymbols), end = _charsEndIndex(strSymbols, chrSymbols) + 1; return _castSlice(strSymbols, start, end).join(''); } var trim_1 = trim; /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject_1(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike_1(object) && _isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq_1(object[index], value); } return false; } var _isIterateeCall = isIterateeCall; /** Used for built-in method references. */ var objectProto$h = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$f = objectProto$h.hasOwnProperty; /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = _baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && _isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn_1(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq_1(value, objectProto$h[key]) && !hasOwnProperty$f.call(object, key))) { object[key] = source[key]; } } } return object; }); var defaults_1 = defaults; /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq_1(object[key], value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignMergeValue = assignMergeValue; /** * Gets the value at `key`, unless `key` is "__proto__". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key == '__proto__') { return; } return object[key]; } var _safeGet = safeGet; /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return _copyObject(value, keysIn_1(value)); } var toPlainObject_1 = toPlainObject; /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = _safeGet(object, key), srcValue = _safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { _assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray_1(srcValue), isBuff = !isArr && isBuffer_1(srcValue), isTyped = !isArr && !isBuff && isTypedArray_1(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray_1(objValue)) { newValue = objValue; } else if (isArrayLikeObject_1(objValue)) { newValue = _copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = _cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = _cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject_1(srcValue) || isArguments_1(srcValue)) { newValue = objValue; if (isArguments_1(objValue)) { newValue = toPlainObject_1(objValue); } else if (!isObject_1(objValue) || isFunction_1(objValue)) { newValue = _initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } _assignMergeValue(object, key, newValue); } var _baseMergeDeep = baseMergeDeep; /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } _baseFor(source, function(srcValue, key) { if (isObject_1(srcValue)) { stack || (stack = new _Stack); _baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(_safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } _assignMergeValue(object, key, newValue); } }, keysIn_1); } var _baseMerge = baseMerge; /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return _baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && _isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } var _createAssigner = createAssigner; /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = _createAssigner(function(object, source, srcIndex) { _baseMerge(object, source, srcIndex); }); var merge_1 = merge; function valToNumber(v) { if (isNumber_1(v)) { return v; } else if (isString_1(v)) { return parseFloat(v); } else if (Array.isArray(v)) { return map_1(v, valToNumber); } throw new Error('The value should be a number, a parseable string or an array of those.'); } var valToNumber_1 = valToNumber; function filterState(state, filters) { var partialState = {}; var attributeFilters = filter_1(filters, function(f) { return f.indexOf('attribute:') !== -1; }); var attributes = map_1(attributeFilters, function(aF) { return aF.split(':')[1]; }); if (indexOf_1(attributes, '*') === -1) { forEach_1(attributes, function(attr) { if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) { if (!partialState.facetsRefinements) partialState.facetsRefinements = {}; partialState.facetsRefinements[attr] = state.facetsRefinements[attr]; } if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) { if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {}; partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr]; } if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) { if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {}; partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr]; } var numericRefinements = state.getNumericRefinements(attr); if (!isEmpty_1(numericRefinements)) { if (!partialState.numericRefinements) partialState.numericRefinements = {}; partialState.numericRefinements[attr] = state.numericRefinements[attr]; } }); } else { if (!isEmpty_1(state.numericRefinements)) { partialState.numericRefinements = state.numericRefinements; } if (!isEmpty_1(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements; if (!isEmpty_1(state.disjunctiveFacetsRefinements)) { partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements; } if (!isEmpty_1(state.hierarchicalFacetsRefinements)) { partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements; } } var searchParameters = filter_1( filters, function(f) { return f.indexOf('attribute:') === -1; } ); forEach_1( searchParameters, function(parameterKey) { partialState[parameterKey] = state[parameterKey]; } ); return partialState; } var filterState_1 = filterState; /** * Functions to manipulate refinement lists * * The RefinementList is not formally defined through a prototype but is based * on a specific structure. * * @module SearchParameters.refinementList * * @typedef {string[]} SearchParameters.refinementList.Refinements * @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList */ var lib = { /** * Adds a refinement to a RefinementList * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement, if the value is not a string it will be converted * @return {RefinementList} a new and updated refinement list */ addRefinement: function addRefinement(refinementList, attribute, value) { if (lib.isRefined(refinementList, attribute, value)) { return refinementList; } var valueAsString = '' + value; var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString); var mod = {}; mod[attribute] = facetRefinement; return defaults_1({}, mod, refinementList); }, /** * Removes refinement(s) for an attribute: * - if the value is specified removes the refinement for the value on the attribute * - if no value is specified removes all the refinements for this attribute * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} [value] the value of the refinement * @return {RefinementList} a new and updated refinement lst */ removeRefinement: function removeRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) { return lib.clearRefinement(refinementList, attribute); } var valueAsString = '' + value; return lib.clearRefinement(refinementList, function(v, f) { return attribute === f && valueAsString === v; }); }, /** * Toggles the refinement value for an attribute. * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement * @return {RefinementList} a new and updated list */ toggleRefinement: function toggleRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) throw new Error('toggleRefinement should be used with a value'); if (lib.isRefined(refinementList, attribute, value)) { return lib.removeRefinement(refinementList, attribute, value); } return lib.addRefinement(refinementList, attribute, value); }, /** * Clear all or parts of a RefinementList. Depending on the arguments, three * kinds of behavior can happen: * - if no attribute is provided: clears the whole list * - if an attribute is provided as a string: clears the list for the specific attribute * - if an attribute is provided as a function: discards the elements for which the function returns true * @param {RefinementList} refinementList the initial list * @param {string} [attribute] the attribute or function to discard * @param {string} [refinementType] optional parameter to give more context to the attribute function * @return {RefinementList} a new and updated refinement list */ clearRefinement: function clearRefinement(refinementList, attribute, refinementType) { if (isUndefined_1(attribute)) { if (isEmpty_1(refinementList)) return refinementList; return {}; } else if (isString_1(attribute)) { if (isEmpty_1(refinementList[attribute])) return refinementList; return omit_1(refinementList, attribute); } else if (isFunction_1(attribute)) { var hasChanged = false; var newRefinementList = reduce_1(refinementList, function(memo, values, key) { var facetList = filter_1(values, function(value) { return !attribute(value, key, refinementType); }); if (!isEmpty_1(facetList)) { if (facetList.length !== values.length) hasChanged = true; memo[key] = facetList; } else hasChanged = true; return memo; }, {}); if (hasChanged) return newRefinementList; return refinementList; } }, /** * Test if the refinement value is used for the attribute. If no refinement value * is provided, test if the refinementList contains any refinement for the * given attribute. * @param {RefinementList} refinementList the list of refinement * @param {string} attribute name of the attribute * @param {string} [refinementValue] value of the filter/refinement * @return {boolean} */ isRefined: function isRefined(refinementList, attribute, refinementValue) { var indexOf = indexOf_1; var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (isUndefined_1(refinementValue) || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return indexOf(refinementList[attribute], refinementValueAsString) !== -1; } }; var RefinementList = lib; /** * like _.find but using _.isEqual to be able to use it * to find arrays. * @private * @param {any[]} array array to search into * @param {any} searchedValue the value we're looking for * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find_1(array, function(currentValue) { return isEqual_1(currentValue, searchedValue); }); } /** * The facet list is the structure used to store the list of values used to * filter a single attribute. * @typedef {string[]} SearchParameters.FacetList */ /** * Structure to store numeric filters with the operator as the key. The supported operators * are `=`, `>`, `<`, `>=`, `<=` and `!=`. * @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList */ /** * SearchParameters is the data structure that contains all the information * usable for making a search to Algolia API. It doesn't do the search itself, * nor does it contains logic about the parameters. * It is an immutable object, therefore it has been created in a way that each * changes does not change the object itself but returns a copy with the * modification. * This object should probably not be instantiated outside of the helper. It will * be provided when needed. This object is documented for reference as you'll * get it from events generated by the {@link AlgoliaSearchHelper}. * If need be, instantiate the Helper from the factory function {@link SearchParameters.make} * @constructor * @classdesc contains all the parameters of a search * @param {object|SearchParameters} newParameters existing parameters or partial object * for the properties of a new SearchParameters * @see SearchParameters.make * @example <caption>SearchParameters of the first query in * <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption> { "query": "", "disjunctiveFacets": [ "customerReviewCount", "category", "salePrice_range", "manufacturer" ], "maxValuesPerFacet": 30, "page": 0, "hitsPerPage": 10, "facets": [ "type", "shipping" ] } */ function SearchParameters(newParameters) { var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {}; /** * Targeted index. This parameter is mandatory. * @member {string} */ this.index = params.index || ''; // Query /** * Query string of the instant search. The empty string is a valid query. * @member {string} * @see https://www.algolia.com/doc/rest#param-query */ this.query = params.query || ''; // Facets /** * This attribute contains the list of all the conjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.facets = params.facets || []; /** * This attribute contains the list of all the disjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.disjunctiveFacets = params.disjunctiveFacets || []; /** * This attribute contains the list of all the hierarchical facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * Hierarchical facets are a sub type of disjunctive facets that * let you filter faceted attributes hierarchically. * @member {string[]|object[]} */ this.hierarchicalFacets = params.hierarchicalFacets || []; // Refinements /** * This attribute contains all the filters that need to be * applied on the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsRefinements = params.facetsRefinements || {}; /** * This attribute contains all the filters that need to be * excluded from the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters excluded for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsExcludes = params.facetsExcludes || {}; /** * This attribute contains all the filters that need to be * applied on the disjunctive facets. Each facet must be properly * defined in the `disjunctiveFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {}; /** * This attribute contains all the filters that need to be * applied on the numeric attributes. * * The key is the name of the attribute, and the value is the * filters to apply to this attribute. * * When querying algolia, the values stored in this attribute will * be translated into the `numericFilters` attribute. * @member {Object.<string, SearchParameters.OperatorList>} */ this.numericRefinements = params.numericRefinements || {}; /** * This attribute contains all the tags used to refine the query. * * When querying algolia, the values stored in this attribute will * be translated into the `tagFilters` attribute. * @member {string[]} */ this.tagRefinements = params.tagRefinements || []; /** * This attribute contains all the filters that need to be * applied on the hierarchical facets. Each facet must be properly * defined in the `hierarchicalFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. The FacetList values * are structured as a string that contain the values for each level * separated by the configured separator. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {}; /** * Contains the numeric filters in the raw format of the Algolia API. Setting * this parameter is not compatible with the usage of numeric filters methods. * @see https://www.algolia.com/doc/javascript#numericFilters * @member {string} */ this.numericFilters = params.numericFilters; /** * Contains the tag filters in the raw format of the Algolia API. Setting this * parameter is not compatible with the of the add/remove/toggle methods of the * tag api. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.tagFilters = params.tagFilters; /** * Contains the optional tag filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalTagFilters = params.optionalTagFilters; /** * Contains the optional facet filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalFacetFilters = params.optionalFacetFilters; // Misc. parameters /** * Number of hits to be returned by the search API * @member {number} * @see https://www.algolia.com/doc/rest#param-hitsPerPage */ this.hitsPerPage = params.hitsPerPage; /** * Number of values for each faceted attribute * @member {number} * @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet */ this.maxValuesPerFacet = params.maxValuesPerFacet; /** * The current page number * @member {number} * @see https://www.algolia.com/doc/rest#param-page */ this.page = params.page || 0; /** * How the query should be treated by the search engine. * Possible values: prefixAll, prefixLast, prefixNone * @see https://www.algolia.com/doc/rest#param-queryType * @member {string} */ this.queryType = params.queryType; /** * How the typo tolerance behave in the search engine. * Possible values: true, false, min, strict * @see https://www.algolia.com/doc/rest#param-typoTolerance * @member {string} */ this.typoTolerance = params.typoTolerance; /** * Number of characters to wait before doing one character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo * @member {number} */ this.minWordSizefor1Typo = params.minWordSizefor1Typo; /** * Number of characters to wait before doing a second character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos * @member {number} */ this.minWordSizefor2Typos = params.minWordSizefor2Typos; /** * Configure the precision of the proximity ranking criterion * @see https://www.algolia.com/doc/rest#param-minProximity */ this.minProximity = params.minProximity; /** * Should the engine allow typos on numerics. * @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens * @member {boolean} */ this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens; /** * Should the plurals be ignored * @see https://www.algolia.com/doc/rest#param-ignorePlurals * @member {boolean} */ this.ignorePlurals = params.ignorePlurals; /** * Restrict which attribute is searched. * @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes * @member {string} */ this.restrictSearchableAttributes = params.restrictSearchableAttributes; /** * Enable the advanced syntax. * @see https://www.algolia.com/doc/rest#param-advancedSyntax * @member {boolean} */ this.advancedSyntax = params.advancedSyntax; /** * Enable the analytics * @see https://www.algolia.com/doc/rest#param-analytics * @member {boolean} */ this.analytics = params.analytics; /** * Tag of the query in the analytics. * @see https://www.algolia.com/doc/rest#param-analyticsTags * @member {string} */ this.analyticsTags = params.analyticsTags; /** * Enable the synonyms * @see https://www.algolia.com/doc/rest#param-synonyms * @member {boolean} */ this.synonyms = params.synonyms; /** * Should the engine replace the synonyms in the highlighted results. * @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight * @member {boolean} */ this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight; /** * Add some optional words to those defined in the dashboard * @see https://www.algolia.com/doc/rest#param-optionalWords * @member {string} */ this.optionalWords = params.optionalWords; /** * Possible values are "lastWords" "firstWords" "allOptional" "none" (default) * @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults * @member {string} */ this.removeWordsIfNoResults = params.removeWordsIfNoResults; /** * List of attributes to retrieve * @see https://www.algolia.com/doc/rest#param-attributesToRetrieve * @member {string} */ this.attributesToRetrieve = params.attributesToRetrieve; /** * List of attributes to highlight * @see https://www.algolia.com/doc/rest#param-attributesToHighlight * @member {string} */ this.attributesToHighlight = params.attributesToHighlight; /** * Code to be embedded on the left part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPreTag * @member {string} */ this.highlightPreTag = params.highlightPreTag; /** * Code to be embedded on the right part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPostTag * @member {string} */ this.highlightPostTag = params.highlightPostTag; /** * List of attributes to snippet * @see https://www.algolia.com/doc/rest#param-attributesToSnippet * @member {string} */ this.attributesToSnippet = params.attributesToSnippet; /** * Enable the ranking informations in the response, set to 1 to activate * @see https://www.algolia.com/doc/rest#param-getRankingInfo * @member {number} */ this.getRankingInfo = params.getRankingInfo; /** * Remove duplicates based on the index setting attributeForDistinct * @see https://www.algolia.com/doc/rest#param-distinct * @member {boolean|number} */ this.distinct = params.distinct; /** * Center of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundLatLng * @member {string} */ this.aroundLatLng = params.aroundLatLng; /** * Center of the search, retrieve from the user IP. * @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP * @member {boolean} */ this.aroundLatLngViaIP = params.aroundLatLngViaIP; /** * Radius of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundRadius * @member {number} */ this.aroundRadius = params.aroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundPrecision * @member {number} */ this.minimumAroundRadius = params.minimumAroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-minimumAroundRadius * @member {number} */ this.aroundPrecision = params.aroundPrecision; /** * Geo search inside a box. * @see https://www.algolia.com/doc/rest#param-insideBoundingBox * @member {string} */ this.insideBoundingBox = params.insideBoundingBox; /** * Geo search inside a polygon. * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.insidePolygon = params.insidePolygon; /** * Allows to specify an ellipsis character for the snippet when we truncate the text * (added before and after if truncated). * The default value is an empty string and we recommend to set it to "…" * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.snippetEllipsisText = params.snippetEllipsisText; /** * Allows to specify some attributes name on which exact won't be applied. * Attributes are separated with a comma (for example "name,address" ), you can also use a * JSON string array encoding (for example encodeURIComponent('["name","address"]') ). * By default the list is empty. * @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes * @member {string|string[]} */ this.disableExactOnAttributes = params.disableExactOnAttributes; /** * Applies 'exact' on single word queries if the word contains at least 3 characters * and is not a stop word. * Can take two values: true or false. * By default, its set to false. * @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery * @member {boolean} */ this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery; // Undocumented parameters, still needed otherwise we fail this.offset = params.offset; this.length = params.length; var self = this; forOwn_1(params, function checkForUnknownParameter(paramValue, paramName) { if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) { self[paramName] = paramValue; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = keys_1(new SearchParameters()); /** * @private * @param {object} partialState full or part of a state * @return {object} a new object with the number keys as number */ SearchParameters._parseNumbers = function(partialState) { // Do not reparse numbers in SearchParameters, they ought to be parsed already if (partialState instanceof SearchParameters) return partialState; var numbers = {}; var numberKeys = [ 'aroundPrecision', 'aroundRadius', 'getRankingInfo', 'minWordSizefor2Typos', 'minWordSizefor1Typo', 'page', 'maxValuesPerFacet', 'distinct', 'minimumAroundRadius', 'hitsPerPage', 'minProximity' ]; forEach_1(numberKeys, function(k) { var value = partialState[k]; if (isString_1(value)) { var parsedValue = parseFloat(value); numbers[k] = _isNaN(parsedValue) ? value : parsedValue; } }); // there's two formats of insideBoundingBox, we need to parse // the one which is an array of float geo rectangles if (Array.isArray(partialState.insideBoundingBox)) { numbers.insideBoundingBox = partialState.insideBoundingBox.map(function(geoRect) { return geoRect.map(function(value) { return parseFloat(value); }); }); } if (partialState.numericRefinements) { var numericRefinements = {}; forEach_1(partialState.numericRefinements, function(operators, attribute) { numericRefinements[attribute] = {}; forEach_1(operators, function(values, operator) { var parsedValues = map_1(values, function(v) { if (Array.isArray(v)) { return map_1(v, function(vPrime) { if (isString_1(vPrime)) { return parseFloat(vPrime); } return vPrime; }); } else if (isString_1(v)) { return parseFloat(v); } return v; }); numericRefinements[attribute][operator] = parsedValues; }); }); numbers.numericRefinements = numericRefinements; } return merge_1({}, partialState, numbers); }; /** * Factory for SearchParameters * @param {object|SearchParameters} newParameters existing parameters or partial * object for the properties of a new SearchParameters * @return {SearchParameters} frozen instance of SearchParameters */ SearchParameters.make = function makeSearchParameters(newParameters) { var instance = new SearchParameters(newParameters); forEach_1(newParameters.hierarchicalFacets, function(facet) { if (facet.rootPath) { var currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) { instance = instance.clearRefinements(facet.name); } // get it again in case it has been cleared currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length === 0) { instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath); } } }); return instance; }; /** * Validates the new parameters based on the previous state * @param {SearchParameters} currentState the current state * @param {object|SearchParameters} parameters the new parameters to set * @return {Error|null} Error if the modification is invalid, null otherwise */ SearchParameters.validate = function(currentState, parameters) { var params = parameters || {}; if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) { return new Error( '[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' + 'an error, if it is really what you want, you should first clear the tags with clearTags method.'); } if (currentState.tagRefinements.length > 0 && params.tagFilters) { return new Error( '[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' + 'an error, if it is not, you should first clear the tags with clearTags method.'); } if (currentState.numericFilters && params.numericRefinements && !isEmpty_1(params.numericRefinements)) { return new Error( "[Numeric filters] Can't switch from the advanced to the managed API. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } if (!isEmpty_1(currentState.numericRefinements) && params.numericFilters) { return new Error( "[Numeric filters] Can't switch from the managed API to the advanced. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } return null; }; SearchParameters.prototype = { constructor: SearchParameters, /** * Remove all refinements (disjunctive + conjunctive + excludes + numeric filters) * @method * @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {SearchParameters} */ clearRefinements: function clearRefinements(attribute) { var clear = RefinementList.clearRefinement; var patch = { numericRefinements: this._clearNumericRefinements(attribute), facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'), facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'), disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'), hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet') }; if (patch.numericRefinements === this.numericRefinements && patch.facetsRefinements === this.facetsRefinements && patch.facetsExcludes === this.facetsExcludes && patch.disjunctiveFacetsRefinements === this.disjunctiveFacetsRefinements && patch.hierarchicalFacetsRefinements === this.hierarchicalFacetsRefinements) { return this; } return this.setQueryParameters(patch); }, /** * Remove all the refined tags from the SearchParameters * @method * @return {SearchParameters} */ clearTags: function clearTags() { if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this; return this.setQueryParameters({ tagFilters: undefined, tagRefinements: [] }); }, /** * Set the index. * @method * @param {string} index the index name * @return {SearchParameters} */ setIndex: function setIndex(index) { if (index === this.index) return this; return this.setQueryParameters({ index: index }); }, /** * Query setter * @method * @param {string} newQuery value for the new query * @return {SearchParameters} */ setQuery: function setQuery(newQuery) { if (newQuery === this.query) return this; return this.setQueryParameters({ query: newQuery }); }, /** * Page setter * @method * @param {number} newPage new page number * @return {SearchParameters} */ setPage: function setPage(newPage) { if (newPage === this.page) return this; return this.setQueryParameters({ page: newPage }); }, /** * Facets setter * The facets are the simple facets, used for conjunctive (and) faceting. * @method * @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting * @return {SearchParameters} */ setFacets: function setFacets(facets) { return this.setQueryParameters({ facets: facets }); }, /** * Disjunctive facets setter * Change the list of disjunctive (or) facets the helper chan handle. * @method * @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting * @return {SearchParameters} */ setDisjunctiveFacets: function setDisjunctiveFacets(facets) { return this.setQueryParameters({ disjunctiveFacets: facets }); }, /** * HitsPerPage setter * Hits per page represents the number of hits retrieved for this query * @method * @param {number} n number of hits retrieved per page of results * @return {SearchParameters} */ setHitsPerPage: function setHitsPerPage(n) { if (this.hitsPerPage === n) return this; return this.setQueryParameters({ hitsPerPage: n }); }, /** * typoTolerance setter * Set the value of typoTolerance * @method * @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict") * @return {SearchParameters} */ setTypoTolerance: function setTypoTolerance(typoTolerance) { if (this.typoTolerance === typoTolerance) return this; return this.setQueryParameters({ typoTolerance: typoTolerance }); }, /** * Add a numeric filter for a given attribute * When value is an array, they are combined with OR * When value is a single value, it will combined with AND * @method * @param {string} attribute attribute to set the filter on * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number | number[]} value value of the filter * @return {SearchParameters} * @example * // for price = 50 or 40 * searchparameter.addNumericRefinement('price', '=', [50, 40]); * @example * // for size = 38 and 40 * searchparameter.addNumericRefinement('size', '=', 38); * searchparameter.addNumericRefinement('size', '=', 40); */ addNumericRefinement: function(attribute, operator, v) { var value = valToNumber_1(v); if (this.isNumericRefined(attribute, operator, value)) return this; var mod = merge_1({}, this.numericRefinements); mod[attribute] = merge_1({}, mod[attribute]); if (mod[attribute][operator]) { // Array copy mod[attribute][operator] = mod[attribute][operator].slice(); // Add the element. Concat can't be used here because value can be an array. mod[attribute][operator].push(value); } else { mod[attribute][operator] = [value]; } return this.setQueryParameters({ numericRefinements: mod }); }, /** * Get the list of conjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getConjunctiveRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsRefinements[facetName] || []; }, /** * Get the list of disjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getDisjunctiveRefinements: function(facetName) { if (!this.isDisjunctiveFacet(facetName)) { throw new Error( facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ); } return this.disjunctiveFacetsRefinements[facetName] || []; }, /** * Get the list of hierarchical refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getHierarchicalRefinement: function(facetName) { // we send an array but we currently do not support multiple // hierarchicalRefinements for a hierarchicalFacet return this.hierarchicalFacetsRefinements[facetName] || []; }, /** * Get the list of exclude refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getExcludeRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsExcludes[facetName] || []; }, /** * Remove all the numeric filter for a given (attribute, operator) * @method * @param {string} attribute attribute to set the filter on * @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number} [number] the value to be removed * @return {SearchParameters} */ removeNumericRefinement: function(attribute, operator, paramValue) { if (paramValue !== undefined) { var paramValueAsNumber = valToNumber_1(paramValue); if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator && isEqual_1(value.val, paramValueAsNumber); }) }); } else if (operator !== undefined) { if (!this.isNumericRefined(attribute, operator)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator; }) }); } if (!this.isNumericRefined(attribute)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute; }) }); }, /** * Get the list of numeric refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {SearchParameters.OperatorList[]} list of refinements */ getNumericRefinements: function(facetName) { return this.numericRefinements[facetName] || {}; }, /** * Return the current refinement for the (attribute, operator) * @param {string} attribute attribute in the record * @param {string} operator operator applied on the refined values * @return {Array.<number|number[]>} refined values */ getNumericRefinement: function(attribute, operator) { return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator]; }, /** * Clear numeric filters. * @method * @private * @param {string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {Object.<string, OperatorList>} */ _clearNumericRefinements: function _clearNumericRefinements(attribute) { if (isUndefined_1(attribute)) { if (isEmpty_1(this.numericRefinements)) return this.numericRefinements; return {}; } else if (isString_1(attribute)) { if (isEmpty_1(this.numericRefinements[attribute])) return this.numericRefinements; return omit_1(this.numericRefinements, attribute); } else if (isFunction_1(attribute)) { var hasChanged = false; var newNumericRefinements = reduce_1(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach_1(operators, function(values, operator) { var outValues = []; forEach_1(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty_1(outValues)) { if (outValues.length !== values.length) hasChanged = true; operatorList[operator] = outValues; } else hasChanged = true; }); if (!isEmpty_1(operatorList)) memo[key] = operatorList; return memo; }, {}); if (hasChanged) return newNumericRefinements; return this.numericRefinements; } }, /** * Add a facet to the facets attribute of the helper configuration, if it * isn't already present. * @method * @param {string} facet facet name to add * @return {SearchParameters} */ addFacet: function addFacet(facet) { if (this.isConjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ facets: this.facets.concat([facet]) }); }, /** * Add a disjunctive facet to the disjunctiveFacets attribute of the helper * configuration, if it isn't already present. * @method * @param {string} facet disjunctive facet name to add * @return {SearchParameters} */ addDisjunctiveFacet: function addDisjunctiveFacet(facet) { if (this.isDisjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.concat([facet]) }); }, /** * Add a hierarchical facet to the hierarchicalFacets attribute of the helper * configuration. * @method * @param {object} hierarchicalFacet hierarchical facet to add * @return {SearchParameters} * @throws will throw an error if a hierarchical facet with the same name was already declared */ addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) { if (this.isHierarchicalFacet(hierarchicalFacet.name)) { throw new Error( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`'); } return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) }); }, /** * Add a refinement on a "normal" facet * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addFacetRefinement: function addFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) }); }, /** * Exclude a value from a "normal" facet * @method * @param {string} facet attribute to apply the exclusion on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addExcludeRefinement: function addExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) }); }, /** * Adds a refinement on a disjunctive facet. * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * addTagRefinement adds a tag to the list used to filter the results * @param {string} tag tag to be added * @return {SearchParameters} */ addTagRefinement: function addTagRefinement(tag) { if (this.isTagRefined(tag)) return this; var modification = { tagRefinements: this.tagRefinements.concat(tag) }; return this.setQueryParameters(modification); }, /** * Remove a facet from the facets attribute of the helper configuration, if it * is present. * @method * @param {string} facet facet name to remove * @return {SearchParameters} */ removeFacet: function removeFacet(facet) { if (!this.isConjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ facets: filter_1(this.facets, function(f) { return f !== facet; }) }); }, /** * Remove a disjunctive facet from the disjunctiveFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet disjunctive facet name to remove * @return {SearchParameters} */ removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) { if (!this.isDisjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: filter_1(this.disjunctiveFacets, function(f) { return f !== facet; }) }); }, /** * Remove a hierarchical facet from the hierarchicalFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet hierarchical facet name to remove * @return {SearchParameters} */ removeHierarchicalFacet: function removeHierarchicalFacet(facet) { if (!this.isHierarchicalFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: filter_1(this.hierarchicalFacets, function(f) { return f.name !== facet; }) }); }, /** * Remove a refinement set on facet. If a value is provided, it will clear the * refinement for the given value, otherwise it will clear all the refinement * values for the faceted attribute. * @method * @param {string} facet name of the attribute used for faceting * @param {string} [value] value used to filter * @return {SearchParameters} */ removeFacetRefinement: function removeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) }); }, /** * Remove a negative refinement on a facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeExcludeRefinement: function removeExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) }); }, /** * Remove a refinement on a disjunctive facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Remove a tag from the list of tag refinements * @method * @param {string} tag the tag to remove * @return {SearchParameters} */ removeTagRefinement: function removeTagRefinement(tag) { if (!this.isTagRefined(tag)) return this; var modification = { tagRefinements: filter_1(this.tagRefinements, function(t) { return t !== tag; }) }; return this.setQueryParameters(modification); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper * @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement} */ toggleRefinement: function toggleRefinement(facet, value) { return this.toggleFacetRefinement(facet, value); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper */ toggleFacetRefinement: function toggleFacetRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleConjunctiveFacetRefinement(facet, value); } else if (this.isDisjunctiveFacet(facet)) { return this.toggleDisjunctiveFacetRefinement(facet, value); } throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.toggleRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet)); var mod = {}; var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined && this.hierarchicalFacetsRefinements[facet].length > 0 && ( // remove current refinement: // refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0] === value || // remove a parent refinement of the current refinement: // - refinement was 'beer > IPA > Flying dog' // - call is toggleRefine('beer > IPA') // - refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0 ); if (upOneOrMultipleLevel) { if (value.indexOf(separator) === -1) { // go back to root level mod[facet] = []; } else { mod[facet] = [value.slice(0, value.lastIndexOf(separator))]; } } else { mod[facet] = [value]; } return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Adds a refinement on a hierarchical facet. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is refined */ addHierarchicalFacetRefinement: function(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is not refined */ removeHierarchicalFacetRefinement: function(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Switch the tag refinement * @method * @param {string} tag the tag to remove or add * @return {SearchParameters} */ toggleTagRefinement: function toggleTagRefinement(tag) { if (this.isTagRefined(tag)) { return this.removeTagRefinement(tag); } return this.addTagRefinement(tag); }, /** * Test if the facet name is from one of the disjunctive facets * @method * @param {string} facet facet name to test * @return {boolean} */ isDisjunctiveFacet: function(facet) { return indexOf_1(this.disjunctiveFacets, facet) > -1; }, /** * Test if the facet name is from one of the hierarchical facets * @method * @param {string} facetName facet name to test * @return {boolean} */ isHierarchicalFacet: function(facetName) { return this.getHierarchicalFacetByName(facetName) !== undefined; }, /** * Test if the facet name is from one of the conjunctive/normal facets * @method * @param {string} facet facet name to test * @return {boolean} */ isConjunctiveFacet: function(facet) { return indexOf_1(this.facets, facet) > -1; }, /** * Returns true if the facet is refined, either for a specific value or in * general. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value, optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isFacetRefined: function isFacetRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsRefinements, facet, value); }, /** * Returns true if the facet contains exclusions or if a specific value is * excluded. * * @method * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isExcludeRefined: function isExcludeRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsExcludes, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return indexOf_1(refinements, value) !== -1; }, /** * Test if the triple (attribute, operator, value) is already refined. * If only the attribute and the operator are provided, it tests if the * contains any refinement value. * @method * @param {string} attribute attribute for which the refinement is applied * @param {string} [operator] operator of the refinement * @param {string} [value] value of the refinement * @return {boolean} true if it is refined */ isNumericRefined: function isNumericRefined(attribute, operator, value) { if (isUndefined_1(value) && isUndefined_1(operator)) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && !isUndefined_1(this.numericRefinements[attribute][operator]); if (isUndefined_1(value) || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber_1(value); var isAttributeValueDefined = !isUndefined_1( findArray(this.numericRefinements[attribute][operator], parsedValue) ); return isOperatorDefined && isAttributeValueDefined; }, /** * Returns true if the tag refined, false otherwise * @method * @param {string} tag the tag to check * @return {boolean} */ isTagRefined: function isTagRefined(tag) { return indexOf_1(this.tagRefinements, tag) !== -1; }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection_1( keys_1(this.numericRefinements), this.disjunctiveFacets ); return keys_1(this.disjunctiveFacetsRefinements) .concat(disjunctiveNumericRefinedFacets) .concat(this.getRefinedHierarchicalFacets()); }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() { return intersection_1( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index map_1(this.hierarchicalFacets, 'name'), keys_1(this.hierarchicalFacetsRefinements) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return filter_1(this.disjunctiveFacets, function(f) { return indexOf_1(refinedFacets, f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; forOwn_1(this, function(paramValue, paramName) { if (indexOf_1(managedParameters, paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * Let the user retrieve any parameter value from the SearchParameters * @param {string} paramName name of the parameter * @return {any} the value of the parameter */ getQueryParameter: function getQueryParameter(paramName) { if (!this.hasOwnProperty(paramName)) { throw new Error( "Parameter '" + paramName + "' is not an attribute of SearchParameters " + '(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)'); } return this[paramName]; }, /** * Let the user set a specific value for a given parameter. Will return the * same instance if the parameter is invalid or if the value is the same as the * previous one. * @method * @param {string} parameter the parameter name * @param {any} value the value to be set, must be compliant with the definition * of the attribute on the object * @return {SearchParameters} the updated state */ setQueryParameter: function setParameter(parameter, value) { if (this[parameter] === value) return this; var modification = {}; modification[parameter] = value; return this.setQueryParameters(modification); }, /** * Let the user set any of the parameters with a plain object. * @method * @param {object} params all the keys and the values to be updated * @return {SearchParameters} a new updated instance */ setQueryParameters: function setQueryParameters(params) { if (!params) return this; var error = SearchParameters.validate(this, params); if (error) { throw error; } var parsedParams = SearchParameters._parseNumbers(params); return this.mutateMe(function mergeWith(newInstance) { var ks = keys_1(params); forEach_1(ks, function(k) { newInstance[k] = parsedParams[k]; }); return newInstance; }); }, /** * Returns an object with only the selected attributes. * @param {string[]} filters filters to retrieve only a subset of the state. It * accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage) * or attributes of the index with the notation 'attribute:nameOfMyAttribute' * @return {object} */ filter: function(filters) { return filterState_1(this, filters); }, /** * Helper function to make it easier to build new instances from a mutating * function * @private * @param {function} fn newMutableState -> previousState -> () function that will * change the value of the newMutable to the desired state * @return {SearchParameters} a new instance with the specified modifications applied */ mutateMe: function mutateMe(fn) { var newState = new this.constructor(this); fn(newState, this); return newState; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSortBy: function(hierarchicalFacet) { return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc']; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSeparator: function(hierarchicalFacet) { return hierarchicalFacet.separator || ' > '; }, /** * Helper function to get the hierarchicalFacet prefix path or null * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.rootPath or null as default */ _getHierarchicalRootPath: function(hierarchicalFacet) { return hierarchicalFacet.rootPath || null; }, /** * Helper function to check if we show the parent level of the hierarchicalFacet * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.showParentLevel or true as default */ _getHierarchicalShowParentLevel: function(hierarchicalFacet) { if (typeof hierarchicalFacet.showParentLevel === 'boolean') { return hierarchicalFacet.showParentLevel; } return true; }, /** * Helper function to get the hierarchicalFacet by it's name * @param {string} hierarchicalFacetName * @return {object} a hierarchicalFacet */ getHierarchicalFacetByName: function(hierarchicalFacetName) { return find_1( this.hierarchicalFacets, {name: hierarchicalFacetName} ); }, /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ getHierarchicalFacetBreadcrumb: function(facetName) { if (!this.isHierarchicalFacet(facetName)) { throw new Error( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`'); } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return map_1(path, trim_1); }, toString: function() { return JSON.stringify(this, null, 2); } }; /** * Callback used for clearRefinement method * @callback SearchParameters.clearCallback * @param {OperatorList|FacetList} value the value of the filter * @param {string} key the current attribute name * @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude` * depending on the type of facet * @return {boolean} `true` if the element should be removed. `false` otherwise. */ var SearchParameters_1 = SearchParameters; /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } var compact_1 = compact; /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } var _baseSum = baseSum; /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? _baseSum(array, _baseIteratee(iteratee, 2)) : 0; } var sumBy_1 = sumBy; /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return _arrayMap(props, function(key) { return object[key]; }); } var _baseValues = baseValues; /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : _baseValues(object, keys_1(object)); } var values_1 = values; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$3 = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike_1(collection) ? collection : values_1(collection); fromIndex = (fromIndex && !guard) ? toInteger_1(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax$3(length + fromIndex, 0); } return isString_1(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && _baseIndexOf(collection, value, fromIndex) > -1); } var includes_1 = includes; /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } var _baseSortBy = baseSortBy; /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } var _compareAscending = compareAscending; /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = _compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } var _compareMultiple = compareMultiple; /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = _arrayMap(iteratees.length ? iteratees : [identity_1], _baseUnary(_baseIteratee)); var result = _baseMap(collection, function(value, key, collection) { var criteria = _arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return _baseSortBy(result, function(object, other) { return _compareMultiple(object, other, orders); }); } var _baseOrderBy = baseOrderBy; /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray_1(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray_1(orders)) { orders = orders == null ? [] : [orders]; } return _baseOrderBy(collection, iteratees, orders); } var orderBy_1 = orderBy; /** Used to store function metadata. */ var metaMap = _WeakMap && new _WeakMap; var _metaMap = metaMap; /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !_metaMap ? identity_1 : function(func, data) { _metaMap.set(func, data); return func; }; var _baseSetData = baseSetData; /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = _baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject_1(result) ? result : thisBinding; }; } var _createCtor = createCtor; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = _createCtor(func); function wrapper() { var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } var _createBind = createBind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$4 = Math.max; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax$4(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } var _composeArgs = composeArgs; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$5 = Math.max; /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax$5(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } var _composeArgsRight = composeArgsRight; /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } var _countHolders = countHolders; /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } var _baseLodash = baseLodash; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; var _LazyWrapper = LazyWrapper; /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop$1() { // No operation performed. } var noop_1 = noop$1; /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !_metaMap ? noop_1 : function(func) { return _metaMap.get(func); }; var _getData = getData; /** Used to lookup unminified function names. */ var realNames = {}; var _realNames = realNames; /** Used for built-in method references. */ var objectProto$i = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$g = objectProto$i.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = _realNames[result], length = hasOwnProperty$g.call(_realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } var _getFuncName = getFuncName; /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = _baseCreate(_baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; var _LodashWrapper = LodashWrapper; /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof _LazyWrapper) { return wrapper.clone(); } var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = _copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } var _wrapperClone = wrapperClone; /** Used for built-in method references. */ var objectProto$j = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$h = objectProto$j.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) { if (value instanceof _LodashWrapper) { return value; } if (hasOwnProperty$h.call(value, '__wrapped__')) { return _wrapperClone(value); } } return new _LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = _baseLodash.prototype; lodash.prototype.constructor = lodash; var wrapperLodash = lodash; /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = _getFuncName(func), other = wrapperLodash[funcName]; if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = _getData(other); return !!data && func === data[0]; } var _isLaziable = isLaziable; /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = _shortOut(_baseSetData); var _setData = setData; /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } var _getWrapDetails = getWrapDetails; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } var _insertWrapDetails = insertWrapDetails; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$1 = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG$1], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { _arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } var _updateWrapDetails = updateWrapDetails; /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask))); } var _setWrapToString = setWrapToString; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$2 = 1, WRAP_BIND_KEY_FLAG$1 = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG$1 = 8, WRAP_PARTIAL_FLAG$1 = 32, WRAP_PARTIAL_RIGHT_FLAG$1 = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG$1, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG$2 | WRAP_BIND_KEY_FLAG$1); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (_isLaziable(func)) { _setData(result, newData); } result.placeholder = placeholder; return _setWrapToString(result, func, bitmask); } var _createRecurry = createRecurry; /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = func; return object.placeholder; } var _getHolder = getHolder; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$1 = Math.min; /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin$1(indexes.length, arrLength), oldArray = _copyArray(array); while (length--) { var index = indexes[length]; array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } var _reorder = reorder; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } var _replaceHolders = replaceHolders; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$3 = 1, WRAP_BIND_KEY_FLAG$2 = 2, WRAP_CURRY_FLAG$2 = 8, WRAP_CURRY_RIGHT_FLAG$1 = 16, WRAP_ARY_FLAG$1 = 128, WRAP_FLIP_FLAG$1 = 512; /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG$1, isBind = bitmask & WRAP_BIND_FLAG$3, isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2, isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1), isFlip = bitmask & WRAP_FLIP_FLAG$1, Ctor = isBindKey ? undefined : _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = _getHolder(wrapper), holdersCount = _countHolders(args, placeholder); } if (partials) { args = _composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = _composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = _replaceHolders(args, placeholder); return _createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = _reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== _root && this instanceof wrapper) { fn = Ctor || _createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } var _createHybrid = createHybrid; /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = _getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : _replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return _createRecurry( func, bitmask, _createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return _apply(fn, this, args); } return wrapper; } var _createCurry = createCurry; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$4 = 1; /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG$4, Ctor = _createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return _apply(fn, isBind ? thisArg : this, args); } return wrapper; } var _createPartial = createPartial; /** Used as the internal argument placeholder. */ var PLACEHOLDER$1 = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$5 = 1, WRAP_BIND_KEY_FLAG$3 = 2, WRAP_CURRY_BOUND_FLAG$1 = 4, WRAP_CURRY_FLAG$3 = 8, WRAP_ARY_FLAG$2 = 128, WRAP_REARG_FLAG$1 = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$2 = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG$5 | WRAP_BIND_KEY_FLAG$3 | WRAP_ARY_FLAG$2); var isCombo = ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_CURRY_FLAG$3)) || ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$3)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG$5) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG$5 ? 0 : WRAP_CURRY_BOUND_FLAG$1; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? _composeArgs(partials, value, source[4]) : value; data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER$1) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER$1) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG$2) { data[8] = data[8] == null ? source[8] : nativeMin$2(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } var _mergeData = mergeData; /** Error message constants. */ var FUNC_ERROR_TEXT$1 = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$6 = 1, WRAP_BIND_KEY_FLAG$4 = 2, WRAP_CURRY_FLAG$4 = 8, WRAP_CURRY_RIGHT_FLAG$2 = 16, WRAP_PARTIAL_FLAG$2 = 32, WRAP_PARTIAL_RIGHT_FLAG$2 = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$6 = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG$4; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT$1); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG$2 | WRAP_PARTIAL_RIGHT_FLAG$2); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax$6(toInteger_1(ary), 0); arity = arity === undefined ? arity : toInteger_1(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG$2) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : _getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { _mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax$6(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2)) { bitmask &= ~(WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2); } if (!bitmask || bitmask == WRAP_BIND_FLAG$6) { var result = _createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG$4 || bitmask == WRAP_CURRY_RIGHT_FLAG$2) { result = _createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG$2 || bitmask == (WRAP_BIND_FLAG$6 | WRAP_PARTIAL_FLAG$2)) && !holders.length) { result = _createPartial(func, bitmask, thisArg, partials); } else { result = _createHybrid.apply(undefined, newData); } var setter = data ? _baseSetData : _setData; return _setWrapToString(setter(result, newData), func, bitmask); } var _createWrap = createWrap; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_FLAG$3 = 32; /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partial)); return _createWrap(func, WRAP_PARTIAL_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partial.placeholder = {}; var partial_1 = partial; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_RIGHT_FLAG$3 = 64; /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partialRight)); return _createWrap(func, WRAP_PARTIAL_RIGHT_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partialRight.placeholder = {}; var partialRight_1 = partialRight; /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } var _baseClamp = baseClamp; /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString_1(string); position = position == null ? 0 : _baseClamp(toInteger_1(position), 0, string.length); target = _baseToString(target); return string.slice(position, position + target.length) == target; } var startsWith_1 = startsWith; /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ var formatSort = function formatSort(sortBy, defaults) { return reduce_1(sortBy, function preparePredicate(out, sortInstruction) { var sortInstructions = sortInstruction.split(':'); if (defaults && sortInstructions.length === 1) { var similarDefault = find_1(defaults, function(predicate) { return startsWith_1(predicate, sortInstruction[0]); }); if (similarDefault) { sortInstructions = similarDefault.split(':'); } } out[0].push(sortInstructions[0]); out[1].push(sortInstructions[1]); return out; }, [[], []]); }; /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject_1(object)) { return object; } path = _castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = _toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject_1(objValue) ? objValue : (_isIndex(path[index + 1]) ? [] : {}); } } _assignValue(nested, key, newValue); nested = nested[key]; } return object; } var _baseSet = baseSet; /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = _baseGet(object, path); if (predicate(value, path)) { _baseSet(result, _castPath(path, object), value); } } return result; } var _basePickBy = basePickBy; /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = _arrayMap(_getAllKeysIn(object), function(prop) { return [prop]; }); predicate = _baseIteratee(predicate); return _basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } var pickBy_1 = pickBy; var generateHierarchicalTree_1 = generateTrees; function generateTrees(state) { return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) { var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex]; var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || ''; var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet); var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet); var sortBy = formatSort(state._getHierarchicalFacetSortBy(hierarchicalFacet)); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return reduce_1(results, generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path data: null }); }; } function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) { return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) { var parent = hierarchicalTree; if (currentHierarchicalLevel > 0) { var level = 0; parent = hierarchicalTree; while (level < currentHierarchicalLevel) { parent = parent && find_1(parent.data, {isRefined: true}); level++; } } // we found a refined parent, let's add current level data under it if (parent) { // filter values in case an object has multiple categories: // { // categories: { // level0: ['beers', 'bières'], // level1: ['beers > IPA', 'bières > Belges'] // } // } // // If parent refinement is `beers`, then we do not want to have `bières > Belges` // showing up var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); parent.data = orderBy_1( map_1( pickBy_1(hierarchicalFacetResult.data, onlyMatchingValuesFn), formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) ), sortBy[0], sortBy[1] ); } return hierarchicalTree; }; } function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { return function(facetCount, facetValue) { // we want the facetValue is a child of hierarchicalRootPath if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) { return false; } // we always want root levels (only when there is no prefix path) return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || // if there is a rootPath, being root level mean 1 level under rootPath hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || // if current refinement is a root level and current facetValue is a root level, // keep the facetValue facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || // currentRefinement is a child of the facet value currentRefinement.indexOf(facetValue) === 0 || // facetValue is a child of the current parent, add it facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0); }; } function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) { return function format(facetCount, facetValue) { return { name: trim_1(last_1(facetValue.split(hierarchicalSeparator))), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, data: null }; }; } /** * @typedef SearchResults.Facet * @type {object} * @property {string} name name of the attribute in the record * @property {object} data the faceting data: value, number of entries * @property {object} stats undefined unless facet_stats is retrieved from algolia */ /** * @typedef SearchResults.HierarchicalFacet * @type {object} * @property {string} name name of the current value given the hierarchical level, trimmed. * If root node, you get the facet name * @property {number} count number of objects matching this hierarchical value * @property {string} path the current hierarchical value full path * @property {boolean} isRefined `true` if the current value was refined, `false` otherwise * @property {HierarchicalFacet[]} data sub values for the current level */ /** * @typedef SearchResults.FacetValue * @type {object} * @property {string} name the facet value itself * @property {number} count times this facet appears in the results * @property {boolean} isRefined is the facet currently selected * @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets) */ /** * @typedef Refinement * @type {object} * @property {string} type the type of filter used: * `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical` * @property {string} attributeName name of the attribute used for filtering * @property {string} name the value of the filter * @property {number} numericValue the value as a number. Only for numeric filters. * @property {string} operator the operator used. Only for numeric filters. * @property {number} count the number of computed hits for this filter. Only on facets. * @property {boolean} exhaustive if the count is exhaustive */ function getIndices(obj) { var indices = {}; forEach_1(obj, function(val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find_1( hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { return includes_1(hierarchicalFacet.attributes, hierarchicalAttributeName); } ); } /*eslint-disable */ /** * Constructor for SearchResults * @class * @classdesc SearchResults contains the results of a query to Algolia using the * {@link AlgoliaSearchHelper}. * @param {SearchParameters} state state that led to the response * @param {array.<object>} results the results from algolia client * @example <caption>SearchResults of the first query in * <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption> { "hitsPerPage": 10, "processingTimeMS": 2, "facets": [ { "name": "type", "data": { "HardGood": 6627, "BlackTie": 550, "Music": 665, "Software": 131, "Game": 456, "Movie": 1571 }, "exhaustive": false }, { "exhaustive": false, "data": { "Free shipping": 5507 }, "name": "shipping" } ], "hits": [ { "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif", "_highlightResult": { "shortDescription": { "matchLevel": "none", "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "matchedWords": [] }, "category": { "matchLevel": "none", "value": "Computer Security Software", "matchedWords": [] }, "manufacturer": { "matchedWords": [], "value": "Webroot", "matchLevel": "none" }, "name": { "value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "matchedWords": [], "matchLevel": "none" } }, "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg", "shipping": "Free shipping", "bestSellingRank": 4, "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ", "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "category": "Computer Security Software", "salePrice_range": "1 - 50", "objectID": "1688832", "type": "Software", "customerReviewCount": 5980, "salePrice": 49.99, "manufacturer": "Webroot" }, .... ], "nbHits": 10000, "disjunctiveFacets": [ { "exhaustive": false, "data": { "5": 183, "12": 112, "7": 149, ... }, "name": "customerReviewCount", "stats": { "max": 7461, "avg": 157.939, "min": 1 } }, { "data": { "Printer Ink": 142, "Wireless Speakers": 60, "Point & Shoot Cameras": 48, ... }, "name": "category", "exhaustive": false }, { "exhaustive": false, "data": { "> 5000": 2, "1 - 50": 6524, "501 - 2000": 566, "201 - 500": 1501, "101 - 200": 1360, "2001 - 5000": 47 }, "name": "salePrice_range" }, { "data": { "Dynex™": 202, "Insignia™": 230, "PNY": 72, ... }, "name": "manufacturer", "exhaustive": false } ], "query": "", "nbPages": 100, "page": 0, "index": "bestbuy" } **/ /*eslint-enable */ function SearchResults(state, results) { var mainSubResponse = results[0]; this._rawResults = results; /** * query used to generate the results * @member {string} */ this.query = mainSubResponse.query; /** * The query as parsed by the engine given all the rules. * @member {string} */ this.parsedQuery = mainSubResponse.parsedQuery; /** * all the records that match the search parameters. Each record is * augmented with a new attribute `_highlightResult` * which is an object keyed by attribute and with the following properties: * - `value` : the value of the facet highlighted (html) * - `matchLevel`: full, partial or none depending on how the query terms match * @member {object[]} */ this.hits = mainSubResponse.hits; /** * index where the results come from * @member {string} */ this.index = mainSubResponse.index; /** * number of hits per page requested * @member {number} */ this.hitsPerPage = mainSubResponse.hitsPerPage; /** * total number of hits of this query on the index * @member {number} */ this.nbHits = mainSubResponse.nbHits; /** * total number of pages with respect to the number of hits per page and the total number of hits * @member {number} */ this.nbPages = mainSubResponse.nbPages; /** * current page * @member {number} */ this.page = mainSubResponse.page; /** * sum of the processing time of all the queries * @member {number} */ this.processingTimeMS = sumBy_1(results, 'processingTimeMS'); /** * The position if the position was guessed by IP. * @member {string} * @example "48.8637,2.3615", */ this.aroundLatLng = mainSubResponse.aroundLatLng; /** * The radius computed by Algolia. * @member {string} * @example "126792922", */ this.automaticRadius = mainSubResponse.automaticRadius; /** * String identifying the server used to serve this request. * @member {string} * @example "c7-use-2.algolia.net", */ this.serverUsed = mainSubResponse.serverUsed; /** * Boolean that indicates if the computation of the counts did time out. * @deprecated * @member {boolean} */ this.timeoutCounts = mainSubResponse.timeoutCounts; /** * Boolean that indicates if the computation of the hits did time out. * @deprecated * @member {boolean} */ this.timeoutHits = mainSubResponse.timeoutHits; /** * True if the counts of the facets is exhaustive * @member {boolean} */ this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount; /** * True if the number of hits is exhaustive * @member {boolean} */ this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits; /** * Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/). * @member {object[]} */ this.userData = mainSubResponse.userData; /** * queryID is the unique identifier of the query used to generate the current search results. * This value is only available if the `clickAnalytics` search parameter is set to `true`. * @member {string} */ this.queryID = mainSubResponse.queryID; /** * disjunctive facets results * @member {SearchResults.Facet[]} */ this.disjunctiveFacets = []; /** * disjunctive facets results * @member {SearchResults.HierarchicalFacet[]} */ this.hierarchicalFacets = map_1(state.hierarchicalFacets, function initFutureTree() { return []; }); /** * other facets results * @member {SearchResults.Facet[]} */ this.facets = []; var disjunctiveFacets = state.getRefinedDisjunctiveFacets(); var facetsIndices = getIndices(state.facets); var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets); var nextDisjunctiveResult = 1; var self = this; // Since we send request only for disjunctive facets that have been refined, // we get the facets informations from the first, general, response. forEach_1(mainSubResponse.facets, function(facetValueObject, facetKey) { var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName( state.hierarchicalFacets, facetKey ); if (hierarchicalFacet) { // Place the hierarchicalFacet data at the correct index depending on // the attributes order that was defined at the helper initialization var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey); var idxAttributeName = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = indexOf_1(state.disjunctiveFacets, facetKey) !== -1; var isFacetConjunctive = indexOf_1(state.facets, facetKey) !== -1; var position; if (isFacetDisjunctive) { position = disjunctiveFacetsIndices[facetKey]; self.disjunctiveFacets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey); } if (isFacetConjunctive) { position = facetsIndices[facetKey]; self.facets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey); } } }); // Make sure we do not keep holes within the hierarchical facets this.hierarchicalFacets = compact_1(this.hierarchicalFacets); // aggregate the refined disjunctive facets forEach_1(disjunctiveFacets, function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. forEach_1(result.facets, function(facetResults, dfacet) { var position; if (hierarchicalFacet) { position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } self.hierarchicalFacets[position][attributeIndex].data = merge_1( {}, self.hierarchicalFacets[position][attributeIndex].data, facetResults ); } else { position = disjunctiveFacetsIndices[dfacet]; var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}; self.disjunctiveFacets[position] = { name: dfacet, data: defaults_1({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { forEach_1(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && indexOf_1(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are already at a root refinement (or no refinement at all), there is no // root level values request if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) { return; } var result = results[nextDisjunctiveResult]; forEach_1(result.facets, function(facetResults, dfacet) { var position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5), // then the disjunctive values will be `beers` (count: 100), // but we do not want to display // | beers (100) // > IPA (5) // We want // | beers (5) // > IPA (5) var defaultData = {}; if (currentRefinement.length > 0) { var root = currentRefinement[0].split(separator)[0]; defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root]; } self.hierarchicalFacets[position][attributeIndex].data = defaults_1( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes forEach_1(state.facetsExcludes, function(excludes, facetName) { var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; forEach_1(excludes, function(facetValue) { self.facets[position] = self.facets[position] || {name: facetName}; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); this.hierarchicalFacets = map_1(this.hierarchicalFacets, generateHierarchicalTree_1(state)); this.facets = compact_1(this.facets); this.disjunctiveFacets = compact_1(this.disjunctiveFacets); this._state = state; } /** * Get a facet object with its name * @deprecated * @param {string} name name of the faceted attribute * @return {SearchResults.Facet} the facet object */ SearchResults.prototype.getFacetByName = function(name) { var predicate = {name: name}; return find_1(this.facets, predicate) || find_1(this.disjunctiveFacets, predicate) || find_1(this.hierarchicalFacets, predicate); }; /** * Get the facet values of a specified attribute from a SearchResults object. * @private * @param {SearchResults} results the search results to search in * @param {string} attribute name of the faceted attribute to search for * @return {array|object} facet values. For the hierarchical facets it is an object. */ function extractNormalizedFacetValues(results, attribute) { var predicate = {name: attribute}; if (results._state.isConjunctiveFacet(attribute)) { var facet = find_1(results.facets, predicate); if (!facet) return []; return map_1(facet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isFacetRefined(attribute, k), isExcluded: results._state.isExcludeRefined(attribute, k) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find_1(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return map_1(disjunctiveFacet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isDisjunctiveFacetRefined(attribute, k) }; }); } else if (results._state.isHierarchicalFacet(attribute)) { return find_1(results.hierarchicalFacets, predicate); } } /** * Sort nodes of a hierarchical facet results * @private * @param {HierarchicalFacet} node node to upon which we want to apply the sort */ function recSort(sortFn, node) { if (!node.data || node.data.length === 0) { return node; } var children = map_1(node.data, partial_1(recSort, sortFn)); var sortedChildren = sortFn(children); var newNode = merge_1({}, node, {data: sortedChildren}); return newNode; } SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc']; function vanillaSortFn(order, data) { return data.sort(order); } /** * Get a the list of values for a given facet attribute. Those values are sorted * refinement first, descending count (bigger value on top), and name ascending * (alphabetical order). The sort formula can overridden using either string based * predicates or a function. * * This method will return all the values returned by the Algolia engine plus all * the values already refined. This means that it can happen that the * `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet) * might not be respected if you have facet values that are already refined. * @param {string} attribute attribute name * @param {object} opts configuration options. * @param {Array.<string> | function} opts.sortBy * When using strings, it consists of * the name of the [FacetValue](#SearchResults.FacetValue) or the * [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the * order (`asc` or `desc`). For example to order the value by count, the * argument would be `['count:asc']`. * * If only the attribute name is specified, the ordering defaults to the one * specified in the default value for this attribute. * * When not specified, the order is * ascending. This parameter can also be a function which takes two facet * values and should return a number, 0 if equal, 1 if the first argument is * bigger or -1 otherwise. * * The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']` * @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('results', function(content){ * //get values ordered only by name ascending using the string predicate * content.getFacetValues('city', {sortBy: ['name:asc']}); * //get values ordered only by count ascending using a function * content.getFacetValues('city', { * // this is equivalent to ['count:asc'] * sortBy: function(a, b) { * if (a.count === b.count) return 0; * if (a.count > b.count) return 1; * if (b.count > a.count) return -1; * } * }); * }); */ SearchResults.prototype.getFacetValues = function(attribute, opts) { var facetValues = extractNormalizedFacetValues(this, attribute); if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.'); var options = defaults_1({}, opts, {sortBy: SearchResults.DEFAULT_SORT}); if (Array.isArray(options.sortBy)) { var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT); if (Array.isArray(facetValues)) { return orderBy_1(facetValues, order[0], order[1]); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partialRight_1(orderBy_1, order[0], order[1]), facetValues); } else if (isFunction_1(options.sortBy)) { if (Array.isArray(facetValues)) { return facetValues.sort(options.sortBy); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partial_1(vanillaSortFn, options.sortBy), facetValues); } throw new Error( 'options.sortBy is optional but if defined it must be ' + 'either an array of string (predicates) or a sorting function' ); }; /** * Returns the facet stats if attribute is defined and the facet contains some. * Otherwise returns undefined. * @param {string} attribute name of the faceted attribute * @return {object} The stats of the facet */ SearchResults.prototype.getFacetStats = function(attribute) { if (this._state.isConjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.facets, attribute); } else if (this._state.isDisjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute); } throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`'); }; function getFacetStatsIfAvailable(facetList, facetName) { var data = find_1(facetList, {name: facetName}); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhausistivity for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function() { var state = this._state; var results = this; var res = []; forEach_1(state.facetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); forEach_1(state.facetsExcludes, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); forEach_1(state.hierarchicalFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); forEach_1(state.numericRefinements, function(operators, attributeName) { forEach_1(operators, function(values, operator) { forEach_1(values, function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); forEach_1(state.tagRefinements, function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var count = get_1(facet, 'data[' + name + ']'); var exhaustive = get_1(facet, 'exhaustive'); return { type: type, attributeName: attributeName, name: name, count: count || 0, exhaustive: exhaustive || false }; } function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var splitted = name.split(facetDeclaration.separator); var configuredName = splitted[splitted.length - 1]; for (var i = 0; facet !== undefined && i < splitted.length; ++i) { facet = find_1(facet.data, {name: splitted[i]}); } var count = get_1(facet, 'count'); var exhaustive = get_1(facet, 'exhaustive'); return { type: 'hierarchical', attributeName: attributeName, name: configuredName, count: count || 0, exhaustive: exhaustive || false }; } var SearchResults_1 = SearchResults; var isBufferBrowser = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }; var inherits_browser = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var util = createCommonjsModule(function (module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(commonjsGlobal.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var length = output.reduce(function(prev, cur) { if (cur.indexOf('\n') >= 0) ; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = isBufferBrowser; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = inherits_browser; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }); var util_1 = util.format; var util_2 = util.deprecate; var util_3 = util.debuglog; var util_4 = util.inspect; var util_5 = util.isArray; var util_6 = util.isBoolean; var util_7 = util.isNull; var util_8 = util.isNullOrUndefined; var util_9 = util.isNumber; var util_10 = util.isString; var util_11 = util.isSymbol; var util_12 = util.isUndefined; var util_13 = util.isRegExp; var util_14 = util.isObject; var util_15 = util.isDate; var util_16 = util.isError; var util_17 = util.isFunction; var util_18 = util.isPrimitive; var util_19 = util.isBuffer; var util_20 = util.log; var util_21 = util.inherits; var util_22 = util._extend; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } var events = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber$1(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject$1(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined$1(handler)) return false; if (isFunction$1(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject$1(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction$1(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction$1(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject$1(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject$1(this._events[type]) && !this._events[type].warned) { if (!isUndefined$1(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction$1(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction$1(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction$1(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject$1(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction$1(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction$1(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction$1(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction$1(arg) { return typeof arg === 'function'; } function isNumber$1(arg) { return typeof arg === 'number'; } function isObject$1(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined$1(arg) { return arg === void 0; } /** * A DerivedHelper is a way to create sub requests to * Algolia from a main helper. * @class * @classdesc The DerivedHelper provides an event based interface for search callbacks: * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. */ function DerivedHelper(mainHelper, fn) { this.main = mainHelper; this.fn = fn; this.lastResults = null; } util.inherits(DerivedHelper, events.EventEmitter); /** * Detach this helper from the main helper * @return {undefined} * @throws Error if the derived helper is already detached */ DerivedHelper.prototype.detach = function() { this.removeAllListeners(); this.main.detachDerivedHelper(this); }; DerivedHelper.prototype.getModifiedState = function(parameters) { return this.fn(parameters); }; var DerivedHelper_1 = DerivedHelper; var requestBuilder = { /** * Get all the queries to send to the client, those queries can used directly * with the Algolia client. * @private * @return {object[]} The queries */ _getQueries: function getQueries(index, state) { var queries = []; // One query for the hits queries.push({ indexName: index, params: requestBuilder._getHitsSearchParams(state) }); // One for each disjunctive facets forEach_1(state.getRefinedDisjunctiveFacets(), function(refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are deeper than level 0 (starting from `beer > IPA`) // we want to get the root values var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true) }); } }); return queries; }, /** * Build search parameters used to fetch hits * @private * @return {object.<string, any>} */ _getHitsSearchParams: function(state) { var facets = state.facets .concat(state.disjunctiveFacets) .concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state)); var facetFilters = requestBuilder._getFacetFilters(state); var numericFilters = requestBuilder._getNumericFilters(state); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { facets: facets, tagFilters: tagFilters }; if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Build search parameters used to fetch a disjunctive facet * @private * @param {string} facet the associated facet name * @param {boolean} hierarchicalRootLevel ?? FIXME * @return {object} */ _getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) { var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel); var numericFilters = requestBuilder._getNumericFilters(state, facet); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], tagFilters: tagFilters, analytics: false, clickAnalytics: false }; var hierarchicalFacet = state.getHierarchicalFacetByName(facet); if (hierarchicalFacet) { additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute( state, hierarchicalFacet, hierarchicalRootLevel ); } else { additionalParams.facets = facet; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Return the numeric filters in an algolia request fashion * @private * @param {string} [facetName] the name of the attribute for which the filters should be excluded * @return {string[]} the numeric filters in the algolia format */ _getNumericFilters: function(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; forEach_1(state.numericRefinements, function(operators, attribute) { forEach_1(operators, function(values, operator) { if (facetName !== attribute) { forEach_1(values, function(value) { if (Array.isArray(value)) { var vs = map_1(value, function(v) { return attribute + operator + v; }); numericFilters.push(vs); } else { numericFilters.push(attribute + operator + value); } }); } }); }); return numericFilters; }, /** * Return the tags filters depending * @private * @return {string} */ _getTagFilters: function(state) { if (state.tagFilters) { return state.tagFilters; } return state.tagRefinements.join(','); }, /** * Build facetFilters parameter based on current refinements. The array returned * contains strings representing the facet filters in the algolia format. * @private * @param {string} [facet] if set, the current disjunctive facet * @return {array.<string>} */ _getFacetFilters: function(state, facet, hierarchicalRootLevel) { var facetFilters = []; forEach_1(state.facetsRefinements, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); forEach_1(state.facetsExcludes, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(facetValues, facetName) { if (facetName === facet || !facetValues || facetValues.length === 0) return; var orFilters = []; forEach_1(facetValues, function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); forEach_1(state.hierarchicalFacetsRefinements, function(facetValues, facetName) { var facetValue = facetValues[0]; if (facetValue === undefined) { return; } var hierarchicalFacet = state.getHierarchicalFacetByName(facetName); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeToRefine; var attributesIndex; // we ask for parent facet values only when the `facet` is the current hierarchical facet if (facet === facetName) { // if we are at the root level already, no need to ask for facet values, we get them from // the hits query if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) || (rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) { return; } if (!rootPath) { attributesIndex = facetValue.split(separator).length - 2; facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator)); } else { attributesIndex = rootPath.split(separator).length - 1; facetValue = rootPath; } attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } else { attributesIndex = facetValue.split(separator).length - 1; attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } if (attributeToRefine) { facetFilters.push([attributeToRefine + ':' + facetValue]); } }); return facetFilters; }, _getHitsHierarchicalFacetsAttributes: function(state) { var out = []; return reduce_1( state.hierarchicalFacets, // ask for as much levels as there's hierarchical refinements function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) { var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0]; // if no refinement, ask for root level if (!hierarchicalRefinement) { allAttributes.push(hierarchicalFacet.attributes[0]); return allAttributes; } var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var level = hierarchicalRefinement.split(separator).length; var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1); return allAttributes.concat(newAttributes); }, out); }, _getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) { var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (rootLevel === true) { var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeIndex = 0; if (rootPath) { attributeIndex = rootPath.split(separator).length; } return [hierarchicalFacet.attributes[attributeIndex]]; } var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || ''; // if refinement is 'beers > IPA > Flying dog', // then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values) var parentLevel = hierarchicalRefinement.split(separator).length - 1; return hierarchicalFacet.attributes.slice(0, parentLevel + 1); }, getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) { var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state; var searchForFacetSearchParameters = { facetQuery: query, facetName: facetName }; if (typeof maxFacetHits === 'number') { searchForFacetSearchParameters.maxFacetHits = maxFacetHits; } var queries = merge_1(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters); return queries; } }; var requestBuilder_1 = requestBuilder; /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { _baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } var _baseInverter = baseInverter; /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return _baseInverter(object, setter, toIteratee(iteratee), {}); }; } var _createInverter = createInverter; /** Used for built-in method references. */ var objectProto$k = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$2 = objectProto$k.toString; /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = _createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString$2.call(value); } result[value] = key; }, constant_1(identity_1)); var invert_1 = invert; var keys2Short = { advancedSyntax: 'aS', allowTyposOnNumericTokens: 'aTONT', analyticsTags: 'aT', analytics: 'a', aroundLatLngViaIP: 'aLLVIP', aroundLatLng: 'aLL', aroundPrecision: 'aP', aroundRadius: 'aR', attributesToHighlight: 'aTH', attributesToRetrieve: 'aTR', attributesToSnippet: 'aTS', disjunctiveFacetsRefinements: 'dFR', disjunctiveFacets: 'dF', distinct: 'd', facetsExcludes: 'fE', facetsRefinements: 'fR', facets: 'f', getRankingInfo: 'gRI', hierarchicalFacetsRefinements: 'hFR', hierarchicalFacets: 'hF', highlightPostTag: 'hPoT', highlightPreTag: 'hPrT', hitsPerPage: 'hPP', ignorePlurals: 'iP', index: 'idx', insideBoundingBox: 'iBB', insidePolygon: 'iPg', length: 'l', maxValuesPerFacet: 'mVPF', minimumAroundRadius: 'mAR', minProximity: 'mP', minWordSizefor1Typo: 'mWS1T', minWordSizefor2Typos: 'mWS2T', numericFilters: 'nF', numericRefinements: 'nR', offset: 'o', optionalWords: 'oW', page: 'p', queryType: 'qT', query: 'q', removeWordsIfNoResults: 'rWINR', replaceSynonymsInHighlight: 'rSIH', restrictSearchableAttributes: 'rSA', synonyms: 's', tagFilters: 'tF', tagRefinements: 'tR', typoTolerance: 'tT', optionalTagFilters: 'oTF', optionalFacetFilters: 'oFF', snippetEllipsisText: 'sET', disableExactOnAttributes: 'dEOA', enableExactOnSingleWordQuery: 'eEOSWQ' }; var short2Keys = invert_1(keys2Short); var shortener = { /** * All the keys of the state, encoded. * @const */ ENCODED_PARAMETERS: keys_1(short2Keys), /** * Decode a shorten attribute * @param {string} shortKey the shorten attribute * @return {string} the decoded attribute, undefined otherwise */ decode: function(shortKey) { return short2Keys[shortKey]; }, /** * Encode an attribute into a short version * @param {string} key the attribute * @return {string} the shorten attribute */ encode: function(key) { return keys2Short[key]; } }; var utils = createCommonjsModule(function (module, exports) { var has = Object.prototype.hasOwnProperty; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { var obj; while (queue.length) { var item = queue.pop(); obj = item.obj[item.prop]; if (Array.isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } return obj; }; exports.arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.merge = function merge(target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = exports.arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = exports.merge(target[i], item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = exports.merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; exports.assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.encode = function encode(str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; exports.compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } return compactQueue(queue); }; exports.isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function isBuffer(obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; }); var utils_1 = utils.arrayToObject; var utils_2 = utils.merge; var utils_3 = utils.assign; var utils_4 = utils.decode; var utils_5 = utils.encode; var utils_6 = utils.compact; var utils_7 = utils.isRegExp; var utils_8 = utils.isBuffer; var replace = String.prototype.replace; var percentTwenties = /%20/g; var formats = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching return prefix + '[]'; }, indices: function indices(prefix, key) { // eslint-disable-line func-name-matching return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { // eslint-disable-line func-name-matching return prefix; } }; var toISO = Date.prototype.toISOString; var defaults$1 = { delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify( // eslint-disable-line func-name-matching object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults$1.encoder) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$1.encoder); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$1.encoder))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } } return values; }; var stringify_1 = function (object, opts) { var obj = object; var options = opts ? utils.assign({}, opts) : {}; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var delimiter = typeof options.delimiter === 'undefined' ? defaults$1.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$1.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults$1.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults$1.encode; var encoder = typeof options.encoder === 'function' ? options.encoder : defaults$1.encoder; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults$1.serializeDate; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults$1.encodeValuesOnly; if (typeof options.format === 'undefined') { options.format = formats['default']; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; return joined.length > 0 ? prefix + joined : ''; }; var has = Object.prototype.hasOwnProperty; var defaults$2 = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults$2.decoder); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults$2.decoder); val = options.decoder(part.slice(pos + 1), defaults$2.decoder); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]') { obj = []; obj = obj.concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; var parse = function (str, opts) { var options = opts ? utils.assign({}, opts) : {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults$2.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults$2.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults$2.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults$2.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults$2.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults$2.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults$2.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults$2.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$2.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; var lib$1 = { formats: formats, parse: parse, stringify: stringify_1 }; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$7 = 1, WRAP_PARTIAL_FLAG$4 = 32; /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = _baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG$7; if (partials.length) { var holders = _replaceHolders(partials, _getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG$4; } return _createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; var bind_1 = bind; /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return _basePickBy(object, paths, function(value, path) { return hasIn_1(object, path); }); } var _basePick = basePick; /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = _flatRest(function(object, paths) { return object == null ? {} : _basePick(object, paths); }); var pick_1 = pick; /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, iteratee(value, key, object), value); }); return result; } var mapKeys_1 = mapKeys; /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } var mapValues_1 = mapValues; /** * Module containing the functions to serialize and deserialize * {SearchParameters} in the query string format * @module algoliasearchHelper.url */ var encode = utils.encode; function recursiveEncode(input) { if (isPlainObject_1(input)) { return mapValues_1(input, recursiveEncode); } if (Array.isArray(input)) { return map_1(input, recursiveEncode); } if (isString_1(input)) { return encode(input); } return input; } var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR']; var stateKeys = shortener.ENCODED_PARAMETERS; function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) { if (prefixRegexp !== null) { a = a.replace(prefixRegexp, ''); b = b.replace(prefixRegexp, ''); } a = invertedMapping[a] || a; b = invertedMapping[b] || b; if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) { if (a === 'q') return -1; if (b === 'q') return 1; var isARefinements = refinementsParameters.indexOf(a) !== -1; var isBRefinements = refinementsParameters.indexOf(b) !== -1; if (isARefinements && !isBRefinements) { return 1; } else if (isBRefinements && !isARefinements) { return -1; } } return a.localeCompare(b); } /** * Read a query string and return an object containing the state * @param {string} queryString the query string that will be decoded * @param {object} [options] accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) */ var getStateFromQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var partialStateWithPrefix = lib$1.parse(queryString); var prefixRegexp = new RegExp('^' + prefixForParameters); var partialState = mapKeys_1( partialStateWithPrefix, function(v, k) { var hasPrefix = prefixForParameters && prefixRegexp.test(k); var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k; var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey); return decodedKey || unprefixedKey; } ); var partialStateWithParsedNumbers = SearchParameters_1._parseNumbers(partialState); return pick_1(partialStateWithParsedNumbers, SearchParameters_1.PARAMETERS); }; /** * Retrieve an object of all the properties that are not understandable as helper * parameters. * @param {string} queryString the query string to read * @param {object} [options] the options * - prefixForParameters : prefix used for the helper configuration keys * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} the object containing the parsed configuration that doesn't * to the helper */ var getUnrecognizedParametersInQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var foreignConfig = {}; var config = lib$1.parse(queryString); if (prefixForParameters) { var prefixRegexp = new RegExp('^' + prefixForParameters); forEach_1(config, function(v, key) { if (!prefixRegexp.test(key)) foreignConfig[key] = v; }); } else { forEach_1(config, function(v, key) { if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v; }); } return foreignConfig; }; /** * Generate a query string for the state passed according to the options * @param {SearchParameters} state state to serialize * @param {object} [options] May contain the following parameters : * - prefix : prefix in front of the keys * - mapping : map short attributes to another value e.g. {q: 'query'} * - moreAttributes : more values to be added in the query string. Those values * won't be prefixed. * - safe : get safe urls for use in emails, chat apps or any application auto linking urls. * All parameters and values will be encoded in a way that it's safe to share them. * Default to false for legacy reasons () * @return {string} the query string */ var getQueryStringFromState = function(state, options) { var moreAttributes = options && options.moreAttributes; var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var safe = options && options.safe || false; var invertedMapping = invert_1(mapping); var stateForUrl = safe ? state : recursiveEncode(state); var encodedState = mapKeys_1( stateForUrl, function(v, k) { var shortK = shortener.encode(k); return prefixForParameters + (mapping[shortK] || shortK); } ); var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters); var sort = bind_1(sortQueryStringValues, null, prefixRegexp, invertedMapping); if (!isEmpty_1(moreAttributes)) { var stateQs = lib$1.stringify(encodedState, {encode: safe, sort: sort}); var moreQs = lib$1.stringify(moreAttributes, {encode: safe}); if (!stateQs) return moreQs; return stateQs + '&' + moreQs; } return lib$1.stringify(encodedState, {encode: safe, sort: sort}); }; var url = { getStateFromQueryString: getStateFromQueryString, getUnrecognizedParametersInQueryString: getUnrecognizedParametersInQueryString, getQueryStringFromState: getQueryStringFromState }; var version$1 = '2.26.0'; /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {SearchParameters} state the current parameters with the latest changes applied * @property {SearchResults} lastResults the previous results received from Algolia. `null` before * the first request * @example * helper.on('change', function(state, lastResults) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when a main search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {SearchParameters} state the parameters used for this search * @property {SearchResults} lastResults the results from the previous search. `null` if * it is the first search. * @example * helper.on('search', function(state, lastResults) { * console.log('Search sent'); * }); */ /** * Event triggered when a search using `searchForFacetValues` is sent to Algolia * @event AlgoliaSearchHelper#event:searchForFacetValues * @property {SearchParameters} state the parameters used for this search * it is the first search. * @property {string} facet the facet searched into * @property {string} query the query used to search in the facets * @example * helper.on('searchForFacetValues', function(state, facet, query) { * console.log('searchForFacetValues sent'); * }); */ /** * Event triggered when a search using `searchOnce` is sent to Algolia * @event AlgoliaSearchHelper#event:searchOnce * @property {SearchParameters} state the parameters used for this search * it is the first search. * @example * helper.on('searchOnce', function(state) { * console.log('searchOnce sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {SearchResults} results the results received from Algolia * @property {SearchParameters} state the parameters used to query Algolia. Those might * be different from the one in the helper instance (for example if the network is unreliable). * @example * helper.on('result', function(results, state) { * console.log('Search results received'); * }); */ /** * Event triggered when Algolia sends back an error. For example, if an unknown parameter is * used, the error can be caught using this event. * @event AlgoliaSearchHelper#event:error * @property {Error} error the error returned by the Algolia. * @example * helper.on('error', function(error) { * console.log('Houston we got a problem.'); * }); */ /** * Event triggered when the queue of queries have been depleted (with any result or outdated queries) * @event AlgoliaSearchHelper#event:searchQueueEmpty * @example * helper.on('searchQueueEmpty', function() { * console.log('No more search pending'); * // This is received before the result event if we're not expecting new results * }); * * helper.search(); */ /** * Initialize a new AlgoliaSearchHelper * @class * @classdesc The AlgoliaSearchHelper is a class that ease the management of the * search. It provides an event based interface for search callbacks: * - change: when the internal search state is changed. * This event contains a {@link SearchParameters} object and the * {@link SearchResults} of the last result if any. * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. * - error: when the response is an error. This event contains the error returned by the server. * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {SearchParameters | object} options an object defining the initial * config of the search. It doesn't have to be a {SearchParameters}, * just an object containing the properties you need from it. */ function AlgoliaSearchHelper(client, index, options) { if (client.addAlgoliaAgent && !doesClientAgentContainsHelper(client)) { client.addAlgoliaAgent('JS Helper ' + version$1); } this.setClient(client); var opts = options || {}; opts.index = index; this.state = SearchParameters_1.make(opts); this.lastResults = null; this._queryId = 0; this._lastQueryIdReceived = -1; this.derivedHelpers = []; this._currentNbQueries = 0; } util.inherits(AlgoliaSearchHelper, events.EventEmitter); /** * Start the search with the parameters set in the state. When the * method is called, it triggers a `search` event. The results will * be available through the `result` event. If an error occurs, an * `error` will be fired instead. * @return {AlgoliaSearchHelper} * @fires search * @fires result * @fires error * @chainable */ AlgoliaSearchHelper.prototype.search = function() { this._search(); return this; }; /** * Gets the search query parameters that would be sent to the Algolia Client * for the hits * @return {object} Query Parameters */ AlgoliaSearchHelper.prototype.getQuery = function() { var state = this.state; return requestBuilder_1._getHitsSearchParams(state); }; /** * Start a search using a modified version of the current state. This method does * not trigger the helper lifecycle and does not modify the state kept internally * by the helper. This second aspect means that the next search call will be the * same as a search call before calling searchOnce. * @param {object} options can contain all the parameters that can be set to SearchParameters * plus the index * @param {function} [callback] optional callback executed when the response from the * server is back. * @return {promise|undefined} if a callback is passed the method returns undefined * otherwise it returns a promise containing an object with two keys : * - content with a SearchResults * - state with the state used for the query as a SearchParameters * @example * // Changing the number of records returned per page to 1 * // This example uses the callback API * var state = helper.searchOnce({hitsPerPage: 1}, * function(error, content, state) { * // if an error occurred it will be passed in error, otherwise its value is null * // content contains the results formatted as a SearchResults * // state is the instance of SearchParameters used for this search * }); * @example * // Changing the number of records returned per page to 1 * // This example uses the promise API * var state1 = helper.searchOnce({hitsPerPage: 1}) * .then(promiseHandler); * * function promiseHandler(res) { * // res contains * // { * // content : SearchResults * // state : SearchParameters (the one used for this specific search) * // } * } */ AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) { var tempState = !options ? this.state : this.state.setQueryParameters(options); var queries = requestBuilder_1._getQueries(tempState.index, tempState); var self = this; this._currentNbQueries++; this.emit('searchOnce', tempState); if (cb) { this.client .search(queries) .then(function(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) { self.emit('searchQueueEmpty'); } cb(null, new SearchResults_1(tempState, content.results), tempState); }) .catch(function(err) { self._currentNbQueries--; if (self._currentNbQueries === 0) { self.emit('searchQueueEmpty'); } cb(err, null, tempState); }); return undefined; } return this.client.search(queries).then(function(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); return { content: new SearchResults_1(tempState, content.results), state: tempState, _originalResponse: content }; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Structure of each result when using * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * @typedef FacetSearchHit * @type {object} * @property {string} value the facet value * @property {string} highlighted the facet value highlighted with the query string * @property {number} count number of occurrence of this facet value * @property {boolean} isRefined true if the value is already refined */ /** * Structure of the data resolved by the * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * promise. * @typedef FacetSearchResult * @type {object} * @property {FacetSearchHit} facetHits the results for this search for facet values * @property {number} processingTimeMS time taken by the query inside the engine */ /** * Search for facet values based on an query and the name of a faceted attribute. This * triggers a search and will return a promise. On top of using the query, it also sends * the parameters from the state so that the search is narrowed down to only the possible values. * * See the description of [FacetSearchResult](reference.html#FacetSearchResult) * @param {string} facet the name of the faceted attribute * @param {string} query the string query for the search * @param {number} [maxFacetHits] the maximum number values returned. Should be > 0 and <= 100 * @param {object} [userState] the set of custom parameters to use on top of the current state. Setting a property to `undefined` removes * it in the generated query. * @return {promise.<FacetSearchResult>} the results of the search */ AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits, userState) { var state = this.state.setQueryParameters(userState || {}); var isDisjunctive = state.isDisjunctiveFacet(facet); var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, state); this._currentNbQueries++; var self = this; this.emit('searchForFacetValues', state, facet, query); var searchForFacetValuesPromise = typeof this.client.searchForFacetValues === 'function' ? this.client.searchForFacetValues([{indexName: state.index, params: algoliaQuery}]) : this.client.initIndex(state.index).searchForFacetValues(algoliaQuery); return searchForFacetValuesPromise.then(function addIsRefined(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); content = Array.isArray(content) ? content[0] : content; content.facetHits = forEach_1(content.facetHits, function(f) { f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value); }); return content; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Sets the text query used for the search. * * This method resets the current page to 0. * @param {string} q the user query * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setQuery = function(q) { this._change(this.state.setPage(0).setQuery(q)); return this; }; /** * Remove all the types of refinements except tags. A string can be provided to remove * only the refinements of a specific attribute. For more advanced use case, you can * provide a function instead. This function should follow the * [clearCallback definition](#SearchParameters.clearCallback). * * This method resets the current page to 0. * @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * // Removing all the refinements * helper.clearRefinements().search(); * @example * // Removing all the filters on a the category attribute. * helper.clearRefinements('category').search(); * @example * // Removing only the exclude filters on the category facet. * helper.clearRefinements(function(value, attribute, type) { * return type === 'exclude' && attribute === 'category'; * }).search(); */ AlgoliaSearchHelper.prototype.clearRefinements = function(name) { this._change(this.state.setPage(0).clearRefinements(name)); return this; }; /** * Remove all the tag filters. * * This method resets the current page to 0. * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.clearTags = function() { this._change(this.state.setPage(0).clearTags()); return this; }; /** * Adds a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() { return this.addDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Adds a refinement on a hierarchical facet. It will throw * an exception if the facet is not defined or if the facet * is already refined. * * This method resets the current page to 0. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is refined * @chainable * @fires change */ AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addHierarchicalFacetRefinement(facet, value)); return this; }; /** * Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} operator the operator of the filter * @param {number} value the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) { this._change(this.state.setPage(0).addNumericRefinement(attribute, operator, value)); return this; }; /** * Adds a filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement} */ AlgoliaSearchHelper.prototype.addRefine = function() { return this.addFacetRefinement.apply(this, arguments); }; /** * Adds a an exclusion filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).addExcludeRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion} */ AlgoliaSearchHelper.prototype.addExclude = function() { return this.addFacetExclusion.apply(this, arguments); }; /** * Adds a tag filter with the `tag` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag the tag to add to the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addTag = function(tag) { this._change(this.state.setPage(0).addTagRefinement(tag)); return this; }; /** * Removes an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is not set, it doesn't change the filters. * * Some parameters are optional, triggering different behavior: * - if the value is not provided, then all the numeric value will be removed for the * specified attribute/operator couple. * - if the operator is not provided either, then all the numeric filter on this attribute * will be removed. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} [operator] the operator of the filter * @param {number} [value] the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) { this._change(this.state.setPage(0).removeNumericRefinement(attribute, operator, value)); return this; }; /** * Removes a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() { return this.removeDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is not refined * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) { this._change(this.state.setPage(0).removeHierarchicalFacetRefinement(facet)); return this; }; /** * Removes a filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).removeFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement} */ AlgoliaSearchHelper.prototype.removeRefine = function() { return this.removeFacetRefinement.apply(this, arguments); }; /** * Removes an exclusion filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).removeExcludeRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion} */ AlgoliaSearchHelper.prototype.removeExclude = function() { return this.removeFacetExclusion.apply(this, arguments); }; /** * Removes a tag filter with the `tag` provided. If the * filter is not set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag tag to remove from the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeTag = function(tag) { this._change(this.state.setPage(0).removeTagRefinement(tag)); return this; }; /** * Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).toggleExcludeFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion} */ AlgoliaSearchHelper.prototype.toggleExclude = function() { return this.toggleFacetExclusion.apply(this, arguments); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable * @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) { return this.toggleFacetRefinement(facet, value); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).toggleFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefine = function() { return this.toggleFacetRefinement.apply(this, arguments); }; /** * Adds or removes a tag filter with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} tag tag to remove or add * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleTag = function(tag) { this._change(this.state.setPage(0).toggleTagRefinement(tag)); return this; }; /** * Increments the page number by one. * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setPage(0).nextPage().getPage(); * // returns 1 */ AlgoliaSearchHelper.prototype.nextPage = function() { return this.setPage(this.state.page + 1); }; /** * Decrements the page number by one. * @fires change * @return {AlgoliaSearchHelper} * @chainable * @example * helper.setPage(1).previousPage().getPage(); * // returns 0 */ AlgoliaSearchHelper.prototype.previousPage = function() { return this.setPage(this.state.page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this._change(this.state.setPage(page)); return this; } /** * Change the current page * @deprecated * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage; /** * Updates the current page. * @function * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setPage = setCurrentPage; /** * Updates the name of the index that will be targeted by the query. * * This method resets the current page to 0. * @param {string} name the index name * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setIndex = function(name) { this._change(this.state.setPage(0).setIndex(name)); return this; }; /** * Update a parameter of the search. This method reset the page * * The complete list of parameters is available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters and facets have their own API) * * This method resets the current page to 0. * @param {string} parameter name of the parameter to update * @param {any} value new value of the parameter * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setQueryParameter('hitsPerPage', 20).search(); */ AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) { this._change(this.state.setPage(0).setQueryParameter(parameter, value)); return this; }; /** * Set the whole state (warning: will erase previous state) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setState = function(newState) { this._change(SearchParameters_1.make(newState)); return this; }; /** * Get the current search state stored in the helper. This object is immutable. * @param {string[]} [filters] optional filters to retrieve only a subset of the state * @return {SearchParameters|object} if filters is specified a plain object is * returned containing only the requested fields, otherwise return the unfiltered * state * @example * // Get the complete state as stored in the helper * helper.getState(); * @example * // Get a part of the state with all the refinements on attributes and the query * helper.getState(['query', 'attribute:category']); */ AlgoliaSearchHelper.prototype.getState = function(filters) { if (filters === undefined) return this.state; return this.state.filter(filters); }; /** * DEPRECATED Get part of the state as a query string. By default, the output keys will not * be prefixed and will only take the applied refinements and the query. * @deprecated * @param {object} [options] May contain the following parameters : * * **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for * the index, all the refinements with `attribute:*` or for some specific attributes with * `attribute:theAttribute` * * **prefix** : prefix in front of the keys * * **moreAttributes** : more values to be added in the query string. Those values * won't be prefixed. * @return {string} the query string */ AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) { var filters = options && options.filters || ['query', 'attribute:*']; var partialState = this.getState(filters); return url.getQueryStringFromState(partialState, options); }; /** * DEPRECATED Read a query string and return an object containing the state. Use * url module. * @deprecated * @static * @param {string} queryString the query string that will be decoded * @param {object} options accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) * @see {@link url#getStateFromQueryString} */ AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString; /** * DEPRECATED Retrieve an object of all the properties that are not understandable as helper * parameters. Use url module. * @deprecated * @static * @param {string} queryString the query string to read * @param {object} options the options * - prefixForParameters : prefix used for the helper configuration keys * @return {object} the object containing the parsed configuration that doesn't * to the helper */ AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString; /** * DEPRECATED Overrides part of the state with the properties stored in the provided query * string. * @deprecated * @param {string} queryString the query string containing the informations to url the state * @param {object} options optional parameters : * - prefix : prefix used for the algolia parameters * - triggerChange : if set to true the state update will trigger a change event */ AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) { var triggerChange = options && options.triggerChange || false; var configuration = url.getStateFromQueryString(queryString, options); var updatedState = this.state.setQueryParameters(configuration); if (triggerChange) this.setState(updatedState); else this.overrideStateWithoutTriggeringChangeEvent(updatedState); }; /** * Override the current state without triggering a change event. * Do not use this method unless you know what you are doing. (see the example * for a legit use case) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @example * helper.on('change', function(state){ * // In this function you might want to find a way to store the state in the url/history * updateYourURL(state) * }) * window.onpopstate = function(event){ * // This is naive though as you should check if the state is really defined etc. * helper.overrideStateWithoutTriggeringChangeEvent(event.state).search() * } * @chainable */ AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) { this.state = new SearchParameters_1(newState); return this; }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isRefined = function(facet, value) { if (this.state.isConjunctiveFacet(facet)) { return this.state.isFacetRefined(facet, value); } else if (this.state.isDisjunctiveFacet(facet)) { return this.state.isDisjunctiveFacetRefined(facet, value); } throw new Error(facet + ' is not properly defined in this helper configuration' + '(use the facets or disjunctiveFacets keys to configure it)'); }; /** * Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters. * @param {string} attribute the name of the attribute * @return {boolean} true if the attribute is filtered by at least one value * @example * // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters * helper.hasRefinements('price'); // false * helper.addNumericRefinement('price', '>', 100); * helper.hasRefinements('price'); // true * * helper.hasRefinements('color'); // false * helper.addFacetRefinement('color', 'blue'); * helper.hasRefinements('color'); // true * * helper.hasRefinements('material'); // false * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * helper.hasRefinements('material'); // true * * helper.hasRefinements('categories'); // false * helper.toggleFacetRefinement('categories', 'kitchen > knife'); * helper.hasRefinements('categories'); // true * */ AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) { if (!isEmpty_1(this.state.getNumericRefinements(attribute))) { return true; } else if (this.state.isConjunctiveFacet(attribute)) { return this.state.isFacetRefined(attribute); } else if (this.state.isDisjunctiveFacet(attribute)) { return this.state.isDisjunctiveFacetRefined(attribute); } else if (this.state.isHierarchicalFacet(attribute)) { return this.state.isHierarchicalFacetRefined(attribute); } // there's currently no way to know that the user did call `addNumericRefinement` at some point // thus we cannot distinguish if there once was a numeric refinement that was cleared // so we will return false in every other situations to be consistent // while what we should do here is throw because we did not find the attribute in any type // of refinement return false; }; /** * Check if a value is excluded for a specific faceted attribute. If the value * is omitted then the function checks if there is any excluding refinements. * * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} true if refined * @example * helper.isExcludeRefined('color'); // false * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // false * * helper.addFacetExclusion('color', 'red'); * * helper.isExcludeRefined('color'); // true * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // true */ AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) { return this.state.isExcludeRefined(facet, value); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) { return this.state.isDisjunctiveFacetRefined(facet, value); }; /** * Check if the string is a currently filtering tag. * @param {string} tag tag to check * @return {boolean} */ AlgoliaSearchHelper.prototype.hasTag = function(tag) { return this.state.isTagRefined(tag); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag} */ AlgoliaSearchHelper.prototype.isTagRefined = function() { return this.hasTagRefinements.apply(this, arguments); }; /** * Get the name of the currently used index. * @return {string} * @example * helper.setIndex('highestPrice_products').getIndex(); * // returns 'highestPrice_products' */ AlgoliaSearchHelper.prototype.getIndex = function() { return this.state.index; }; function getCurrentPage() { return this.state.page; } /** * Get the currently selected page * @deprecated * @return {number} the current page */ AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage; /** * Get the currently selected page * @function * @return {number} the current page */ AlgoliaSearchHelper.prototype.getPage = getCurrentPage; /** * Get all the tags currently set to filters the results. * * @return {string[]} The list of tags currently set. */ AlgoliaSearchHelper.prototype.getTags = function() { return this.state.tagRefinements; }; /** * Get a parameter of the search by its name. It is possible that a parameter is directly * defined in the index dashboard, but it will be undefined using this method. * * The complete list of parameters is * available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters have their own API) * @param {string} parameterName the parameter name * @return {any} the parameter value * @example * var hitsPerPage = helper.getQueryParameter('hitsPerPage'); */ AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) { return this.state.getQueryParameter(parameterName); }; /** * Get the list of refinements for a given attribute. This method works with * conjunctive, disjunctive, excluding and numerical filters. * * See also SearchResults#getRefinements * * @param {string} facetName attribute name used for faceting * @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and * a type. Numeric also contains an operator. * @example * helper.addNumericRefinement('price', '>', 100); * helper.getRefinements('price'); * // [ * // { * // "value": [ * // 100 * // ], * // "operator": ">", * // "type": "numeric" * // } * // ] * @example * helper.addFacetRefinement('color', 'blue'); * helper.addFacetExclusion('color', 'red'); * helper.getRefinements('color'); * // [ * // { * // "value": "blue", * // "type": "conjunctive" * // }, * // { * // "value": "red", * // "type": "exclude" * // } * // ] * @example * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * // [ * // { * // "value": "plastic", * // "type": "disjunctive" * // } * // ] */ AlgoliaSearchHelper.prototype.getRefinements = function(facetName) { var refinements = []; if (this.state.isConjunctiveFacet(facetName)) { var conjRefinements = this.state.getConjunctiveRefinements(facetName); forEach_1(conjRefinements, function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); forEach_1(excludeRefinements, function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); forEach_1(disjRefinements, function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); forEach_1(numericRefinements, function(value, operator) { refinements.push({ value: value, operator: operator, type: 'numeric' }); }); return refinements; }; /** * Return the current refinement for the (attribute, operator) * @param {string} attribute attribute in the record * @param {string} operator operator applied on the refined values * @return {Array.<number|number[]>} refined values */ AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) { return this.state.getNumericRefinement(attribute, operator); }; /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) { return this.state.getHierarchicalFacetBreadcrumb(facetName); }; // /////////// PRIVATE /** * Perform the underlying queries * @private * @return {undefined} * @fires search * @fires result * @fires error */ AlgoliaSearchHelper.prototype._search = function() { var state = this.state; var mainQueries = requestBuilder_1._getQueries(state.index, state); var states = [{ state: state, queriesCount: mainQueries.length, helper: this }]; this.emit('search', state, this.lastResults); var derivedQueries = map_1(this.derivedHelpers, function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var queries = requestBuilder_1._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: queries.length, helper: derivedHelper }); derivedHelper.emit('search', derivedState, derivedHelper.lastResults); return queries; }); var queries = mainQueries.concat(flatten_1(derivedQueries)); var queryId = this._queryId++; this._currentNbQueries++; try { this.client.search(queries) .then(this._dispatchAlgoliaResponse.bind(this, states, queryId)) .catch(this._dispatchAlgoliaError.bind(this, queryId)); } catch (err) { // If we reach this part, we're in an internal error state this.emit('error', err); } }; /** * Transform the responses as sent by the server and transform them into a user * usable object that merge the results of all the batch requests. It will dispatch * over the different helper + derived helpers (when there are some). * @private * @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>} * state state used for to generate the request * @param {number} queryId id of the current request * @param {object} content content of the response * @return {undefined} */ AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, content) { // FIXME remove the number of outdated queries discarded instead of just one if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= (queryId - this._lastQueryIdReceived); this._lastQueryIdReceived = queryId; if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); var results = content.results; forEach_1(states, function(s) { var state = s.state; var queriesCount = s.queriesCount; var helper = s.helper; var specificResults = results.splice(0, queriesCount); var formattedResponse = helper.lastResults = new SearchResults_1(state, specificResults); helper.emit('result', formattedResponse, state); }); }; AlgoliaSearchHelper.prototype._dispatchAlgoliaError = function(queryId, err) { if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= queryId - this._lastQueryIdReceived; this._lastQueryIdReceived = queryId; this.emit('error', err); if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); }; AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) { return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0; }; /** * Test if there are some disjunctive refinements on the facet * @private * @param {string} facet the attribute to test * @return {boolean} */ AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) { return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0; }; AlgoliaSearchHelper.prototype._change = function(newState) { if (newState !== this.state) { this.state = newState; this.emit('change', this.state, this.lastResults); } }; /** * Clears the cache of the underlying Algolia client. * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.clearCache = function() { this.client.clearCache && this.client.clearCache(); return this; }; /** * Updates the internal client instance. If the reference of the clients * are equal then no update is actually done. * @param {AlgoliaSearch} newClient an AlgoliaSearch client * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.setClient = function(newClient) { if (this.client === newClient) return this; if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version$1); this.client = newClient; return this; }; /** * Gets the instance of the currently used client. * @return {AlgoliaSearch} */ AlgoliaSearchHelper.prototype.getClient = function() { return this.client; }; /** * Creates an derived instance of the Helper. A derived helper * is a way to request other indices synchronised with the lifecycle * of the main Helper. This mechanism uses the multiqueries feature * of Algolia to aggregate all the requests in a single network call. * * This method takes a function that is used to create a new SearchParameter * that will be used to create requests to Algolia. Those new requests * are created just before the `search` event. The signature of the function * is `SearchParameters -> SearchParameters`. * * This method returns a new DerivedHelper which is an EventEmitter * that fires the same `search`, `result` and `error` events. Those * events, however, will receive data specific to this DerivedHelper * and the SearchParameters that is returned by the call of the * parameter function. * @param {function} fn SearchParameters -> SearchParameters * @return {DerivedHelper} */ AlgoliaSearchHelper.prototype.derive = function(fn) { var derivedHelper = new DerivedHelper_1(this, fn); this.derivedHelpers.push(derivedHelper); return derivedHelper; }; /** * This method detaches a derived Helper from the main one. Prefer using the one from the * derived helper itself, to remove the event listeners too. * @private * @return {undefined} * @throws Error */ AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) { var pos = this.derivedHelpers.indexOf(derivedHelper); if (pos === -1) throw new Error('Derived helper already detached'); this.derivedHelpers.splice(pos, 1); }; /** * This method returns true if there is currently at least one on-going search. * @return {boolean} true if there is a search pending */ AlgoliaSearchHelper.prototype.hasPendingRequests = function() { return this._currentNbQueries > 0; }; /** * @typedef AlgoliaSearchHelper.NumericRefinement * @type {object} * @property {number[]} value the numbers that are used for filtering this attribute with * the operator specified. * @property {string} operator the faceting data: value, number of entries * @property {string} type will be 'numeric' */ /** * @typedef AlgoliaSearchHelper.FacetRefinement * @type {object} * @property {string} value the string use to filter the attribute * @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude' */ /* * This function tests if the _ua parameter of the client * already contains the JS Helper UA */ function doesClientAgentContainsHelper(client) { // this relies on JS Client internal variable, this might break if implementation changes var currentAgent = client._ua; return !currentAgent ? false : currentAgent.indexOf('JS Helper') !== -1; } var algoliasearch_helper = AlgoliaSearchHelper; /** * The algoliasearchHelper module is the function that will let its * contains everything needed to use the Algoliasearch * Helper. It is a also a function that instanciate the helper. * To use the helper, you also need the Algolia JS client v3. * @example * //using the UMD build * var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76'); * var helper = algoliasearchHelper(client, 'bestbuy', { * facets: ['shipping'], * disjunctiveFacets: ['category'] * }); * helper.on('result', function(result) { * console.log(result); * }); * helper.toggleRefine('Movies & TV Shows') * .toggleRefine('Free shipping') * .search(); * @example * // The helper is an event emitter using the node API * helper.on('result', updateTheResults); * helper.once('result', updateTheResults); * helper.removeListener('result', updateTheResults); * helper.removeAllListeners('result'); * @module algoliasearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the name of the index to query * @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it. * @return {AlgoliaSearchHelper} */ function algoliasearchHelper(client, index, opts) { return new algoliasearch_helper(client, index, opts); } /** * The version currently used * @member module:algoliasearchHelper.version * @type {number} */ algoliasearchHelper.version = version$1; /** * Constructor for the Helper. * @member module:algoliasearchHelper.AlgoliaSearchHelper * @type {AlgoliaSearchHelper} */ algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper; /** * Constructor for the object containing all the parameters of the search. * @member module:algoliasearchHelper.SearchParameters * @type {SearchParameters} */ algoliasearchHelper.SearchParameters = SearchParameters_1; /** * Constructor for the object containing the results of the search. * @member module:algoliasearchHelper.SearchResults * @type {SearchResults} */ algoliasearchHelper.SearchResults = SearchResults_1; /** * URL tools to generate query string and parse them from/into * SearchParameters * @member module:algoliasearchHelper.url * @type {object} {@link url} * */ algoliasearchHelper.url = url; var algoliasearchHelper_1 = algoliasearchHelper; var shallowEqual = function shallowEqual(objA, objB) { if (objA === objB) { return true; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; }; var getDisplayName = function getDisplayName(Component) { return Component.displayName || Component.name || 'UnknownComponent'; }; var resolved = Promise.resolve(); var defer = function defer(f) { resolved.then(f); }; var removeEmptyKey = function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (isEmpty_1(value) && isPlainObject_1(value)) { delete obj[key]; } else if (isPlainObject_1(value)) { removeEmptyKey(value); } }); return obj; }; function 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 createWidgetsManager(onWidgetsUpdate) { var widgets = []; // Is an update scheduled? var scheduled = false; // The state manager's updates need to be batched since more than one // component can register or unregister widgets during the same tick. function scheduleUpdate() { if (scheduled) { return; } scheduled = true; defer(function () { scheduled = false; onWidgetsUpdate(); }); } return { registerWidget: function registerWidget(widget) { widgets.push(widget); scheduleUpdate(); return function unregisterWidget() { widgets.splice(widgets.indexOf(widget), 1); scheduleUpdate(); }; }, update: scheduleUpdate, getWidgets: function getWidgets() { return widgets; } }; } function createStore(initialState) { var state = initialState; var listeners = []; function dispatch() { listeners.forEach(function (listener) { return listener(); }); } return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; dispatch(); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubcribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } var HIGHLIGHT_TAGS = { highlightPreTag: "<ais-highlight-0000000000>", highlightPostTag: "</ais-highlight-0000000000>" }; /** * Parses an highlighted attribute into an array of objects with the string value, and * a boolean that indicated if this part is highlighted. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature * @return {object[]} - An array of {value: string, 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 = get_1(hit[highlightProperty], attribute, {}); if (Array.isArray(highlightObject)) { return highlightObject.map(function (item) { return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: item.value }); }); } return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightObject.value }); } function getIndexId(context) { return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (searchResults.results && !searchResults.results.hits) { return searchResults.results[getIndexId(context)] ? searchResults.results[getIndexId(context)] : null; } else { return searchResults.results ? searchResults.results : 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] && searchState.indices[indexId][namespace].hasOwnProperty(attributeName); } if (multiIndex) { return searchState.indices && searchState.indices[indexId] && searchState.indices[indexId].hasOwnProperty(id); } if (namespace) { return searchState[namespace] && searchState[namespace].hasOwnProperty(attributeName); } return searchState.hasOwnProperty(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 cleanUpValueWithMutliIndex({ 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_1(searchState[namespace], attribute))); } return omit_1(searchState, id); } function cleanUpValueWithMutliIndex(_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_1(indexSearchState[namespace], attribute))))) }); } return omit_1(searchState, "indices.".concat(indexId, ".").concat(id)); } var isMultiIndexContext = function isMultiIndexContext(widget) { return hasMultipleIndices(widget.context); }; var isTargetedIndexEqualIndex = function isTargetedIndexEqualIndex(widget, indexId) { return widget.context.multiIndexContext.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; }; /** * 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)); 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); var store = createStore({ widgets: initialState, metadata: [], results: resultsState || null, error: null, searching: false, isSearchStalled: true, searchingForFacetValues: false }); function skipSearch() { skip = true; } function updateClient(client) { helper.setClient(client); search(); } function clearCache() { helper.clearCache(); search(); } function getMetadata(state) { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getMetadata); }).map(function (widget) { return widget.getMetadata(state); }); } function getSearchParameters() { 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; }).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; }).reduce(function (indices, widget) { var indexId = isMultiIndexContext(widget) ? widget.context.multiIndexContext.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(helper.state), 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 (content) { 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] = content; } else { results = content; } var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); stalledSearchTimer = null; nextIsSearchStalled = false; } var nextState = omit_1(_objectSpread({}, currentState, { results: results, isSearchStalled: nextIsSearchStalled, searching: false, error: null }), 'resultsFacetValues'); store.setState(nextState); }; } function handleSearchError(error) { var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); nextIsSearchStalled = false; } var nextState = omit_1(_objectSpread({}, currentState, { isSearchStalled: nextIsSearchStalled, error: error, searching: false }), 'resultsFacetValues'); store.setState(nextState); } function handleNewSearch() { if (!stalledSearchTimer) { stalledSearchTimer = setTimeout(function () { var nextState = omit_1(_objectSpread({}, store.getState(), { isSearchStalled: true }), 'resultsFacetValues'); store.setState(nextState); }, stalledSearchDelay); } } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_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(_ref4) { var facetName = _ref4.facetName, query = _ref4.query, _ref4$maxFacetHits = _ref4.maxFacetHits, maxFacetHits = _ref4$maxFacetHits === void 0 ? 10 : _ref4$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 _objectSpread3; store.setState(_objectSpread({}, store.getState(), { error: null, searchingForFacetValues: false, resultsFacetValues: _objectSpread({}, store.getState().resultsFacetValues, (_objectSpread3 = {}, _defineProperty(_objectSpread3, facetName, content.facetHits), _defineProperty(_objectSpread3, "query", query), _objectSpread3)) })); }, 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); 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, getSearchParameters: getSearchParameters, onSearchForFacetValues: onSearchForFacetValues, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, updateClient: updateClient, updateIndex: updateIndex, clearCache: clearCache, skipSearch: skipSearch }; } 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"); } } /** * @description * `<InstantSearch>` is the root component of all React InstantSearch implementations. * It provides all the connected components (aka widgets) a means to interact * with the searchState. * @kind widget * @name <InstantSearch> * @requirements You will need to have an Algolia account to be able to use this widget. * [Create one now](https://www.algolia.com/users/sign_up). * @propType {string} appId - Your Algolia application id. * @propType {string} apiKey - Your Algolia search-only API key. * @propType {string} indexName - Main index in which to search. * @propType {boolean} [refresh=false] - Flag to activate when the cache needs to be cleared so that the front-end is updated when a change occurs in the index. * @propType {object} [algoliaClient] - Provide a custom Algolia client instead of the internal one (deprecated in favor of `searchClient`). * @propType {object} [searchClient] - Provide a custom search client. * @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html). * @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html). * @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html). * @propType {SearchResults|SearchResults[]} [resultsState] - Use this to inject the results that will be used at first rendering. Those results are found by using the `findResultsState` function. Useful for [Server Side Rendering](guide/Server-side_rendering.html). * @propType {number} [stalledSearchDelay=200] - The amount of time before considering that the search takes too much time. The time is expressed in milliseconds. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import React from 'react'; * import { InstantSearch, SearchBox, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); */ var InstantSearch = /*#__PURE__*/ function (_Component) { _inherits(InstantSearch, _Component); function InstantSearch(props) { var _this; _classCallCheck(this, InstantSearch); _this = _possibleConstructorReturn(this, _getPrototypeOf(InstantSearch).call(this, props)); _this.isControlled = Boolean(props.searchState); var initialState = _this.isControlled ? props.searchState : {}; _this.isUnmounting = false; _this.aisManager = createInstantSearchManager({ indexName: props.indexName, searchClient: props.searchClient, initialState: initialState, resultsState: props.resultsState, stalledSearchDelay: props.stalledSearchDelay }); return _this; } _createClass(InstantSearch, [{ key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { validateNextProps(this.props, nextProps); if (this.props.indexName !== nextProps.indexName) { this.aisManager.updateIndex(nextProps.indexName); } if (this.props.refresh !== nextProps.refresh) { if (nextProps.refresh) { this.aisManager.clearCache(); } } if (this.props.searchClient !== nextProps.searchClient) { this.aisManager.updateClient(nextProps.searchClient); } if (this.isControlled) { this.aisManager.onExternalStateUpdate(nextProps.searchState); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.isUnmounting = true; this.aisManager.skipSearch(); } }, { key: "getChildContext", value: function getChildContext() { // If not already cached, cache the bound methods so that we can forward them as part // of the context. if (!this._aisContextCache) { this._aisContextCache = { ais: { onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this), createHrefForState: this.createHrefForState.bind(this), onSearchForFacetValues: this.onSearchForFacetValues.bind(this), onSearchStateChange: this.onSearchStateChange.bind(this), onSearchParameters: this.onSearchParameters.bind(this) } }; } return { ais: _objectSpread({}, this._aisContextCache.ais, { store: this.aisManager.store, widgetsManager: this.aisManager.widgetsManager, mainTargetedIndex: this.props.indexName }) }; } }, { key: "createHrefForState", value: function createHrefForState(searchState) { searchState = this.aisManager.transitionState(searchState); return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: "onWidgetsInternalStateUpdate", value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.aisManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.isControlled) { this.aisManager.onExternalStateUpdate(searchState); } } }, { key: "onSearchStateChange", value: function onSearchStateChange(searchState) { if (this.props.onSearchStateChange && !this.isUnmounting) { this.props.onSearchStateChange(searchState); } } }, { key: "onSearchParameters", value: function onSearchParameters(getSearchParameters, context, props) { if (this.props.onSearchParameters) { var searchState = this.props.searchState ? this.props.searchState : {}; this.props.onSearchParameters(getSearchParameters, context, props, searchState); } } }, { key: "onSearchForFacetValues", value: function onSearchForFacetValues(searchState) { this.aisManager.onSearchForFacetValues(searchState); } }, { key: "getKnownKeys", value: function getKnownKeys() { return this.aisManager.getWidgetsIds(); } }, { key: "render", value: function render() { var childrenCount = React.Children.count(this.props.children); var _this$props$root = this.props.root, Root = _this$props$root.Root, props = _this$props$root.props; if (childrenCount === 0) return null;else return React__default.createElement(Root, props, this.props.children); } }]); return InstantSearch; }(React.Component); InstantSearch.defaultProps = { stalledSearchDelay: 200 }; InstantSearch.childContextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; var version$2 = '5.7.0'; /** * 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 = /*#__PURE__*/ function (_Component) { _inherits(CreateInstantSearch, _Component); function CreateInstantSearch() { var _getPrototypeOf2; var _this; _classCallCheck(this, CreateInstantSearch); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(CreateInstantSearch)).call.apply(_getPrototypeOf2, [this].concat(args))); if (_this.props.searchClient) { if (_this.props.appId || _this.props.apiKey || _this.props.algoliaClient) { throw new Error('react-instantsearch:: `searchClient` cannot be used with `appId`, `apiKey` or `algoliaClient`.'); } } if (_this.props.algoliaClient) { // eslint-disable-next-line no-console console.warn('`algoliaClient` option was renamed `searchClient`. Please use this new option before the next major version.'); } _this.client = _this.props.searchClient || _this.props.algoliaClient || defaultAlgoliaClient(_this.props.appId, _this.props.apiKey, { _useRequestCache: true }); if (typeof _this.client.addAlgoliaAgent === 'function') { _this.client.addAlgoliaAgent("react (".concat(React__default.version, ")")); _this.client.addAlgoliaAgent("react-instantsearch (".concat(version$2, ")")); } return _this; } _createClass(CreateInstantSearch, [{ key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { var props = this.props; if (nextProps.searchClient) { this.client = nextProps.searchClient; } else if (nextProps.algoliaClient) { this.client = nextProps.algoliaClient; } else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) { this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey); } if (typeof this.client.addAlgoliaAgent === 'function') { this.client.addAlgoliaAgent("react (".concat(React__default.version, ")")); this.client.addAlgoliaAgent("react-instantsearch (".concat(version$2, ")")); } } }, { key: "render", value: function render() { return React__default.createElement(InstantSearch, { createURL: this.props.createURL, indexName: this.props.indexName, searchState: this.props.searchState, onSearchStateChange: this.props.onSearchStateChange, onSearchParameters: this.props.onSearchParameters, root: this.props.root, searchClient: this.client, algoliaClient: this.client, refresh: this.props.refresh, resultsState: this.props.resultsState }, this.props.children); } }]); return CreateInstantSearch; }(React.Component), _defineProperty(_class, "propTypes", { algoliaClient: propTypes.object, searchClient: propTypes.object, appId: propTypes.string, apiKey: propTypes.string, children: propTypes.oneOfType([propTypes.arrayOf(propTypes.node), propTypes.node]), indexName: propTypes.string.isRequired, createURL: propTypes.func, searchState: propTypes.object, refresh: propTypes.bool.isRequired, onSearchStateChange: propTypes.func, onSearchParameters: propTypes.func, resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]), root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func, propTypes.object]).isRequired, props: propTypes.object }) }), _defineProperty(_class, "defaultProps", { refresh: false, root: root }), _temp; } /** * @description * `<Index>` is the component that allows you to apply widgets to a dedicated index. It's * useful if you want to build an interface that targets multiple indices. * @kind widget * @name <Index> * @propType {string} indexName - index in which to search. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import React from 'react'; * import { InstantSearch, Index, SearchBox, Hits, Configure } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="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); function Index() { var _getPrototypeOf2; var _this; _classCallCheck(this, Index); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Index)).call.apply(_getPrototypeOf2, [this].concat(args))); /* we want <Index> to be seen as a regular widget. It means that with only <Index> present a new query will be sent to Algolia. That way you don't need a virtual hits widget to use the connectAutoComplete. */ _this.unregisterWidget = _this.context.ais.widgetsManager.registerWidget(_assertThisInitialized(_this)); return _this; } _createClass(Index, [{ key: "componentWillMount", value: function componentWillMount() { this.context.ais.onSearchParameters(this.getSearchParameters.bind(this), this.getChildContext(), this.props); } }, { key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { if (this.props.indexName !== nextProps.indexName) { this.context.ais.widgetsManager.update(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unregisterWidget(); } }, { key: "getChildContext", value: function getChildContext() { return { multiIndexContext: { targetedIndex: this.props.indexId } }; } }, { key: "getSearchParameters", value: function getSearchParameters(searchParameters, props) { return searchParameters.setIndex(this.props ? this.props.indexName : props.indexName); } }, { key: "render", value: function render() { var childrenCount = React.Children.count(this.props.children); var _this$props$root = this.props.root, Root = _this$props$root.Root, props = _this$props$root.props; if (childrenCount === 0) return null;else return React__default.createElement(Root, props, this.props.children); } }]); return Index; }(React.Component); Index.childContextTypes = { multiIndexContext: propTypes.object.isRequired }; Index.contextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; /** * Creates a specialized root Index component. It accepts * a specification of the root Element. * @param {object} defaultRoot - the defininition of the root of an Index sub tree. * @return {object} a Index root */ var createIndex = function createIndex(defaultRoot) { var CreateIndex = function CreateIndex(_ref) { var indexName = _ref.indexName, indexId = _ref.indexId, root = _ref.root, children = _ref.children; return React__default.createElement(Index, { indexName: indexName, indexId: indexId || indexName, root: root }, children); }; CreateIndex.defaultProps = { root: defaultRoot }; return CreateIndex; }; 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); } /** Used for built-in method references. */ var objectProto$l = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$i = objectProto$l.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty$i.call(object, key); } var _baseHas = baseHas; /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has$1(object, path) { return object != null && _hasPath(object, path, _baseHas); } var has_1 = has$1; /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = has_1(connectorDesc, 'refine'); var hasSearchForFacetValues = has_1(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = has_1(connectorDesc, 'getSearchParameters'); var hasMetadata = has_1(connectorDesc, 'getMetadata'); var hasTransitionState = has_1(connectorDesc, 'transitionState'); var hasCleanUp = has_1(connectorDesc, 'cleanUp'); var hasShouldComponentUpdate = has_1(connectorDesc, 'shouldComponentUpdate'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp; return _temp = _class = /*#__PURE__*/ function (_Component) { _inherits(Connector, _Component); function Connector() { var _getPrototypeOf2; var _this; _classCallCheck(this, Connector); for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) { _args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Connector)).call.apply(_getPrototypeOf2, [this].concat(_args))); _defineProperty(_assertThisInitialized(_this), "mounted", false); _defineProperty(_assertThisInitialized(_this), "unmounting", false); _defineProperty(_assertThisInitialized(_this), "refine", function () { var _connectorDesc$refine; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_assertThisInitialized(_this), _this.props, _this.context.ais.store.getState().widgets].concat(args))); }); _defineProperty(_assertThisInitialized(_this), "createURL", function () { var _connectorDesc$refine2; for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_assertThisInitialized(_this), _this.props, _this.context.ais.store.getState().widgets].concat(args))); }); _defineProperty(_assertThisInitialized(_this), "searchForFacetValues", function () { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } _this.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this.props, _this.context.ais.store.getState().widgets].concat(args))); }); _this.state = { props: _this.getProvidedProps(_objectSpread({}, _this.props, { // @MAJOR: We cannot drop this beacuse it's a breaking change. The // prop is provided to `createConnector.getProvidedProps`. All the // custom connectors are impacted by this change. It should be fine // to drop it in the next major though. canRender: false })) }; return _this; } _createClass(Connector, [{ key: "componentWillMount", value: function componentWillMount() { if (connectorDesc.getSearchParameters) { this.context.ais.onSearchParameters(connectorDesc.getSearchParameters.bind(this), this.context, this.props); } } }, { key: "componentDidMount", value: function componentDidMount() { var _this2 = this; this.mounted = true; this.unsubscribe = this.context.ais.store.subscribe(function () { if (!_this2.unmounting) { _this2.setState({ props: _this2.getProvidedProps(_objectSpread({}, _this2.props, { // @MAJOR: see constructor canRender: true })) }); } }); if (isWidget) { this.unregisterWidget = this.context.ais.widgetsManager.registerWidget(this); } } }, { key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { if (!isEqual_1(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(_objectSpread({}, nextProps, { // @MAJOR: see constructor canRender: this.mounted })) }); if (isWidget) { 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: "shouldComponentUpdate", value: function shouldComponentUpdate(nextProps, nextState) { if (hasShouldComponentUpdate) { return connectorDesc.shouldComponentUpdate.call(this, this.props, nextProps, this.state, nextState); } var propsEqual = shallowEqual(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !shallowEqual(this.state.props, nextState.props); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unmounting = true; if (this.unsubscribe) { this.unsubscribe(); } if (this.unregisterWidget) { this.unregisterWidget(); if (hasCleanUp) { var nextState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_objectSpread({}, this.context.ais.store.getState(), { widgets: nextState })); this.context.ais.onSearchStateChange(removeEmptyKey(nextState)); } } } }, { key: "getProvidedProps", value: function getProvidedProps(props) { var _this$context$ais$sto = this.context.ais.store.getState(), widgets = _this$context$ais$sto.widgets, results = _this$context$ais$sto.results, resultsFacetValues = _this$context$ais$sto.resultsFacetValues, searching = _this$context$ais$sto.searching, searchingForFacetValues = _this$context$ais$sto.searchingForFacetValues, isSearchStalled = _this$context$ais$sto.isSearchStalled, metadata = _this$context$ais$sto.metadata, error = _this$context$ais$sto.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 resutls? resultsFacetValues); } }, { key: "getSearchParameters", value: function getSearchParameters(searchParameters) { if (hasSearchParameters) { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.context.ais.store.getState().widgets); } return null; } }, { key: "getMetadata", value: function getMetadata(nextWidgetsState) { if (hasMetadata) { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: "transitionState", value: function transitionState(prevWidgetsState, nextWidgetsState) { if (hasTransitionState) { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { key: "render", value: function render() { if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues } : {}; return React__default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component), _defineProperty(_class, "displayName", "".concat(connectorDesc.displayName, "(").concat(getDisplayName(Composed), ")")), _defineProperty(_class, "defaultClassNames", Composed.defaultClassNames), _defineProperty(_class, "propTypes", connectorDesc.propTypes), _defineProperty(_class, "defaultProps", connectorDesc.defaultProps), _defineProperty(_class, "contextTypes", { // @TODO: more precise state manager propType ais: propTypes.object.isRequired, multiIndexContext: propTypes.object }), _temp; }; } 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 && has_1(translations, 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; }; } /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE$1 = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = _arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = _arrayMap(values, _baseUnary(iteratee)); } if (comparator) { includes = _arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE$1) { includes = _cacheHas; isCommon = false; values = new _SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } var _baseDifference = baseDifference; /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = _baseRest(function(array, values) { return isArrayLikeObject_1(array) ? _baseDifference(array, _baseFlatten(values, 1, isArrayLikeObject_1, true)) : []; }); var difference_1 = difference; function getId() { return 'configure'; } var connectConfigure = createConnector({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var items = omit_1(props, 'children'); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var items = omit_1(props, 'children'); var nonPresentKeys = this._props ? difference_1(keys_1(this._props), keys_1(props)) : []; this._props = props; var nextValue = _defineProperty({}, id, _objectSpread({}, omit_1(nextSearchState[id], nonPresentKeys), items)); return refineValue(nextSearchState, nextValue, this.context); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var indexId = getIndexId(this.context); var subState = hasMultipleIndices(this.context) && 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, this.context); } }); /** * Configure is a widget that lets you provide raw search parameters * to the Algolia API. * * Any of the props added to this widget will be forwarded to Algolia. For more information * on the different parameters that can be set, have a look at the * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). * * This widget can be used either with react-dom and react-native. It will not render anything * on screen, only configure some parameters. * * Read more in the [Search parameters](guide/Search_parameters.html) guide. * @name Configure * @kind widget * @example * import React from 'react'; * import { InstantSearch, Configure, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <Configure hitsPerPage={5} /> * <Hits /> * </InstantSearch> * ); */ var Configure = connectConfigure(function () { return null; }); 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(); } 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, acc)); } } return acc; }, []); } /** * The breadcrumb component is s a type of secondary navigation scheme that * reveals the user’s location in a website or web application. * * @name connectBreadcrumb * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a Breadcrumb of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display. */ var connectBreadcrumb = createConnector({ displayName: 'AlgoliaBreadcrumb', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error("Invalid prop ".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, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], canRefine: false }; } var values = results.getFacetValues(id); var items = values.data ? transformValue(values.data) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { canRefine: transformedItems.length > 0, items: transformedItems }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); } }); /** * connectCurrentRefinements connector provides the logic to build a widget that will * give the user the ability to remove all or some of the filters that were * set. * @name connectCurrentRefinements * @kind connector * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {function} [clearsQuery=false] - Pass true to also clear the search query * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {array.<{label: string, attribute: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attribute` and `currentRefinement` are metadata containing row values. * @providedPropType {string} query - the search query */ var connectCurrentRefinements = createConnector({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) { var items = metadata.reduce(function (res, meta) { if (typeof meta.items !== 'undefined') { if (!props.clearsQuery && meta.id === 'query') { return res; } else { if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') { return res; } return res.concat(meta.items.map(function (item) { return _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); } }); 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; } 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$1(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$1(v.path, props, searchState, context), count: v.count, isRefined: v.isRefined, items: v.data && transformValue$1(v.data, props, searchState, context) }; }); } var truncate = function truncate() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; return items.slice(0, limit).map(function () { var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return Array.isArray(item.items) ? _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 = createConnector({ displayName: 'AlgoliaHierarchicalMenu', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error("Invalid prop ".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, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: false }; } var itemsLimit = showMore ? showMoreLimit : limit; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue$1(value.data, props, searchState, this.context) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: truncate(transformedItems, itemsLimit), currentRefinement: getCurrentRefinement(props, searchState, this.context), canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$1(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel, showMore = props.showMore, limit = props.limit, showMoreLimit = props.showMoreLimit; 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, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var rootAttribute = props.attributes[0]; var id = getId$2(props); var currentRefinement = getCurrentRefinement(props, searchState, this.context); return { id: id, index: getIndexId(this.context), items: !currentRefinement ? [] : [{ label: "".concat(rootAttribute, ": ").concat(currentRefinement), attribute: rootAttribute, value: function value(nextState) { return _refine$1(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); var highlight = function highlight(_ref) { var attribute = _ref.attribute, hit = _ref.hit, highlightProperty = _ref.highlightProperty, _ref$preTag = _ref.preTag, preTag = _ref$preTag === 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 { InstantSearch, SearchBox, Hits, connectHighlight } from 'react-instantsearch-dom'; * * const CustomHighlight = connectHighlight( * ({ highlight, attribute, hit, highlightProperty }) => { * const highlights = highlight({ * highlightProperty: '_highlightResult', * attribute, * hit * }); * * return highlights.map(part => part.isHighlighted ? ( * <mark>{part.value}</mark> * ) : ( * <span>{part.value}</span> * )); * } * ); * * const Hit = ({ hit }) => ( * <p> * <CustomHighlight attribute="name" hit={hit} /> * </p> * ); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <SearchBox defaultRefinement="pho" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var connectHighlight = createConnector({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); /** * connectHits connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * * **Warning:** you will need to use the **objectID** property available on every hit as a key * when iterating over them. This will ensure you have the best possible UI experience * especially on slow networks. * @name connectHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @example * import React from 'react'; * import { InstantSearch, Highlight, connectHits } from 'react-instantsearch-dom'; * * const CustomHits = connectHits(({ hits }) => ( * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attribute="name" hit={hit} /> * </p> * )} * </div> * )); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <CustomHits /> * </InstantSearch> * ); */ var connectHits = createConnector({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); 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 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; } }); 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 = createConnector({ displayName: 'AlgoliaHitsPerPage', propTypes: { defaultRefinement: propTypes.number.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.number.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$1(props, searchState, this.context); 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, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$3()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement$1(props, searchState, this.context)); }, 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 = createConnector({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var _this = this; var results = getResults(searchResults, this.context); 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 || !isEqual_1(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, this.context) - 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, this.context); } var id = getId$4(); var nextValue = _defineProperty({}, id, index + 1); // `index` is indexed from 0 but page number is indexed from 1 var resetPage = false; return refineValue(searchState, nextValue, this.context, 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$2(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 sortBy$1 = ['count:desc', 'name:asc']; /** * connectMenu connector provides the logic to build a widget that will * give the user the ability to choose a single value for a specific facet. * @name connectMenu * @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @kind connector * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limit=10] - the minimum number of diplayed items * @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {boolean} [searchable=false] - allow search inside values * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var connectMenu = createConnector({ displayName: 'AlgoliaMenu', propTypes: { attribute: propTypes.string.isRequired, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, defaultRefinement: propTypes.string, transformItems: propTypes.func, searchable: propTypes.bool }, defaultProps: { showMore: false, limit: 10, showMoreLimit: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var _this = this; var attribute = props.attribute, searchable = props.searchable; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search) if (searchable && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$3(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$2(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attribute, { sortBy: sortBy$1 }).map(function (v) { return { label: v.name, value: getValue$2(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var sortedItems = searchable && !isFromSearch ? orderBy_1(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items; var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems; return { items: transformedItems.slice(0, getLimit(props)), currentRefinement: getCurrentRefinement$3(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$2(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$1(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit(props)) }); searchParameters = searchParameters.addDisjunctiveFacet(attribute); var currentRefinement = getCurrentRefinement$3(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this2 = this; var id = getId$5(props); var currentRefinement = getCurrentRefinement$3(props, searchState, this.context); return { id: id, index: getIndexId(this.context), items: currentRefinement === null ? [] : [{ label: "".concat(props.attribute, ": ").concat(currentRefinement), attribute: props.attribute, value: function value(nextState) { return _refine$2(props, nextState, '', _this2.context); }, 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 (currentRefinement) { if (currentRefinement === '') { return ''; } return currentRefinement; }); } function isRefinementsRangeIncludesInsideItemRange(stats, start, end) { return stats.min > start && stats.min < end || stats.max > start && stats.max < end; } function isItemRangeIncludedInsideRefinementsRange(stats, start, end) { return start > stats.min && start < stats.max || end > stats.min && end < stats.max; } function itemHasRefinement(attribute, results, value) { var stats = results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null; var range = value.split(':'); var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]); var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]); return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end))); } function _refine$3(props, searchState, nextRefinement, context) { var nextValue = _defineProperty({}, getId$6(props, searchState), 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 = createConnector({ displayName: 'AlgoliaNumericMenu', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node, start: propTypes.number, end: propTypes.number })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute; var currentRefinement = getCurrentRefinement$4(props, searchState, this.context); var results = getResults(searchResults, this.context); var items = props.items.map(function (item) { var value = stringifyItem(item); return { label: item.label, value: value, isRefined: value === currentRefinement, noRefinement: results ? itemHasRefinement(getId$6(props), results, value) : false }; }); var stats = results && results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null; var refinedItem = find_1(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: isEmpty_1(refinedItem), noRefinement: !stats, label: 'All' }); } 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, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$2(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; var _parseItem = parseItem(getCurrentRefinement$4(props, searchState, this.context)), start = _parseItem.start, end = _parseItem.end; searchParameters = searchParameters.addDisjunctiveFacet(attribute); if (start) { searchParameters = searchParameters.addNumericRefinement(attribute, '>=', start); } if (end) { searchParameters = searchParameters.addNumericRefinement(attribute, '<=', end); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$6(props); var value = getCurrentRefinement$4(props, searchState, this.context); var items = []; var index = getIndexId(this.context); if (value !== '') { var _find2 = find_1(props.items, function (item) { return stringifyItem(item) === value; }), label = _find2.label; items.push({ label: "".concat(props.attribute, ": ").concat(label), attribute: props.attribute, currentRefinement: label, value: function value(nextState) { return _refine$3(props, nextState, '', _this.context); } }); } return { id: id, index: index, items: items }; } }); function getId$7() { return 'page'; } function getCurrentRefinement$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 = createConnector({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement$5(props, searchState, this.context), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine$4(props, searchState, nextPage, this.context); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$7()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement$5(props, searchState, this.context) - 1); }, getMetadata: function getMetadata() { return { id: getId$7() }; } }); /** * connectPoweredBy connector provides the logic to build a widget that * will display a link to algolia. * @name connectPoweredBy * @kind connector * @providedPropType {string} url - the url to redirect to algolia */ var connectPoweredBy = createConnector({ displayName: 'AlgoliaPoweredBy', getProvidedProps: function getProvidedProps() { var isServer = typeof window === 'undefined'; var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + "utm_content=".concat(!isServer ? window.location.hostname : '', "&") + 'utm_campaign=poweredby'; return { url: url }; } }); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsFinite = _root.isFinite; /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite$1(value) { return typeof value == 'number' && nativeIsFinite(value); } var _isFinite = isFinite$1; /** * 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 (_isFinite(boundaries.min)) { min = boundaries.min; } else if (_isFinite(stats.min)) { min = stats.min; } else { min = undefined; } var max; if (_isFinite(boundaries.max)) { max = boundaries.max; } else if (_isFinite(stats.max)) { max = stats.max; } else { max = undefined; } return { min: min !== undefined ? Math.floor(min * pow) / pow : min, max: max !== undefined ? Math.ceil(max * pow) / pow : max }; } function getCurrentRefinement$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 = createConnector({ displayName: 'AlgoliaRange', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, defaultRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }), min: propTypes.number, max: propTypes.number, precision: propTypes.number, header: propTypes.node, footer: propTypes.node }, defaultProps: { precision: 0 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute, precision = props.precision, minBound = props.min, maxBound = props.max; var results = getResults(searchResults, this.context); var hasFacet = results && results.getFacetByName(attribute); var stats = hasFacet ? results.getFacetStats(attribute) || {} : {}; var facetValues = hasFacet ? results.getFacetValues(attribute) : []; var count = facetValues.map(function (v) { return { value: v.name, count: v.count }; }); var _getCurrentRange = getCurrentRange({ min: minBound, max: maxBound }, stats, precision), rangeMin = _getCurrentRange.min, rangeMax = _getCurrentRange.max; // The searchState is not always in sync with the helper state. For example // when we set boundaries on the first render the searchState don't have // the correct refinement. If this behaviour change in the upcoming version // we could store the range inside the searchState instead of rely on `this`. this._currentRange = { min: rangeMin, max: rangeMax }; var currentRefinement = getCurrentRefinement$6(props, searchState, this._currentRange, this.context); return { min: rangeMin, max: rangeMax, canRefine: count.length > 0, currentRefinement: getCurrentRefinementWithRange(currentRefinement, this._currentRange), count: count, precision: precision }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$5(props, searchState, nextRefinement, this._currentRange, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$3(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attribute = props.attribute; var _getCurrentRefinement2 = getCurrentRefinement$6(props, searchState, this._currentRange, this.context), 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, this.context), minValue = _getCurrentRefinement3.min, maxValue = _getCurrentRefinement3.max; var items = []; var hasMin = minValue !== undefined; var hasMax = maxValue !== undefined; var shouldDisplayMinLabel = hasMin && minValue !== minRange; var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange; if (shouldDisplayMinLabel || shouldDisplayMaxLabel) { var fragments = [hasMin ? "".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, _this.context); }, currentRefinement: getCurrentRefinementWithRange({ min: minValue, max: maxValue }, { min: minRange, max: maxRange }) }); } return { id: getId$8(props), index: getIndexId(this.context), 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$3(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$2 = ['isRefined', 'count:desc', 'name:asc']; var connectRefinementList = createConnector({ displayName: 'AlgoliaRefinementList', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, operator: propTypes.oneOf(['and', 'or']), showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), searchable: propTypes.bool, transformItems: propTypes.func }, defaultProps: { operator: 'or', showMore: false, limit: 10, showMoreLimit: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) { var _this = this; var attribute = props.attribute, searchable = props.searchable; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search) if (searchable && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$7(props, searchState, this.context), canRefine: canRefine, isFromSearch: isFromSearch, searchable: searchable }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$3(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attribute, { sortBy: sortBy$2 }).map(function (v) { return { label: v.name, value: getValue$3(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit$1(props)), currentRefinement: getCurrentRefinement$7(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$6(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit$1(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$4(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, operator = props.operator; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = "".concat(addKey, "Refinement"); searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props)) }); searchParameters = searchParameters[addKey](attribute); return getCurrentRefinement$7(props, searchState, this.context).reduce(function (res, val) { return res[addRefinementKey](attribute, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId$9(props); var context = this.context; return { id: id, index: getIndexId(this.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 = createConnector({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: propTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = getCurrentRefinementValue(props, searchState, this.context, id, null); if (!this._prevSearchState) { this._prevSearchState = {}; } /* Get the subpart of the state that interest us*/ if (hasMultipleIndices(this.context)) { searchState = searchState.indices ? searchState.indices[getIndexId(this.context)] : {}; } /* if there is a change in the app that has been triggered by another element than "props.scrollOn (id) or the Configure widget, we need to keep track of the search state to know if there's a change in the app that was not triggered by the props.scrollOn (id) or the Configure widget. This is useful when using ScrollTo in combination of Pagination. As pagination can be change by every widget, we want to scroll only if it cames from the pagination widget itself. We also remove the configure key from the search state to do this comparaison because for now configure values are not present in the search state before a first refinement has been made and will false the results. See: https://github.com/algolia/react-instantsearch/issues/164 */ var cleanedSearchState = omit_1(omit_1(searchState, 'configure'), id); var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState); this._prevSearchState = cleanedSearchState; return { value: value, hasNotChanged: hasNotChanged }; } }); function getId$a() { return 'query'; } function getCurrentRefinement$8(props, searchState, context) { var id = getId$a(props); 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 = createConnector({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: propTypes.string }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { currentRefinement: getCurrentRefinement$8(props, searchState, this.context), isSearchStalled: searchResults.isSearchStalled }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$7(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$5(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$8(props, searchState, this.context)); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$a(props); var currentRefinement = getCurrentRefinement$8(props, searchState, this.context); return { id: id, index: getIndexId(this.context), items: currentRefinement === null ? [] : [{ label: "".concat(id, ": ").concat(currentRefinement), value: function value(nextState) { return _refine$7(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); function getId$b() { return 'sortBy'; } function getCurrentRefinement$9(props, searchState, context) { var id = getId$b(props); 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 = createConnector({ displayName: 'AlgoliaSortBy', propTypes: { defaultRefinement: propTypes.string, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$9(props, searchState, this.context); 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, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$b()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement$9(props, searchState, this.context); 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 = createConnector({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); function getId$c(props) { return props.attribute; } var namespace$6 = 'toggle'; function getCurrentRefinement$a(props, searchState, context) { var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$6, ".").concat(getId$c(props)), false); if (currentRefinement) { return currentRefinement; } return false; } 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 = createConnector({ 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, this.context); var currentRefinement = getCurrentRefinement$a(props, searchState, this.context); 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_1(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, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$6(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, value = props.value, filter = props.filter; var checked = getCurrentRefinement$a(props, searchState, this.context); 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 _this = this; var id = getId$c(props); var checked = getCurrentRefinement$a(props, searchState, this.context); var items = []; var index = getIndexId(this.context); if (checked) { items.push({ label: props.label, currentRefinement: checked, attribute: props.attribute, value: function value(nextState) { return _refine$8(props, nextState, false, _this.context); } }); } return { id: id, index: index, items: items }; } }); // Core var inherits_browser$1 = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var hasOwn = Object.prototype.hasOwnProperty; var toString$1 = Object.prototype.toString; var foreach = function forEach (obj, fn, ctx) { if (toString$1.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); } } } }; // 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.. function AlgoliaSearchError(message, extraProperties) { var forEach = foreach; 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_browser$1(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_browser$1(AlgoliaSearchCustomError, AlgoliaSearchError); return AlgoliaSearchCustomError; } // late exports to let various fn defs and inherits take place var errors = { AlgoliaSearchError: AlgoliaSearchError, UnparsableJSON: createCustomError( 'UnparsableJSON', 'Could not parse the incoming response as JSON, see err.more for details' ), RequestTimeout: createCustomError( 'RequestTimeout', 'Request timed out 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' ) }; // 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 var exitPromise = function exitPromise(fn, _setTimeout) { _setTimeout(fn, 0); }; var buildSearchMethod_1 = buildSearchMethod; /** * Creates a search method to be used in clients * @param {string} queryParam the name of the attribute used for the query * @param {string} url the url * @return {function} the search method */ function buildSearchMethod(queryParam, url) { /** * The search method. Prepares the data and send the query to Algolia. * @param {string} query the string used for query search * @param {object} args additional parameters to send with the search * @param {function} [callback] the callback to be called with the client gets the answer * @return {undefined|Promise} If the callback is not provided then this methods returns a Promise */ return function search(query, args, callback) { // warn V2 users on how to search if (typeof query === 'function' && typeof args === 'object' || typeof callback === 'object') { // .search(query, params, cb) // .search(cb, params) throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)'); } // Normalizing the function signature if (arguments.length === 0 || typeof query === 'function') { // Usage : .search(), .search(cb) callback = query; query = ''; } else if (arguments.length === 1 || typeof args === 'function') { // Usage : .search(query/args), .search(query, cb) callback = args; args = undefined; } // At this point we have 3 arguments with values // Usage : .search(args) // careful: typeof null === 'object' if (typeof query === 'object' && query !== null) { args = query; query = undefined; } else if (query === undefined || query === null) { // .search(undefined/null) query = ''; } var params = ''; if (query !== undefined) { params += queryParam + '=' + encodeURIComponent(query); } var additionalUA; if (args !== undefined) { if (args.additionalUA) { additionalUA = args.additionalUA; delete args.additionalUA; } // `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if params = this.as._getSearchParams(args, params); } return this._search(params, url, callback, additionalUA); }; } var deprecate = function deprecate(fn, message) { var warned = false; function deprecated() { if (!warned) { /* eslint no-console:0 */ console.warn(message); warned = true; } return fn.apply(this, arguments); } return deprecated; }; var deprecatedMessage = function deprecatedMessage(previousUsage, newUsage) { var githubAnchorLink = previousUsage.toLowerCase() .replace(/[\.\(\)]/g, ''); return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage + '`. Please see https://github.com/algolia/algoliasearch-client-javascript/wiki/Deprecated#' + githubAnchorLink; }; var merge$1 = 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; }; var clone = function clone(obj) { return JSON.parse(JSON.stringify(obj)); }; var toStr = Object.prototype.toString; var isArguments$1 = 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; }; var keysShim; if (!Object.keys) { // modified from https://github.com/es-shims/es5-shim var has$2 = Object.prototype.hasOwnProperty; var toStr$1 = Object.prototype.toString; var isArgs = isArguments$1; // eslint-disable-line global-require 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 = { $applicationCache: true, $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $onmozfullscreenchange: true, $onmozfullscreenerror: 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$2.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; } }; keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr$1.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr$1.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$2.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$2.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$2.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; } var implementation = keysShim; var slice = Array.prototype.slice; var origKeys = Object.keys; var keysShim$1 = origKeys ? function keys(o) { return origKeys(o); } : implementation; var originalKeys = Object.keys; keysShim$1.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug var args = Object.keys(arguments); return args && args.length === arguments.length; }(1, 2)); if (!keysWorksWithArguments) { Object.keys = function keys(object) { // eslint-disable-line func-name-matching if (isArguments$1(object)) { return originalKeys(slice.call(object)); } return originalKeys(object); }; } } else { Object.keys = keysShim$1; } return Object.keys || keysShim$1; }; var objectKeys = keysShim$1; var omit$1 = function omit(obj, test) { var keys = objectKeys; var foreach$1 = foreach; var filtered = {}; foreach$1(keys(obj), function doFilter(keyName) { if (test(keyName) !== true) { filtered[keyName] = obj[keyName]; } }); return filtered; }; var toString$2 = {}.toString; var isarray = Array.isArray || function (arr) { return toString$2.call(arr) == '[object Array]'; }; var map$1 = function map(arr, fn) { var newArr = []; foreach(arr, function(item, itemIndex) { newArr.push(fn(item, itemIndex, arr)); }); return newArr; }; var IndexCore_1 = IndexCore; /* * Index class constructor. * You should not use this method directly but use initIndex() function */ function IndexCore(algoliasearch, indexName) { this.indexName = indexName; this.as = algoliasearch; this.typeAheadArgs = null; this.typeAheadValueOption = null; // make sure every index instance has it's own cache this.cache = {}; } /* * Clear all queries in cache */ IndexCore.prototype.clearCache = function() { this.cache = {}; }; /* * Search inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the full text query * @param {object} [args] (optional) if set, contains an object with query parameters: * - page: (integer) Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, * to retrieve the 10th page you need to set page=9 * - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. * - attributesToRetrieve: a string that contains the list of object attributes * you want to retrieve (let you minimize the answer size). * Attributes are separated with a comma (for example "name,address"). * You can also use an array (for example ["name","address"]). * By default, all attributes are retrieved. You can also use '*' to retrieve all * values when an attributesToRetrieve setting is specified for your index. * - attributesToHighlight: a string that contains the list of attributes you * want to highlight according to the query. * Attributes are separated by a comma. You can also use an array (for example ["name","address"]). * If an attribute has no match for the query, the raw value is returned. * By default all indexed text attributes are highlighted. * You can use `*` if you want to highlight all textual attributes. * Numerical attributes are not highlighted. * A matchLevel is returned for each highlighted attribute and can contain: * - full: if all the query terms were found in the attribute, * - partial: if only some of the query terms were found, * - none: if none of the query terms were found. * - attributesToSnippet: a string that contains the list of attributes to snippet alongside * the number of words to return (syntax is `attributeName:nbWords`). * Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). * You can also use an array (Example: attributesToSnippet: ['name:10','content:10']). * By default no snippet is computed. * - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. * Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters in a query word * to accept two typos in this word. Defaults to 7. * - getRankingInfo: if set to 1, the result hits will contain ranking * information in _rankingInfo attribute. * - aroundLatLng: search for entries around a given * latitude/longitude (specified as two floats separated by a comma). * For example aroundLatLng=47.316669,5.016670). * You can specify the maximum distance in meters with the aroundRadius parameter (in meters) * and the precision for ranking with aroundPrecision * (for example if you set aroundPrecision=100, two objects that are distant of * less than 100m will be considered as identical for "geo" ranking parameter). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - insideBoundingBox: search entries inside a given area defined by the two extreme points * of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). * For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - numericFilters: a string that contains the list of numeric filters you want to * apply separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value`. * Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. * You can also use an array (for example numericFilters: ["price>100","price<1000"]). * - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. * To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). * You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]] * means tag1 AND (tag2 OR tag3). * At indexing, tags should be added in the _tags** attribute * of objects (for example {"_tags":["tag1","tag2"]}). * - facetFilters: filter the query by a list of facets. * Facets are separated by commas and each facet is encoded as `attributeName:value`. * For example: `facetFilters=category:Book,author:John%20Doe`. * You can also use an array (for example `["category:Book","author:John%20Doe"]`). * - facets: List of object attributes that you want to use for faceting. * Comma separated list: `"category,author"` or array `['category','author']` * Only attributes that have been added in **attributesForFaceting** index setting * can be used in this parameter. * You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. * - queryType: select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - optionalWords: a string that contains the list of words that should * be considered as optional when found in the query. * Comma separated and array are accepted. * - distinct: If set to 1, enable the distinct feature (disabled by default) * if the attributeForDistinct index setting is set. * This feature is similar to the SQL "distinct" keyword: when enabled * in a query with the distinct=1 parameter, * all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have * the same value for show_name, then only the best * one is kept and others are removed. * - restrictSearchableAttributes: List of attributes you want to use for * textual search (must be a subset of the attributesToIndex index setting) * either comma separated or as an array * @param {function} [callback] the result callback called with two arguments: * error: null or Error('message'). If false, the content contains the error. * content: the server answer that contains the list of results. */ IndexCore.prototype.search = buildSearchMethod_1('query'); /* * -- BETA -- * Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the similar query * @param {object} [args] (optional) if set, contains an object with query parameters. * All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters * are the two most useful to restrict the similar results and get more relevant content */ IndexCore.prototype.similarSearch = deprecate( buildSearchMethod_1('similarQuery'), deprecatedMessage( 'index.similarSearch(query[, callback])', 'index.search({ similarQuery: query }[, callback])' ) ); /* * 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 = merge$1; var indexObj = this; var page; var hitsPerPage; // we check variadic calls that are not the one defined // .browse()/.browse(fn) // => page = 0 if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') { page = 0; callback = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'number') { // .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn) page = arguments[0]; if (typeof arguments[1] === 'number') { hitsPerPage = arguments[1]; } else if (typeof arguments[1] === 'function') { callback = arguments[1]; hitsPerPage = undefined; } query = undefined; queryParameters = undefined; } else if (typeof arguments[0] === 'object') { // .browse(queryParameters)/.browse(queryParameters, cb) if (typeof arguments[1] === 'function') { callback = arguments[1]; } queryParameters = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') { // .browse(query, cb) callback = arguments[1]; queryParameters = undefined; } // otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb) // get search query parameters combining various possible calls // to .browse(); queryParameters = merge({}, queryParameters || {}, { page: page, hitsPerPage: hitsPerPage, query: query }); var params = this.as._getSearchParams(queryParameters, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse', body: {params: params}, hostType: 'read', callback: callback }); }; /* * Continue browsing from a previous position (cursor), obtained via a call to `.browse()`. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browseFrom('14lkfsakl32', callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browseFrom = function(cursor, callback) { return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse', body: {cursor: cursor}, hostType: 'read', callback: callback }); }; /* * Search for facet values * https://www.algolia.com/doc/rest-api/search#search-for-facet-values * * @param {string} params.facetName Facet name, name of the attribute to search for values in. * Must be declared as a facet * @param {string} params.facetQuery Query for the facet search * @param {string} [params.*] Any search parameter of Algolia, * see https://www.algolia.com/doc/api-client/javascript/search#search-parameters * Pagination is not supported. The page and hitsPerPage parameters will be ignored. * @param callback (optional) */ IndexCore.prototype.searchForFacetValues = function(params, callback) { var clone$1 = clone; var omit = omit$1; 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$1(params), function(keyName) { return keyName === 'facetName'; }); var searchParameters = this.as._getSearchParams(filteredParams, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query', hostType: 'read', body: {params: searchParameters}, callback: callback }); }; IndexCore.prototype.searchFacet = deprecate(function(params, callback) { return this.searchForFacetValues(params, callback); }, deprecatedMessage( 'index.searchFacet(params[, callback])', 'index.searchForFacetValues(params[, callback])' )); IndexCore.prototype._search = function(params, url, callback, additionalUA) { return this.as._jsonRequest({ cache: this.cache, method: 'POST', url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: {params: params}, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName), body: {params: params} }, callback: callback, additionalUA: additionalUA }); }; /* * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param attrs (optional) if set, contains the array of attribute names to retrieve * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the object to retrieve or the error message if a failure occurred */ 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 = isarray; var map = map$1; 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; /** * 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 */ var ms = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse$1(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$1(str) { str = String(str); if (str.length > 100) { 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'; } var debug = createCommonjsModule(function (module, exports) { /** * 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 = ms; /** * 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); exports.names = []; exports.skips = []; var split = (typeof namespaces === 'string' ? 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; } }); var debug_1 = debug.coerce; var debug_2 = debug.disable; var debug_3 = debug.enable; var debug_4 = debug.enabled; var debug_5 = debug.humanize; var debug_6 = debug.names; var debug_7 = debug.skips; var debug_8 = debug.formatters; var browser$1 = createCommonjsModule(function (module, exports) { /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug; 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.process && 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.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && 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.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() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * 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) {} } }); var browser_1 = browser$1.log; var browser_2 = browser$1.formatArgs; var browser_3 = browser$1.save; var browser_4 = browser$1.load; var browser_5 = browser$1.useColors; var browser_6 = browser$1.storage; var browser_7 = browser$1.colors; var debug$1 = browser$1('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(commonjsGlobal.localStorage[localStorageNamespace]); namespace[key] = data; commonjsGlobal.localStorage[localStorageNamespace] = JSON.stringify(namespace); return namespace[key]; } catch (e) { return localStorageFailure(key, e); } }, get: function(key) { try { return JSON.parse(commonjsGlobal.localStorage[localStorageNamespace])[key] || null; } catch (e) { return localStorageFailure(key, e); } } }; function localStorageFailure(key, e) { debug$1('localStorage failed with', e); cleanup(); store = moduleStore; return store.get(key); } store = supportsLocalStorage() ? localStorageStore : moduleStore; var store_1 = { 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 commonjsGlobal && commonjsGlobal.localStorage !== null) { if (!commonjsGlobal.localStorage[localStorageNamespace]) { // actual creation of the namespace commonjsGlobal.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 { commonjsGlobal.localStorage.removeItem(localStorageNamespace); } catch (_) { // nothing to do } } var AlgoliaSearchCore_1 = AlgoliaSearchCore; // We will always put the API KEY in the JSON body in case of too long API KEY, // to avoid query string being too long and failing in various conditions (our server limit, browser limit, // proxies limit) var MAX_API_KEY_LENGTH = 500; var RESET_APP_DATA_TIMER = process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) || 60 * 2 * 1000; // after 2 minutes reset to first host /* * Algolia Search library initialization * https://www.algolia.com/ * * @param {string} applicationID - Your applicationID, found in your dashboard * @param {string} apiKey - Your API key, found in your dashboard * @param {Object} [opts] * @param {number} [opts.timeout=2000] - The request timeout set in milliseconds, * another request will be issued after this timeout * @param {string} [opts.protocol='https:'] - The protocol used to query Algolia Search API. * Set to 'http:' to force using http. * @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 = browser$1('algoliasearch'); var clone$1 = clone; var isArray = isarray; var map = map$1; 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 || {}; 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; } var protocol = opts.protocol || 'https:'; // 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 (protocol !== 'http:' && 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 var mainSuffix = (opts.dsn === false ? '' : '-dsn') + '.algolia.net'; this.hosts.read = [this.applicationID + mainSuffix].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$1(opts.hosts); this.hosts.write = clone$1(opts.hosts); } else { this.hosts.read = clone$1(opts.hosts.read); this.hosts.write = clone$1(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._useRequestCache = this._useCache && opts._useRequestCache; 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_1(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[name.toLowerCase()] = value; }; /** * Get the value of an extra HTTP header * * @param name the header field name */ AlgoliaSearchCore.prototype.getExtraHeader = function(name) { return this.extraHeaders[name.toLowerCase()]; }; /** * Remove an extra field from the HTTP request * * @param name the header field name */ AlgoliaSearchCore.prototype.unsetExtraHeader = function(name) { delete this.extraHeaders[name.toLowerCase()]; }; /** * 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) { var algoliaAgentWithDelimiter = '; ' + algoliaAgent; if (this._ua.indexOf(algoliaAgentWithDelimiter) === -1) { this._ua += algoliaAgentWithDelimiter; } }; /* * Wrapper that try all hosts to maximize the quality of service */ AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) { this._checkAppIdData(); var requestDebug = browser$1('algoliasearch:' + initialOpts.url); var body; var cacheID; var additionalUA = initialOpts.additionalUA || ''; var cache = initialOpts.cache; var client = this; var tries = 0; var usingFallback = false; var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback; var headers; if ( this.apiKey.length > MAX_API_KEY_LENGTH && initialOpts.body !== undefined && (initialOpts.body.params !== undefined || // index.search() initialOpts.body.requests !== undefined) // client.search() ) { initialOpts.body.apiKey = this.apiKey; headers = this._computeRequestHeaders({ additionalUA: additionalUA, withApiKey: false, headers: initialOpts.headers }); } else { headers = this._computeRequestHeaders({ additionalUA: additionalUA, headers: initialOpts.headers }); } if (initialOpts.body !== undefined) { body = safeJSONStringify(initialOpts.body); } requestDebug('request start'); var debugData = []; function doRequest(requester, reqOpts) { client._checkAppIdData(); var startTime = new Date(); if (client._useCache && !client._useRequestCache) { 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 && !client._useRequestCache && body) { cacheID += '_body_' + reqOpts.body; } // handle cache existence if (isCacheValidWithCurrentID(!client._useRequestCache, cache, cacheID)) { requestDebug('serving response from cache'); var responseText = cache[cacheID]; // Cache response must match the type of the original one return client._promise.resolve({ body: JSON.parse(responseText), responseText: responseText }); } // 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 support@algolia.com to report and resolve the issue.' + ' Application id was: ' + client.applicationID, {debugData: debugData} )); } requestDebug('switching to fallback'); // let's try the fallback starting from here tries = 0; // method, url and body are fallback dependent reqOpts.method = initialOpts.fallback.method; reqOpts.url = initialOpts.fallback.url; reqOpts.jsonBody = initialOpts.fallback.body; if (reqOpts.jsonBody) { reqOpts.body = safeJSONStringify(reqOpts.jsonBody); } // re-compute headers, they could be omitting the API KEY headers = client._computeRequestHeaders({ additionalUA: additionalUA, headers: initialOpts.headers }); 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, forceAuthHeaders: reqOpts.forceAuthHeaders }; 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 && !client._useRequestCache && cache) { cache[cacheID] = httpResponse.responseText; } return { responseText: httpResponse.responseText, body: 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 occurred, 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); } } function isCacheValidWithCurrentID( useRequestCache, currentCache, currentCacheID ) { return ( client._useCache && useRequestCache && currentCache && currentCache[currentCacheID] !== undefined ); } function interopCallbackReturn(request, callback) { if (isCacheValidWithCurrentID(client._useRequestCache, cache, cacheID)) { request.catch(function() { // Release the cache on error delete cache[cacheID]; }); } if (typeof initialOpts.callback === 'function') { // either we have a callback request.then(function okCb(content) { exitPromise(function() { initialOpts.callback(null, callback(content)); }, client._setTimeout || setTimeout); }, function nookCb(err) { exitPromise(function() { initialOpts.callback(err); }, client._setTimeout || setTimeout); }); } else { // either we are using promises return request.then(callback); } } if (client._useCache && client._useRequestCache) { 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 && client._useRequestCache && body) { cacheID += '_body_' + body; } if (isCacheValidWithCurrentID(client._useRequestCache, cache, cacheID)) { requestDebug('serving request from cache'); var maybePromiseForCache = cache[cacheID]; // In case the cache is warmup with value that is not a promise var promiseForCache = typeof maybePromiseForCache.then !== 'function' ? client._promise.resolve({responseText: maybePromiseForCache}) : maybePromiseForCache; return interopCallbackReturn(promiseForCache, function(content) { // In case of the cache request, return the original value return JSON.parse(content.responseText); }); } var request = doRequest( client._request, { url: initialOpts.url, method: initialOpts.method, body: body, jsonBody: initialOpts.body, timeouts: client._getTimeoutsForRequest(initialOpts.hostType), forceAuthHeaders: initialOpts.forceAuthHeaders } ); if (client._useCache && client._useRequestCache && cache) { cache[cacheID] = request; } return interopCallbackReturn(request, function(content) { // In case of the first request, return the JSON value return content.body; }); }; /* * Transform search param object in query string * @param {object} args arguments to add to the current query string * @param {string} params current query string * @return {string} the final query string */ AlgoliaSearchCore.prototype._getSearchParams = function(args, params) { if (args === undefined || args === null) { return params; } for (var key in args) { if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) { params += params === '' ? '' : '&'; params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]); } } return params; }; /** * Compute the headers for a request * * @param [string] options.additionalUA semi-colon separated string with other user agents to add * @param [boolean=true] options.withApiKey Send the api key as a header * @param [Object] options.headers Extra headers to send */ AlgoliaSearchCore.prototype._computeRequestHeaders = function(options) { var forEach = foreach; var ua = options.additionalUA ? this._ua + '; ' + options.additionalUA : this._ua; var requestHeaders = { 'x-algolia-agent': ua, 'x-algolia-application-id': this.applicationID }; // browser will inline headers in the url, node.js will use http headers // but in some situations, the API KEY will be too long (big secured API keys) // so if the request is a POST and the KEY is very long, we will be asked to not put // it into headers but in the JSON body if (options.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; } forEach(this.extraHeaders, function addToRequestHeaders(value, key) { requestHeaders[key] = value; }); if (options.headers) { forEach(options.headers, function addToRequestHeaders(value, key) { requestHeaders[key] = 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 = isarray; var map = map$1; 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) { postObj.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 }); }; /** * Search for facet values * https://www.algolia.com/doc/rest-api/search#search-for-facet-values * This is the top-level API for SFFV. * * @param {object[]} queries An array of queries to run. * @param {string} queries[].indexName Index name, name of the index to search. * @param {object} queries[].params Query parameters. * @param {string} queries[].params.facetName Facet name, name of the attribute to search for values in. * Must be declared as a facet * @param {string} queries[].params.facetQuery Query for the facet search * @param {string} [queries[].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. */ AlgoliaSearchCore.prototype.searchForFacetValues = function(queries) { var isArray = isarray; var map = map$1; var usage = 'Usage: client.searchForFacetValues([{indexName, params: {facetName, facetQuery, ...params}}, ...queries])'; // eslint-disable-line max-len if (!isArray(queries)) { throw new Error(usage); } var client = this; return client._promise.all(map(queries, function performQuery(query) { if ( !query || query.indexName === undefined || query.params.facetName === undefined || query.params.facetQuery === undefined ) { throw new Error(usage); } var clone$1 = clone; var omit = omit$1; var indexName = query.indexName; var params = query.params; var facetName = params.facetName; var filteredParams = omit(clone$1(params), function(keyName) { return keyName === 'facetName'; }); var searchParameters = client._getSearchParams(filteredParams, ''); return client._jsonRequest({ cache: client.cache, method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexName) + '/facets/' + encodeURIComponent(facetName) + '/query', hostType: 'read', body: {params: searchParameters} }); })); }; /** * 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_1.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_1.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$1 = foreach; var currentData = this._getAppIdData(); foreach$1(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$1 = clone; var newHostIndexes = clone$1(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; } var win; if (typeof window !== "undefined") { win = window; } else if (typeof commonjsGlobal !== "undefined") { win = commonjsGlobal; } else if (typeof self !== "undefined"){ win = self; } else { win = {}; } var window_1 = win; var es6Promise = createCommonjsModule(function (module, exports) { /*! * @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 v4.2.6+9869a4bc */ (function (global, factory) { module.exports = factory(); }(commonjsGlobal, (function () { function objectOrFunction(x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); } function isFunction(x) { return typeof x === 'function'; } var _isArray = void 0; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } var isArray = _isArray; var len = 0; var vertxNext = void 0; var customSchedulerFn = void 0; 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 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 vertx = Function('return this')().require('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = void 0; // 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 && typeof commonjsRequire === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { 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$1(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(2); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var TRY_CATCH_ERROR = { error: null }; 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) { TRY_CATCH_ERROR.error = error; return TRY_CATCH_ERROR; } } function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { try { then$$1.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then$$1) { asap(function (promise) { var sealed = false; var error = tryThen(then$$1, 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$$1) { if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { handleOwnThenable(promise, maybeThenable); } else { if (then$$1 === TRY_CATCH_ERROR) { reject(promise, TRY_CATCH_ERROR.error); TRY_CATCH_ERROR.error = null; } else if (then$$1 === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$1)) { handleForeignThenable(promise, maybeThenable, then$$1); } 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 = void 0, callback = void 0, 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 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 = void 0, error = void 0, succeeded = void 0, failed = void 0; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value.error = null; } else { succeeded = true; } if (promise === value) { reject(promise, cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) ; 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 validationError() { return new Error('Array Methods must be provided an Array'); } var Enumerator = function () { function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(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(input); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { reject(this.promise, validationError()); } } Enumerator.prototype._enumerate = function _enumerate(input) { for (var i = 0; this._state === PENDING && i < input.length; i++) { this._eachEntry(input[i], i); } }; Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { var c = this._instanceConstructor; var resolve$$1 = c.resolve; if (resolve$$1 === resolve$1) { 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$1) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$1) { return resolve$$1(entry); }), i); } } else { this._willSettleAt(resolve$$1(entry), i); } }; Enumerator.prototype._settledAt = function _settledAt(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 _willSettleAt(promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; return Enumerator; }(); /** `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$1(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 */ var Promise$1 = function () { 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(); } } /** 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} */ /** `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} */ Promise.prototype.catch = function _catch(onRejection) { return this.then(null, onRejection); }; /** `finally` will be invoked regardless of the promise's fate just as native try/catch/finally behaves Synchronous example: ```js findAuthor() { if (Math.random() > 0.5) { throw new Error(); } return new Author(); } try { return findAuthor(); // succeed or fail } catch(error) { return findOtherAuther(); } finally { // always runs // doesn't affect the return value } ``` Asynchronous example: ```js findAuthor().catch(function(reason){ return findOtherAuther(); }).finally(function(){ // author was either found, or not }); ``` @method finally @param {Function} callback @return {Promise} */ Promise.prototype.finally = function _finally(callback) { var promise = this; var constructor = promise.constructor; if (isFunction(callback)) { return promise.then(function (value) { return constructor.resolve(callback()).then(function () { return value; }); }, function (reason) { return constructor.resolve(callback()).then(function () { throw reason; }); }); } return promise.then(callback, callback); }; return Promise; }(); Promise$1.prototype.then = then; Promise$1.all = all; Promise$1.race = race; Promise$1.resolve = resolve$1; Promise$1.reject = reject$1; Promise$1._setScheduler = setScheduler; Promise$1._setAsap = setAsap; Promise$1._asap = asap; /*global self*/ function polyfill() { var local = void 0; if (typeof commonjsGlobal !== 'undefined') { local = commonjsGlobal; } 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$1; } // Strange compat.. Promise$1.polyfill = polyfill; Promise$1.Promise = Promise$1; return Promise$1; }))); }); // Copyright Joyent, Inc. and other Node contributors. 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 ''; } }; var encode$1 = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map$2(objectKeys$1(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray$1(obj[k])) { return map$2(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$1 = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map$2 (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$1 = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; var inlineHeaders_1 = inlineHeaders; function inlineHeaders(url, headers) { if (/\?/.test(url)) { url += '&'; } else { url += '?'; } return url + encode$1(headers); } var jsonpRequest_1 = jsonpRequest; 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, responseText: JSON.stringify(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()); } } // Copyright Joyent, Inc. and other Node contributors. // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty$j(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var decode = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty$j(obj, k)) { obj[k] = v; } else if (isArray$2(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray$2 = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; var querystringEs3 = createCommonjsModule(function (module, exports) { exports.decode = exports.parse = decode; exports.encode = exports.stringify = encode$1; }); var querystringEs3_1 = querystringEs3.decode; var querystringEs3_2 = querystringEs3.parse; var querystringEs3_3 = querystringEs3.encode; var querystringEs3_4 = querystringEs3.stringify; var places = createPlacesClient; function createPlacesClient(algoliasearch) { return function places(appID, apiKey, opts) { var cloneDeep = clone; 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_1('query', '/1/places/query'); index.reverse = function(options, callback) { var encoded = querystringEs3.encode(options); return this.as._jsonRequest({ method: 'GET', url: '/1/places/reverse?' + encoded, hostType: 'read', callback: callback }); }; index.getObject = function(objectID, callback) { return this.as._jsonRequest({ method: 'GET', url: '/1/places/' + encodeURIComponent(objectID), hostType: 'read', callback: callback }); }; return index; }; } var version$3 = '3.33.0'; var Promise$2 = window_1.Promise || es6Promise.Promise; // This is the standalone browser build entry point // Browser implementation of the Algolia Search JavaScript client, // using XMLHttpRequest, XDomainRequest and JSONP as fallback var createAlgoliasearch = function createAlgoliasearch(AlgoliaSearch, uaSuffix) { var inherits = inherits_browser$1; var errors$1 = errors; var inlineHeaders = inlineHeaders_1; var jsonpRequest = jsonpRequest_1; var places$1 = places; uaSuffix = uaSuffix || ''; function algoliasearch(applicationID, apiKey, opts) { var cloneDeep = clone; opts = cloneDeep(opts || {}); opts._ua = opts._ua || algoliasearch.ua; return new AlgoliaSearchBrowser(applicationID, apiKey, opts); } algoliasearch.version = version$3; algoliasearch.ua = 'Algolia for JavaScript (' + algoliasearch.version + '); ' + uaSuffix; algoliasearch.initPlaces = places$1(algoliasearch); // we expose into window no matter how we are used, this will allow // us to easily debug any website running algolia window_1.__algolia = { debug: browser$1, algoliasearch: algoliasearch }; var support = { hasXMLHttpRequest: 'XMLHttpRequest' in window_1, hasXDomainRequest: 'XDomainRequest' in window_1 }; 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$2(function wrapRequest(resolve, reject) { // no cors or XDomainRequest, no request if (!support.cors && !support.hasXDomainRequest) { // very old browser, not supported reject(new errors$1.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); // The Analytics API never accepts Auth headers as query string // this option exists specifically for them. if (opts.forceAuthHeaders) { req.setRequestHeader( 'x-algolia-application-id', opts.headers['x-algolia-application-id'] ); req.setRequestHeader( 'x-algolia-api-key', opts.headers['x-algolia-api-key'] ); } } 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'); } if (body) { req.send(body); } else { req.send(); } // 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$1.UnparsableJSON({ more: req.responseText }); } if (out instanceof errors$1.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$1.Network({ more: event }) ); } function onTimeout() { timedOut = true; req.abort(); reject(new errors$1.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$2(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$2.reject(val); }, resolve: function resolvePromise(val) { return Promise$2.resolve(val); }, delay: function delayPromise(ms) { return new Promise$2(function resolveOnTimeout(resolve/* , reject*/) { setTimeout(resolve, ms); }); }, all: function all(promises) { return Promise$2.all(promises); } }; return algoliasearch; }; var algoliasearchLite = createAlgoliasearch(AlgoliaSearchCore_1, 'Browser (lite)'); var InstantSearch$1 = createInstantSearch(algoliasearchLite, { Root: 'div', props: { className: 'ais-InstantSearch__root' } }); var Index$1 = createIndex({ Root: 'div', props: { className: 'ais-MultiIndex__root' } }); var PanelCallbackHandler = /*#__PURE__*/ function (_Component) { _inherits(PanelCallbackHandler, _Component); function PanelCallbackHandler() { _classCallCheck(this, PanelCallbackHandler); return _possibleConstructorReturn(this, _getPrototypeOf(PanelCallbackHandler).apply(this, arguments)); } _createClass(PanelCallbackHandler, [{ key: "componentWillMount", value: function componentWillMount() { if (this.context.setCanRefine) { this.context.setCanRefine(this.props.canRefine); } } }, { key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { if (this.context.setCanRefine && this.props.canRefine !== nextProps.canRefine) { this.context.setCanRefine(nextProps.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 }); _defineProperty(PanelCallbackHandler, "contextTypes", { setCanRefine: propTypes.func }); 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)); }; 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({}, omit_1(this.props, 'onClick'), { onClick: this.onClick })); } }]); return Link; }(React.Component); _defineProperty(Link, "propTypes", { onClick: propTypes.func.isRequired }); var cx = 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('item') }, React__default.createElement(Link, { className: cx('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('item', isLast && 'item--selected'), key: idx }, React__default.createElement("span", { className: cx('separator') }, separator), !isLast ? React__default.createElement(Link, { className: cx('link'), onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }, item.label) : item.label); }); return React__default.createElement("div", { className: classnames(cx('', !canRefine && '-noRefinement'), className) }, React__default.createElement("ul", { className: cx('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 { Breadcrumb, InstantSearch, HierarchicalMenu } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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(PanelCallbackHandler, props, React__default.createElement(Breadcrumb$1, props)); }; var Breadcrumb$2 = connectBreadcrumb(BreadcrumbWidget); var cx$1 = 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$1(''), className) }, React__default.createElement("button", { className: cx$1('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 { InstantSearch, ClearRefinements, RefinementList } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <ClearRefinements /> * <RefinementList * attribute="brand" * defaultRefinement={['Apple']} * /> * </InstantSearch> * ); */ var ClearRefinementsWidget = function ClearRefinementsWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(ClearRefinements$1, props)); }; var ClearRefinements$2 = connectCurrentRefinements(ClearRefinementsWidget); var cx$2 = 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$2('', !canRefine && '-noRefinement'), className) }, React__default.createElement("ul", { className: cx$2('list', !canRefine && 'list--noRefinement') }, items.map(function (item) { return React__default.createElement("li", { key: item.label, className: cx$2('item') }, React__default.createElement("span", { className: cx$2('label') }, item.label), item.items ? item.items.map(function (nest) { return React__default.createElement("span", { key: nest.label, className: cx$2('category') }, React__default.createElement("span", { className: cx$2('categoryLabel') }, nest.label), React__default.createElement("button", { className: cx$2('delete'), onClick: function onClick() { return refine(nest.value); } }, translate('clearFilter', nest))); }) : React__default.createElement("span", { className: cx$2('category') }, React__default.createElement("button", { className: cx$2('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 { InstantSearch, CurrentRefinements, RefinementList } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <CurrentRefinements /> * <RefinementList * attribute="brand" * defaultRefinement={['Colors']} * /> * </InstantSearch> * ); */ var CurrentRefinementsWidget = function CurrentRefinementsWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(CurrentRefinements$1, props)); }; var CurrentRefinements$2 = connectCurrentRefinements(CurrentRefinementsWidget); var cx$3 = 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$3('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$3('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$3('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: "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 }); } } }, { 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$3(''), className) }, React__default.createElement("form", { noValidate: true, onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit, onReset: this.onReset, className: cx$3('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$3('input') })), React__default.createElement("button", { type: "submit", title: translate('submitTitle'), className: cx$3('submit') }, submit), React__default.createElement("button", { type: "reset", title: translate('resetTitle'), className: cx$3('reset'), hidden: !query || isSearchStalled }, reset), this.props.showLoadingIndicator && React__default.createElement("span", { hidden: !isSearchStalled, className: cx$3('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$4 = 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$4('link'), onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }, React__default.createElement("span", { className: cx$4('label') }, item.label), ' ', React__default.createElement("span", { className: cx$4('count') }, item.count)); }); return _this; } _createClass(HierarchicalMenu, [{ key: "render", value: function render() { return React__default.createElement(List, _extends({ renderItem: this.renderItem, cx: cx$4 }, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isEmpty', 'canRefine', '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 { InstantSearch, HierarchicalMenu } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <HierarchicalMenu * attributes={[ * 'hierarchicalCategories.lvl0', * 'hierarchicalCategories.lvl1', * 'hierarchicalCategories.lvl2', * ]} * /> * </InstantSearch> * ); */ var HierarchicalMenuWidget = function HierarchicalMenuWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(HierarchicalMenu$1, props)); }; var HierarchicalMenu$2 = connectHierarchicalMenu(HierarchicalMenuWidget); function generateKey(i, value) { return "split-".concat(i, "-").concat(value); } 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: generateKey(i, hit[attribute][i]) }, item.map(function (element, index) { return React__default.createElement(Highlight, { cx: cx, key: generateKey(index, element.value), 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: generateKey(i, item.value), value: item.value, highlightedTagName: tagName, nonHighlightedTagName: nonHighlightedTagName, isHighlighted: item.isHighlighted }); })); }; Highlighter.defaultProps = { tagName: 'em', nonHighlightedTagName: 'span', className: '', separator: ', ' }; var cx$5 = createClassNames('Highlight'); var Highlight$1 = function Highlight(props) { return React__default.createElement(Highlighter, _extends({}, props, { highlightProperty: "_highlightResult", cx: cx$5 })); }; /** * 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 { InstantSearch, SearchBox, Hits, Highlight } from 'react-instantsearch-dom'; * * const Hit = ({ hit }) => ( * <div> * <Highlight attribute="name" hit={hit} /> * </div> * ); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <SearchBox defaultRefinement="Pho" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var Highlight$2 = connectHighlight(Highlight$1); var cx$6 = createClassNames('Hits'); 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$6(''), className) }, React__default.createElement("ul", { className: cx$6('list') }, hits.map(function (hit) { return React__default.createElement("li", { className: cx$6('item'), key: hit.objectID }, React__default.createElement(HitComponent, { hit: hit })); }))); }; 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 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 { InstantSearch, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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: has_1(item, 'key') ? item.key : item.value, disabled: item.disabled, value: item.value }, has_1(item, 'label') ? item.label : item.value); })); } }]); 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$7 = 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$7(''), className) }, React__default.createElement(Select, { onSelect: refine, selectedItem: currentRefinement, items: items, cx: cx$7 })); } }]); 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 { InstantSearch, HitsPerPage, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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$8 = 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$8(''), className) }, showPrevious && React__default.createElement("button", { className: cx$8('loadPrevious', !hasPrevious && 'loadPrevious--disabled'), onClick: function onClick() { return refinePrevious(); }, disabled: !hasPrevious }, translate('loadPrevious')), React__default.createElement("ul", { className: cx$8('list') }, hits.map(function (hit) { return React__default.createElement("li", { key: hit.objectID, className: cx$8('item') }, React__default.createElement(HitComponent, { hit: hit })); })), React__default.createElement("button", { className: cx$8('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 { InstantSearch, InfiniteHits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <InfiniteHits /> * </InstantSearch> * ); */ var InfiniteHits$2 = connectInfiniteHits(InfiniteHits$1); var cx$9 = 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$9('link'), onClick: function onClick() { return _this.selectItem(item, resetQuery); }, href: createURL(item.value) }, React__default.createElement("span", { className: cx$9('label') }, label), ' ', React__default.createElement("span", { className: cx$9('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() { return React__default.createElement(List, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$9 }, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isFromSearch', 'searchForItems', 'searchable', 'canRefine', '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 { InstantSearch, Menu } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <Menu attribute="categories" /> * </InstantSearch> * ); */ var MenuWidget = function MenuWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(Menu$1, props)); }; var Menu$2 = connectMenu(MenuWidget); var cx$a = 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$a('', !canRefine && '-noRefinement'), className) }, React__default.createElement("select", { value: this.selectedValue, onChange: this.handleSelectChange, className: cx$a('select') }, React__default.createElement("option", { value: "ais__see__all__option", className: cx$a('option') }, translate('seeAllOption')), items.map(function (item) { return React__default.createElement("option", { key: item.value, value: item.value, className: cx$a('option') }, item.label, " (", item.count, ")"); }))); } }, { key: "selectedValue", get: function get() { var _ref2 = find_1(this.props.items, { 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 { InstantSearch, MenuSelect } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <MenuSelect attribute="categories" /> * </InstantSearch> * ); */ var MenuSelectWidget = function MenuSelectWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(MenuSelect$1, props)); }; var MenuSelect$2 = connectMenu(MenuSelectWidget); var cx$b = 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$b('label') }, React__default.createElement("input", { className: cx$b('radio'), type: "radio", checked: item.isRefined, disabled: item.noRefinement, onChange: function onChange() { return refine(item.value); } }), React__default.createElement("span", { className: cx$b('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$b, 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 { InstantSearch, NumericMenu } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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(PanelCallbackHandler, props, React__default.createElement(NumericMenu$1, props)); }; var NumericMenu$2 = connectNumericMenu(NumericMenuWidget); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeMax$7 = 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$7(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } var _baseRange = baseRange; /** * 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_1(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite_1(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite_1(step); return _baseRange(start, end, step, fromRight); }; } var _createRange = createRange; /** * 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(); var range_1 = range; 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: has_1(item, 'key') ? item.key : item.value, className: cx('item', item.selected && !item.disabled && 'item--selected', item.disabled && 'item--disabled', item.modifier) }, item.disabled ? React__default.createElement("span", { className: cx('link') }, has_1(item, 'label') ? item.label : item.value) : 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); } }, has_1(item, 'label') ? item.label : item.value)); })); } }]); 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$c = 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_1(1, maxPages + 1); var paddingLeft = calculatePaddingLeft(currentPage, padding, maxPages, size); var paddingRight = size - paddingLeft; var first = currentPage - paddingLeft; var last = currentPage + paddingRight; return range_1(first + 1, 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$c('', !canRefine && '-noRefinement'), className) }, React__default.createElement(ListComponent, _extends({}, otherProps, { cx: cx$c, 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 { InstantSearch, Pagination } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <Pagination /> * </InstantSearch> * ); */ var PaginationWidget = function PaginationWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(Pagination$1, props)); }; var Pagination$2 = connectPagination(PaginationWidget); var cx$d = createClassNames('Panel'); 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: "getChildContext", value: function getChildContext() { return { setCanRefine: this.setCanRefine }; } }, { 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$d('', !canRefine && '-noRefinement'), className) }, header && React__default.createElement("div", { className: cx$d('header') }, header), React__default.createElement("div", { className: cx$d('body') }, children), footer && React__default.createElement("div", { className: cx$d('footer') }, footer)); } }]); return Panel; }(React.Component); _defineProperty(Panel, "propTypes", { children: propTypes.node.isRequired, className: propTypes.string, header: propTypes.node, footer: propTypes.node }); _defineProperty(Panel, "childContextTypes", { setCanRefine: propTypes.func.isRequired }); _defineProperty(Panel, "defaultProps", { className: '', header: null, footer: null }); 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'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { // In react@16.0.0 the call to setState on the inputs trigger this lifecycle hook // because the context has changed (for react). I don't think that the bug is related // to react because I failed to reproduce it with a simple hierarchy of components. // The workaround here is to check the differences between previous & next props in order // to avoid to override current state when values are not yet refined. In the react documentation, // they DON'T categorically say that setState never run componentWillReceiveProps. // see: https://reactjs.org/docs/react-component.html#componentwillreceiveprops if (nextProps.canRefine && (this.props.canRefine !== nextProps.canRefine || this.props.currentRefinement.min !== nextProps.currentRefinement.min || this.props.currentRefinement.max !== nextProps.currentRefinement.max)) { this.setState(this.normalizeStateForRendering(nextProps)); } } }, { 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 { InstantSearch, RangeInput } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <RangeInput attribute="price" /> * </InstantSearch> * ); */ var RangeInputWidget = function RangeInputWidget(props) { return React__default.createElement(PanelCallbackHandler, 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 } }; componentWillReceiveProps(sliderState) { if (sliderState.canRefine) { this.setState({ currentValues: { min: sliderState.currentRefinement.min, max: sliderState.currentRefinement.max } }); } } onValuesUpdated = sliderState => { this.setState({ currentValues: { min: sliderState.values[0], max: sliderState.values[1] } }); }; onChange = sliderState => { if ( this.props.currentRefinement.min !== sliderState.values[0] || this.props.currentRefinement.max !== sliderState.values[1] ) { this.props.refine({ min: sliderState.values[0], max: sliderState.values[1] }); } }; render() { const { min, max, currentRefinement } = this.props; const { currentValues } = this.state; return min !== max ? ( <div> <Rheostat 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/")); }); /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH$1 = 4294967295; /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is 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 convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? _baseClamp(toInteger_1(value), 0, MAX_ARRAY_LENGTH$1) : 0; } var toLength_1 = toLength; /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger_1(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger_1(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength_1(end); while (start < end) { array[start++] = value; } return array; } var _baseFill = baseFill; /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && _isIterateeCall(array, value, start)) { start = 0; end = length; } return _baseFill(array, value, start, end); } var fill_1 = fill; 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 safeInclusiveLength = Math.max(inclusiveLength, 0); var values = count.map(function (item) { return _objectSpread({}, item, { value: parseFloat(item.value) }); }).filter(function (item) { return item.value >= limitMin && item.value <= limitMax; }); var range = fill_1(new Array(safeInclusiveLength), null).map(function (_, index) { var element = find_1(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 })); }, []); var items = range.map(function (item, index) { return _this.buildItem({ lowerBound: item.value, count: item.total, isLastSelectableItem: range.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 { InstantSearch, RatingMenu } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <RatingMenu attribute="rating" /> * </InstantSearch> * ); */ var RatingMenuWidget = function RatingMenuWidget(props) { return React__default.createElement(PanelCallbackHandler, 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() { return React__default.createElement(List, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$h }, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isFromSearch', 'searchForItems', 'searchable', 'canRefine', '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 { InstantSearch, RefinementList } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <RefinementList attribute="brand" /> * </InstantSearch> * ); */ var RefinementListWidget = function RefinementListWidget(props) { return React__default.createElement(PanelCallbackHandler, 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 { InstantSearch, ScrollTo, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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 { InstantSearch, SearchBox } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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 { InstantSearch, SearchBox, Hits, Snippet } from 'react-instantsearch-dom'; * * const Hit = ({ hit }) => ( * <div> * <Snippet attribute="description" hit={hit} /> * </div> * ); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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 { InstantSearch, SortBy } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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 { InstantSearch, ToggleRefinement } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <ToggleRefinement * attribute="free_shipping" * label="Free Shipping" * value={true} * /> * </InstantSearch> * ); */ var ToggleRefinement$1 = connectToggleRefinement(ToggleRefinement); // Core 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 = Index$1; exports.InfiniteHits = InfiniteHits$2; exports.InstantSearch = InstantSearch$1; 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/boardgame-io/0.39.16/boardgameio.es.js
cdnjs/cdnjs
import { compose, applyMiddleware, createStore } from 'redux'; import produce from 'immer'; import { stringify, parse } from 'flatted'; import React from 'react'; import PropTypes from 'prop-types'; import io from 'socket.io-client'; function noop() { } const identity = x => x; function assign(tar, src) { // @ts-ignore for (const k in src) tar[k] = src[k]; return tar; } function run(fn) { return fn(); } function blank_object() { return Object.create(null); } function run_all(fns) { fns.forEach(run); } function is_function(thing) { return typeof thing === 'function'; } function safe_not_equal(a, b) { return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function'); } function subscribe(store, callback) { const unsub = store.subscribe(callback); return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub; } function component_subscribe(component, store, callback) { component.$$.on_destroy.push(subscribe(store, callback)); } function create_slot(definition, ctx, fn) { if (definition) { const slot_ctx = get_slot_context(definition, ctx, fn); return definition[0](slot_ctx); } } function get_slot_context(definition, ctx, fn) { return definition[1] ? assign({}, assign(ctx.$$scope.ctx, definition[1](fn ? fn(ctx) : {}))) : ctx.$$scope.ctx; } function get_slot_changes(definition, ctx, changed, fn) { return definition[1] ? assign({}, assign(ctx.$$scope.changed || {}, definition[1](fn ? fn(changed) : {}))) : ctx.$$scope.changed || {}; } function exclude_internal_props(props) { const result = {}; for (const k in props) if (k[0] !== '$') result[k] = props[k]; return result; } 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(); let running = false; function run_tasks() { tasks.forEach(task => { if (!task[0](now())) { tasks.delete(task); task[1](); } }); running = tasks.size > 0; if (running) raf(run_tasks); } function loop(fn) { let task; if (!running) { running = true; raf(run_tasks); } return { promise: new Promise(fulfil => { tasks.add(task = [fn, fulfil]); }), abort() { tasks.delete(task); } }; } function append(target, node) { target.appendChild(node); } function insert(target, node, anchor) { target.insertBefore(node, anchor || null); } function detach(node) { node.parentNode.removeChild(node); } function destroy_each(iterations, detaching) { for (let i = 0; i < iterations.length; i += 1) { if (iterations[i]) iterations[i].d(detaching); } } function element(name) { return document.createElement(name); } function svg_element(name) { return document.createElementNS('http://www.w3.org/2000/svg', name); } function text(data) { return document.createTextNode(data); } function space() { return text(' '); } function empty() { return text(''); } function listen(node, event, handler, options) { node.addEventListener(event, handler, options); return () => node.removeEventListener(event, handler, options); } function stop_propagation(fn) { return function (event) { event.stopPropagation(); // @ts-ignore return fn.call(this, event); }; } function attr(node, attribute, value) { if (value == null) node.removeAttribute(attribute); else node.setAttribute(attribute, value); } function to_number(value) { return value === '' ? undefined : +value; } function children(element) { return Array.from(element.childNodes); } function set_data(text, data) { data = '' + data; if (text.data !== data) text.data = data; } function set_input_value(input, value) { if (value != null || input.value) { input.value = value; } } function select_option(select, value) { for (let i = 0; i < select.options.length; i += 1) { const option = select.options[i]; if (option.__value === value) { option.selected = true; return; } } } function select_value(select) { const selected_option = select.querySelector(':checked') || select.options[0]; return selected_option && selected_option.__value; } function toggle_class(element, name, toggle) { element.classList[toggle ? 'add' : 'remove'](name); } function custom_event(type, detail) { const e = document.createEvent('CustomEvent'); e.initCustomEvent(type, false, false, detail); return e; } let stylesheet; let active = 0; let current_rules = {}; // 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}`; if (!current_rules[name]) { if (!stylesheet) { const style = element('style'); document.head.appendChild(style); stylesheet = style.sheet; } 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) { node.style.animation = (node.style.animation || '') .split(', ') .filter(name ? anim => anim.indexOf(name) < 0 // remove specific animation : anim => anim.indexOf('__svelte') === -1 // remove all Svelte animations ) .join(', '); if (name && !--active) clear_rules(); } function clear_rules() { raf(() => { if (active) return; let i = stylesheet.cssRules.length; while (i--) stylesheet.deleteRule(i); current_rules = {}; }); } 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 = 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); } 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); } function flush() { const seen_callbacks = new Set(); do { // first, call beforeUpdate functions // and update components while (dirty_components.length) { const component = dirty_components.shift(); set_current_component(component); update(component.$$); } 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)) { callback(); // ...so guard against infinite loops seen_callbacks.add(callback); } } render_callbacks.length = 0; } while (dirty_components.length); while (flush_callbacks.length) { flush_callbacks.pop()(); } update_scheduled = false; } function update($$) { if ($$.fragment) { $$.update($$.dirty); run_all($$.before_update); $$.fragment.p($$.dirty, $$.ctx); $$.dirty = null; $$.after_update.forEach(add_render_callback); } } let promise; function wait() { if (!promise) { promise = Promise.resolve(); promise.then(() => { promise = null; }); } return promise; } function dispatch(node, direction, kind) { node.dispatchEvent(custom_event(`${direction ? 'intro' : 'outro'}${kind}`)); } const outroing = new Set(); let outros; function group_outros() { outros = { r: 0, c: [], p: outros // parent group }; } function check_outros() { if (!outros.r) { run_all(outros.c); } outros = outros.p; } function transition_in(block, local) { if (block && block.i) { outroing.delete(block); block.i(local); } } function transition_out(block, local, detach, callback) { if (block && block.o) { if (outroing.has(block)) return; outroing.add(block); outros.c.push(() => { outroing.delete(block); if (callback) { if (detach) block.d(1); callback(); } }); block.o(local); } } const null_transition = { duration: 0 }; function create_bidirectional_transition(node, fn, params, intro) { let config = fn(node, params); let t = intro ? 0 : 1; let running_program = null; let pending_program = null; let animation_name = null; function clear_animation() { if (animation_name) delete_rule(node, animation_name); } function init(program, duration) { const d = program.b - t; duration *= Math.abs(d); return { a: t, b: program.b, d, duration, start: program.start, end: program.start + duration, group: program.group }; } function go(b) { const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition; const program = { start: now() + delay, b }; if (!b) { // @ts-ignore todo: improve typings program.group = outros; outros.r += 1; } if (running_program) { pending_program = program; } else { // if this is an intro, and there's a delay, we need to do // an initial tick and/or apply CSS animation immediately if (css) { clear_animation(); animation_name = create_rule(node, t, b, duration, delay, easing, css); } if (b) tick(0, 1); running_program = init(program, duration); add_render_callback(() => dispatch(node, b, 'start')); loop(now => { if (pending_program && now > pending_program.start) { running_program = init(pending_program, duration); pending_program = null; dispatch(node, running_program.b, 'start'); if (css) { clear_animation(); animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css); } } if (running_program) { if (now >= running_program.end) { tick(t = running_program.b, 1 - t); dispatch(node, running_program.b, 'end'); if (!pending_program) { // we're done if (running_program.b) { // intro — we can tidy up immediately clear_animation(); } else { // outro — needs to be coordinated if (!--running_program.group.r) run_all(running_program.group.c); } } running_program = null; } else if (now >= running_program.start) { const p = now - running_program.start; t = running_program.a + running_program.d * easing(p / running_program.duration); tick(t, 1 - t); } } return !!(running_program || pending_program); }); } } return { run(b) { if (is_function(config)) { wait().then(() => { // @ts-ignore config = config(); go(b); }); } else { go(b); } }, end() { clear_animation(); running_program = pending_program = null; } }; } const globals = (typeof window !== 'undefined' ? window : global); function get_spread_update(levels, updates) { const update = {}; const to_null_out = {}; const accounted_for = { $$scope: 1 }; let i = levels.length; while (i--) { const o = levels[i]; const n = updates[i]; if (n) { for (const key in o) { if (!(key in n)) to_null_out[key] = 1; } for (const key in n) { if (!accounted_for[key]) { update[key] = n[key]; accounted_for[key] = 1; } } levels[i] = n; } else { for (const key in o) { accounted_for[key] = 1; } } } for (const key in to_null_out) { if (!(key in update)) update[key] = undefined; } return update; } function get_spread_object(spread_props) { return typeof spread_props === 'object' && spread_props !== null ? spread_props : {}; } function mount_component(component, target, anchor) { const { fragment, on_mount, on_destroy, after_update } = component.$$; fragment.m(target, anchor); // onMount happens before the initial afterUpdate add_render_callback(() => { const new_on_destroy = on_mount.map(run).filter(is_function); if (on_destroy) { on_destroy.push(...new_on_destroy); } else { // Edge case - component was destroyed immediately, // most likely as a result of a binding initialising run_all(new_on_destroy); } component.$$.on_mount = []; }); after_update.forEach(add_render_callback); } function destroy_component(component, detaching) { if (component.$$.fragment) { run_all(component.$$.on_destroy); component.$$.fragment.d(detaching); // TODO null out other refs, including component.$$ (but need to // preserve final state?) component.$$.on_destroy = component.$$.fragment = null; component.$$.ctx = {}; } } function make_dirty(component, key) { if (!component.$$.dirty) { dirty_components.push(component); schedule_update(); component.$$.dirty = blank_object(); } component.$$.dirty[key] = true; } function init(component, options, instance, create_fragment, not_equal, prop_names) { const parent_component = current_component; set_current_component(component); const props = options.props || {}; const $$ = component.$$ = { fragment: null, ctx: null, // state props: prop_names, update: noop, not_equal, bound: blank_object(), // lifecycle on_mount: [], on_destroy: [], before_update: [], after_update: [], context: new Map(parent_component ? parent_component.$$.context : []), // everything else callbacks: blank_object(), dirty: null }; let ready = false; $$.ctx = instance ? instance(component, props, (key, ret, value = ret) => { if ($$.ctx && not_equal($$.ctx[key], $$.ctx[key] = value)) { if ($$.bound[key]) $$.bound[key](value); if (ready) make_dirty(component, key); } return ret; }) : props; $$.update(); ready = true; run_all($$.before_update); $$.fragment = create_fragment($$.ctx); if (options.target) { if (options.hydrate) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion $$.fragment.l(children(options.target)); } else { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion $$.fragment.c(); } if (options.intro) transition_in(component.$$.fragment); mount_component(component, options.target, options.anchor); flush(); } set_current_component(parent_component); } class SvelteComponent { $destroy() { destroy_component(this, 1); this.$destroy = noop; } $on(type, callback) { const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = [])); callbacks.push(callback); return () => { const index = callbacks.indexOf(callback); if (index !== -1) callbacks.splice(index, 1); }; } $set() { // overridden by instance, if it has props } } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const MAKE_MOVE = 'MAKE_MOVE'; const GAME_EVENT = 'GAME_EVENT'; const REDO = 'REDO'; const RESET = 'RESET'; const SYNC = 'SYNC'; const UNDO = 'UNDO'; const UPDATE = 'UPDATE'; const PLUGIN = 'PLUGIN'; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Generate a move to be dispatched to the game move reducer. * * @param {string} type - The move type. * @param {Array} args - Additional arguments. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const makeMove = (type, args, playerID, credentials) => ({ type: MAKE_MOVE, payload: { type, args, playerID, credentials }, }); /** * Generate a game event to be dispatched to the flow reducer. * * @param {string} type - The event type. * @param {Array} args - Additional arguments. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const gameEvent = (type, args, playerID, credentials) => ({ type: GAME_EVENT, payload: { type, args, playerID, credentials }, }); /** * Generate an automatic game event that is a side-effect of a move. * @param {string} type - The event type. * @param {Array} args - Additional arguments. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const automaticGameEvent = (type, args, playerID, credentials) => ({ type: GAME_EVENT, payload: { type, args, playerID, credentials }, automatic: true, }); const sync = (info) => ({ type: SYNC, state: info.state, log: info.log, initialState: info.initialState, clientOnly: true, }); /** * Used to update the Redux store's state in response to * an action coming from another player. * @param {object} state - The state to restore. * @param {Array} deltalog - A log delta. */ const update$1 = (state, deltalog) => ({ type: UPDATE, state, deltalog, clientOnly: true, }); /** * Used to reset the game state. * @param {object} state - The initial state. */ const reset = (state) => ({ type: RESET, state, clientOnly: true, }); /** * Used to undo the last move. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const undo = (playerID, credentials) => ({ type: UNDO, payload: { type: null, args: null, playerID, credentials }, }); /** * Used to redo the last undone move. * @param {string} playerID - The ID of the player making this action. * @param {string} credentials - (optional) The credentials for the player making this action. */ const redo = (playerID, credentials) => ({ type: REDO, payload: { type: null, args: null, playerID, credentials }, }); /** * Allows plugins to define their own actions and intercept them. */ const plugin = (type, args, playerID, credentials) => ({ type: PLUGIN, payload: { type, args, playerID, credentials }, }); var ActionCreators = /*#__PURE__*/Object.freeze({ makeMove: makeMove, gameEvent: gameEvent, automaticGameEvent: automaticGameEvent, sync: sync, update: update$1, reset: reset, undo: undo, redo: redo, plugin: plugin }); /** * Moves can return this when they want to indicate * that the combination of arguments is illegal and * the move ought to be discarded. */ const INVALID_MOVE = 'INVALID_MOVE'; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Plugin that allows using Immer to make immutable changes * to G by just mutating it. */ const ImmerPlugin = { name: 'plugin-immer', fnWrap: (move) => (G, ctx, ...args) => { let isInvalid = false; const newG = produce(G, G => { const result = move(G, ctx, ...args); if (result === INVALID_MOVE) { isInvalid = true; return; } return result; }); if (isInvalid) return INVALID_MOVE; return newG; }, }; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (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 _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } 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"); } // Inlined version of Alea from https://github.com/davidbau/seedrandom. /* * Copyright 2015 David Bau. * * 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 Alea(seed) { var me = this, mash = Mash(); me.next = function () { var t = 2091639 * me.s0 + me.c * 2.3283064365386963e-10; // 2^-32 me.s0 = me.s1; me.s1 = me.s2; return me.s2 = t - (me.c = t | 0); }; // Apply the seeding algorithm from Baagoe. me.c = 1; me.s0 = mash(' '); me.s1 = mash(' '); me.s2 = mash(' '); me.s0 -= mash(seed); if (me.s0 < 0) { me.s0 += 1; } me.s1 -= mash(seed); if (me.s1 < 0) { me.s1 += 1; } me.s2 -= mash(seed); if (me.s2 < 0) { me.s2 += 1; } mash = null; } function copy(f, t) { t.c = f.c; t.s0 = f.s0; t.s1 = f.s1; t.s2 = f.s2; return t; } function Mash() { var n = 0xefc8249d; var mash = function mash(data) { data = data.toString(); for (var i = 0; i < data.length; i++) { n += data.charCodeAt(i); var 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 alea(seed, opts) { var xg = new Alea(seed), state = opts && opts.state, prng = xg.next; prng.quick = prng; if (state) { if (_typeof(state) == 'object') copy(state, xg); prng.state = function () { return copy(xg, {}); }; } return prng; } /** * 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. */ var Random = /*#__PURE__*/ function () { /** * constructor * @param {object} ctx - The ctx object to initialize from. */ function Random(state) { _classCallCheck(this, Random); // 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; this.used = false; } _createClass(Random, [{ key: "isUsed", value: function isUsed() { return this.used; } }, { key: "getState", value: function getState() { return this.state; } /** * Generate a random number. */ }, { key: "_random", value: function _random() { this.used = true; var R = this.state; var fn; if (R.prngstate === undefined) { // No call to a random function has been made. fn = new alea(R.seed, { state: true }); } else { fn = new alea('', { state: R.prngstate }); } var number = fn(); this.state = _objectSpread2({}, R, { prngstate: fn.state() }); return number; } }, { key: "api", value: function api() { var random = this._random.bind(this); var SpotValue = { D4: 4, D6: 6, D8: 8, D10: 10, D12: 12, D20: 20 }; // Generate functions for predefined dice values D4 - D20. var predefined = {}; var _loop = function _loop(key) { var spotvalue = SpotValue[key]; predefined[key] = function (diceCount) { if (diceCount === undefined) { return Math.floor(random() * spotvalue) + 1; } else { return _toConsumableArray(new Array(diceCount).keys()).map(function () { return Math.floor(random() * spotvalue) + 1; }); } }; }; for (var key in SpotValue) { _loop(key); } return _objectSpread2({}, 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: function Die(spotvalue, diceCount) { if (spotvalue === undefined) { spotvalue = 6; } if (diceCount === undefined) { return Math.floor(random() * spotvalue) + 1; } else { return _toConsumableArray(new Array(diceCount).keys()).map(function () { return Math.floor(random() * spotvalue) + 1; }); } }, /** * Generate a random number between 0 and 1. */ Number: function Number() { return random(); }, /** * Shuffle an array. * * @param {Array} deck - The array to shuffle. Does not mutate * the input, but returns the shuffled array. */ Shuffle: function Shuffle(deck) { var clone = deck.slice(0); var srcIndex = deck.length; var dstIndex = 0; var shuffled = new Array(srcIndex); while (srcIndex) { var randIndex = srcIndex * random() | 0; shuffled[dstIndex++] = clone[randIndex]; clone[randIndex] = clone[--srcIndex]; } return shuffled; }, _obj: this }); } }]); return Random; }(); /** * Generates a new seed from the current date / time. */ Random.seed = function () { return (+new Date()).toString(36).slice(-10); }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const RandomPlugin = { name: 'random', noClient: ({ api }) => { return api._obj.isUsed(); }, flush: ({ api }) => { return api._obj.getState(); }, api: ({ data }) => { const random = new Random(data); return random.api(); }, setup: ({ game }) => { let seed = game.seed; if (seed === undefined) { seed = Random.seed(); } return { seed }; }, }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Events */ class Events { constructor(flow, playerID) { this.flow = flow; this.playerID = playerID; this.dispatch = []; } /** * Attaches the Events API to ctx. * @param {object} ctx - The ctx object to attach to. */ api(ctx) { const events = { _obj: this, }; const { phase, turn } = ctx; for (const key of this.flow.eventNames) { events[key] = (...args) => { this.dispatch.push({ key, args, phase, turn }); }; } return events; } isUsed() { return this.dispatch.length > 0; } /** * Updates ctx with the triggered events. * @param {object} state - The state object { G, ctx }. */ update(state) { for (let i = 0; i < this.dispatch.length; i++) { const item = this.dispatch[i]; // If the turn already ended some other way, // don't try to end the turn again. if (item.key === 'endTurn' && item.turn !== state.ctx.turn) { continue; } // If the phase already ended some other way, // don't try to end the phase again. if ((item.key === 'endPhase' || item.key === 'setPhase') && item.phase !== state.ctx.phase) { continue; } const action = automaticGameEvent(item.key, item.args, this.playerID); state = { ...state, ...this.flow.processEvent(state, action), }; } return state; } } /* * Copyright 2020 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const EventsPlugin = { name: 'events', noClient: ({ api }) => { return api._obj.isUsed(); }, dangerouslyFlushRawState: ({ state, api }) => { return api._obj.update(state); }, api: ({ game, playerID, ctx }) => { return new Events(game.flow, playerID).api(ctx); }, }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * List of plugins that are always added. */ const DEFAULT_PLUGINS = [ImmerPlugin, RandomPlugin, EventsPlugin]; /** * Allow plugins to intercept actions and process them. */ const ProcessAction = (state, action, opts) => { opts.game.plugins .filter(plugin => plugin.action !== undefined) .filter(plugin => plugin.name === action.payload.type) .forEach(plugin => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; const data = plugin.action(pluginState.data, action.payload); state = { ...state, plugins: { ...state.plugins, [name]: { ...pluginState, data }, }, }; }); return state; }; /** * The API's created by various plugins are stored in the plugins * section of the state object: * * { * G: {}, * ctx: {}, * plugins: { * plugin-a: { * data: {}, // this is generated by the plugin at Setup / Flush. * api: {}, // this is ephemeral and generated by Enhance. * } * } * } * * This function takes these API's and stuffs them back into * ctx for consumption inside a move function or hook. */ const EnhanceCtx = (state) => { let ctx = { ...state.ctx }; const plugins = state.plugins || {}; Object.entries(plugins).forEach(([name, { api }]) => { ctx[name] = api; }); return ctx; }; /** * Applies the provided plugins to the given move / flow function. * * @param {function} fn - The move function or trigger to apply the plugins to. * @param {object} plugins - The list of plugins. */ const FnWrap = (fn, plugins) => { const reducer = (acc, { fnWrap }) => fnWrap(acc); return [...DEFAULT_PLUGINS, ...plugins] .filter(plugin => plugin.fnWrap !== undefined) .reduce(reducer, fn); }; /** * Allows the plugin to generate its initial state. */ const Setup = (state, opts) => { [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter(plugin => plugin.setup !== undefined) .forEach(plugin => { const name = plugin.name; const data = plugin.setup({ G: state.G, ctx: state.ctx, game: opts.game, }); state = { ...state, plugins: { ...state.plugins, [name]: { data }, }, }; }); return state; }; /** * Invokes the plugin before a move or event. * The API that the plugin generates is stored inside * the `plugins` section of the state (which is subsequently * merged into ctx). */ const Enhance = (state, opts) => { [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter(plugin => plugin.api !== undefined) .forEach(plugin => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; const api = plugin.api({ G: state.G, ctx: state.ctx, data: pluginState.data, game: opts.game, playerID: opts.playerID, }); state = { ...state, plugins: { ...state.plugins, [name]: { ...pluginState, api }, }, }; }); return state; }; /** * Allows plugins to update their state after a move / event. */ const Flush = (state, opts) => { // Note that we flush plugins in reverse order, to make sure that plugins // that come before in the chain are still available. [...DEFAULT_PLUGINS, ...opts.game.plugins].reverse().forEach(plugin => { const name = plugin.name; const pluginState = state.plugins[name] || { data: {} }; if (plugin.flush) { const newData = plugin.flush({ G: state.G, ctx: state.ctx, game: opts.game, api: pluginState.api, data: pluginState.data, }); state = { ...state, plugins: { ...state.plugins, [plugin.name]: { data: newData }, }, }; } else if (plugin.dangerouslyFlushRawState) { state = plugin.dangerouslyFlushRawState({ state, game: opts.game, api: pluginState.api, data: pluginState.data, }); // Remove everything other than data. const data = state.plugins[name].data; state = { ...state, plugins: { ...state.plugins, [plugin.name]: { data }, }, }; } }); return state; }; /** * Allows plugins to indicate if they should not be materialized on the client. * This will cause the client to discard the state update and wait for the * master instead. */ const NoClient = (state, opts) => { return [...DEFAULT_PLUGINS, ...opts.game.plugins] .filter(plugin => plugin.noClient !== undefined) .map(plugin => { const name = plugin.name; const pluginState = state.plugins[name]; if (pluginState) { return plugin.noClient({ G: state.G, ctx: state.ctx, game: opts.game, api: pluginState.api, data: pluginState.data, }); } return false; }) .some(value => value === true); }; /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ const production = process.env.NODE_ENV === 'production'; const logfn = production ? () => { } : console.log; const errorfn = console.error; function info(msg) { logfn(`INFO: ${msg}`); } function error(error) { errorfn('ERROR:', error); } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Event to change the active players (and their stages) in the current turn. */ function SetActivePlayersEvent(state, _playerID, arg) { return { ...state, ctx: SetActivePlayers(state.ctx, arg) }; } function SetActivePlayers(ctx, arg) { let { _prevActivePlayers } = ctx; let activePlayers = {}; let _nextActivePlayers = null; let _activePlayersMoveLimit = {}; if (Array.isArray(arg)) { // support a simple array of player IDs as active players let value = {}; arg.forEach(v => (value[v] = Stage.NULL)); activePlayers = value; } else { // process active players argument object if (arg.next) { _nextActivePlayers = arg.next; } if (arg.revert) { _prevActivePlayers = _prevActivePlayers.concat({ activePlayers: ctx.activePlayers, _activePlayersMoveLimit: ctx._activePlayersMoveLimit, _activePlayersNumMoves: ctx._activePlayersNumMoves, }); } else { _prevActivePlayers = []; } if (arg.currentPlayer !== undefined) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, ctx.currentPlayer, arg.currentPlayer); } if (arg.others !== undefined) { for (let i = 0; i < ctx.playOrder.length; i++) { const id = ctx.playOrder[i]; if (id !== ctx.currentPlayer) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.others); } } } if (arg.all !== undefined) { for (let i = 0; i < ctx.playOrder.length; i++) { const id = ctx.playOrder[i]; ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.all); } } if (arg.value) { for (const id in arg.value) { ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.value[id]); } } if (arg.moveLimit) { for (const id in activePlayers) { if (_activePlayersMoveLimit[id] === undefined) { _activePlayersMoveLimit[id] = arg.moveLimit; } } } } if (Object.keys(activePlayers).length == 0) { activePlayers = null; } if (Object.keys(_activePlayersMoveLimit).length == 0) { _activePlayersMoveLimit = null; } let _activePlayersNumMoves = {}; for (const id in activePlayers) { _activePlayersNumMoves[id] = 0; } return { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, _nextActivePlayers, }; } /** * Update activePlayers, setting it to previous, next or null values * when it becomes empty. * @param ctx */ function UpdateActivePlayersOnceEmpty(ctx) { let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, } = ctx; if (activePlayers && Object.keys(activePlayers).length == 0) { if (ctx._nextActivePlayers) { ctx = SetActivePlayers(ctx, ctx._nextActivePlayers); ({ activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, } = ctx); } else if (_prevActivePlayers.length > 0) { const lastIndex = _prevActivePlayers.length - 1; ({ activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, } = _prevActivePlayers[lastIndex]); _prevActivePlayers = _prevActivePlayers.slice(0, lastIndex); } else { activePlayers = null; _activePlayersMoveLimit = null; } } return { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, }; } /** * Apply an active player argument to the given player ID * @param {Object} activePlayers * @param {Object} _activePlayersMoveLimit * @param {String} playerID The player to apply the parameter to * @param {(String|Object)} arg An active player argument */ function ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, playerID, arg) { if (typeof arg !== 'object' || arg === Stage.NULL) { arg = { stage: arg }; } if (arg.stage !== undefined) { activePlayers[playerID] = arg.stage; if (arg.moveLimit) _activePlayersMoveLimit[playerID] = arg.moveLimit; } } /** * Converts a playOrderPos index into its value in playOrder. * @param {Array} playOrder - An array of player ID's. * @param {number} playOrderPos - An index into the above. */ function getCurrentPlayer(playOrder, playOrderPos) { // convert to string in case playOrder is set to number[] return playOrder[playOrderPos] + ''; } /** * Called at the start of a turn to initialize turn order state. * * TODO: This is called inside StartTurn, which is called from * both UpdateTurn and StartPhase (so it's called at the beginning * of a new phase as well as between turns). We should probably * split it into two. */ function InitTurnOrderState(state, turn) { let { G, ctx } = state; const ctxWithAPI = EnhanceCtx(state); const order = turn.order; let playOrder = [...new Array(ctx.numPlayers)].map((_, i) => i + ''); if (order.playOrder !== undefined) { playOrder = order.playOrder(G, ctxWithAPI); } const playOrderPos = order.first(G, ctxWithAPI); const posType = typeof playOrderPos; if (posType !== 'number') { error(`invalid value returned by turn.order.first — expected number got ${posType} “${playOrderPos}”.`); } const currentPlayer = getCurrentPlayer(playOrder, playOrderPos); ctx = { ...ctx, currentPlayer, playOrderPos, playOrder }; ctx = SetActivePlayers(ctx, turn.activePlayers || {}); return ctx; } /** * Called at the end of each turn to update the turn order state. * @param {object} G - The game object G. * @param {object} ctx - The game object ctx. * @param {object} turn - A turn object for this phase. * @param {string} endTurnArg - An optional argument to endTurn that may specify the next player. */ function UpdateTurnOrderState(state, currentPlayer, turn, endTurnArg) { const order = turn.order; let { G, ctx } = state; let playOrderPos = ctx.playOrderPos; let endPhase = false; if (endTurnArg && endTurnArg !== true) { if (typeof endTurnArg !== 'object') { error(`invalid argument to endTurn: ${endTurnArg}`); } Object.keys(endTurnArg).forEach(arg => { switch (arg) { case 'remove': currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos); break; case 'next': playOrderPos = ctx.playOrder.indexOf(endTurnArg.next); currentPlayer = endTurnArg.next; break; default: error(`invalid argument to endTurn: ${arg}`); } }); } else { const ctxWithAPI = EnhanceCtx(state); const t = order.next(G, ctxWithAPI); const type = typeof t; if (t !== undefined && type !== 'number') { error(`invalid value returned by turn.order.next — expected number or undefined got ${type} “${t}”.`); } if (t === undefined) { endPhase = true; } else { playOrderPos = t; currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos); } } ctx = { ...ctx, playOrderPos, currentPlayer, }; return { endPhase, ctx }; } /** * Set of different turn orders possible in a phase. * These are meant to be passed to the `turn` setting * in the flow objects. * * Each object defines the first player when the phase / game * begins, and also a function `next` to determine who the * next player is when the turn ends. * * The phase ends if next() returns undefined. */ const TurnOrder = { /** * DEFAULT * * The default round-robin turn order. */ DEFAULT: { first: (G, ctx) => ctx.turn === 0 ? ctx.playOrderPos : (ctx.playOrderPos + 1) % ctx.playOrder.length, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * RESET * * Similar to DEFAULT, but starts from 0 each time. */ RESET: { first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * CONTINUE * * Similar to DEFAULT, but starts with the player who ended the last phase. */ CONTINUE: { first: (G, ctx) => ctx.playOrderPos, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }, /** * ONCE * * Another round-robin turn order, but goes around just once. * The phase ends after all players have played. */ ONCE: { first: () => 0, next: (G, ctx) => { if (ctx.playOrderPos < ctx.playOrder.length - 1) { return ctx.playOrderPos + 1; } }, }, /** * CUSTOM * * Identical to DEFAULT, but also sets playOrder at the * beginning of the phase. * * @param {Array} playOrder - The play order. */ CUSTOM: (playOrder) => ({ playOrder: () => playOrder, first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }), /** * CUSTOM_FROM * * Identical to DEFAULT, but also sets playOrder at the * beginning of the phase to a value specified by a field * in G. * * @param {string} playOrderField - Field in G. */ CUSTOM_FROM: (playOrderField) => ({ playOrder: (G) => G[playOrderField], first: () => 0, next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length, }), }; const Stage = { NULL: null, }; /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Flow * * Creates a reducer that updates ctx (analogous to how moves update G). */ function Flow({ moves, phases, endIf, onEnd, turn, events, plugins, disableUndo, }) { // 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[''] = {}; let moveMap = {}; let moveNames = new Set(); let startingPhase = null; Object.keys(moves).forEach(name => moveNames.add(name)); const HookWrapper = (fn) => { const withPlugins = FnWrap(fn, plugins); return (state) => { const ctxWithAPI = EnhanceCtx(state); return withPlugins(state.G, ctxWithAPI); }; }; const TriggerWrapper = (endIf) => { return (state) => { let ctxWithAPI = EnhanceCtx(state); return endIf(state.G, ctxWithAPI); }; }; const wrapped = { onEnd: HookWrapper(onEnd), endIf: TriggerWrapper(endIf), }; for (let phase in phaseMap) { const conf = phaseMap[phase]; if (conf.start === true) { startingPhase = phase; } if (conf.moves !== undefined) { for (let move of Object.keys(conf.moves)) { moveMap[phase + '.' + move] = conf.moves[move]; moveNames.add(move); } } if (conf.endIf === undefined) { conf.endIf = () => undefined; } if (conf.onBegin === undefined) { conf.onBegin = G => G; } if (conf.onEnd === undefined) { conf.onEnd = G => G; } if (conf.turn === undefined) { conf.turn = turn; } if (conf.turn.order === undefined) { conf.turn.order = TurnOrder.DEFAULT; } if (conf.turn.onBegin === undefined) { conf.turn.onBegin = G => G; } if (conf.turn.onEnd === undefined) { conf.turn.onEnd = G => G; } if (conf.turn.endIf === undefined) { conf.turn.endIf = () => false; } if (conf.turn.onMove === undefined) { conf.turn.onMove = G => G; } if (conf.turn.stages === undefined) { conf.turn.stages = {}; } for (const stage in conf.turn.stages) { const stageConfig = conf.turn.stages[stage]; const moves = stageConfig.moves || {}; for (let move of Object.keys(moves)) { let key = phase + '.' + stage + '.' + move; moveMap[key] = moves[move]; moveNames.add(move); } } conf.wrapped = { onBegin: HookWrapper(conf.onBegin), onEnd: HookWrapper(conf.onEnd), endIf: TriggerWrapper(conf.endIf), }; conf.turn.wrapped = { onMove: HookWrapper(conf.turn.onMove), onBegin: HookWrapper(conf.turn.onBegin), onEnd: HookWrapper(conf.turn.onEnd), endIf: TriggerWrapper(conf.turn.endIf), }; } function GetPhase(ctx) { return ctx.phase ? phaseMap[ctx.phase] : phaseMap['']; } function OnMove(s) { return s; } function Process(state, events) { const phasesEnded = new Set(); const turnsEnded = new Set(); for (let i = 0; i < events.length; i++) { const { fn, arg, ...rest } = events[i]; // Detect a loop of EndPhase calls. // This could potentially even be an infinite loop // if the endIf condition of each phase blindly // returns true. The moment we detect a single // loop, we just bail out of all phases. if (fn === EndPhase) { turnsEnded.clear(); const phase = state.ctx.phase; if (phasesEnded.has(phase)) { const ctx = { ...state.ctx, phase: null }; return { ...state, ctx }; } phasesEnded.add(phase); } // Process event. let next = []; state = fn(state, { ...rest, arg, next, }); if (fn === EndGame) { break; } // Check if we should end the game. const shouldEndGame = ShouldEndGame(state); if (shouldEndGame) { events.push({ fn: EndGame, arg: shouldEndGame, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } // Check if we should end the phase. const shouldEndPhase = ShouldEndPhase(state); if (shouldEndPhase) { events.push({ fn: EndPhase, arg: shouldEndPhase, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } // Check if we should end the turn. if (fn === OnMove) { const shouldEndTurn = ShouldEndTurn(state); if (shouldEndTurn) { events.push({ fn: EndTurn, arg: shouldEndTurn, turn: state.ctx.turn, phase: state.ctx.phase, automatic: true, }); continue; } } events.push(...next); } return state; } /////////// // Start // /////////// function StartGame(state, { next }) { next.push({ fn: StartPhase }); return state; } function StartPhase(state, { next }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Run any phase setup code provided by the user. G = conf.wrapped.onBegin(state); next.push({ fn: StartTurn }); return { ...state, G, ctx }; } function StartTurn(state, { currentPlayer }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Initialize the turn order state. if (currentPlayer) { ctx = { ...ctx, currentPlayer }; if (conf.turn.activePlayers) { ctx = SetActivePlayers(ctx, conf.turn.activePlayers); } } else { // This is only called at the beginning of the phase // when there is no currentPlayer yet. ctx = InitTurnOrderState(state, conf.turn); } const turn = ctx.turn + 1; ctx = { ...ctx, turn, numMoves: 0, _prevActivePlayers: [] }; G = conf.turn.wrapped.onBegin({ ...state, G, ctx }); const _undo = disableUndo ? [] : [{ G, ctx }]; return { ...state, G, ctx, _undo, _redo: [] }; } //////////// // Update // //////////// function UpdatePhase(state, { arg, next, phase }) { const conf = GetPhase({ phase }); let { ctx } = state; if (arg && arg.next) { if (arg.next in phaseMap) { ctx = { ...ctx, phase: arg.next }; } else { error('invalid phase: ' + arg.next); return state; } } else if (conf.next !== undefined) { ctx = { ...ctx, phase: conf.next }; } else { ctx = { ...ctx, phase: null }; } state = { ...state, ctx }; // Start the new phase. next.push({ fn: StartPhase }); return state; } function UpdateTurn(state, { arg, currentPlayer, next }) { let { G, ctx } = state; const conf = GetPhase(ctx); // Update turn order state. const { endPhase, ctx: newCtx } = UpdateTurnOrderState(state, currentPlayer, conf.turn, arg); ctx = newCtx; state = { ...state, G, ctx }; if (endPhase) { next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase }); } else { next.push({ fn: StartTurn, currentPlayer: ctx.currentPlayer }); } return state; } function UpdateStage(state, { arg, playerID }) { if (typeof arg === 'string') { arg = { stage: arg }; } let { ctx } = state; let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, } = ctx; if (arg.stage) { if (activePlayers === null) { activePlayers = {}; } activePlayers[playerID] = arg.stage; _activePlayersNumMoves[playerID] = 0; if (arg.moveLimit) { if (_activePlayersMoveLimit === null) { _activePlayersMoveLimit = {}; } _activePlayersMoveLimit[playerID] = arg.moveLimit; } } ctx = { ...ctx, activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, }; return { ...state, ctx }; } /////////////// // ShouldEnd // /////////////// function ShouldEndGame(state) { return wrapped.endIf(state); } function ShouldEndPhase(state) { const conf = GetPhase(state.ctx); return conf.wrapped.endIf(state); } function ShouldEndTurn(state) { const conf = GetPhase(state.ctx); // End the turn if the required number of moves has been made. const currentPlayerMoves = state.ctx.numMoves || 0; if (conf.turn.moveLimit && currentPlayerMoves >= conf.turn.moveLimit) { return true; } return conf.turn.wrapped.endIf(state); } ///////// // End // ///////// function EndGame(state, { arg, phase }) { state = EndPhase(state, { phase }); if (arg === undefined) { arg = true; } state = { ...state, ctx: { ...state.ctx, gameover: arg } }; // Run game end hook. const G = wrapped.onEnd(state); return { ...state, G }; } function EndPhase(state, { arg, next, turn, automatic }) { // End the turn first. state = EndTurn(state, { turn, force: true }); let G = state.G; let ctx = state.ctx; if (next) { next.push({ fn: UpdatePhase, arg, phase: ctx.phase }); } // If we aren't in a phase, there is nothing else to do. if (ctx.phase === null) { return state; } // Run any cleanup code for the phase that is about to end. const conf = GetPhase(ctx); G = conf.wrapped.onEnd(state); // Reset the phase. ctx = { ...ctx, phase: null }; // Add log entry. const action = gameEvent('endPhase', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...state.deltalog, logEntry]; return { ...state, G, ctx, deltalog }; } function EndTurn(state, { arg, next, turn, force, automatic, playerID }) { // This is not the turn that EndTurn was originally // called for. The turn was probably ended some other way. if (turn !== state.ctx.turn) { return state; } let { G, ctx } = state; const conf = GetPhase(ctx); // Prevent ending the turn if moveLimit hasn't been reached. const currentPlayerMoves = ctx.numMoves || 0; if (!force && conf.turn.moveLimit && currentPlayerMoves < conf.turn.moveLimit) { info(`cannot end turn before making ${conf.turn.moveLimit} moves`); return state; } // Run turn-end triggers. G = conf.turn.wrapped.onEnd(state); if (next) { next.push({ fn: UpdateTurn, arg, currentPlayer: ctx.currentPlayer }); } // Reset activePlayers. ctx = { ...ctx, activePlayers: null }; // Remove player from playerOrder if (arg && arg.remove) { playerID = playerID || ctx.currentPlayer; const playOrder = ctx.playOrder.filter(i => i != playerID); const playOrderPos = ctx.playOrderPos > playOrder.length - 1 ? 0 : ctx.playOrderPos; ctx = { ...ctx, playOrder, playOrderPos }; if (playOrder.length === 0) { next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase }); return state; } } // Add log entry. const action = gameEvent('endTurn', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...(state.deltalog || []), logEntry]; return { ...state, G, ctx, deltalog, _undo: [], _redo: [] }; } function EndStage(state, { arg, next, automatic, playerID }) { playerID = playerID || state.ctx.currentPlayer; let { ctx } = state; let { activePlayers, _activePlayersMoveLimit } = ctx; const playerInStage = activePlayers !== null && playerID in activePlayers; if (!arg && playerInStage) { const conf = GetPhase(ctx); const stage = conf.turn.stages[activePlayers[playerID]]; if (stage && stage.next) arg = stage.next; } if (next && arg) { next.push({ fn: UpdateStage, arg, playerID }); } // If player isn’t in a stage, there is nothing else to do. if (!playerInStage) return state; // Remove player from activePlayers. activePlayers = Object.keys(activePlayers) .filter(id => id !== playerID) .reduce((obj, key) => { obj[key] = activePlayers[key]; return obj; }, {}); if (_activePlayersMoveLimit) { // Remove player from _activePlayersMoveLimit. _activePlayersMoveLimit = Object.keys(_activePlayersMoveLimit) .filter(id => id !== playerID) .reduce((obj, key) => { obj[key] = _activePlayersMoveLimit[key]; return obj; }, {}); } ctx = UpdateActivePlayersOnceEmpty({ ...ctx, activePlayers, _activePlayersMoveLimit, }); // Add log entry. const action = gameEvent('endStage', arg); const logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (automatic) { logEntry.automatic = true; } const deltalog = [...(state.deltalog || []), logEntry]; return { ...state, ctx, deltalog }; } /** * Retrieves the relevant move that can be played by playerID. * * If ctx.activePlayers is set (i.e. one or more players are in some stage), * then it attempts to find the move inside the stages config for * that turn. If the stage for a player is '', then the player is * allowed to make a move (as determined by the phase config), but * isn't restricted to a particular set as defined in the stage config. * * If not, it then looks for the move inside the phase. * * If it doesn't find the move there, it looks at the global move definition. * * @param {object} ctx * @param {string} name * @param {string} playerID */ function GetMove(ctx, name, playerID) { const conf = GetPhase(ctx); const stages = conf.turn.stages; const { activePlayers } = ctx; if (activePlayers && activePlayers[playerID] !== undefined && activePlayers[playerID] !== Stage.NULL && stages[activePlayers[playerID]] !== undefined && stages[activePlayers[playerID]].moves !== undefined) { // Check if moves are defined for the player's stage. const stage = stages[activePlayers[playerID]]; const moves = stage.moves; if (name in moves) { return moves[name]; } } else if (conf.moves) { // Check if moves are defined for the current phase. if (name in conf.moves) { return conf.moves[name]; } } else if (name in moves) { // Check for the move globally. return moves[name]; } return null; } function ProcessMove(state, action) { let conf = GetPhase(state.ctx); const move = GetMove(state.ctx, action.type, action.playerID); const shouldCount = !move || typeof move === 'function' || move.noLimit !== true; let { ctx } = state; let { _activePlayersNumMoves } = ctx; const { playerID } = action; let numMoves = state.ctx.numMoves; if (shouldCount) { if (playerID == state.ctx.currentPlayer) { numMoves++; } if (ctx.activePlayers) _activePlayersNumMoves[playerID]++; } state = { ...state, ctx: { ...ctx, numMoves, _activePlayersNumMoves, }, }; if (ctx._activePlayersMoveLimit && _activePlayersNumMoves[playerID] >= ctx._activePlayersMoveLimit[playerID]) { state = EndStage(state, { playerID, automatic: true }); } const G = conf.turn.wrapped.onMove(state); state = { ...state, G }; let events = [{ fn: OnMove }]; return Process(state, events); } function SetStageEvent(state, playerID, arg) { return Process(state, [{ fn: EndStage, arg, playerID }]); } function EndStageEvent(state, playerID) { return Process(state, [{ fn: EndStage, playerID }]); } function SetPhaseEvent(state, _playerID, newPhase) { return Process(state, [ { fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn, arg: { next: newPhase }, }, ]); } function EndPhaseEvent(state) { return Process(state, [ { fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn }, ]); } function EndTurnEvent(state, _playerID, arg) { return Process(state, [ { fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, arg }, ]); } function PassEvent(state, _playerID, arg) { return Process(state, [ { fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, force: true, arg, }, ]); } function EndGameEvent(state, _playerID, arg) { return Process(state, [ { fn: EndGame, turn: state.ctx.turn, phase: state.ctx.phase, arg }, ]); } const eventHandlers = { endStage: EndStageEvent, setStage: SetStageEvent, endTurn: EndTurnEvent, pass: PassEvent, endPhase: EndPhaseEvent, setPhase: SetPhaseEvent, endGame: EndGameEvent, setActivePlayers: SetActivePlayersEvent, }; let 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 (eventHandlers.hasOwnProperty(type)) { const eventArgs = [state, playerID].concat(args); return eventHandlers[type].apply({}, eventArgs); } return state; } function IsPlayerActive(_G, ctx, playerID) { if (ctx.activePlayers) { return playerID in ctx.activePlayers; } return ctx.currentPlayer === playerID; } return { ctx: (numPlayers) => ({ numPlayers, turn: 0, currentPlayer: '0', playOrder: [...new Array(numPlayers)].map((_d, i) => i + ''), playOrderPos: 0, phase: startingPhase, activePlayers: null, }), init: (state) => { return Process(state, [{ fn: StartGame }]); }, isPlayerActive: IsPlayerActive, eventHandlers, eventNames: Object.keys(eventHandlers), enabledEventNames, moveMap, moveNames: [...moveNames.values()], processMove: ProcessMove, processEvent: ProcessEvent, getMove: GetMove, }; } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ function IsProcessed(game) { return game.processMove !== undefined; } /** * Helper to generate the game move reducer. The returned * reducer has the following signature: * * (G, action, ctx) => {} * * You can roll your own if you like, or use any Redux * addon to generate such a reducer. * * The convention used in this framework is to * have action.type contain the name of the move, and * action.args contain any additional arguments as an * Array. */ function ProcessGameConfig(game) { // The Game() function has already been called on this // config object, so just pass it through. if (IsProcessed(game)) { return game; } if (game.name === undefined) game.name = 'default'; if (game.disableUndo === undefined) game.disableUndo = false; if (game.setup === undefined) game.setup = () => ({}); if (game.moves === undefined) game.moves = {}; if (game.playerView === undefined) game.playerView = G => G; if (game.plugins === undefined) game.plugins = []; game.plugins.forEach(plugin => { if (plugin.name === undefined) { throw new Error('Plugin missing name attribute'); } if (plugin.name.includes(' ')) { throw new Error(plugin.name + ': Plugin name must not include spaces'); } }); if (game.name.includes(' ')) { throw new Error(game.name + ': Game name must not include spaces'); } const flow = Flow(game); return { ...game, flow, moveNames: flow.moveNames, pluginNames: game.plugins.map(p => p.name), processMove: (state, action) => { let moveFn = flow.getMove(state.ctx, action.type, action.playerID); if (IsLongFormMove(moveFn)) { moveFn = moveFn.move; } if (moveFn instanceof Function) { const fn = FnWrap(moveFn, game.plugins); const ctxWithAPI = { ...EnhanceCtx(state), playerID: action.playerID, }; let args = []; if (action.args !== undefined) { args = args.concat(action.args); } return fn(state.G, ctxWithAPI, ...args); } error(`invalid move object: ${action.type}`); return state.G; }, }; } function IsLongFormMove(move) { return move instanceof Object && move.move !== undefined; } const subscriber_queue = []; /** * Create a `Writable` store that allows both updating and reading by subscription. * @param {*=}value initial value * @param {StartStopNotifier=}start start and stop notifications for subscriptions */ function writable(value, start = noop) { let stop; const subscribers = []; function set(new_value) { if (safe_not_equal(value, new_value)) { value = new_value; if (stop) { // store is ready const run_queue = !subscriber_queue.length; for (let i = 0; i < subscribers.length; i += 1) { const s = subscribers[i]; s[1](); subscriber_queue.push(s, value); } if (run_queue) { for (let i = 0; i < subscriber_queue.length; i += 2) { subscriber_queue[i][0](subscriber_queue[i + 1]); } subscriber_queue.length = 0; } } } } function update(fn) { set(fn(value)); } function subscribe(run, invalidate = noop) { const subscriber = [run, invalidate]; subscribers.push(subscriber); if (subscribers.length === 1) { stop = start(set) || noop; } run(value); return () => { const index = subscribers.indexOf(subscriber); if (index !== -1) { subscribers.splice(index, 1); } if (subscribers.length === 0) { stop(); stop = null; } }; } return { set, update, subscribe }; } function cubicOut(t) { const f = t - 1.0; return f * f * f + 1.0; } function fly(node, { delay = 0, duration = 400, easing = cubicOut, x = 0, y = 0, opacity = 0 }) { const style = getComputedStyle(node); const target_opacity = +style.opacity; const transform = style.transform === 'none' ? '' : style.transform; const od = target_opacity * (1 - opacity); return { delay, duration, easing, css: (t, u) => ` transform: ${transform} translate(${(1 - t) * x}px, ${(1 - t) * y}px); opacity: ${target_opacity - (od * u)}` }; } /* src/client/debug/Menu.svelte generated by Svelte v3.12.1 */ function add_css() { var style = element("style"); style.id = 'svelte-19bfq8g-style'; style.textContent = ".menu.svelte-19bfq8g{display:flex;margin-top:-10px;flex-direction:row;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-19bfq8g{line-height:25px;cursor:pointer;background:#fefefe;color:#555;padding-left:15px;padding-right:15px;text-align:center}.menu-item.svelte-19bfq8g:last-child{border-radius:0 5px 0 0}.menu-item.svelte-19bfq8g:first-child{border-radius:5px 0 0 0}.menu-item.active.svelte-19bfq8g{cursor:default;font-weight:bold;background:#ddd;color:#555}.menu-item.svelte-19bfq8g:hover{background:#ddd;color:#555}"; append(document.head, style); } function get_each_context(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.key = list[i][0]; child_ctx.label = list[i][1].label; return child_ctx; } // (55:2) {#each Object.entries(panes).reverse() as [key, {label} function create_each_block(ctx) { var div, t0_value = ctx.label + "", t0, t1, dispose; function click_handler() { return ctx.click_handler(ctx); } return { c() { div = element("div"); t0 = text(t0_value); t1 = space(); attr(div, "class", "menu-item svelte-19bfq8g"); toggle_class(div, "active", ctx.pane == ctx.key); dispose = listen(div, "click", click_handler); }, m(target, anchor) { insert(target, div, anchor); append(div, t0); append(div, t1); }, p(changed, new_ctx) { ctx = new_ctx; if ((changed.panes) && t0_value !== (t0_value = ctx.label + "")) { set_data(t0, t0_value); } if ((changed.pane || changed.panes)) { toggle_class(div, "active", ctx.pane == ctx.key); } }, d(detaching) { if (detaching) { detach(div); } dispose(); } }; } function create_fragment(ctx) { var div; let each_value = Object.entries(ctx.panes).reverse(); 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() { div = element("div"); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].c(); } attr(div, "class", "menu svelte-19bfq8g"); }, m(target, anchor) { insert(target, div, anchor); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(div, null); } }, p(changed, ctx) { if (changed.pane || changed.panes) { each_value = Object.entries(ctx.panes).reverse(); 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(changed, child_ctx); } else { each_blocks[i] = create_each_block(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($$self, $$props, $$invalidate) { let { pane, panes } = $$props; const dispatch = createEventDispatcher(); const click_handler = ({ key }) => dispatch('change', key); $$self.$set = $$props => { if ('pane' in $$props) $$invalidate('pane', pane = $$props.pane); if ('panes' in $$props) $$invalidate('panes', panes = $$props.panes); }; return { pane, panes, dispatch, click_handler }; } class Menu extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-19bfq8g-style")) add_css(); init(this, options, instance, create_fragment, safe_not_equal, ["pane", "panes"]); } } /* src/client/debug/main/Hotkey.svelte generated by Svelte v3.12.1 */ function add_css$1() { var style = element("style"); style.id = 'svelte-1olzq4i-style'; style.textContent = ".key.svelte-1olzq4i{display:flex;flex-direction:row;align-items:center}.key-box.svelte-1olzq4i{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}.key-box.svelte-1olzq4i:hover{background:#ddd}.key.active.svelte-1olzq4i .key-box.svelte-1olzq4i{background:#ddd;border:1px solid #999;box-shadow:none}.label.svelte-1olzq4i{margin-left:10px}"; append(document.head, style); } // (77:2) {#if label} function create_if_block(ctx) { var div, t; return { c() { div = element("div"); t = text(ctx.label); attr(div, "class", "label svelte-1olzq4i"); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p(changed, ctx) { if (changed.label) { set_data(t, ctx.label); } }, d(detaching) { if (detaching) { detach(div); } } }; } function create_fragment$1(ctx) { var div1, div0, t0, t1, dispose; var if_block = (ctx.label) && create_if_block(ctx); return { c() { div1 = element("div"); div0 = element("div"); t0 = text(ctx.value); t1 = space(); if (if_block) if_block.c(); attr(div0, "class", "key-box svelte-1olzq4i"); attr(div1, "class", "key svelte-1olzq4i"); toggle_class(div1, "active", ctx.active); dispose = [ listen(window, "keydown", ctx.Keypress), listen(div0, "click", ctx.Activate) ]; }, m(target, anchor) { insert(target, div1, anchor); append(div1, div0); append(div0, t0); append(div1, t1); if (if_block) if_block.m(div1, null); }, p(changed, ctx) { if (changed.value) { set_data(t0, ctx.value); } if (ctx.label) { if (if_block) { if_block.p(changed, ctx); } else { if_block = create_if_block(ctx); if_block.c(); if_block.m(div1, null); } } else if (if_block) { if_block.d(1); if_block = null; } if (changed.active) { toggle_class(div1, "active", ctx.active); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div1); } if (if_block) if_block.d(); run_all(dispose); } }; } function instance$1($$self, $$props, $$invalidate) { let $disableHotkeys; let { value, onPress = null, label = null, disable = false } = $$props; const { disableHotkeys } = getContext('hotkeys'); component_subscribe($$self, disableHotkeys, $$value => { $disableHotkeys = $$value; $$invalidate('$disableHotkeys', $disableHotkeys); }); let active = false; function Deactivate() { $$invalidate('active', active = false); } function Activate() { $$invalidate('active', 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('value', value = $$props.value); if ('onPress' in $$props) $$invalidate('onPress', onPress = $$props.onPress); if ('label' in $$props) $$invalidate('label', label = $$props.label); if ('disable' in $$props) $$invalidate('disable', disable = $$props.disable); }; return { value, onPress, label, disable, disableHotkeys, active, Activate, Keypress }; } class Hotkey extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1olzq4i-style")) add_css$1(); init(this, options, instance$1, create_fragment$1, safe_not_equal, ["value", "onPress", "label", "disable"]); } } /* src/client/debug/main/InteractiveFunction.svelte generated by Svelte v3.12.1 */ function add_css$2() { var style = element("style"); style.id = 'svelte-1mppqmp-style'; style.textContent = ".move.svelte-1mppqmp{display:flex;flex-direction:row;cursor:pointer;margin-left:10px;color:#666}.move.svelte-1mppqmp:hover{color:#333}.move.active.svelte-1mppqmp{color:#111;font-weight:bold}.arg-field.svelte-1mppqmp{outline:none;font-family:monospace}"; append(document.head, style); } function create_fragment$2(ctx) { var div, span0, t0, t1, span1, t3, span2, t4, span3, dispose; return { c() { div = element("div"); span0 = element("span"); t0 = text(ctx.name); 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", ctx.active); dispose = [ listen(span2, "blur", ctx.Deactivate), listen(span2, "keypress", stop_propagation(keypress_handler)), listen(span2, "keydown", ctx.OnKeyDown), listen(div, "click", ctx.Activate) ]; }, 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); ctx.span2_binding(span2); append(div, t4); append(div, span3); }, p(changed, ctx) { if (changed.name) { set_data(t0, ctx.name); } if (changed.active) { toggle_class(div, "active", ctx.active); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div); } ctx.span2_binding(null); run_all(dispose); } }; } const keypress_handler = () => {}; function instance$2($$self, $$props, $$invalidate) { let { Activate, Deactivate, name, 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('span', 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'](() => { $$invalidate('span', span = $$value); }); } $$self.$set = $$props => { if ('Activate' in $$props) $$invalidate('Activate', Activate = $$props.Activate); if ('Deactivate' in $$props) $$invalidate('Deactivate', Deactivate = $$props.Deactivate); if ('name' in $$props) $$invalidate('name', name = $$props.name); if ('active' in $$props) $$invalidate('active', active = $$props.active); }; return { Activate, Deactivate, name, active, span, OnKeyDown, span2_binding }; } class InteractiveFunction extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1mppqmp-style")) add_css$2(); init(this, options, instance$2, create_fragment$2, safe_not_equal, ["Activate", "Deactivate", "name", "active"]); } } /* src/client/debug/main/Move.svelte generated by Svelte v3.12.1 */ function add_css$3() { var style = element("style"); style.id = 'svelte-smqssc-style'; style.textContent = ".move-error.svelte-smqssc{color:#a00;font-weight:bold}.wrapper.svelte-smqssc{display:flex;flex-direction:row;align-items:center}"; append(document.head, style); } // (65:2) {#if error} function create_if_block$1(ctx) { var span, t; return { c() { span = element("span"); t = text(ctx.error); attr(span, "class", "move-error svelte-smqssc"); }, m(target, anchor) { insert(target, span, anchor); append(span, t); }, p(changed, ctx) { if (changed.error) { set_data(t, ctx.error); } }, d(detaching) { if (detaching) { detach(span); } } }; } function create_fragment$3(ctx) { var div1, div0, t0, t1, current; var hotkey = new Hotkey({ props: { value: ctx.shortcut, onPress: ctx.Activate } }); var interactivefunction = new InteractiveFunction({ props: { Activate: ctx.Activate, Deactivate: ctx.Deactivate, name: ctx.name, active: ctx.active } }); interactivefunction.$on("submit", ctx.Submit); interactivefunction.$on("error", ctx.Error); var if_block = (ctx.error) && create_if_block$1(ctx); return { c() { div1 = element("div"); div0 = element("div"); hotkey.$$.fragment.c(); t0 = space(); interactivefunction.$$.fragment.c(); 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(changed, ctx) { var hotkey_changes = {}; if (changed.shortcut) hotkey_changes.value = ctx.shortcut; hotkey.$set(hotkey_changes); var interactivefunction_changes = {}; if (changed.name) interactivefunction_changes.name = ctx.name; if (changed.active) interactivefunction_changes.active = ctx.active; interactivefunction.$set(interactivefunction_changes); if (ctx.error) { if (if_block) { if_block.p(changed, ctx); } else { if_block = create_if_block$1(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$3($$self, $$props, $$invalidate) { let { shortcut, name, fn } = $$props; const {disableHotkeys} = getContext('hotkeys'); let error$1 = ''; let active = false; function Activate() { disableHotkeys.set(true); $$invalidate('active', active = true); } function Deactivate() { disableHotkeys.set(false); $$invalidate('error', error$1 = ''); $$invalidate('active', active = false); } function Submit(e) { $$invalidate('error', error$1 = ''); Deactivate(); fn.apply(this, e.detail); } function Error(e) { $$invalidate('error', error$1 = e.detail); error(e.detail); } $$self.$set = $$props => { if ('shortcut' in $$props) $$invalidate('shortcut', shortcut = $$props.shortcut); if ('name' in $$props) $$invalidate('name', name = $$props.name); if ('fn' in $$props) $$invalidate('fn', fn = $$props.fn); }; return { shortcut, name, fn, error: error$1, active, Activate, Deactivate, Submit, Error }; } class Move extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-smqssc-style")) add_css$3(); init(this, options, instance$3, create_fragment$3, safe_not_equal, ["shortcut", "name", "fn"]); } } /* src/client/debug/main/Controls.svelte generated by Svelte v3.12.1 */ function add_css$4() { var style = element("style"); style.id = 'svelte-1x2w9i0-style'; style.textContent = "li.svelte-1x2w9i0{list-style:none;margin:none;margin-bottom:5px}"; append(document.head, style); } function create_fragment$4(ctx) { var section, li0, t0, li1, t1, li2, t2, li3, current; var hotkey0 = new Hotkey({ props: { value: "1", onPress: ctx.client.reset, label: "reset" } }); var hotkey1 = new Hotkey({ props: { value: "2", onPress: ctx.Save, label: "save" } }); var hotkey2 = new Hotkey({ props: { value: "3", onPress: ctx.Restore, label: "restore" } }); var hotkey3 = new Hotkey({ props: { value: ".", disable: true, label: "hide" } }); return { c() { section = element("section"); li0 = element("li"); hotkey0.$$.fragment.c(); t0 = space(); li1 = element("li"); hotkey1.$$.fragment.c(); t1 = space(); li2 = element("li"); hotkey2.$$.fragment.c(); t2 = space(); li3 = element("li"); hotkey3.$$.fragment.c(); attr(li0, "class", "svelte-1x2w9i0"); attr(li1, "class", "svelte-1x2w9i0"); attr(li2, "class", "svelte-1x2w9i0"); attr(li3, "class", "svelte-1x2w9i0"); attr(section, "id", "debug-controls"); attr(section, "class", "controls"); }, m(target, anchor) { insert(target, section, anchor); append(section, li0); mount_component(hotkey0, li0, null); append(section, t0); append(section, li1); mount_component(hotkey1, li1, null); append(section, t1); append(section, li2); mount_component(hotkey2, li2, null); append(section, t2); append(section, li3); mount_component(hotkey3, li3, null); current = true; }, p(changed, ctx) { var hotkey0_changes = {}; if (changed.client) hotkey0_changes.onPress = ctx.client.reset; hotkey0.$set(hotkey0_changes); }, i(local) { if (current) return; transition_in(hotkey0.$$.fragment, local); transition_in(hotkey1.$$.fragment, local); transition_in(hotkey2.$$.fragment, local); transition_in(hotkey3.$$.fragment, local); current = true; }, o(local) { transition_out(hotkey0.$$.fragment, local); transition_out(hotkey1.$$.fragment, local); transition_out(hotkey2.$$.fragment, local); transition_out(hotkey3.$$.fragment, local); current = false; }, d(detaching) { if (detaching) { detach(section); } destroy_component(hotkey0); destroy_component(hotkey1); destroy_component(hotkey2); destroy_component(hotkey3); } }; } function instance$4($$self, $$props, $$invalidate) { let { client } = $$props; function Save() { // get state to persist and overwrite deltalog, _undo, and _redo const state = client.getState(); const json = stringify({ ...state, _undo: [], _redo: [], deltalog: [], }); window.localStorage.setItem('gamestate', json); window.localStorage.setItem('initialState', stringify(client.initialState)); } function Restore() { const gamestateJSON = window.localStorage.getItem('gamestate'); const initialStateJSON = window.localStorage.getItem('initialState'); if (gamestateJSON !== null && initialStateJSON !== null) { const gamestate = parse(gamestateJSON); const initialState = parse(initialStateJSON); client.store.dispatch(sync({ state: gamestate, initialState })); } } $$self.$set = $$props => { if ('client' in $$props) $$invalidate('client', client = $$props.client); }; return { client, Save, Restore }; } class Controls extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1x2w9i0-style")) add_css$4(); init(this, options, instance$4, create_fragment$4, safe_not_equal, ["client"]); } } /* src/client/debug/main/PlayerInfo.svelte generated by Svelte v3.12.1 */ function add_css$5() { var style = element("style"); style.id = 'svelte-6sf87x-style'; style.textContent = ".player-box.svelte-6sf87x{display:flex;flex-direction:row}.player.svelte-6sf87x{cursor:pointer;text-align:center;width:30px;height:30px;line-height:30px;background:#eee;border:3px solid #fefefe;box-sizing:content-box}.player.current.svelte-6sf87x{background:#555;color:#eee;font-weight:bold}.player.active.svelte-6sf87x{border:3px solid #ff7f50}"; append(document.head, style); } function get_each_context$1(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.player = list[i]; return child_ctx; } // (49:2) {#each players as player} function create_each_block$1(ctx) { var div, t0_value = ctx.player + "", t0, t1, dispose; function click_handler() { return ctx.click_handler(ctx); } return { c() { div = element("div"); t0 = text(t0_value); t1 = space(); attr(div, "class", "player svelte-6sf87x"); toggle_class(div, "current", ctx.player == ctx.ctx.currentPlayer); toggle_class(div, "active", ctx.player == ctx.playerID); dispose = listen(div, "click", click_handler); }, m(target, anchor) { insert(target, div, anchor); append(div, t0); append(div, t1); }, p(changed, new_ctx) { ctx = new_ctx; if ((changed.players) && t0_value !== (t0_value = ctx.player + "")) { set_data(t0, t0_value); } if ((changed.players || changed.ctx)) { toggle_class(div, "current", ctx.player == ctx.ctx.currentPlayer); } if ((changed.players || changed.playerID)) { toggle_class(div, "active", ctx.player == ctx.playerID); } }, d(detaching) { if (detaching) { detach(div); } dispose(); } }; } function create_fragment$5(ctx) { var div; let each_value = ctx.players; 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)); } 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-6sf87x"); }, m(target, anchor) { insert(target, div, anchor); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(div, null); } }, p(changed, ctx) { if (changed.players || changed.ctx || changed.playerID) { each_value = ctx.players; 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(changed, child_ctx); } else { each_blocks[i] = create_each_block$1(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$5($$self, $$props, $$invalidate) { let { ctx, playerID } = $$props; const dispatch = createEventDispatcher(); function OnClick(player) { if (player == playerID) { dispatch("change", { playerID: null }); } else { dispatch("change", { playerID: player }); } } let players; const click_handler = ({ player }) => OnClick(player); $$self.$set = $$props => { if ('ctx' in $$props) $$invalidate('ctx', ctx = $$props.ctx); if ('playerID' in $$props) $$invalidate('playerID', playerID = $$props.playerID); }; $$self.$$.update = ($$dirty = { ctx: 1 }) => { if ($$dirty.ctx) { $$invalidate('players', players = ctx ? [...Array(ctx.numPlayers).keys()].map(i => i.toString()) : []); } }; return { ctx, playerID, OnClick, players, click_handler }; } class PlayerInfo extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-6sf87x-style")) add_css$5(); init(this, options, instance$5, create_fragment$5, safe_not_equal, ["ctx", "playerID"]); } } /* * 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, eventNames, blacklist) { var shortcuts = {}; var events = {}; for (var name in moveNames) { events[name] = name; } for (var _name in eventNames) { events[_name] = _name; } var taken = {}; for (var i = 0; i < blacklist.length; i++) { var c = blacklist[i]; taken[c] = true; } // Try assigning the first char of each move as the shortcut. var t = taken; var canUseFirstChar = true; for (var _name2 in events) { var shortcut = _name2[0]; if (t[shortcut]) { canUseFirstChar = false; break; } t[shortcut] = true; shortcuts[_name2] = shortcut; } if (canUseFirstChar) { return shortcuts; } // If those aren't unique, use a-z. t = taken; var next = 97; shortcuts = {}; for (var _name3 in events) { var _shortcut = String.fromCharCode(next); while (t[_shortcut]) { next++; _shortcut = String.fromCharCode(next); } t[_shortcut] = true; shortcuts[_name3] = _shortcut; } return shortcuts; } /* src/client/debug/main/Main.svelte generated by Svelte v3.12.1 */ function add_css$6() { var style = element("style"); style.id = 'svelte-1vg2l2b-style'; style.textContent = ".json.svelte-1vg2l2b{font-family:monospace;color:#888}label.svelte-1vg2l2b{font-weight:bold;font-size:1.1em;display:inline}h3.svelte-1vg2l2b{text-transform:uppercase}li.svelte-1vg2l2b{list-style:none;margin:none;margin-bottom:5px}.events.svelte-1vg2l2b{display:flex;flex-direction:column}.events.svelte-1vg2l2b button.svelte-1vg2l2b{width:100px}.events.svelte-1vg2l2b button.svelte-1vg2l2b:not(:last-child){margin-bottom:10px}"; append(document.head, style); } function get_each_context$2(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.name = list[i][0]; child_ctx.fn = list[i][1]; return child_ctx; } // (85:2) {#each Object.entries(client.moves) as [name, fn]} function create_each_block$2(ctx) { var li, t, current; var move = new Move({ props: { shortcut: ctx.shortcuts[ctx.name], fn: ctx.fn, name: ctx.name } }); return { c() { li = element("li"); move.$$.fragment.c(); t = space(); attr(li, "class", "svelte-1vg2l2b"); }, m(target, anchor) { insert(target, li, anchor); mount_component(move, li, null); append(li, t); current = true; }, p(changed, ctx) { var move_changes = {}; if (changed.client) move_changes.shortcut = ctx.shortcuts[ctx.name]; if (changed.client) move_changes.fn = ctx.fn; if (changed.client) move_changes.name = ctx.name; 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); } }; } // (96:2) {#if client.events.endTurn} function create_if_block_2(ctx) { var button, dispose; return { c() { button = element("button"); button.textContent = "End Turn"; attr(button, "class", "svelte-1vg2l2b"); dispose = listen(button, "click", ctx.click_handler); }, m(target, anchor) { insert(target, button, anchor); }, d(detaching) { if (detaching) { detach(button); } dispose(); } }; } // (99:2) {#if ctx.phase && client.events.endPhase} function create_if_block_1(ctx) { var button, dispose; return { c() { button = element("button"); button.textContent = "End Phase"; attr(button, "class", "svelte-1vg2l2b"); dispose = listen(button, "click", ctx.click_handler_1); }, m(target, anchor) { insert(target, button, anchor); }, d(detaching) { if (detaching) { detach(button); } dispose(); } }; } // (102:2) {#if ctx.activePlayers && client.events.endStage} function create_if_block$2(ctx) { var button, dispose; return { c() { button = element("button"); button.textContent = "End Stage"; attr(button, "class", "svelte-1vg2l2b"); dispose = listen(button, "click", ctx.click_handler_2); }, m(target, anchor) { insert(target, button, anchor); }, d(detaching) { if (detaching) { detach(button); } dispose(); } }; } function create_fragment$6(ctx) { var section0, h30, t1, t2, section1, h31, t4, t5, section2, h32, t7, t8, section3, h33, t10, div, t11, t12, t13, section4, label0, t15, pre0, t16_value = JSON.stringify(ctx.G, null, 2) + "", t16, t17, section5, label1, t19, pre1, t20_value = JSON.stringify(SanitizeCtx(ctx.ctx), null, 2) + "", t20, current; var controls = new Controls({ props: { client: ctx.client } }); var playerinfo = new PlayerInfo({ props: { ctx: ctx.ctx, playerID: ctx.playerID } }); playerinfo.$on("change", ctx.change_handler); let each_value = Object.entries(ctx.client.moves); 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)); } const out = i => transition_out(each_blocks[i], 1, 1, () => { each_blocks[i] = null; }); var if_block0 = (ctx.client.events.endTurn) && create_if_block_2(ctx); var if_block1 = (ctx.ctx.phase && ctx.client.events.endPhase) && create_if_block_1(ctx); var if_block2 = (ctx.ctx.activePlayers && ctx.client.events.endStage) && create_if_block$2(ctx); return { c() { section0 = element("section"); h30 = element("h3"); h30.textContent = "Controls"; t1 = space(); controls.$$.fragment.c(); t2 = space(); section1 = element("section"); h31 = element("h3"); h31.textContent = "Players"; t4 = space(); playerinfo.$$.fragment.c(); t5 = space(); section2 = element("section"); h32 = element("h3"); h32.textContent = "Moves"; t7 = space(); 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(); div = element("div"); 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"); label0 = element("label"); label0.textContent = "G"; t15 = space(); pre0 = element("pre"); t16 = text(t16_value); t17 = space(); section5 = element("section"); label1 = element("label"); label1.textContent = "ctx"; t19 = space(); pre1 = element("pre"); t20 = text(t20_value); attr(h30, "class", "svelte-1vg2l2b"); attr(h31, "class", "svelte-1vg2l2b"); attr(h32, "class", "svelte-1vg2l2b"); attr(h33, "class", "svelte-1vg2l2b"); attr(div, "class", "events svelte-1vg2l2b"); attr(label0, "class", "svelte-1vg2l2b"); attr(pre0, "class", "json svelte-1vg2l2b"); attr(label1, "class", "svelte-1vg2l2b"); attr(pre1, "class", "json svelte-1vg2l2b"); }, 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); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(section2, null); } insert(target, t8, anchor); insert(target, section3, anchor); append(section3, h33); append(section3, t10); append(section3, div); if (if_block0) if_block0.m(div, null); append(div, t11); if (if_block1) if_block1.m(div, null); append(div, t12); if (if_block2) if_block2.m(div, null); insert(target, t13, anchor); insert(target, section4, anchor); append(section4, label0); append(section4, t15); append(section4, pre0); append(pre0, t16); insert(target, t17, anchor); insert(target, section5, anchor); append(section5, label1); append(section5, t19); append(section5, pre1); append(pre1, t20); current = true; }, p(changed, ctx) { var controls_changes = {}; if (changed.client) controls_changes.client = ctx.client; controls.$set(controls_changes); var playerinfo_changes = {}; if (changed.ctx) playerinfo_changes.ctx = ctx.ctx; if (changed.playerID) playerinfo_changes.playerID = ctx.playerID; playerinfo.$set(playerinfo_changes); if (changed.shortcuts || changed.client) { each_value = Object.entries(ctx.client.moves); 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(changed, child_ctx); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$2(child_ctx); each_blocks[i].c(); transition_in(each_blocks[i], 1); each_blocks[i].m(section2, null); } } group_outros(); for (i = each_value.length; i < each_blocks.length; i += 1) { out(i); } check_outros(); } if (ctx.client.events.endTurn) { if (!if_block0) { if_block0 = create_if_block_2(ctx); if_block0.c(); if_block0.m(div, t11); } } else if (if_block0) { if_block0.d(1); if_block0 = null; } if (ctx.ctx.phase && ctx.client.events.endPhase) { if (!if_block1) { if_block1 = create_if_block_1(ctx); if_block1.c(); if_block1.m(div, t12); } } else if (if_block1) { if_block1.d(1); if_block1 = null; } if (ctx.ctx.activePlayers && ctx.client.events.endStage) { if (!if_block2) { if_block2 = create_if_block$2(ctx); if_block2.c(); if_block2.m(div, null); } } else if (if_block2) { if_block2.d(1); if_block2 = null; } if ((!current || changed.G) && t16_value !== (t16_value = JSON.stringify(ctx.G, null, 2) + "")) { set_data(t16, t16_value); } if ((!current || changed.ctx) && t20_value !== (t20_value = JSON.stringify(SanitizeCtx(ctx.ctx), null, 2) + "")) { set_data(t20, t20_value); } }, 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]); } 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]); } current = false; }, d(detaching) { if (detaching) { detach(section0); } destroy_component(controls); if (detaching) { detach(t2); detach(section1); } destroy_component(playerinfo); if (detaching) { detach(t5); detach(section2); } destroy_each(each_blocks, detaching); if (detaching) { detach(t8); detach(section3); } if (if_block0) if_block0.d(); if (if_block1) if_block1.d(); if (if_block2) if_block2.d(); if (detaching) { detach(t13); detach(section4); detach(t17); detach(section5); } } }; } function SanitizeCtx(ctx) { let r = {}; for (const key in ctx) { if (!key.startsWith('_')) { r[key] = ctx[key]; } } return r; } function instance$6($$self, $$props, $$invalidate) { let { client } = $$props; const shortcuts = AssignShortcuts(client.moves, client.events, 'mlia'); let playerID = client.playerID; let ctx = {}; let G = {}; client.subscribe((state) => { if (state) { $$invalidate('G', G = state.G); $$invalidate('ctx', ctx = state.ctx); } $$invalidate('playerID', playerID = client.playerID); }); const change_handler = (e) => client.updatePlayerID(e.detail.playerID); const click_handler = () => client.events.endTurn(); const click_handler_1 = () => client.events.endPhase(); const click_handler_2 = () => client.events.endStage(); $$self.$set = $$props => { if ('client' in $$props) $$invalidate('client', client = $$props.client); }; return { client, shortcuts, playerID, ctx, G, change_handler, click_handler, click_handler_1, click_handler_2 }; } class Main extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1vg2l2b-style")) add_css$6(); init(this, options, instance$6, create_fragment$6, safe_not_equal, ["client"]); } } /* src/client/debug/info/Item.svelte generated by Svelte v3.12.1 */ function add_css$7() { var style = element("style"); style.id = 'svelte-13qih23-style'; style.textContent = ".item.svelte-13qih23{padding:10px}.item.svelte-13qih23:not(:first-child){border-top:1px dashed #aaa}.item.svelte-13qih23 div.svelte-13qih23{float:right;text-align:right}"; append(document.head, style); } function create_fragment$7(ctx) { var div1, strong, t0, t1, div0, t2_value = JSON.stringify(ctx.value) + "", t2; return { c() { div1 = element("div"); strong = element("strong"); t0 = text(ctx.name); 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(changed, ctx) { if (changed.name) { set_data(t0, ctx.name); } if ((changed.value) && t2_value !== (t2_value = JSON.stringify(ctx.value) + "")) { set_data(t2, t2_value); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div1); } } }; } function instance$7($$self, $$props, $$invalidate) { let { name, value } = $$props; $$self.$set = $$props => { if ('name' in $$props) $$invalidate('name', name = $$props.name); if ('value' in $$props) $$invalidate('value', value = $$props.value); }; return { name, value }; } class Item extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-13qih23-style")) add_css$7(); init(this, options, instance$7, create_fragment$7, safe_not_equal, ["name", "value"]); } } /* src/client/debug/info/Info.svelte generated by Svelte v3.12.1 */ function add_css$8() { var style = element("style"); style.id = 'svelte-1yzq5o8-style'; style.textContent = ".gameinfo.svelte-1yzq5o8{padding:10px}"; append(document.head, style); } // (17:2) {#if $client.isMultiplayer} function create_if_block$3(ctx) { var span, t, current; var item0 = new Item({ props: { name: "isConnected", value: ctx.$client.isConnected } }); var item1 = new Item({ props: { name: "isMultiplayer", value: ctx.$client.isMultiplayer } }); return { c() { span = element("span"); item0.$$.fragment.c(); t = space(); item1.$$.fragment.c(); }, m(target, anchor) { insert(target, span, anchor); mount_component(item0, span, null); append(span, t); mount_component(item1, span, null); current = true; }, p(changed, ctx) { var item0_changes = {}; if (changed.$client) item0_changes.value = ctx.$client.isConnected; item0.$set(item0_changes); var item1_changes = {}; if (changed.$client) item1_changes.value = ctx.$client.isMultiplayer; item1.$set(item1_changes); }, i(local) { if (current) return; transition_in(item0.$$.fragment, local); transition_in(item1.$$.fragment, local); current = true; }, o(local) { transition_out(item0.$$.fragment, local); transition_out(item1.$$.fragment, local); current = false; }, d(detaching) { if (detaching) { detach(span); } destroy_component(item0); destroy_component(item1); } }; } function create_fragment$8(ctx) { var section, t0, t1, t2, current; var item0 = new Item({ props: { name: "gameID", value: ctx.client.gameID } }); var item1 = new Item({ props: { name: "playerID", value: ctx.client.playerID } }); var item2 = new Item({ props: { name: "isActive", value: ctx.$client.isActive } }); var if_block = (ctx.$client.isMultiplayer) && create_if_block$3(ctx); return { c() { section = element("section"); item0.$$.fragment.c(); t0 = space(); item1.$$.fragment.c(); t1 = space(); item2.$$.fragment.c(); 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(changed, ctx) { var item0_changes = {}; if (changed.client) item0_changes.value = ctx.client.gameID; item0.$set(item0_changes); var item1_changes = {}; if (changed.client) item1_changes.value = ctx.client.playerID; item1.$set(item1_changes); var item2_changes = {}; if (changed.$client) item2_changes.value = ctx.$client.isActive; item2.$set(item2_changes); if (ctx.$client.isMultiplayer) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block$3(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$8($$self, $$props, $$invalidate) { let $client; let { client } = $$props; component_subscribe($$self, client, $$value => { $client = $$value; $$invalidate('$client', $client); }); $$self.$set = $$props => { if ('client' in $$props) $$invalidate('client', client = $$props.client); }; return { client, $client }; } class Info extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1yzq5o8-style")) add_css$8(); init(this, options, instance$8, create_fragment$8, safe_not_equal, ["client"]); } } /* src/client/debug/log/TurnMarker.svelte generated by Svelte v3.12.1 */ function add_css$9() { var style = element("style"); style.id = 'svelte-6eza86-style'; style.textContent = ".turn-marker.svelte-6eza86{display:flex;justify-content:center;align-items:center;grid-column:1;background:#555;color:#eee;text-align:center;font-weight:bold;border:1px solid #888}"; append(document.head, style); } function create_fragment$9(ctx) { var div, t; return { c() { div = element("div"); t = text(ctx.turn); attr(div, "class", "turn-marker svelte-6eza86"); attr(div, "style", ctx.style); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p(changed, ctx) { if (changed.turn) { set_data(t, ctx.turn); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div); } } }; } function instance$9($$self, $$props, $$invalidate) { let { turn, numEvents } = $$props; const style = `grid-row: span ${numEvents}`; $$self.$set = $$props => { if ('turn' in $$props) $$invalidate('turn', turn = $$props.turn); if ('numEvents' in $$props) $$invalidate('numEvents', numEvents = $$props.numEvents); }; return { turn, numEvents, style }; } class TurnMarker extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-6eza86-style")) add_css$9(); init(this, options, instance$9, create_fragment$9, safe_not_equal, ["turn", "numEvents"]); } } /* src/client/debug/log/PhaseMarker.svelte generated by Svelte v3.12.1 */ function add_css$a() { var style = element("style"); style.id = 'svelte-1t4xap-style'; style.textContent = ".phase-marker.svelte-1t4xap{grid-column:3;background:#555;border:1px solid #888;color:#eee;text-align:center;font-weight:bold;padding-top:10px;padding-bottom:10px;text-orientation:sideways;writing-mode:vertical-rl;line-height:30px;width:100%}"; append(document.head, style); } function create_fragment$a(ctx) { var div, t_value = ctx.phase || '' + "", t; return { c() { div = element("div"); t = text(t_value); attr(div, "class", "phase-marker svelte-1t4xap"); attr(div, "style", ctx.style); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p(changed, ctx) { if ((changed.phase) && t_value !== (t_value = ctx.phase || '' + "")) { set_data(t, t_value); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div); } } }; } function instance$a($$self, $$props, $$invalidate) { let { phase, numEvents } = $$props; const style = `grid-row: span ${numEvents}`; $$self.$set = $$props => { if ('phase' in $$props) $$invalidate('phase', phase = $$props.phase); if ('numEvents' in $$props) $$invalidate('numEvents', numEvents = $$props.numEvents); }; return { phase, numEvents, style }; } class PhaseMarker extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1t4xap-style")) add_css$a(); init(this, options, instance$a, create_fragment$a, safe_not_equal, ["phase", "numEvents"]); } } /* src/client/debug/log/CustomPayload.svelte generated by Svelte v3.12.1 */ function create_fragment$b(ctx) { var div, t; return { c() { div = element("div"); t = text(ctx.custompayload); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p: noop, i: noop, o: noop, d(detaching) { if (detaching) { detach(div); } } }; } function instance$b($$self, $$props, $$invalidate) { let { payload } = $$props; const custompayload = payload !== undefined ? JSON.stringify(payload, null, 4) : ''; $$self.$set = $$props => { if ('payload' in $$props) $$invalidate('payload', payload = $$props.payload); }; return { payload, custompayload }; } class CustomPayload extends SvelteComponent { constructor(options) { super(); init(this, options, instance$b, create_fragment$b, safe_not_equal, ["payload"]); } } /* src/client/debug/log/LogEvent.svelte generated by Svelte v3.12.1 */ function add_css$b() { var style = element("style"); style.id = 'svelte-10wdo7v-style'; style.textContent = ".log-event.svelte-10wdo7v{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:#888;font-size:14px;min-height:25px;line-height:25px}.log-event.svelte-10wdo7v:hover{border-style:solid;background:#eee}.log-event.pinned.svelte-10wdo7v{border-style:solid;background:#eee;opacity:1}.player0.svelte-10wdo7v{border-left-color:#ff851b}.player1.svelte-10wdo7v{border-left-color:#7fdbff}.player2.svelte-10wdo7v{border-left-color:#0074d9}.player3.svelte-10wdo7v{border-left-color:#39cccc}.player4.svelte-10wdo7v{border-left-color:#3d9970}.player5.svelte-10wdo7v{border-left-color:#2ecc40}.player6.svelte-10wdo7v{border-left-color:#01ff70}.player7.svelte-10wdo7v{border-left-color:#ffdc00}.player8.svelte-10wdo7v{border-left-color:#001f3f}.player9.svelte-10wdo7v{border-left-color:#ff4136}.player10.svelte-10wdo7v{border-left-color:#85144b}.player11.svelte-10wdo7v{border-left-color:#f012be}.player12.svelte-10wdo7v{border-left-color:#b10dc9}.player13.svelte-10wdo7v{border-left-color:#111111}.player14.svelte-10wdo7v{border-left-color:#aaaaaa}.player15.svelte-10wdo7v{border-left-color:#dddddd}"; append(document.head, style); } // (122:2) {:else} function create_else_block(ctx) { var current; var custompayload = new CustomPayload({ props: { payload: ctx.payload } }); return { c() { custompayload.$$.fragment.c(); }, m(target, anchor) { mount_component(custompayload, target, anchor); current = true; }, p(changed, ctx) { var custompayload_changes = {}; if (changed.payload) custompayload_changes.payload = ctx.payload; custompayload.$set(custompayload_changes); }, i(local) { if (current) return; transition_in(custompayload.$$.fragment, local); current = true; }, o(local) { transition_out(custompayload.$$.fragment, local); current = false; }, d(detaching) { destroy_component(custompayload, detaching); } }; } // (120:2) {#if payloadComponent} function create_if_block$4(ctx) { var switch_instance_anchor, current; var switch_value = ctx.payloadComponent; function switch_props(ctx) { return { props: { payload: ctx.payload } }; } if (switch_value) { var switch_instance = new switch_value(switch_props(ctx)); } return { c() { if (switch_instance) switch_instance.$$.fragment.c(); 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(changed, ctx) { var switch_instance_changes = {}; if (changed.payload) switch_instance_changes.payload = ctx.payload; if (switch_value !== (switch_value = ctx.payloadComponent)) { 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)); switch_instance.$$.fragment.c(); 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$c(ctx) { var div1, div0, t0_value = ctx.action.payload.type + "", t0, t1, t2_value = ctx.args.join(',') + "", t2, t3, t4, current_block_type_index, if_block, current, dispose; var if_block_creators = [ create_if_block$4, create_else_block ]; var if_blocks = []; function select_block_type(changed, ctx) { if (ctx.payloadComponent) return 0; return 1; } current_block_type_index = select_block_type(null, ctx); if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); return { c() { div1 = element("div"); div0 = element("div"); t0 = text(t0_value); t1 = text("("); t2 = text(t2_value); t3 = text(")"); t4 = space(); if_block.c(); attr(div1, "class", "log-event player" + ctx.playerID + " svelte-10wdo7v"); toggle_class(div1, "pinned", ctx.pinned); dispose = [ listen(div1, "click", ctx.click_handler), listen(div1, "mouseenter", ctx.mouseenter_handler), listen(div1, "mouseleave", ctx.mouseleave_handler) ]; }, m(target, anchor) { insert(target, div1, anchor); append(div1, div0); append(div0, t0); append(div0, t1); append(div0, t2); append(div0, t3); append(div1, t4); if_blocks[current_block_type_index].m(div1, null); current = true; }, p(changed, ctx) { if ((!current || changed.action) && t0_value !== (t0_value = ctx.action.payload.type + "")) { set_data(t0, t0_value); } var previous_block_index = current_block_type_index; current_block_type_index = select_block_type(changed, ctx); if (current_block_type_index === previous_block_index) { if_blocks[current_block_type_index].p(changed, ctx); } else { group_outros(); transition_out(if_blocks[previous_block_index], 1, 1, () => { if_blocks[previous_block_index] = null; }); check_outros(); if_block = if_blocks[current_block_type_index]; if (!if_block) { if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); if_block.c(); } transition_in(if_block, 1); if_block.m(div1, null); } if (changed.pinned) { toggle_class(div1, "pinned", ctx.pinned); } }, i(local) { if (current) return; transition_in(if_block); current = true; }, o(local) { transition_out(if_block); current = false; }, d(detaching) { if (detaching) { detach(div1); } if_blocks[current_block_type_index].d(); run_all(dispose); } }; } function instance$c($$self, $$props, $$invalidate) { let { logIndex, action, pinned, payload, payloadComponent } = $$props; const dispatch = createEventDispatcher(); const args = action.payload.args || []; const playerID = action.payload.playerID; const click_handler = () => dispatch('click', { logIndex }); const mouseenter_handler = () => dispatch('mouseenter', { logIndex }); const mouseleave_handler = () => dispatch('mouseleave'); $$self.$set = $$props => { if ('logIndex' in $$props) $$invalidate('logIndex', logIndex = $$props.logIndex); if ('action' in $$props) $$invalidate('action', action = $$props.action); if ('pinned' in $$props) $$invalidate('pinned', pinned = $$props.pinned); if ('payload' in $$props) $$invalidate('payload', payload = $$props.payload); if ('payloadComponent' in $$props) $$invalidate('payloadComponent', payloadComponent = $$props.payloadComponent); }; return { logIndex, action, pinned, payload, payloadComponent, dispatch, args, playerID, click_handler, mouseenter_handler, mouseleave_handler }; } class LogEvent extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-10wdo7v-style")) add_css$b(); init(this, options, instance$c, create_fragment$c, safe_not_equal, ["logIndex", "action", "pinned", "payload", "payloadComponent"]); } } /* node_modules/svelte-icons/components/IconBase.svelte generated by Svelte v3.12.1 */ function add_css$c() { var style = element("style"); style.id = 'svelte-c8tyih-style'; style.textContent = "svg.svelte-c8tyih{stroke:currentColor;fill:currentColor;stroke-width:0;width:100%;height:auto;max-height:100%}"; append(document.head, style); } // (18:2) {#if title} function create_if_block$5(ctx) { var title_1, t; return { c() { title_1 = svg_element("title"); t = text(ctx.title); }, m(target, anchor) { insert(target, title_1, anchor); append(title_1, t); }, p(changed, ctx) { if (changed.title) { set_data(t, ctx.title); } }, d(detaching) { if (detaching) { detach(title_1); } } }; } function create_fragment$d(ctx) { var svg, if_block_anchor, current; var if_block = (ctx.title) && create_if_block$5(ctx); const default_slot_template = ctx.$$slots.default; const default_slot = create_slot(default_slot_template, ctx, 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", ctx.viewBox); attr(svg, "class", "svelte-c8tyih"); }, l(nodes) { if (default_slot) default_slot.l(svg_nodes); }, 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(changed, ctx) { if (ctx.title) { if (if_block) { if_block.p(changed, ctx); } else { if_block = create_if_block$5(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 && default_slot.p && changed.$$scope) { default_slot.p( get_slot_changes(default_slot_template, ctx, changed, null), get_slot_context(default_slot_template, ctx, null) ); } if (!current || changed.viewBox) { attr(svg, "viewBox", ctx.viewBox); } }, 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$d($$self, $$props, $$invalidate) { let { title = null, viewBox } = $$props; let { $$slots = {}, $$scope } = $$props; $$self.$set = $$props => { if ('title' in $$props) $$invalidate('title', title = $$props.title); if ('viewBox' in $$props) $$invalidate('viewBox', viewBox = $$props.viewBox); if ('$$scope' in $$props) $$invalidate('$$scope', $$scope = $$props.$$scope); }; return { title, viewBox, $$slots, $$scope }; } class IconBase extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-c8tyih-style")) add_css$c(); init(this, options, instance$d, create_fragment$d, safe_not_equal, ["title", "viewBox"]); } } /* node_modules/svelte-icons/fa/FaArrowAltCircleDown.svelte generated by Svelte v3.12.1 */ // (4:8) <IconBase viewBox="0 0 512 512" {...$$props}> function create_default_slot(ctx) { var 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$e(ctx) { var current; var iconbase_spread_levels = [ { viewBox: "0 0 512 512" }, ctx.$$props ]; let iconbase_props = { $$slots: { default: [create_default_slot] }, $$scope: { ctx } }; for (var i = 0; i < iconbase_spread_levels.length; i += 1) { iconbase_props = assign(iconbase_props, iconbase_spread_levels[i]); } var iconbase = new IconBase({ props: iconbase_props }); return { c() { iconbase.$$.fragment.c(); }, m(target, anchor) { mount_component(iconbase, target, anchor); current = true; }, p(changed, ctx) { var iconbase_changes = (changed.$$props) ? get_spread_update(iconbase_spread_levels, [ iconbase_spread_levels[0], get_spread_object(ctx.$$props) ]) : {}; if (changed.$$scope) iconbase_changes.$$scope = { changed, 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$e($$self, $$props, $$invalidate) { $$self.$set = $$new_props => { $$invalidate('$$props', $$props = assign(assign({}, $$props), $$new_props)); }; return { $$props, $$props: $$props = exclude_internal_props($$props) }; } class FaArrowAltCircleDown extends SvelteComponent { constructor(options) { super(); init(this, options, instance$e, create_fragment$e, safe_not_equal, []); } } /* src/client/debug/mcts/Action.svelte generated by Svelte v3.12.1 */ function add_css$d() { var style = element("style"); style.id = 'svelte-1a7time-style'; style.textContent = "div.svelte-1a7time{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;max-width:500px}"; append(document.head, style); } function create_fragment$f(ctx) { var div, t; return { c() { div = element("div"); t = text(ctx.text); attr(div, "alt", ctx.text); attr(div, "class", "svelte-1a7time"); }, m(target, anchor) { insert(target, div, anchor); append(div, t); }, p(changed, ctx) { if (changed.text) { set_data(t, ctx.text); attr(div, "alt", ctx.text); } }, i: noop, o: noop, d(detaching) { if (detaching) { detach(div); } } }; } function instance$f($$self, $$props, $$invalidate) { let { action } = $$props; let text; $$self.$set = $$props => { if ('action' in $$props) $$invalidate('action', action = $$props.action); }; $$self.$$.update = ($$dirty = { action: 1 }) => { if ($$dirty.action) { { const { type, args } = action.payload; const argsFormatted = (args || []).join(','); $$invalidate('text', text = `${type}(${argsFormatted})`); } } }; return { action, text }; } class Action extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1a7time-style")) add_css$d(); init(this, options, instance$f, create_fragment$f, safe_not_equal, ["action"]); } } /* src/client/debug/mcts/Table.svelte generated by Svelte v3.12.1 */ function add_css$e() { var style = element("style"); style.id = 'svelte-ztcwsu-style'; style.textContent = "table.svelte-ztcwsu{font-size:12px;border-collapse:collapse;border:1px solid #ddd;padding:0}tr.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{padding:10px;height:10px;line-height:10px;font-size:12px;border:none}th.svelte-ztcwsu{background:#888;color:#fff;padding:10px;text-align:center}"; append(document.head, style); } function get_each_context$3(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.child = list[i]; child_ctx.i = i; return child_ctx; } // (86:2) {#each children as child, i} function create_each_block$3(ctx) { var tr, td0, t0_value = ctx.child.value + "", t0, t1, td1, t2_value = ctx.child.visits + "", t2, t3, td2, t4, current, dispose; var action = new Action({ props: { action: ctx.child.parentAction } }); function click_handler() { return ctx.click_handler(ctx); } function mouseout_handler() { return ctx.mouseout_handler(ctx); } function mouseover_handler() { return ctx.mouseover_handler(ctx); } 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"); action.$$.fragment.c(); 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", ctx.children.length > 0); toggle_class(tr, "selected", ctx.i === ctx.selectedIndex); dispose = [ listen(tr, "click", click_handler), listen(tr, "mouseout", mouseout_handler), listen(tr, "mouseover", mouseover_handler) ]; }, 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; }, p(changed, new_ctx) { ctx = new_ctx; if ((!current || changed.children) && t0_value !== (t0_value = ctx.child.value + "")) { set_data(t0, t0_value); } if ((!current || changed.children) && t2_value !== (t2_value = ctx.child.visits + "")) { set_data(t2, t2_value); } var action_changes = {}; if (changed.children) action_changes.action = ctx.child.parentAction; action.$set(action_changes); if (changed.children) { toggle_class(tr, "clickable", ctx.children.length > 0); } if (changed.selectedIndex) { toggle_class(tr, "selected", ctx.i === ctx.selectedIndex); } }, 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); run_all(dispose); } }; } function create_fragment$g(ctx) { var table, thead, t_5, tbody, current; let each_value = ctx.children; 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)); } 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>`; t_5 = 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, t_5); append(table, tbody); for (let i = 0; i < each_blocks.length; i += 1) { each_blocks[i].m(tbody, null); } current = true; }, p(changed, ctx) { if (changed.children || changed.selectedIndex) { each_value = ctx.children; 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(changed, child_ctx); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$3(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$g($$self, $$props, $$invalidate) { let { root, 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('root', root = $$props.root); if ('selectedIndex' in $$props) $$invalidate('selectedIndex', selectedIndex = $$props.selectedIndex); }; $$self.$$.update = ($$dirty = { root: 1, parents: 1 }) => { if ($$dirty.root || $$dirty.parents) { { let t = root; $$invalidate('parents', 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('children', children = [...root.children] .sort((a, b) => (a.visits < b.visits ? 1 : -1)) .slice(0, 50)); } } }; return { root, selectedIndex, children, Select, Preview, click_handler, mouseout_handler, mouseover_handler }; } class Table extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-ztcwsu-style")) add_css$e(); init(this, options, instance$g, create_fragment$g, safe_not_equal, ["root", "selectedIndex"]); } } /* src/client/debug/mcts/MCTS.svelte generated by Svelte v3.12.1 */ function add_css$f() { var style = element("style"); style.id = 'svelte-1f0amz4-style'; style.textContent = ".visualizer.svelte-1f0amz4{display:flex;flex-direction:column;align-items:center;padding:50px}.preview.svelte-1f0amz4{opacity:0.5}.icon.svelte-1f0amz4{color:#777;width:32px;height:32px;margin-bottom:20px}"; append(document.head, style); } function get_each_context$4(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.node = list[i].node; child_ctx.selectedIndex = list[i].selectedIndex; child_ctx.i = i; return child_ctx; } // (50:4) {#if i !== 0} function create_if_block_2$1(ctx) { var div, current; var arrow = new FaArrowAltCircleDown({}); return { c() { div = element("div"); arrow.$$.fragment.c(); 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$1(ctx) { var current; function select_handler_1(...args) { return ctx.select_handler_1(ctx, ...args); } var table = new Table({ props: { root: ctx.node, selectedIndex: ctx.selectedIndex } }); table.$on("select", select_handler_1); return { c() { table.$$.fragment.c(); }, m(target, anchor) { mount_component(table, target, anchor); current = true; }, p(changed, new_ctx) { ctx = new_ctx; var table_changes = {}; if (changed.nodes) table_changes.root = ctx.node; if (changed.nodes) table_changes.selectedIndex = ctx.selectedIndex; 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$1(ctx) { var current; function select_handler(...args) { return ctx.select_handler(ctx, ...args); } function preview_handler(...args) { return ctx.preview_handler(ctx, ...args); } var table = new Table({ props: { root: ctx.node } }); table.$on("select", select_handler); table.$on("preview", preview_handler); return { c() { table.$$.fragment.c(); }, m(target, anchor) { mount_component(table, target, anchor); current = true; }, p(changed, new_ctx) { ctx = new_ctx; var table_changes = {}; if (changed.nodes) table_changes.root = ctx.node; 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$4(ctx) { var t, section, current_block_type_index, if_block1, current; var if_block0 = (ctx.i !== 0) && create_if_block_2$1(); var if_block_creators = [ create_if_block_1$1, create_else_block$1 ]; var if_blocks = []; function select_block_type(changed, ctx) { if (ctx.i === ctx.nodes.length - 1) return 0; return 1; } current_block_type_index = select_block_type(null, 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(changed, ctx) { var previous_block_index = current_block_type_index; current_block_type_index = select_block_type(changed, ctx); if (current_block_type_index === previous_block_index) { if_blocks[current_block_type_index].p(changed, ctx); } else { group_outros(); transition_out(if_blocks[previous_block_index], 1, 1, () => { if_blocks[previous_block_index] = null; }); check_outros(); if_block1 = if_blocks[current_block_type_index]; if (!if_block1) { if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); if_block1.c(); } transition_in(if_block1, 1); if_block1.m(section, null); } }, i(local) { if (current) return; transition_in(if_block0); transition_in(if_block1); current = true; }, o(local) { transition_out(if_block0); transition_out(if_block1); current = false; }, d(detaching) { if (if_block0) if_block0.d(detaching); if (detaching) { detach(t); detach(section); } if_blocks[current_block_type_index].d(); } }; } // (69:2) {#if preview} function create_if_block$6(ctx) { var div, t, section, current; var arrow = new FaArrowAltCircleDown({}); var table = new Table({ props: { root: ctx.preview } }); return { c() { div = element("div"); arrow.$$.fragment.c(); t = space(); section = element("section"); table.$$.fragment.c(); 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(changed, ctx) { var table_changes = {}; if (changed.preview) table_changes.root = ctx.preview; 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); detach(section); } destroy_component(table); } }; } function create_fragment$h(ctx) { var div, t, current; let each_value = ctx.nodes; 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)); } const out = i => transition_out(each_blocks[i], 1, 1, () => { each_blocks[i] = null; }); var if_block = (ctx.preview) && create_if_block$6(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(changed, ctx) { if (changed.nodes) { each_value = ctx.nodes; 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(changed, child_ctx); transition_in(each_blocks[i], 1); } else { each_blocks[i] = create_each_block$4(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 (ctx.preview) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block$6(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$h($$self, $$props, $$invalidate) { let { metadata } = $$props; let nodes = []; let preview = null; function SelectNode({ node, selectedIndex }, i) { $$invalidate('preview', preview = null); $$invalidate('nodes', nodes[i].selectedIndex = selectedIndex, nodes); $$invalidate('nodes', nodes = [...nodes.slice(0, i + 1), { node }]); } function PreviewNode({ node }, i) { $$invalidate('preview', 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('metadata', metadata = $$props.metadata); }; $$self.$$.update = ($$dirty = { metadata: 1 }) => { if ($$dirty.metadata) { { $$invalidate('nodes', nodes = [{ node: metadata }]); } } }; return { metadata, nodes, preview, SelectNode, PreviewNode, select_handler, preview_handler, select_handler_1 }; } class MCTS extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1f0amz4-style")) add_css$f(); init(this, options, instance$h, create_fragment$h, safe_not_equal, ["metadata"]); } } /* src/client/debug/log/Log.svelte generated by Svelte v3.12.1 */ function add_css$g() { var style = element("style"); style.id = 'svelte-1pq5e4b-style'; style.textContent = ".gamelog.svelte-1pq5e4b{display:grid;grid-template-columns:30px 1fr 30px;grid-auto-rows:auto;grid-auto-flow:column}"; append(document.head, style); } function get_each_context$5(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.phase = list[i].phase; child_ctx.i = i; return child_ctx; } function get_each_context_1(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.action = list[i].action; child_ctx.payload = list[i].payload; child_ctx.i = i; return child_ctx; } function get_each_context_2(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.turn = list[i].turn; child_ctx.i = i; return child_ctx; } // (137:4) {#if i in turnBoundaries} function create_if_block_1$2(ctx) { var current; var turnmarker = new TurnMarker({ props: { turn: ctx.turn, numEvents: ctx.turnBoundaries[ctx.i] } }); return { c() { turnmarker.$$.fragment.c(); }, m(target, anchor) { mount_component(turnmarker, target, anchor); current = true; }, p(changed, ctx) { var turnmarker_changes = {}; if (changed.renderedLogEntries) turnmarker_changes.turn = ctx.turn; if (changed.turnBoundaries) turnmarker_changes.numEvents = ctx.turnBoundaries[ctx.i]; 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); } }; } // (136:2) {#each renderedLogEntries as { turn } function create_each_block_2(ctx) { var if_block_anchor, current; var if_block = (ctx.i in ctx.turnBoundaries) && create_if_block_1$2(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(changed, ctx) { if (ctx.i in ctx.turnBoundaries) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block_1$2(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); } } }; } // (142:2) {#each renderedLogEntries as { action, payload } function create_each_block_1(ctx) { var current; var logevent = new LogEvent({ props: { pinned: ctx.i === ctx.pinned, logIndex: ctx.i, action: ctx.action, payload: ctx.payload } }); logevent.$on("click", ctx.OnLogClick); logevent.$on("mouseenter", ctx.OnMouseEnter); logevent.$on("mouseleave", ctx.OnMouseLeave); return { c() { logevent.$$.fragment.c(); }, m(target, anchor) { mount_component(logevent, target, anchor); current = true; }, p(changed, ctx) { var logevent_changes = {}; if (changed.pinned) logevent_changes.pinned = ctx.i === ctx.pinned; if (changed.renderedLogEntries) logevent_changes.action = ctx.action; if (changed.renderedLogEntries) logevent_changes.payload = ctx.payload; 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); } }; } // (154:4) {#if i in phaseBoundaries} function create_if_block$7(ctx) { var current; var phasemarker = new PhaseMarker({ props: { phase: ctx.phase, numEvents: ctx.phaseBoundaries[ctx.i] } }); return { c() { phasemarker.$$.fragment.c(); }, m(target, anchor) { mount_component(phasemarker, target, anchor); current = true; }, p(changed, ctx) { var phasemarker_changes = {}; if (changed.renderedLogEntries) phasemarker_changes.phase = ctx.phase; if (changed.phaseBoundaries) phasemarker_changes.numEvents = ctx.phaseBoundaries[ctx.i]; 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); } }; } // (153:2) {#each renderedLogEntries as { phase } function create_each_block$5(ctx) { var if_block_anchor, current; var if_block = (ctx.i in ctx.phaseBoundaries) && create_if_block$7(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(changed, ctx) { if (ctx.i in ctx.phaseBoundaries) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block$7(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$i(ctx) { var div, t0, t1, current, dispose; let each_value_2 = ctx.renderedLogEntries; 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 = ctx.renderedLogEntries; 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 = ctx.renderedLogEntries; 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_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", ctx.pinned); dispose = listen(window, "keydown", ctx.OnKeyDown); }, 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; }, p(changed, ctx) { if (changed.turnBoundaries || changed.renderedLogEntries) { each_value_2 = ctx.renderedLogEntries; 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(changed, child_ctx); 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 (changed.pinned || changed.renderedLogEntries) { each_value_1 = ctx.renderedLogEntries; 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(changed, child_ctx); 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 (changed.phaseBoundaries || changed.renderedLogEntries) { each_value = ctx.renderedLogEntries; 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(changed, child_ctx); 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(div, null); } } group_outros(); for (i = each_value.length; i < each_blocks.length; i += 1) { out_2(i); } check_outros(); } if (changed.pinned) { toggle_class(div, "pinned", ctx.pinned); } }, 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); dispose(); } }; } function instance$i($$self, $$props, $$invalidate) { let $client; let { client } = $$props; component_subscribe($$self, client, $$value => { $client = $$value; $$invalidate('$client', $client); }); const { secondaryPane } = getContext('secondaryPane'); 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 = client.reducer(state, action); } if (action.type == MAKE_MOVE) { if (logIndex == 0) { break; } logIndex--; } } return { G: state.G, ctx: state.ctx }; } function OnLogClick(e) { const { logIndex } = e.detail; const state = rewind(logIndex); const renderedLogEntries = log.filter(e => e.action.type == MAKE_MOVE); client.overrideGameState(state); if (pinned == logIndex) { $$invalidate('pinned', pinned = null); secondaryPane.set(null); } else { $$invalidate('pinned', 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('pinned', 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) $$invalidate('client', client = $$props.client); }; $$self.$$.update = ($$dirty = { $client: 1, log: 1, renderedLogEntries: 1 }) => { if ($$dirty.$client || $$dirty.log || $$dirty.renderedLogEntries) { { $$invalidate('log', log = $client.log); $$invalidate('renderedLogEntries', renderedLogEntries = log.filter(e => e.action.type == MAKE_MOVE)); let eventsInCurrentPhase = 0; let eventsInCurrentTurn = 0; $$invalidate('turnBoundaries', turnBoundaries = {}); $$invalidate('phaseBoundaries', 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('turnBoundaries', turnBoundaries[i] = eventsInCurrentTurn, turnBoundaries); eventsInCurrentTurn = 0; } if ( i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].phase != phase ) { $$invalidate('phaseBoundaries', phaseBoundaries[i] = eventsInCurrentPhase, phaseBoundaries); eventsInCurrentPhase = 0; } } } } }; return { client, pinned, OnLogClick, OnMouseEnter, OnMouseLeave, OnKeyDown, renderedLogEntries, turnBoundaries, phaseBoundaries }; } class Log extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1pq5e4b-style")) add_css$g(); init(this, options, instance$i, create_fragment$i, safe_not_equal, ["client"]); } } /* src/client/debug/ai/Options.svelte generated by Svelte v3.12.1 */ const { Object: Object_1 } = globals; function add_css$h() { var style = element("style"); style.id = 'svelte-7cel4i-style'; style.textContent = "label.svelte-7cel4i{font-weight:bold;color:#999}.option.svelte-7cel4i{margin-bottom:20px}.value.svelte-7cel4i{font-weight:bold}input[type='checkbox'].svelte-7cel4i{vertical-align:middle}"; append(document.head, style); } function get_each_context$6(ctx, list, i) { const child_ctx = Object_1.create(ctx); child_ctx.key = list[i][0]; child_ctx.value = list[i][1]; return child_ctx; } // (39:4) {#if value.range} function create_if_block_1$3(ctx) { var span, t0_value = ctx.values[ctx.key] + "", t0, t1, input, input_min_value, input_max_value, dispose; function input_change_input_handler() { ctx.input_change_input_handler.call(input, ctx); } return { c() { span = element("span"); t0 = text(t0_value); t1 = space(); input = element("input"); attr(span, "class", "value svelte-7cel4i"); attr(input, "type", "range"); attr(input, "min", input_min_value = ctx.value.range.min); attr(input, "max", input_max_value = ctx.value.range.max); dispose = [ listen(input, "change", input_change_input_handler), listen(input, "input", input_change_input_handler), listen(input, "change", ctx.OnChange) ]; }, m(target, anchor) { insert(target, span, anchor); append(span, t0); insert(target, t1, anchor); insert(target, input, anchor); set_input_value(input, ctx.values[ctx.key]); }, p(changed, new_ctx) { ctx = new_ctx; if ((changed.values || changed.bot) && t0_value !== (t0_value = ctx.values[ctx.key] + "")) { set_data(t0, t0_value); } if ((changed.values || changed.Object || changed.bot)) set_input_value(input, ctx.values[ctx.key]); if ((changed.bot) && input_min_value !== (input_min_value = ctx.value.range.min)) { attr(input, "min", input_min_value); } if ((changed.bot) && input_max_value !== (input_max_value = ctx.value.range.max)) { attr(input, "max", input_max_value); } }, d(detaching) { if (detaching) { detach(span); detach(t1); detach(input); } run_all(dispose); } }; } // (44:4) {#if typeof value.value === 'boolean'} function create_if_block$8(ctx) { var input, dispose; function input_change_handler() { ctx.input_change_handler.call(input, ctx); } return { c() { input = element("input"); attr(input, "type", "checkbox"); attr(input, "class", "svelte-7cel4i"); dispose = [ listen(input, "change", input_change_handler), listen(input, "change", ctx.OnChange) ]; }, m(target, anchor) { insert(target, input, anchor); input.checked = ctx.values[ctx.key]; }, p(changed, new_ctx) { ctx = new_ctx; if ((changed.values || changed.Object || changed.bot)) input.checked = ctx.values[ctx.key]; }, d(detaching) { if (detaching) { detach(input); } run_all(dispose); } }; } // (35:0) {#each Object.entries(bot.opts()) as [key, value]} function create_each_block$6(ctx) { var div, label, t0_value = ctx.key + "", t0, t1, t2, t3; var if_block0 = (ctx.value.range) && create_if_block_1$3(ctx); var if_block1 = (typeof ctx.value.value === 'boolean') && create_if_block$8(ctx); return { c() { div = element("div"); label = element("label"); t0 = text(t0_value); t1 = space(); if (if_block0) if_block0.c(); t2 = space(); if (if_block1) if_block1.c(); t3 = space(); attr(label, "class", "svelte-7cel4i"); attr(div, "class", "option svelte-7cel4i"); }, m(target, anchor) { insert(target, div, anchor); append(div, label); append(label, t0); append(div, t1); if (if_block0) if_block0.m(div, null); append(div, t2); if (if_block1) if_block1.m(div, null); append(div, t3); }, p(changed, ctx) { if ((changed.bot) && t0_value !== (t0_value = ctx.key + "")) { set_data(t0, t0_value); } if (ctx.value.range) { if (if_block0) { if_block0.p(changed, ctx); } else { if_block0 = create_if_block_1$3(ctx); if_block0.c(); if_block0.m(div, t2); } } else if (if_block0) { if_block0.d(1); if_block0 = null; } if (typeof ctx.value.value === 'boolean') { if (if_block1) { if_block1.p(changed, ctx); } else { if_block1 = create_if_block$8(ctx); if_block1.c(); if_block1.m(div, t3); } } else if (if_block1) { if_block1.d(1); if_block1 = null; } }, d(detaching) { if (detaching) { detach(div); } if (if_block0) if_block0.d(); if (if_block1) if_block1.d(); } }; } function create_fragment$j(ctx) { var each_1_anchor; let each_value = ctx.Object.entries(ctx.bot.opts()); 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)); } 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(changed, ctx) { if (changed.Object || changed.bot || changed.values) { each_value = ctx.Object.entries(ctx.bot.opts()); 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(changed, child_ctx); } else { each_blocks[i] = create_each_block$6(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$j($$self, $$props, $$invalidate) { let { bot } = $$props; let values = {}; for (let [key, value] of Object.entries(bot.opts())) { $$invalidate('values', values[key] = value.value, values); } function OnChange() { for (let [key, value] of Object.entries(values)) { bot.setOpt(key, value); } } function input_change_input_handler({ key }) { values[key] = to_number(this.value); $$invalidate('values', values); $$invalidate('Object', Object); $$invalidate('bot', bot); } function input_change_handler({ key }) { values[key] = this.checked; $$invalidate('values', values); $$invalidate('Object', Object); $$invalidate('bot', bot); } $$self.$set = $$props => { if ('bot' in $$props) $$invalidate('bot', bot = $$props.bot); }; return { bot, values, OnChange, Object, input_change_input_handler, input_change_handler }; } class Options extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-7cel4i-style")) add_css$h(); init(this, options, instance$j, create_fragment$j, safe_not_equal, ["bot"]); } } /* * 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. */ /** * 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; }; /** * CreateGameReducer * * Creates the main game state reducer. */ function CreateGameReducer({ game, isClient, }) { game = ProcessGameConfig(game); /** * GameReducer * * Redux reducer that maintains the overall game state. * @param {object} state - The state before the action. * @param {object} action - A Redux action. */ return (state = null, action) => { switch (action.type) { case GAME_EVENT: { state = { ...state, deltalog: [] }; // Process game events only on the server. // These events like `endTurn` typically // contain code that may rely on secret state // and cannot be computed on the client. if (isClient) { return state; } // Disallow events once the game is over. if (state.ctx.gameover !== undefined) { error(`cannot call event after game end`); return state; } // Ignore the event if the player isn't active. if (action.payload.playerID !== null && action.payload.playerID !== undefined && !game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) { error(`disallowed event: ${action.payload.type}`); return state; } // Execute plugins. state = Enhance(state, { game, isClient: false, playerID: action.payload.playerID, }); // Process event. let newState = game.flow.processEvent(state, action); // Execute plugins. newState = Flush(newState, { game, isClient: false }); return { ...newState, _stateID: state._stateID + 1 }; } case MAKE_MOVE: { state = { ...state, deltalog: [] }; // Check whether the move is allowed at this time. const move = game.flow.getMove(state.ctx, action.payload.type, action.payload.playerID || state.ctx.currentPlayer); if (move === null) { error(`disallowed move: ${action.payload.type}`); return state; } // Don't run move on client if move says so. if (isClient && move.client === false) { return state; } // Disallow moves once the game is over. if (state.ctx.gameover !== undefined) { error(`cannot make move after game end`); return state; } // Ignore the move if the player isn't active. if (action.payload.playerID !== null && action.payload.playerID !== undefined && !game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) { error(`disallowed move: ${action.payload.type}`); return state; } // Execute plugins. state = Enhance(state, { game, isClient, playerID: action.payload.playerID, }); // Process the move. let G = game.processMove(state, action.payload); // The game declared the move as invalid. if (G === INVALID_MOVE) { error(`invalid move: ${action.payload.type} args: ${action.payload.args}`); return state; } // Create a log entry for this move. let logEntry = { action, _stateID: state._stateID, turn: state.ctx.turn, phase: state.ctx.phase, }; if (move.redact === true) { logEntry.redact = true; } const newState = { ...state, G, deltalog: [logEntry], _stateID: state._stateID + 1, }; // Some plugin indicated that it is not suitable to be // materialized on the client (and must wait for the server // response instead). if (isClient && NoClient(newState, { game })) { return state; } state = newState; // If we're on the client, just process the move // and no triggers in multiplayer mode. // These will be processed on the server, which // will send back a state update. if (isClient) { state = Flush(state, { game, isClient: true, }); return state; } const prevTurnCount = state.ctx.turn; // Allow the flow reducer to process any triggers that happen after moves. state = game.flow.processMove(state, action.payload); state = Flush(state, { game }); // Update undo / redo state. // Only update undo stack if the turn has not been ended if (state.ctx.turn === prevTurnCount && !game.disableUndo) { state._undo = state._undo.concat({ G: state.G, ctx: state.ctx, moveType: action.payload.type, }); } // Always reset redo stack when making a move state._redo = []; return state; } case RESET: case UPDATE: case SYNC: { return action.state; } case UNDO: { if (game.disableUndo) { error("Undo is not enabled"); return state; } const { _undo, _redo } = state; if (_undo.length < 2) { return state; } const last = _undo[_undo.length - 1]; const restore = _undo[_undo.length - 2]; // Only allow undoable moves to be undone. const lastMove = game.flow.getMove(restore.ctx, last.moveType, action.payload.playerID); if (!CanUndoMove(state.G, state.ctx, lastMove)) { return state; } return { ...state, G: restore.G, ctx: restore.ctx, _undo: _undo.slice(0, _undo.length - 1), _redo: [last, ..._redo], }; } case REDO: { const { _undo, _redo } = state; if (game.disableUndo) { error("Redo is not enabled"); return state; } if (_redo.length == 0) { return state; } const first = _redo[0]; return { ...state, G: first.G, ctx: first.ctx, _undo: [..._undo, first], _redo: _redo.slice(1), }; } case PLUGIN: { return ProcessAction(state, action, { game }); } default: { return state; } } }; } /* * 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) { let r = null; if (this.prngstate) { r = new alea('', { state: this.prngstate }); } else { r = new alea(this.seed, { state: true }); } number = r(); this.prngstate = r.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 (let playerID in ctx.activePlayers) { actions = actions.concat(this.enumerate(G, ctx, playerID)); objectives = objectives.concat(this.objectives(G, ctx, playerID)); } } else { actions = actions.concat(this.enumerate(G, ctx, ctx.currentPlayer)); objectives = objectives.concat(this.objectives(G, ctx, ctx.currentPlayer)); } return { state, parent, parentAction, actions, objectives, children: [], visits: 0, value: 0, }; } select(node) { // This node has unvisited children. if (node.actions.length > 0) { return node; } // This is a terminal node. if (node.children.length == 0) { return node; } let selectedChild = null; let best = 0.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.0); // If so, stop and return the score. if (score > 0) { return { score }; } if (!moves || moves.length == 0) { return undefined; } const id = this.random(moves.length); const childState = this.reducer(state, moves[id]); state = childState; } return state.ctx.gameover; } backpropagate(node, result = {}) { node.visits++; if (result.score !== undefined) { node.value += result.score; } if (result.draw === true) { node.value += 0.5; } if (node.parentAction && result.winner === node.parentAction.payload.playerID) { node.value++; } if (node.parent) { this.backpropagate(node.parent, result); } } play(state, playerID) { const root = this.createNode({ state, playerID }); let numIterations = this.getOpt('iterations'); if (typeof this.iterations === 'function') { numIterations = this.iterations(state.G, state.ctx); } const getResult = () => { let selectedChild = null; for (const child of root.children) { if (selectedChild == null || child.visits > selectedChild.visits) { selectedChild = child; } } const action = selectedChild && selectedChild.parentAction; const metadata = root; return { action, metadata }; }; return new Promise(resolve => { const iteration = () => { for (let i = 0; i < CHUNK_SIZE && this.iterationCounter < numIterations; i++) { const leaf = this.select(root); const child = this.expand(leaf); const result = this.playout(child); this.backpropagate(child, result); this.iterationCounter++; } this.iterationCallback({ iterationCounter: this.iterationCounter, numIterations, metadata: root, }); }; this.iterationCounter = 0; if (this.getOpt('async')) { const asyncIteration = () => { if (this.iterationCounter < numIterations) { iteration(); setTimeout(asyncIteration, 0); } else { resolve(getResult()); } }; asyncIteration(); } else { while (this.iterationCounter < numIterations) { iteration(); } resolve(getResult()); } }); } } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Bot that picks a move at random. */ class RandomBot extends Bot { play({ G, ctx }, playerID) { const moves = this.enumerate(G, ctx, playerID); return Promise.resolve({ action: this.random(moves) }); } } /* * Copyright 2018 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Make a single move on the client with a bot. * * @param {...object} client - The game client. * @param {...object} bot - The bot. */ async function Step(client, bot) { const state = client.store.getState(); let playerID = state.ctx.currentPlayer; if (state.ctx.activePlayers) { playerID = Object.keys(state.ctx.activePlayers)[0]; } const { action, metadata } = await bot.play(state, playerID); if (action) { const a = { ...action, payload: { ...action.payload, metadata, }, }; client.store.dispatch(a); return a; } } /** * Simulates the game till the end or a max depth. * * @param {...object} game - The game object. * @param {...object} bots - An array of bots. * @param {...object} state - The game state to start from. */ async function Simulate({ game, bots, state, depth, }) { if (depth === undefined) depth = 10000; const reducer = CreateGameReducer({ game }); let metadata = null; let iter = 0; while (state.ctx.gameover === undefined && iter < depth) { let playerID = state.ctx.currentPlayer; if (state.ctx.activePlayers) { playerID = Object.keys(state.ctx.activePlayers)[0]; } const bot = bots instanceof Bot ? bots : bots[playerID]; const t = await bot.play(state, playerID); if (!t.action) { break; } metadata = t.metadata; state = reducer(state, t.action); iter++; } return { state, metadata }; } /* src/client/debug/ai/AI.svelte generated by Svelte v3.12.1 */ function add_css$i() { var style = element("style"); style.id = 'svelte-hsd9fq-style'; style.textContent = "li.svelte-hsd9fq{list-style:none;margin:none;margin-bottom:5px}h3.svelte-hsd9fq{text-transform:uppercase}label.svelte-hsd9fq{font-weight:bold;color:#999}input[type='checkbox'].svelte-hsd9fq{vertical-align:middle}"; append(document.head, style); } function get_each_context$7(ctx, list, i) { const child_ctx = Object.create(ctx); child_ctx.bot = list[i]; return child_ctx; } // (193:4) {:else} function create_else_block$2(ctx) { var p0, t_1, p1; return { c() { p0 = element("p"); p0.textContent = "No bots available."; t_1 = 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, t_1, anchor); insert(target, p1, anchor); }, p: noop, i: noop, o: noop, d(detaching) { if (detaching) { detach(p0); detach(t_1); detach(p1); } } }; } // (191:4) {#if client.multiplayer} function create_if_block_5(ctx) { var 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); } } }; } // (145:2) {#if client.game.ai && !client.multiplayer} function create_if_block$9(ctx) { var section0, h30, t1, li0, t2, li1, t3, li2, t4, section1, h31, t6, select, t7, show_if = Object.keys(ctx.bot.opts()).length, t8, if_block1_anchor, current, dispose; var hotkey0 = new Hotkey({ props: { value: "1", onPress: ctx.Reset, label: "reset" } }); var hotkey1 = new Hotkey({ props: { value: "2", onPress: ctx.Step, label: "play" } }); var hotkey2 = new Hotkey({ props: { value: "3", onPress: ctx.Simulate, label: "simulate" } }); let each_value = Object.keys(ctx.bots); 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)); } var if_block0 = (show_if) && create_if_block_4(ctx); var if_block1 = (ctx.botAction || ctx.iterationCounter) && create_if_block_1$4(ctx); return { c() { section0 = element("section"); h30 = element("h3"); h30.textContent = "Controls"; t1 = space(); li0 = element("li"); hotkey0.$$.fragment.c(); t2 = space(); li1 = element("li"); hotkey1.$$.fragment.c(); t3 = space(); li2 = element("li"); hotkey2.$$.fragment.c(); 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-hsd9fq"); attr(li0, "class", "svelte-hsd9fq"); attr(li1, "class", "svelte-hsd9fq"); attr(li2, "class", "svelte-hsd9fq"); attr(h31, "class", "svelte-hsd9fq"); if (ctx.selectedBot === void 0) add_render_callback(() => ctx.select_change_handler.call(select)); dispose = [ listen(select, "change", ctx.select_change_handler), listen(select, "change", ctx.ChangeBot) ]; }, m(target, anchor) { insert(target, section0, anchor); append(section0, h30); append(section0, t1); append(section0, li0); mount_component(hotkey0, li0, null); append(section0, t2); append(section0, li1); mount_component(hotkey1, li1, null); append(section0, t3); append(section0, 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, ctx.selectedBot); 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; }, p(changed, ctx) { if (changed.bots) { each_value = Object.keys(ctx.bots); 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(changed, child_ctx); } else { each_blocks[i] = create_each_block$7(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 (changed.selectedBot) select_option(select, ctx.selectedBot); if (changed.bot) show_if = Object.keys(ctx.bot.opts()).length; if (show_if) { if (if_block0) { if_block0.p(changed, ctx); 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 (ctx.botAction || ctx.iterationCounter) { if (if_block1) { if_block1.p(changed, ctx); } else { if_block1 = create_if_block_1$4(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); 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); } run_all(dispose); } }; } // (162:8) {#each Object.keys(bots) as bot} function create_each_block$7(ctx) { var option, t_value = ctx.bot + "", t; return { c() { option = element("option"); t = text(t_value); option.__value = ctx.bot; option.value = option.__value; }, m(target, anchor) { insert(target, option, anchor); append(option, t); }, p: noop, d(detaching) { if (detaching) { detach(option); } } }; } // (168:4) {#if Object.keys(bot.opts()).length} function create_if_block_4(ctx) { var section, h3, t1, label, t3, input, t4, current, dispose; var options = new Options({ props: { bot: ctx.bot } }); 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(); options.$$.fragment.c(); attr(h3, "class", "svelte-hsd9fq"); attr(label, "class", "svelte-hsd9fq"); attr(input, "type", "checkbox"); attr(input, "class", "svelte-hsd9fq"); dispose = [ listen(input, "change", ctx.input_change_handler), listen(input, "change", ctx.OnDebug) ]; }, m(target, anchor) { insert(target, section, anchor); append(section, h3); append(section, t1); append(section, label); append(section, t3); append(section, input); input.checked = ctx.debug; append(section, t4); mount_component(options, section, null); current = true; }, p(changed, ctx) { if (changed.debug) input.checked = ctx.debug; var options_changes = {}; if (changed.bot) options_changes.bot = ctx.bot; 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); run_all(dispose); } }; } // (177:4) {#if botAction || iterationCounter} function create_if_block_1$4(ctx) { var section, h3, t1, t2; var if_block0 = (ctx.progress && ctx.progress < 1.0) && create_if_block_3(ctx); var if_block1 = (ctx.botAction) && create_if_block_2$2(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-hsd9fq"); }, 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(changed, ctx) { if (ctx.progress && ctx.progress < 1.0) { if (if_block0) { if_block0.p(changed, ctx); } else { if_block0 = create_if_block_3(ctx); if_block0.c(); if_block0.m(section, t2); } } else if (if_block0) { if_block0.d(1); if_block0 = null; } if (ctx.botAction) { if (if_block1) { if_block1.p(changed, ctx); } else { if_block1 = create_if_block_2$2(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(); } }; } // (180:6) {#if progress && progress < 1.0} function create_if_block_3(ctx) { var progress_1; return { c() { progress_1 = element("progress"); progress_1.value = ctx.progress; }, m(target, anchor) { insert(target, progress_1, anchor); }, p(changed, ctx) { if (changed.progress) { progress_1.value = ctx.progress; } }, d(detaching) { if (detaching) { detach(progress_1); } } }; } // (184:6) {#if botAction} function create_if_block_2$2(ctx) { var li0, t0, t1, t2, li1, t3, t4_value = JSON.stringify(ctx.botActionArgs) + "", t4; return { c() { li0 = element("li"); t0 = text("Action: "); t1 = text(ctx.botAction); t2 = space(); li1 = element("li"); t3 = text("Args: "); t4 = text(t4_value); attr(li0, "class", "svelte-hsd9fq"); attr(li1, "class", "svelte-hsd9fq"); }, m(target, anchor) { insert(target, li0, anchor); append(li0, t0); append(li0, t1); insert(target, t2, anchor); insert(target, li1, anchor); append(li1, t3); append(li1, t4); }, p(changed, ctx) { if (changed.botAction) { set_data(t1, ctx.botAction); } if ((changed.botActionArgs) && t4_value !== (t4_value = JSON.stringify(ctx.botActionArgs) + "")) { set_data(t4, t4_value); } }, d(detaching) { if (detaching) { detach(li0); detach(t2); detach(li1); } } }; } function create_fragment$k(ctx) { var section, current_block_type_index, if_block, current, dispose; var if_block_creators = [ create_if_block$9, create_if_block_5, create_else_block$2 ]; var if_blocks = []; function select_block_type(changed, ctx) { if (ctx.client.game.ai && !ctx.client.multiplayer) return 0; if (ctx.client.multiplayer) return 1; return 2; } current_block_type_index = select_block_type(null, 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(); dispose = listen(window, "keydown", ctx.OnKeyDown); }, m(target, anchor) { insert(target, section, anchor); if_blocks[current_block_type_index].m(section, null); current = true; }, p(changed, ctx) { var previous_block_index = current_block_type_index; current_block_type_index = select_block_type(changed, ctx); if (current_block_type_index === previous_block_index) { if_blocks[current_block_type_index].p(changed, ctx); } else { group_outros(); transition_out(if_blocks[previous_block_index], 1, 1, () => { if_blocks[previous_block_index] = null; }); check_outros(); if_block = if_blocks[current_block_type_index]; if (!if_block) { if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx); if_block.c(); } transition_in(if_block, 1); if_block.m(section, null); } }, i(local) { if (current) return; transition_in(if_block); current = true; }, o(local) { transition_out(if_block); current = false; }, d(detaching) { if (detaching) { detach(section); } if_blocks[current_block_type_index].d(); dispose(); } }; } function instance$k($$self, $$props, $$invalidate) { let { client } = $$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('iterationCounter', iterationCounter = c); $$invalidate('progress', 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) { $$invalidate('bot', 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('bot', bot = new botConstructor({ game: client.game, enumerate: client.game.ai.enumerate, iterationCallback, })); bot.setOpt('async', true); $$invalidate('botAction', botAction = null); metadata = null; secondaryPane.set(null); $$invalidate('iterationCounter', iterationCounter = 0); } async function Step$1() { $$invalidate('botAction', botAction = null); metadata = null; $$invalidate('iterationCounter', iterationCounter = 0); const t = await Step(client, bot); if (t) { $$invalidate('botAction', botAction = t.payload.type); $$invalidate('botActionArgs', botActionArgs = t.payload.args); } } function Simulate(iterations = 10000, sleepTimeout = 100) { $$invalidate('botAction', botAction = null); metadata = null; $$invalidate('iterationCounter', 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('debug', debug = false); } function Reset() { client.reset(); $$invalidate('botAction', botAction = null); metadata = null; $$invalidate('iterationCounter', iterationCounter = 0); Exit(); } function OnKeyDown(e) { // ESC. if (e.keyCode == 27) { Exit(); } } onDestroy(Exit); function select_change_handler() { selectedBot = select_value(this); $$invalidate('selectedBot', selectedBot); $$invalidate('bots', bots); } function input_change_handler() { debug = this.checked; $$invalidate('debug', debug); } $$self.$set = $$props => { if ('client' in $$props) $$invalidate('client', client = $$props.client); }; return { client, bots, debug, progress, iterationCounter, OnDebug, bot, selectedBot, botAction, botActionArgs, ChangeBot, Step: Step$1, Simulate, Reset, OnKeyDown, select_change_handler, input_change_handler }; } class AI extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-hsd9fq-style")) add_css$i(); init(this, options, instance$k, create_fragment$k, safe_not_equal, ["client"]); } } /* src/client/debug/Debug.svelte generated by Svelte v3.12.1 */ function add_css$j() { var style = element("style"); style.id = 'svelte-1h5kecx-style'; style.textContent = ".debug-panel.svelte-1h5kecx{position:fixed;color:#555;font-family:monospace;display:flex;flex-direction:row;text-align:left;right:0;top:0;height:100%;font-size:14px;box-sizing:border-box;opacity:0.9}.pane.svelte-1h5kecx{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-1h5kecx{background:#fefefe;overflow-y:scroll}.debug-panel.svelte-1h5kecx button, select{cursor:pointer;outline:none;background:#eee;border:1px solid #bbb;color:#555;padding:3px;border-radius:3px}.debug-panel.svelte-1h5kecx button{padding-left:10px;padding-right:10px}.debug-panel.svelte-1h5kecx button:hover{background:#ddd}.debug-panel.svelte-1h5kecx button:active{background:#888;color:#fff}.debug-panel.svelte-1h5kecx section{margin-bottom:20px}"; append(document.head, style); } // (112:0) {#if visible} function create_if_block$a(ctx) { var div1, t0, div0, t1, div1_transition, current; var menu = new Menu({ props: { panes: ctx.panes, pane: ctx.pane } }); menu.$on("change", ctx.MenuChange); var switch_value = ctx.panes[ctx.pane].component; function switch_props(ctx) { return { props: { client: ctx.client } }; } if (switch_value) { var switch_instance = new switch_value(switch_props(ctx)); } var if_block = (ctx.$secondaryPane) && create_if_block_1$5(ctx); return { c() { div1 = element("div"); menu.$$.fragment.c(); t0 = space(); div0 = element("div"); if (switch_instance) switch_instance.$$.fragment.c(); t1 = space(); if (if_block) if_block.c(); attr(div0, "class", "pane svelte-1h5kecx"); attr(div1, "class", "debug-panel svelte-1h5kecx"); }, m(target, anchor) { insert(target, div1, anchor); mount_component(menu, div1, null); append(div1, t0); append(div1, div0); if (switch_instance) { mount_component(switch_instance, div0, null); } append(div1, t1); if (if_block) if_block.m(div1, null); current = true; }, p(changed, ctx) { var menu_changes = {}; if (changed.pane) menu_changes.pane = ctx.pane; menu.$set(menu_changes); var switch_instance_changes = {}; if (changed.client) switch_instance_changes.client = ctx.client; if (switch_value !== (switch_value = ctx.panes[ctx.pane].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)); switch_instance.$$.fragment.c(); 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 (ctx.$secondaryPane) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block_1$5(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(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 }, true); div1_transition.run(1); }); current = true; }, o(local) { transition_out(menu.$$.fragment, local); if (switch_instance) transition_out(switch_instance.$$.fragment, local); transition_out(if_block); if (!div1_transition) div1_transition = create_bidirectional_transition(div1, fly, { x: 400 }, false); div1_transition.run(0); current = false; }, d(detaching) { if (detaching) { detach(div1); } destroy_component(menu); if (switch_instance) destroy_component(switch_instance); if (if_block) if_block.d(); if (detaching) { if (div1_transition) div1_transition.end(); } } }; } // (118:4) {#if $secondaryPane} function create_if_block_1$5(ctx) { var div, current; var switch_value = ctx.$secondaryPane.component; function switch_props(ctx) { return { props: { metadata: ctx.$secondaryPane.metadata } }; } if (switch_value) { var switch_instance = new switch_value(switch_props(ctx)); } return { c() { div = element("div"); if (switch_instance) switch_instance.$$.fragment.c(); attr(div, "class", "secondary-pane svelte-1h5kecx"); }, m(target, anchor) { insert(target, div, anchor); if (switch_instance) { mount_component(switch_instance, div, null); } current = true; }, p(changed, ctx) { var switch_instance_changes = {}; if (changed.$secondaryPane) switch_instance_changes.metadata = ctx.$secondaryPane.metadata; if (switch_value !== (switch_value = ctx.$secondaryPane.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)); switch_instance.$$.fragment.c(); 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$l(ctx) { var if_block_anchor, current, dispose; var if_block = (ctx.visible) && create_if_block$a(ctx); return { c() { if (if_block) if_block.c(); if_block_anchor = empty(); dispose = listen(window, "keypress", ctx.Keypress); }, m(target, anchor) { if (if_block) if_block.m(target, anchor); insert(target, if_block_anchor, anchor); current = true; }, p(changed, ctx) { if (ctx.visible) { if (if_block) { if_block.p(changed, ctx); transition_in(if_block, 1); } else { if_block = create_if_block$a(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); } dispose(); } }; } function instance$l($$self, $$props, $$invalidate) { let $secondaryPane; let { client } = $$props; 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 => { $secondaryPane = $$value; $$invalidate('$secondaryPane', $secondaryPane); }); setContext('hotkeys', { disableHotkeys }); setContext('secondaryPane', { secondaryPane }); let pane = 'main'; function MenuChange(e) { $$invalidate('pane', pane = e.detail); } let visible = true; function Keypress(e) { // Toggle debugger visibilty if (e.key == '.') { $$invalidate('visible', visible = !visible); return; } // Set displayed pane if (!visible) return; Object.entries(panes).forEach(([key, { shortcut }]) => { if (e.key == shortcut) { $$invalidate('pane', pane = key); } }); } $$self.$set = $$props => { if ('client' in $$props) $$invalidate('client', client = $$props.client); }; return { client, panes, secondaryPane, pane, MenuChange, visible, Keypress, $secondaryPane }; } class Debug extends SvelteComponent { constructor(options) { super(); if (!document.getElementById("svelte-1h5kecx-style")) add_css$j(); init(this, options, instance$l, create_fragment$l, safe_not_equal, ["client"]); } } /* * 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; } let ctx = game.flow.ctx(numPlayers); let state = { // User managed state. G: {}, // Framework managed state. ctx, // Plugin related state. plugins: {}, }; // Run plugins over initial state. state = Setup(state, { game }); state = Enhance(state, { game, playerID: undefined }); const enhancedCtx = EnhanceCtx(state); state.G = game.setup(enhancedCtx, setupData); let initial = { ...state, // List of {G, ctx} pairs that can be undone. _undo: [], // List of {G, ctx} pairs that can be redone. _redo: [], // A monotonically non-decreasing ID to ensure that // state updates are only allowed from clients that // are at the same version that the server. _stateID: 0, }; initial = game.flow.init(initial); initial = Flush(initial, { game }); 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. */ /** * createDispatchers * * Create action dispatcher wrappers with bound playerID and credentials */ function createDispatchers(storeActionType, innerActionNames, store, playerID, credentials, multiplayer) { return innerActionNames.reduce((dispatchers, name) => { dispatchers[name] = function (...args) { let assumedPlayerID = playerID; // 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(); assumedPlayerID = state.ctx.currentPlayer; } store.dispatch(ActionCreators[storeActionType](name, args, assumedPlayerID, credentials)); }; return dispatchers; }, {}); } // Creates a set of dispatchers to make moves. const createMoveDispatchers = createDispatchers.bind(null, 'makeMove'); // Creates a set of dispatchers to dispatch game flow events. const createEventDispatchers = createDispatchers.bind(null, 'gameEvent'); // Creates a set of dispatchers to dispatch actions to plugins. const createPluginDispatchers = createDispatchers.bind(null, 'plugin'); /** * Implementation of Client (see below). */ class _ClientImpl { constructor({ game, debug, numPlayers, multiplayer, gameID, playerID, credentials, enhancer, }) { this.game = ProcessGameConfig(game); this.playerID = playerID; this.gameID = gameID; this.credentials = credentials; this.multiplayer = multiplayer; this.debug = debug; 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 = () => { this.store.dispatch(undo(this.playerID, this.credentials)); }; this.redo = () => { this.store.dispatch(redo(this.playerID, this.credentials)); }; this.store = null; 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: { const deltalog = state.deltalog; this.log = [...this.log, ...deltalog]; break; } case RESET: { this.log = []; break; } case UPDATE: { let id = -1; if (this.log.length > 0) { id = this.log[this.log.length - 1]._stateID; } let deltalog = action.deltalog || []; // Filter out actions that are already present // in the current log. This may occur when the // client adds an entry to the log followed by // the update from the master here. deltalog = deltalog.filter(l => l._stateID > id); this.log = [...this.log, ...deltalog]; break; } case SYNC: { this.initialState = action.initialState; this.log = action.log || []; break; } } return result; }; /** * Middleware that intercepts actions and sends them to the master, * which keeps the authoritative version of the state. */ const TransportMiddleware = (store) => (next) => (action) => { const baseState = store.getState(); const result = next(action); if (!('clientOnly' in action)) { this.transport.onAction(baseState, action); } return result; }; /** * Middleware that intercepts actions and invokes the subscription callback. */ const SubscriptionMiddleware = () => (next) => (action) => { const result = next(action); this.notifySubscribers(); return result; }; if (enhancer !== undefined) { enhancer = compose(applyMiddleware(SubscriptionMiddleware, TransportMiddleware, LogMiddleware), enhancer); } else { enhancer = applyMiddleware(SubscriptionMiddleware, TransportMiddleware, LogMiddleware); } this.store = createStore(this.reducer, this.initialState, enhancer); this.transport = { isConnected: true, onAction: () => { }, subscribe: () => { }, subscribeGameMetadata: () => { }, connect: () => { }, disconnect: () => { }, updateGameID: () => { }, updatePlayerID: () => { }, }; if (multiplayer) { // typeof multiplayer is 'function' this.transport = multiplayer({ gameKey: game, game: this.game, store: this.store, gameID, playerID, gameName: this.game.name, numPlayers, }); } this.createDispatchers(); this.transport.subscribeGameMetadata(metadata => { this.gameMetadata = metadata; }); this._debugPanel = null; } notifySubscribers() { Object.values(this.subscribers).forEach(fn => fn(this.getState())); } overrideGameState(state) { this.gameStateOverride = state; this.notifySubscribers(); } start() { this.transport.connect(); this._running = true; let debugImpl = null; if (process.env.NODE_ENV !== 'production') { debugImpl = Debug; } if (this.debug && this.debug !== true && this.debug.impl) { debugImpl = this.debug.impl; } if (debugImpl !== null && this.debug !== false && this._debugPanel == null && typeof document !== 'undefined') { let target = document.body; if (this.debug && this.debug !== true && this.debug.target !== undefined) { target = this.debug.target; } if (target) { this._debugPanel = new debugImpl({ target, props: { client: this, }, }); } } } stop() { this.transport.disconnect(); this._running = false; if (this._debugPanel != null) { this._debugPanel.$destroy(); this._debugPanel = null; } } subscribe(fn) { const id = Object.keys(this.subscribers).length; this.subscribers[id] = fn; this.transport.subscribe(() => this.notifySubscribers()); if (this._running || !this.multiplayer) { fn(this.getState()); } // Return a handle that allows the caller to unsubscribe. return () => { delete this.subscribers[id]; }; } getInitialState() { return this.initialState; } getState() { let state = this.store.getState(); if (this.gameStateOverride !== null) { state = this.gameStateOverride; } // This is the state before a sync with the game master. if (state === null) { return state; } // isActive. let isActive = true; const isPlayerActive = this.game.flow.isPlayerActive(state.G, state.ctx, this.playerID); if (this.multiplayer && !isPlayerActive) { isActive = false; } if (!this.multiplayer && this.playerID !== null && this.playerID !== undefined && !isPlayerActive) { isActive = false; } if (state.ctx.gameover !== undefined) { isActive = false; } // Secrets are normally stripped on the server, // but we also strip them here so that game developers // can see their effects while prototyping. const G = this.game.playerView(state.G, state.ctx, this.playerID); // Combine into return value. return { ...state, G, 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(); } updateGameID(gameID) { this.gameID = gameID; this.createDispatchers(); this.transport.updateGameID(gameID); this.notifySubscribers(); } updateCredentials(credentials) { this.credentials = credentials; this.createDispatchers(); 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} gameID - The gameID that you want to connect to. * @param {...object} playerID - The playerID associated with this client. * @param {...string} credentials - The authentication credentials associated with this client. * * Returns: * A JS object that provides an API to interact with the * game by dispatching moves and events. */ function Client(opts) { return new _ClientImpl(opts); } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ /** * Client * * boardgame.io React client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} debug - Enables the Debug UI. * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET, * UNDO and REDO. */ function Client$1(opts) { var _a; let { game, numPlayers, loading, board, multiplayer, enhancer, debug } = opts; // Component that is displayed before the client has synced // with the game master. if (loading === undefined) { const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting..."); loading = Loading; } /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _a = class WrappedBoard extends React.Component { constructor(props) { super(props); if (debug === undefined) { debug = props.debug; } this.client = Client({ game, debug, numPlayers, multiplayer, 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; } /** * Client * * boardgame.io React Native client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React Native component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE. */ function Client$2(opts) { var _class, _temp; var game = opts.game, numPlayers = opts.numPlayers, board = opts.board, multiplayer = opts.multiplayer, enhancer = opts.enhancer; /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _temp = _class = /*#__PURE__*/ function (_React$Component) { _inherits(WrappedBoard, _React$Component); function WrappedBoard(props) { var _this; _classCallCheck(this, WrappedBoard); _this = _possibleConstructorReturn(this, _getPrototypeOf(WrappedBoard).call(this, props)); _this.client = Client({ game: game, numPlayers: numPlayers, multiplayer: multiplayer, gameID: props.gameID, 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.gameID != this.props.gameID) { this.client.updateGameID(this.props.gameID); } if (prevProps.playerID != this.props.playerID) { this.client.updatePlayerID(this.props.playerID); } if (prevProps.credentials != this.props.credentials) { this.client.updateCredentials(this.props.credentials); } } }, { key: "render", value: function render() { var _board = null; var state = this.client.getState(); var _this$props = this.props, gameID = _this$props.gameID, playerID = _this$props.playerID, rest = _objectWithoutProperties(_this$props, ["gameID", "playerID"]); if (board) { _board = React.createElement(board, _objectSpread2({}, state, {}, rest, { gameID: gameID, 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, gameMetadata: this.client.gameMetadata })); } return _board; } }]); return WrappedBoard; }(React.Component), _defineProperty(_class, "propTypes", { // The ID of a game to connect to. // Only relevant in multiplayer. gameID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string }), _defineProperty(_class, "defaultProps", { gameID: 'default', playerID: null, credentials: null }), _temp; } var Type; (function (Type) { Type[Type["SYNC"] = 0] = "SYNC"; Type[Type["ASYNC"] = 1] = "ASYNC"; })(Type || (Type = {})); class Sync { type() { return Type.SYNC; } /** * Connect. */ connect() { return; } } /* * 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 game. */ createGame(gameID, opts) { this.initial.set(gameID, opts.initialState); this.setState(gameID, opts.initialState); this.setMetadata(gameID, opts.metadata); } /** * Write the game metadata to the in-memory object. */ setMetadata(gameID, metadata) { this.metadata.set(gameID, metadata); } /** * Write the game state to the in-memory object. */ setState(gameID, state, deltalog) { if (deltalog && deltalog.length > 0) { const log = this.log.get(gameID) || []; this.log.set(gameID, log.concat(deltalog)); } this.state.set(gameID, state); } /** * Fetches state for a particular gameID. */ fetch(gameID, opts) { let result = {}; if (opts.state) { result.state = this.state.get(gameID); } if (opts.metadata) { result.metadata = this.metadata.get(gameID); } if (opts.log) { result.log = this.log.get(gameID) || []; } if (opts.initialState) { result.initialState = this.initial.get(gameID); } return result; } /** * Remove the game state from the in-memory object. */ wipe(gameID) { this.state.delete(gameID); this.metadata.delete(gameID); } /** * Return all keys. */ listGames(opts) { if (opts && opts.gameName !== undefined) { let gameIDs = []; this.metadata.forEach((metadata, gameID) => { if (metadata.gameName === opts.gameName) { gameIDs.push(gameID); } }); return gameIDs; } return [...this.metadata.keys()]; } } /* * 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 getPlayerMetadata = (gameMetadata, playerID) => { if (gameMetadata && gameMetadata.players) { return gameMetadata.players[playerID]; } }; function IsSynchronous(storageAPI) { return storageAPI.type() === Type.SYNC; } /** * 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 }, }; /* eslint-disable-next-line no-unused-vars */ const { redact, ...remaining } = filteredEvent; return remaining; }); } /** * Verifies that the game has metadata and is using credentials. */ const doesGameRequireAuthentication = (gameMetadata) => { if (!gameMetadata) return false; const { players } = gameMetadata; const hasCredentials = Object.keys(players).some(key => { return !!(players[key] && players[key].credentials); }); return hasCredentials; }; /** * Verifies that the move came from a player with the correct credentials. */ const isActionFromAuthenticPlayer = (actionCredentials, playerMetadata) => { if (!actionCredentials) return false; if (!playerMetadata) return false; return actionCredentials === playerMetadata.credentials; }; /** * Remove player credentials from action payload */ const stripCredentialsFromAction = (action) => { // eslint-disable-next-line no-unused-vars 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.auth = null; this.subscribeCallback = () => { }; this.shouldAuth = () => false; if (auth === true) { this.auth = isActionFromAuthenticPlayer; this.shouldAuth = doesGameRequireAuthentication; } else if (typeof auth === 'function') { this.auth = auth; this.shouldAuth = () => true; } } 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, gameID, playerID) { let isActionAuthentic; let metadata; const credentials = credAction.payload.credentials; if (IsSynchronous(this.storageAPI)) { ({ metadata } = this.storageAPI.fetch(gameID, { metadata: true })); const playerMetadata = getPlayerMetadata(metadata, playerID); isActionAuthentic = this.shouldAuth(metadata) ? this.auth(credentials, playerMetadata) : true; } else { ({ metadata } = await this.storageAPI.fetch(gameID, { metadata: true, })); const playerMetadata = getPlayerMetadata(metadata, playerID); isActionAuthentic = this.shouldAuth(metadata) ? await this.auth(credentials, playerMetadata) : true; } if (!isActionAuthentic) { return { error: 'unauthorized action' }; } let action = stripCredentialsFromAction(credAction); const key = gameID; let state; let result; if (IsSynchronous(this.storageAPI)) { result = this.storageAPI.fetch(key, { state: true }); } else { result = await this.storageAPI.fetch(key, { state: true }); } state = result.state; if (state === undefined) { error(`game not found, gameID=[${key}]`); return { error: 'game not found' }; } if (state.ctx.gameover !== undefined) { error(`game over - gameID=[${key}]`); return; } const reducer = CreateGameReducer({ game: this.game, }); const store = createStore(reducer, state); // Only allow UNDO / REDO if there is exactly one player // that can make moves right now and the person doing the // action is that player. if (action.type == UNDO || action.type == REDO) { if (state.ctx.currentPlayer !== playerID || state.ctx.activePlayers !== null) { 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}]`); return; } // Check whether the player is allowed to make the move. if (action.type == MAKE_MOVE && !this.game.flow.getMove(state.ctx, action.payload.type, playerID)) { error(`move not processed - canPlayerMakeMove=false, playerID=[${playerID}]`); return; } if (state._stateID !== stateID) { error(`invalid stateID, was=[${stateID}], expected=[${state._stateID}]`); return; } // Update server's version of the store. store.dispatch(action); state = store.getState(); this.subscribeCallback({ state, action, gameID, }); this.transportAPI.sendAll((playerID) => { const filteredState = { ...state, G: this.game.playerView(state.G, state.ctx, playerID), deltalog: undefined, _undo: [], _redo: [], }; const log = redactLog(state.deltalog, playerID); return { type: 'update', args: [gameID, filteredState, log], }; }); const { deltalog, ...stateWithoutDeltalog } = state; let newMetadata; if (metadata && !('gameover' in metadata) && state.ctx.gameover !== undefined) { newMetadata = { ...metadata, 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(gameID, playerID, numPlayers) { const key = gameID; let state; let initialState; let log; let gameMetadata; let filteredMetadata; let result; if (IsSynchronous(this.storageAPI)) { result = this.storageAPI.fetch(key, { state: true, metadata: true, log: true, initialState: true, }); } else { result = await this.storageAPI.fetch(key, { state: true, metadata: true, log: true, initialState: true, }); } state = result.state; initialState = result.initialState; log = result.log; gameMetadata = result.metadata; if (gameMetadata) { filteredMetadata = Object.values(gameMetadata.players).map(player => { const { credentials, ...filteredData } = player; return filteredData; }); } // If the game doesn't exist, then create one on demand. // TODO: Move this out of the sync call. if (state === undefined) { initialState = state = InitializeGame({ game: this.game, numPlayers }); this.subscribeCallback({ state, gameID, }); if (IsSynchronous(this.storageAPI)) { this.storageAPI.setState(key, state); } else { await this.storageAPI.setState(key, state); } } const filteredState = { ...state, G: this.game.playerView(state.G, state.ctx, playerID), deltalog: undefined, _undo: [], _redo: [], }; log = redactLog(log, playerID); const syncInfo = { state: filteredState, log, filteredMetadata, initialState, }; this.transportAPI.send({ playerID, type: 'sync', args: [gameID, syncInfo], }); return; } } /* * Copyright 2017 The boardgame.io Authors * * Use of this source code is governed by a MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ class Transport { constructor({ store, gameName, playerID, gameID, numPlayers, }) { this.store = store; this.gameName = gameName || 'default'; this.playerID = playerID || null; this.gameID = gameID || 'default'; this.numPlayers = numPlayers || 2; } } /* * 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 }) { 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, type, args }) => { const callback = clientCallbacks[playerID]; if (callback !== undefined) { callback.apply(null, [type, ...args]); } }; const transportAPI = { send, sendAll: makePlayerData => { for (const playerID in clientCallbacks) { const data = makePlayerData(playerID); send({ playerID, ...data }); } }, }; super(game, new InMemory(), transportAPI, false); this.connect = (gameID, playerID, callback) => { clientCallbacks[playerID] = callback; }; this.subscribe(({ state, gameID }) => { 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, gameID, 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} gameID - The game ID to connect to. * @param {string} playerID - The player ID associated with this client. * @param {string} gameName - The game type (the `name` field in `Game`). * @param {string} numPlayers - The number of players. */ constructor({ master, store, gameID, playerID, gameName, numPlayers, }) { super({ store, gameName, playerID, gameID, numPlayers }); this.master = master; this.isConnected = true; } /** * Called when another player makes a move and the * master broadcasts the update to other clients (including * this one). */ async onUpdate(gameID, state, deltalog) { const currentState = this.store.getState(); if (gameID == this.gameID && state._stateID >= currentState._stateID) { const action = update$1(state, deltalog); this.store.dispatch(action); } } /** * Called when the client first connects to the master * and requests the current game state. */ onSync(gameID, syncInfo) { if (gameID == this.gameID) { const action = sync(syncInfo); this.store.dispatch(action); } } /** * Called when an action that has to be relayed to the * game master is made. */ onAction(state, action) { this.master.onUpdate(action, state._stateID, this.gameID, this.playerID); } /** * Connect to the master. */ connect() { this.master.connect(this.gameID, this.playerID, (type, ...args) => { if (type == 'sync') { this.onSync.apply(this, args); } if (type == 'update') { this.onUpdate.apply(this, args); } }); this.master.onSync(this.gameID, this.playerID, this.numPlayers); } /** * Disconnect from the master. */ disconnect() { } /** * Subscribe to connection state changes. */ subscribe() { } subscribeGameMetadata() { } /** * Updates the game id. * @param {string} id - The new game id. */ updateGameID(id) { this.gameID = id; const action = reset(null); this.store.dispatch(action); this.connect(); } /** * Updates the player associated with this client. * @param {string} id - The new player id. */ updatePlayerID(id) { this.playerID = id; const action = reset(null); this.store.dispatch(action); this.connect(); } } const localMasters = new Map(); function Local(opts) { return (transportOpts) => { let master; if (localMasters.has(transportOpts.gameKey) && !opts) { master = localMasters.get(transportOpts.gameKey); } else { master = new LocalMaster({ game: transportOpts.game, bots: opts && opts.bots, }); localMasters.set(transportOpts.gameKey, master); } 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. */ /** * SocketIO * * Transport interface that interacts with the Master via socket.io. */ class SocketIOTransport extends Transport { /** * Creates a new Mutiplayer instance. * @param {object} socket - Override for unit tests. * @param {object} socketOpts - Options to pass to socket.io. * @param {string} gameID - The game ID to connect to. * @param {string} playerID - The player ID associated with this client. * @param {string} gameName - The game type (the `name` field in `Game`). * @param {string} numPlayers - The number of players. * @param {string} server - The game server in the form of 'hostname:port'. Defaults to the server serving the client if not provided. */ constructor({ socket, socketOpts, store, gameID, playerID, gameName, numPlayers, server, } = {}) { super({ store, gameName, playerID, gameID, numPlayers }); this.server = server; this.socket = socket; this.socketOpts = socketOpts; this.isConnected = false; this.callback = () => { }; this.gameMetadataCallback = () => { }; } /** * Called when an action that has to be relayed to the * game master is made. */ onAction(state, action) { this.socket.emit('update', action, state._stateID, this.gameID, this.playerID); } /** * Connect to the server. */ connect() { if (!this.socket) { if (this.server) { let server = this.server; if (server.search(/^https?:\/\//) == -1) { server = 'http://' + this.server; } if (server.substr(-1) != '/') { // add trailing slash if not already present server = server + '/'; } this.socket = io(server + this.gameName, this.socketOpts); } else { this.socket = io('/' + this.gameName, this.socketOpts); } } // Called when another player makes a move and the // master broadcasts the update to other clients (including // this one). this.socket.on('update', (gameID, state, deltalog) => { const currentState = this.store.getState(); if (gameID == this.gameID && state._stateID >= currentState._stateID) { const action = update$1(state, deltalog); this.store.dispatch(action); } }); // Called when the client first connects to the master // and requests the current game state. this.socket.on('sync', (gameID, syncInfo) => { if (gameID == this.gameID) { const action = sync(syncInfo); this.gameMetadataCallback(syncInfo.filteredMetadata); this.store.dispatch(action); } }); // Keep track of connection status. this.socket.on('connect', () => { // Initial sync to get game state. this.socket.emit('sync', this.gameID, this.playerID, this.numPlayers); this.isConnected = true; this.callback(); }); this.socket.on('disconnect', () => { this.isConnected = false; this.callback(); }); } /** * Disconnect from the server. */ disconnect() { this.socket.close(); this.socket = null; this.isConnected = false; this.callback(); } /** * Subscribe to connection state changes. */ subscribe(fn) { this.callback = fn; } subscribeGameMetadata(fn) { this.gameMetadataCallback = fn; } /** * Updates the game id. * @param {string} id - The new game id. */ updateGameID(id) { this.gameID = id; const action = reset(null); this.store.dispatch(action); if (this.socket) { this.socket.emit('sync', this.gameID, this.playerID, this.numPlayers); } } /** * Updates the player associated with this client. * @param {string} id - The new player id. */ updatePlayerID(id) { this.playerID = id; const action = reset(null); this.store.dispatch(action); if (this.socket) { this.socket.emit('sync', this.gameID, this.playerID, this.numPlayers); } } } 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/primereact/6.6.0/treetable/treetable.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, classNames, OverlayService, ObjectUtils, Ripple, FilterUtils } from 'primereact/core'; import { Paginator } from 'primereact/paginator'; import { InputText } from 'primereact/inputtext'; 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; } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$3(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } 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 _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$3(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 _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 _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.hasClass(targetNode, 'p-sortable-column') || DomHandler.hasClass(targetNode, 'p-column-title') || DomHandler.hasClass(targetNode, 'p-sortable-column-icon') || DomHandler.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.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 }); _this2.filterTimeout = null; }, this.props.filterDelay); } } }, { key: "hasColumnFilter", value: function hasColumnFilter(columns) { if (columns) { var _iterator = _createForOfIteratorHelper$2(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 _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.editorValidator) { var valid = this.props.editorValidator({ 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.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 = this.props.editor(this.props);else throw new Error("Editor is not found on column."); } else { if (this.props.body) content = this.props.body(this.props.node, 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$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 ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$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$1({}, 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$1({}, 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({ originalEvent: event, node: this.props.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()) && this.props.node.selectable !== false) { var selectionKeys; var selected = this.isSelected(); var metaSelection = this.nodeTouched ? false : this.props.metaKeySelection; 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[this.props.node.key]; } if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: this.props.node }); } } else { if (this.isSingleSelectionMode()) { selectionKeys = this.props.node.key; } else if (this.isMultipleSelectionMode()) { selectionKeys = !metaKey ? {} : this.props.selectionKeys ? _objectSpread$1({}, this.props.selectionKeys) : {}; selectionKeys[this.props.node.key] = true; } if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: this.props.node }); } } } else { if (this.isSingleSelectionMode()) { if (selected) { selectionKeys = null; if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: this.props.node }); } } else { selectionKeys = this.props.node.key; if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: this.props.node }); } } } else { if (selected) { selectionKeys = _objectSpread$1({}, this.props.selectionKeys); delete selectionKeys[this.props.node.key]; if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: this.props.node }); } } else { selectionKeys = this.props.selectionKeys ? _objectSpread$1({}, this.props.selectionKeys) : {}; selectionKeys[this.props.node.key] = true; if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: this.props.node }); } } } } if (this.props.onSelectionChange) { this.props.onSelectionChange({ originalEvent: event, value: selectionKeys }); } } 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$1({}, 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.clearSelection(); } }, { key: "onCheckboxFocus", value: function onCheckboxFocus() { DomHandler.addClass(this.checkboxBox, 'p-focus'); } }, { key: "onCheckboxBlur", value: function onCheckboxBlur() { DomHandler.removeClass(this.checkboxBox, 'p-focus'); } }, { key: "propagateUp", value: function propagateUp(event) { var check = event.check; var selectionKeys = event.selectionKeys; var checkedChildCount = 0; var childPartialSelected = false; var _iterator = _createForOfIteratorHelper$1(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.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: "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: "isExpanded", value: function isExpanded() { return this.props.expandedKeys ? this.props.expandedKeys[this.props.node.key] !== undefined : false; } }, { key: "isSelected", value: function isSelected() { if ((this.props.selectionMode === 'single' || this.props.selectionMode === 'multiple') && this.props.selectionKeys) return this.props.selectionMode === 'single' ? this.props.selectionKeys === this.props.node.key : this.props.selectionKeys[this.props.node.key] !== undefined;else return false; } }, { key: "isChecked", value: function isChecked() { return this.props.selectionKeys ? this.props.selectionKeys[this.props.node.key] && this.props.selectionKeys[this.props.node.key].checked : false; } }, { key: "isPartialChecked", value: function isPartialChecked() { return this.props.selectionKeys ? this.props.selectionKeys[this.props.node.key] && this.props.selectionKeys[this.props.node.key].partialChecked : false; } }, { key: "renderToggler", value: function renderToggler() { var expanded = this.isExpanded(); var iconClassName = classNames('"p-treetable-toggler-icon pi pi-fw', { 'pi-chevron-right': !expanded, 'pi-chevron-down': expanded }); var style = { marginLeft: this.props.level * 16 + 'px', visibility: this.props.node.leaf === false || this.props.node.children && this.props.node.children.length ? 'visible' : 'hidden' }; return /*#__PURE__*/React.createElement("button", { type: "button", className: "p-treetable-toggler p-link p-unselectable-text", onClick: this.onTogglerClick, tabIndex: -1, style: style }, /*#__PURE__*/React.createElement("i", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); } }, { key: "renderCheckbox", value: function renderCheckbox() { var _this2 = this; if (this.props.selectionMode === 'checkbox' && this.props.node.selectable !== false) { var checked = this.isChecked(); var partialChecked = this.isPartialChecked(); var className = classNames('p-checkbox-box', { 'p-highlight': checked, 'p-indeterminate': partialChecked }); var icon = classNames('p-checkbox-icon p-c', { 'pi pi-check': checked, 'pi pi-minus': partialChecked }); return /*#__PURE__*/React.createElement("div", { className: "p-checkbox p-treetable-checkbox p-component", onClick: this.onCheckboxChange, role: "checkbox", "aria-checked": checked }, /*#__PURE__*/React.createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React.createElement("input", { type: "checkbox", onFocus: this.onCheckboxFocus, onBlur: this.onCheckboxBlur })), /*#__PURE__*/React.createElement("div", { className: className, ref: function ref(el) { return _this2.checkboxBox = el; } }, /*#__PURE__*/React.createElement("span", { className: icon }))); } else { return null; } } }, { key: "renderCell", value: function renderCell(column) { var toggler, checkbox; if (column.props.expander) { toggler = this.renderToggler(); checkbox = this.renderCheckbox(); } return /*#__PURE__*/React.createElement(TreeTableBodyCell, _extends({ key: column.props.columnKey || column.props.field }, column.props, { selectOnEdit: this.props.selectOnEdit, selected: this.isSelected(), node: this.props.node, rowIndex: this.props.rowIndex }), toggler, checkbox); } }, { key: "renderChildren", value: function renderChildren() { var _this3 = this; if (this.isExpanded() && this.props.node.children) { return this.props.node.children.map(function (childNode, index) { return /*#__PURE__*/React.createElement(TreeTableRow, { key: childNode.key || JSON.stringify(childNode.data), level: _this3.props.level + 1, rowIndex: _this3.props.rowIndex + '_' + index, node: childNode, columns: _this3.props.columns, expandedKeys: _this3.props.expandedKeys, selectOnEdit: _this3.props.selectOnEdit, onToggle: _this3.props.onToggle, onExpand: _this3.props.onExpand, onCollapse: _this3.props.onCollapse, selectionMode: _this3.props.selectionMode, selectionKeys: _this3.props.selectionKeys, onSelectionChange: _this3.props.onSelectionChange, metaKeySelection: _this3.props.metaKeySelection, onRowClick: _this3.props.onRowClick, onSelect: _this3.props.onSelect, onUnselect: _this3.props.onUnselect, propagateSelectionUp: _this3.props.propagateSelectionUp, propagateSelectionDown: _this3.props.propagateSelectionDown, onPropagateUp: _this3.propagateUp, rowClassName: _this3.props.rowClassName, contextMenuSelectionKey: _this3.props.contextMenuSelectionKey, onContextMenuSelectionChange: _this3.props.onContextMenuSelectionChange, onContextMenu: _this3.props.onContextMenu }); }); } else { return null; } } }, { key: "render", value: function render() { var _this4 = this; var cells = this.props.columns.map(function (col) { return _this4.renderCell(col); }); var children = this.renderChildren(); var className = { 'p-highlight': this.isSelected(), 'p-highlight-contextmenu': this.props.contextMenuSelectionKey && this.props.contextMenuSelectionKey === this.props.node.key }; if (this.props.rowClassName) { var rowClassName = this.props.rowClassName(this.props.node); className = _objectSpread$1(_objectSpread$1({}, 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 _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() { _classCallCheck(this, TreeTableBody); return _super.apply(this, arguments); } _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.props.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: "renderRows", value: function renderRows() { var _this = 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 _this.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; return /*#__PURE__*/React.createElement("tr", null, /*#__PURE__*/React.createElement("td", { className: "p-treetable-emptymessage", colSpan: colSpan }, this.props.emptyMessage)); } } }, { 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: "No records found", 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.calculateScrollbarWidth(); this.scrollHeaderBox.style.marginRight = scrollBarWidth + 'px'; if (this.scrollFooterBox) { this.scrollFooterBox.style.marginRight = scrollBarWidth + 'px'; } } else { this.scrollBody.style.paddingBottom = DomHandler.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.getOuterHeight(datatableContainer); var relativeHeight = DomHandler.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.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.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.findSingle(this.scrollTable, 'tr:not(.p-treetable-emptymessage-row)'); if (row) { this.rowHeight = DomHandler.getOuterHeight(row); } } }, { key: "renderColGroup", value: function renderColGroup() { if (this.props.columns && this.props.columns.length) { return /*#__PURE__*/React.createElement("colgroup", { className: "p-treetable-scrollable-colgroup" }, this.props.columns.map(function (col, i) { return /*#__PURE__*/React.createElement("col", { key: col.field + '_' + i }); })); } else { return null; } } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-treetable-scrollable-view', { 'p-treetable-frozen-view': this.props.frozen, 'p-treetable-unfrozen-view': !this.props.frozen && this.props.frozenWidth }); var width = this.props.frozen ? this.props.frozenWidth : 'calc(100% - ' + this.props.frozenWidth + ')'; var left = this.props.frozen ? null : this.props.frozenWidth; var colGroup = this.renderColGroup(); var scrollableBodyStyle = !this.props.frozen && this.props.scrollHeight ? { overflowY: 'scroll' } : null; return /*#__PURE__*/React.createElement("div", { className: className, style: { width: width, left: left }, ref: function ref(el) { _this2.container = el; } }, /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-header", ref: function ref(el) { _this2.scrollHeader = el; }, onScroll: this.onHeaderScroll }, /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-header-box", ref: function ref(el) { _this2.scrollHeaderBox = el; } }, /*#__PURE__*/React.createElement("table", { className: "p-treetable-scrollable-header-table" }, colGroup, this.props.header))), /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-body", ref: function ref(el) { _this2.scrollBody = el; }, style: scrollableBodyStyle, onScroll: this.onBodyScroll }, /*#__PURE__*/React.createElement("table", { ref: function ref(el) { _this2.scrollTable = el; }, style: { top: '0' }, className: "p-treetable-scrollable-body-table" }, colGroup, this.props.body)), /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-footer", ref: function ref(el) { _this2.scrollFooter = el; } }, /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-footer-box", ref: function ref(el) { _this2.scrollFooterBox = el; } }, /*#__PURE__*/React.createElement("table", { className: "p-treetable-scrollable-footer-table" }, colGroup, this.props.footer)))); } }]); return TreeTableScrollableView; }(Component); _defineProperty(TreeTableScrollableView, "defaultProps", { header: null, body: null, footer: null, columns: null, frozen: null, frozenWidth: null, frozenBody: null }); function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TreeTable = /*#__PURE__*/function (_Component) { _inherits(TreeTable, _Component); var _super = _createSuper(TreeTable); function TreeTable(props) { var _this; _classCallCheck(this, TreeTable); _this = _super.call(this, props); var state = {}; if (!_this.props.onToggle) { _this.state = { expandedKeys: _this.props.expandedKeys }; } if (!_this.props.onPage) { state.first = props.first; state.rows = props.rows; } if (!_this.props.onSort) { state.sortField = props.sortField; state.sortOrder = props.sortOrder; state.multiSortMeta = props.multiSortMeta; } if (!_this.props.onFilter) { state.filters = props.filters; } if (Object.keys(state).length) { _this.state = state; } _this.onToggle = _this.onToggle.bind(_assertThisInitialized(_this)); _this.onPageChange = _this.onPageChange.bind(_assertThisInitialized(_this)); _this.onSort = _this.onSort.bind(_assertThisInitialized(_this)); _this.onFilter = _this.onFilter.bind(_assertThisInitialized(_this)); _this.onColumnResizeStart = _this.onColumnResizeStart.bind(_assertThisInitialized(_this)); _this.onColumnDragStart = _this.onColumnDragStart.bind(_assertThisInitialized(_this)); _this.onColumnDragOver = _this.onColumnDragOver.bind(_assertThisInitialized(_this)); _this.onColumnDragLeave = _this.onColumnDragLeave.bind(_assertThisInitialized(_this)); _this.onColumnDrop = _this.onColumnDrop.bind(_assertThisInitialized(_this)); return _this; } _createClass(TreeTable, [{ key: "onToggle", value: function onToggle(event) { if (this.props.onToggle) { this.props.onToggle(event); } else { this.setState({ expandedKeys: event.value }); } } }, { key: "onPageChange", value: function onPageChange(event) { if (this.props.onPage) this.props.onPage(event);else this.setState({ first: event.first, rows: event.rows }); } }, { key: "onSort", value: function onSort(event) { var sortField = event.sortField; var sortOrder = this.props.defaultSortOrder; var multiSortMeta; var eventMeta; this.columnSortable = event.sortable; this.columnSortFunction = event.sortFunction; this.columnField = event.sortField; if (this.props.sortMode === 'multiple') { var metaKey = event.originalEvent.metaKey || event.originalEvent.ctrlKey; multiSortMeta = this.getMultiSortMeta(); if (multiSortMeta && multiSortMeta instanceof Array) { var sortMeta = multiSortMeta.find(function (sortMeta) { return sortMeta.field === sortField; }); sortOrder = sortMeta ? this.getCalculatedSortOrder(sortMeta.order) : sortOrder; } var newMetaData = { field: sortField, order: sortOrder }; if (sortOrder) { if (!multiSortMeta || !metaKey) { multiSortMeta = []; } this.addSortMeta(newMetaData, multiSortMeta); } else if (this.props.removableSort && multiSortMeta) { this.removeSortMeta(newMetaData, multiSortMeta); } eventMeta = { multiSortMeta: multiSortMeta }; } else { sortOrder = this.getSortField() === sortField ? this.getCalculatedSortOrder(this.getSortOrder()) : sortOrder; if (this.props.removableSort) { sortField = sortOrder ? sortField : null; } eventMeta = { sortField: sortField, sortOrder: sortOrder }; } if (this.props.onSort) { this.props.onSort(eventMeta); } else { eventMeta.first = 0; this.setState(eventMeta); } } }, { key: "getCalculatedSortOrder", value: function getCalculatedSortOrder(currentOrder) { return this.props.removableSort ? this.props.defaultSortOrder === currentOrder ? currentOrder * -1 : 0 : currentOrder * -1; } }, { key: "addSortMeta", value: function addSortMeta(meta, multiSortMeta) { var index = -1; for (var i = 0; i < multiSortMeta.length; i++) { if (multiSortMeta[i].field === meta.field) { index = i; break; } } if (index >= 0) multiSortMeta[index] = meta;else multiSortMeta.push(meta); } }, { key: "removeSortMeta", value: function removeSortMeta(meta, multiSortMeta) { var index = -1; for (var i = 0; i < multiSortMeta.length; i++) { if (multiSortMeta[i].field === meta.field) { index = i; break; } } if (index >= 0) { multiSortMeta.splice(index, 1); } multiSortMeta = multiSortMeta.length > 0 ? multiSortMeta : null; } }, { key: "sortSingle", value: function sortSingle(data) { return this.sortNodes(data); } }, { key: "sortNodes", value: function sortNodes(data) { var _this2 = this; var value = _toConsumableArray(data); if (this.columnSortable && this.columnSortable === 'custom' && this.columnSortFunction) { value = this.columnSortFunction({ field: this.getSortField(), order: this.getSortOrder() }); } else { value.sort(function (node1, node2) { var sortField = _this2.getSortField(); var value1 = ObjectUtils.resolveFieldData(node1.data, sortField); var value2 = ObjectUtils.resolveFieldData(node2.data, sortField); var result = null; if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2, undefined, { numeric: true });else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0; return _this2.getSortOrder() * result; }); for (var i = 0; i < value.length; i++) { if (value[i].children && value[i].children.length) { value[i].children = this.sortNodes(value[i].children); } } } return value; } }, { key: "sortMultiple", value: function sortMultiple(data) { var multiSortMeta = this.getMultiSortMeta(); if (multiSortMeta) return this.sortMultipleNodes(data, multiSortMeta);else return data; } }, { key: "sortMultipleNodes", value: function sortMultipleNodes(data, multiSortMeta) { var _this3 = this; var value = _toConsumableArray(data); value.sort(function (node1, node2) { return _this3.multisortField(node1, node2, multiSortMeta, 0); }); for (var i = 0; i < value.length; i++) { if (value[i].children && value[i].children.length) { value[i].children = this.sortMultipleNodes(value[i].children, multiSortMeta); } } return value; } }, { key: "multisortField", value: function multisortField(node1, node2, multiSortMeta, index) { var value1 = ObjectUtils.resolveFieldData(node1.data, multiSortMeta[index].field); var value2 = ObjectUtils.resolveFieldData(node2.data, multiSortMeta[index].field); var result = null; if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else { if (value1 === value2) { return multiSortMeta.length - 1 > index ? this.multisortField(node1, node2, multiSortMeta, index + 1) : 0; } else { if ((typeof value1 === 'string' || value1 instanceof String) && (typeof value2 === 'string' || value2 instanceof String)) return multiSortMeta[index].order * value1.localeCompare(value2, undefined, { numeric: true });else result = value1 < value2 ? -1 : 1; } } return multiSortMeta[index].order * result; } }, { key: "filter", value: function filter(value, field, mode) { this.onFilter({ value: value, field: field, matchMode: mode }); } }, { key: "onFilter", value: function onFilter(event) { var currentFilters = this.getFilters(); var newFilters = currentFilters ? _objectSpread({}, currentFilters) : {}; if (!this.isFilterBlank(event.value)) newFilters[event.field] = { value: event.value, matchMode: event.matchMode };else if (newFilters[event.field]) delete newFilters[event.field]; if (this.props.onFilter) { this.props.onFilter({ filters: newFilters }); } else { this.setState({ first: 0, filters: newFilters }); } } }, { key: "hasFilter", value: function hasFilter() { var filters = this.getFilters(); return filters && Object.keys(filters).length > 0; } }, { key: "isFilterBlank", value: function isFilterBlank(filter) { if (filter !== null && filter !== undefined) { if (typeof filter === 'string' && filter.trim().length === 0 || filter instanceof Array && filter.length === 0) return true;else return false; } return true; } }, { key: "onColumnResizeStart", value: function onColumnResizeStart(event) { var containerLeft = DomHandler.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.getOffset(this.container).left; DomHandler.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.findSingle(scrollableView, 'table.p-treetable-scrollable-body-table'); var scrollableHeaderTable = DomHandler.findSingle(scrollableView, 'table.p-treetable-scrollable-header-table'); var scrollableFooterTable = DomHandler.findSingle(scrollableView, 'table.p-treetable-scrollable-footer-table'); var resizeColumnIndex = DomHandler.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.findSingle(_scrollableView, 'table.p-treetable-scrollable-body-table'); var _scrollableHeaderTable = DomHandler.findSingle(_scrollableView, 'table.p-treetable-scrollable-header-table'); var _scrollableFooterTable = DomHandler.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.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.removeClass(this.container, 'p-unselectable-text'); this.unbindColumnResizeEvents(); } }, { key: "findParentScrollableView", value: function findParentScrollableView(column) { if (column) { var parent = column.parentElement; while (parent && !DomHandler.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.getHiddenElementOuterWidth(this.reorderIndicatorUp); this.iconHeight = DomHandler.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.getOffset(this.container); var dropHeaderOffset = DomHandler.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.index(this.draggedColumnEl); var dropIndex = DomHandler.index(this.findParentHeader(event.currentTarget)); var allowDrop = dragIndex !== dropIndex; if (allowDrop && (dropIndex - dragIndex === 1 && this.dropPosition === -1 || dragIndex - dropIndex === 1 && this.dropPosition === 1)) { allowDrop = false; } if (allowDrop) { var columns = this.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; filterValue = filterMeta.value; filterConstraint = filterMatchMode === 'custom' ? col.props.filterFunction : FilterUtils[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 = FilterUtils['contains']; paramsWithoutNode = { filterField: filterField, filterValue: filterValue, filterConstraint: filterConstraint, isStrictMode: isStrictMode }; if (isStrictMode && (this.findFilteredNodes(copyNodeForGlobal, paramsWithoutNode) || this.isFilterMatched(copyNodeForGlobal, paramsWithoutNode)) || !isStrictMode && (this.isFilterMatched(copyNodeForGlobal, paramsWithoutNode) || this.findFilteredNodes(copyNodeForGlobal, paramsWithoutNode))) { globalMatch = true; copyNode = copyNodeForGlobal; } } } var matches = localMatch; if (this.props.globalFilter) { matches = localMatch && globalMatch; } if (matches) { filteredNodes.push(copyNode); } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } return filteredNodes; } }, { key: "findFilteredNodes", value: function findFilteredNodes(node, paramsWithoutNode) { if (node) { var matched = false; if (node.children) { var childNodes = _toConsumableArray(node.children); node.children = []; var _iterator6 = _createForOfIteratorHelper(childNodes), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var childNode = _step6.value; var copyChildNode = _objectSpread({}, childNode); if (this.isFilterMatched(copyChildNode, paramsWithoutNode)) { matched = true; node.children.push(copyChildNode); } } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } } if (matched) { return true; } } } }, { key: "isFilterMatched", value: function isFilterMatched(node, _ref) { var filterField = _ref.filterField, filterValue = _ref.filterValue, filterConstraint = _ref.filterConstraint, isStrictMode = _ref.isStrictMode, options = _ref.options; var matched = false; var dataFieldValue = ObjectUtils.resolveFieldData(node.data, filterField); if (filterConstraint(dataFieldValue, filterValue, this.props.filterLocale, options)) { matched = true; } if (!matched || isStrictMode && !this.isNodeLeaf(node)) { matched = this.findFilteredNodes(node, { filterField: filterField, filterValue: filterValue, filterConstraint: filterConstraint, isStrictMode: isStrictMode }) || matched; } return matched; } }, { key: "isNodeLeaf", value: function isNodeLeaf(node) { return node.leaf === false ? false : !(node.children && node.children.length); } }, { key: "processValue", value: function processValue() { var data = this.props.value; if (!this.props.lazy) { if (data && data.length) { if (this.getSortField() || this.getMultiSortMeta()) { if (this.props.sortMode === 'single') data = this.sortSingle(data);else if (this.props.sortMode === 'multiple') data = this.sortMultiple(data); } var localFilters = this.getFilters(); if (localFilters || this.props.globalFilter) { data = this.filterLocal(data, localFilters); } } } return data; } }, { key: "createTableHeader", value: function createTableHeader(columns, columnGroup) { return /*#__PURE__*/React.createElement(TreeTableHeader, { columns: columns, columnGroup: columnGroup, tabIndex: this.props.tabIndex, onSort: this.onSort, sortField: this.getSortField(), sortOrder: this.getSortOrder(), multiSortMeta: this.getMultiSortMeta(), resizableColumns: this.props.resizableColumns, onResizeStart: this.onColumnResizeStart, reorderableColumns: this.props.reorderableColumns, onDragStart: this.onColumnDragStart, onDragOver: this.onColumnDragOver, onDragLeave: this.onColumnDragLeave, onDrop: this.onColumnDrop, onFilter: this.onFilter, filters: this.getFilters(), filterDelay: this.props.filterDelay }); } }, { key: "createTableFooter", value: function createTableFooter(columns, columnGroup) { return /*#__PURE__*/React.createElement(TreeTableFooter, { columns: columns, columnGroup: columnGroup }); } }, { key: "createTableBody", value: function createTableBody(value, columns) { return /*#__PURE__*/React.createElement(TreeTableBody, { value: value, columns: columns, expandedKeys: this.getExpandedKeys(), selectOnEdit: this.props.selectOnEdit, onToggle: this.onToggle, onExpand: this.props.onExpand, onCollapse: this.props.onCollapse, paginator: this.props.paginator, first: this.getFirst(), rows: this.getRows(), selectionMode: this.props.selectionMode, selectionKeys: this.props.selectionKeys, onSelectionChange: this.props.onSelectionChange, metaKeySelection: this.props.metaKeySelection, onRowClick: this.props.onRowClick, onSelect: this.props.onSelect, onUnselect: this.props.onUnselect, propagateSelectionUp: this.props.propagateSelectionUp, propagateSelectionDown: this.props.propagateSelectionDown, lazy: this.props.lazy, rowClassName: this.props.rowClassName, emptyMessage: this.props.emptyMessage, loading: this.props.loading, contextMenuSelectionKey: this.props.contextMenuSelectionKey, onContextMenuSelectionChange: this.props.onContextMenuSelectionChange, onContextMenu: this.props.onContextMenu }); } }, { key: "createPaginator", value: function createPaginator(position, totalRecords) { var className = classNames('p-paginator-' + position, this.props.paginatorClassName); return /*#__PURE__*/React.createElement(Paginator, { first: this.getFirst(), rows: this.getRows(), pageLinkSize: this.props.pageLinkSize, className: className, onPageChange: this.onPageChange, template: this.props.paginatorTemplate, totalRecords: totalRecords, rowsPerPageOptions: this.props.rowsPerPageOptions, currentPageReportTemplate: this.props.currentPageReportTemplate, leftContent: this.props.paginatorLeft, rightContent: this.props.paginatorRight, alwaysShow: this.props.alwaysShowPaginator, dropdownAppendTo: this.props.paginatorDropdownAppendTo }); } }, { key: "createScrollableView", value: function createScrollableView(value, columns, frozen, headerColumnGroup, footerColumnGroup) { var header = this.createTableHeader(columns, headerColumnGroup); var footer = this.createTableFooter(columns, footerColumnGroup); var body = this.createTableBody(value, columns); return /*#__PURE__*/React.createElement(TreeTableScrollableView, { columns: columns, header: header, body: body, footer: footer, scrollHeight: this.props.scrollHeight, frozen: frozen, frozenWidth: this.props.frozenWidth }); } }, { key: "renderScrollableTable", value: function renderScrollableTable(value) { var columns = this.getColumns(); var frozenColumns = this.getFrozenColumns(columns); var scrollableColumns = frozenColumns ? this.getScrollableColumns(columns) : columns; var frozenView, scrollableView; if (frozenColumns) { frozenView = this.createScrollableView(value, frozenColumns, true, this.props.frozenHeaderColumnGroup, this.props.frozenFooterColumnGroup); } scrollableView = this.createScrollableView(value, scrollableColumns, false, this.props.headerColumnGroup, this.props.footerColumnGroup); return /*#__PURE__*/React.createElement("div", { className: "p-treetable-scrollable-wrapper" }, frozenView, scrollableView); } }, { key: "renderRegularTable", value: function renderRegularTable(value) { var _this6 = this; var columns = this.getColumns(); var header = this.createTableHeader(columns, this.props.headerColumnGroup); var footer = this.createTableFooter(columns, this.props.footerColumnGroup); var body = this.createTableBody(value, columns); return /*#__PURE__*/React.createElement("div", { className: "p-treetable-wrapper" }, /*#__PURE__*/React.createElement("table", { style: this.props.tableStyle, className: this.props.tableClassName, ref: function ref(el) { return _this6.table = el; } }, header, footer, body)); } }, { key: "renderTable", value: function renderTable(value) { if (this.props.scrollable) return this.renderScrollableTable(value);else return this.renderRegularTable(value); } }, { key: "renderLoader", value: function renderLoader() { if (this.props.loading) { var iconClassName = classNames('p-treetable-loading-icon pi-spin', this.props.loadingIcon); return /*#__PURE__*/React.createElement("div", { className: "p-treetable-loading" }, /*#__PURE__*/React.createElement("div", { className: "p-treetable-loading-overlay p-component-overlay" }, /*#__PURE__*/React.createElement("i", { className: iconClassName }))); } return null; } }, { key: "render", value: function render() { var _this7 = this; var value = this.processValue(); var className = classNames('p-treetable p-component', { 'p-treetable-hoverable-rows': this.isRowSelectionMode(), 'p-treetable-resizable': this.props.resizableColumns, 'p-treetable-resizable-fit': this.props.resizableColumns && this.props.columnResizeMode === 'fit', 'p-treetable-auto-layout': this.props.autoLayout, 'p-treetable-striped': this.props.stripedRows, 'p-treetable-gridlines': this.props.showGridlines }, this.props.className); var table = this.renderTable(value); var totalRecords = this.getTotalRecords(value); var headerFacet = this.props.header && /*#__PURE__*/React.createElement("div", { className: "p-treetable-header" }, this.props.header); var footerFacet = this.props.footer && /*#__PURE__*/React.createElement("div", { className: "p-treetable-footer" }, this.props.footer); var paginatorTop = this.props.paginator && this.props.paginatorPosition !== 'bottom' && this.createPaginator('top', totalRecords); var paginatorBottom = this.props.paginator && this.props.paginatorPosition !== 'top' && this.createPaginator('bottom', totalRecords); var loader = this.renderLoader(); var resizeHelper = this.props.resizableColumns && /*#__PURE__*/React.createElement("div", { ref: function ref(el) { _this7.resizerHelper = el; }, className: "p-column-resizer-helper", style: { display: 'none' } }); var reorderIndicatorUp = this.props.reorderableColumns && /*#__PURE__*/React.createElement("span", { ref: function ref(el) { return _this7.reorderIndicatorUp = el; }, className: "pi pi-arrow-down p-datatable-reorder-indicator-up", style: { position: 'absolute', display: 'none' } }); var reorderIndicatorDown = this.props.reorderableColumns && /*#__PURE__*/React.createElement("span", { ref: function ref(el) { return _this7.reorderIndicatorDown = el; }, className: "pi pi-arrow-up p-datatable-reorder-indicator-down", style: { position: 'absolute', display: 'none' } }); return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: className, style: this.props.style, ref: function ref(el) { return _this7.container = el; }, "data-scrollselectors": ".p-treetable-scrollable-body" }, loader, headerFacet, paginatorTop, table, paginatorBottom, footerFacet, resizeHelper, reorderIndicatorUp, reorderIndicatorDown); } }]); return TreeTable; }(Component); _defineProperty(TreeTable, "defaultProps", { id: null, value: null, header: null, footer: null, style: null, className: null, tableStyle: null, tableClassName: null, expandedKeys: null, paginator: false, paginatorPosition: 'bottom', alwaysShowPaginator: true, paginatorClassName: null, paginatorTemplate: 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown', paginatorLeft: null, paginatorRight: null, paginatorDropdownAppendTo: null, pageLinkSize: 5, rowsPerPageOptions: null, currentPageReportTemplate: '({currentPage} of {totalPages})', first: null, rows: null, totalRecords: null, lazy: false, sortField: null, sortOrder: null, multiSortMeta: null, sortMode: 'single', defaultSortOrder: 1, removableSort: false, selectionMode: null, selectionKeys: null, contextMenuSelectionKey: null, metaKeySelection: true, selectOnEdit: true, propagateSelectionUp: true, propagateSelectionDown: true, autoLayout: false, rowClassName: null, loading: false, loadingIcon: 'pi pi-spinner', tabIndex: 0, scrollable: false, scrollHeight: null, reorderableColumns: false, headerColumnGroup: null, footerColumnGroup: null, frozenHeaderColumnGroup: null, frozenFooterColumnGroup: null, frozenWidth: null, resizableColumns: false, columnResizeMode: 'fit', emptyMessage: "No records found", filters: null, globalFilter: null, filterMode: 'lenient', filterDelay: 300, filterLocale: undefined, showGridlines: false, stripedRows: false, onFilter: null, onExpand: null, onCollapse: null, onToggle: null, onPage: null, onSort: null, onSelect: null, onUnselect: null, onRowClick: null, onSelectionChange: null, onContextMenuSelectionChange: null, onColumnResizeEnd: null, onColReorder: null, onContextMenu: null }); export { TreeTable };
ajax/libs/material-ui/4.9.4/esm/Paper/Paper.js
cdnjs/cdnjs
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import _extends from "@babel/runtime/helpers/esm/extends"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; export var styles = function styles(theme) { var elevations = {}; theme.shadows.forEach(function (shadow, index) { elevations["elevation".concat(index)] = { boxShadow: shadow }; }); return _extends({ /* Styles applied to the root element. */ root: { backgroundColor: theme.palette.background.paper, color: theme.palette.text.primary, transition: theme.transitions.create('box-shadow') }, /* Styles applied to the root element if `square={false}`. */ rounded: { borderRadius: theme.shape.borderRadius }, /* Styles applied to the root element if `variant="outlined"` */ outlined: { border: "1px solid ".concat(theme.palette.divider) } }, elevations); }; var Paper = React.forwardRef(function Paper(props, ref) { var classes = props.classes, className = props.className, _props$component = props.component, Component = _props$component === void 0 ? 'div' : _props$component, _props$square = props.square, square = _props$square === void 0 ? false : _props$square, _props$elevation = props.elevation, elevation = _props$elevation === void 0 ? 1 : _props$elevation, _props$variant = props.variant, variant = _props$variant === void 0 ? 'elevation' : _props$variant, other = _objectWithoutProperties(props, ["classes", "className", "component", "square", "elevation", "variant"]); if (process.env.NODE_ENV !== 'production') { if (classes["elevation".concat(elevation)] === undefined) { console.error("Material-UI: this elevation `".concat(elevation, "` is not implemented.")); } } return React.createElement(Component, _extends({ className: clsx(classes.root, className, variant === 'outlined' ? classes.outlined : classes["elevation".concat(elevation)], !square && classes.rounded), ref: ref }, other)); }); process.env.NODE_ENV !== "production" ? Paper.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * Shadow depth, corresponds to `dp` in the spec. * It accepts values between 0 and 24 inclusive. */ elevation: PropTypes.number, /** * If `true`, rounded corners are disabled. */ square: PropTypes.bool, /** * The variant to use. */ variant: PropTypes.oneOf(['elevation', 'outlined']) } : void 0; export default withStyles(styles, { name: 'MuiPaper' })(Paper);
ajax/libs/react-native-web/0.0.0-aa93652b6/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.13.8/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/material-ui/4.12.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'; var warnedOnce = 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> * ); * } * ``` * * @deprecated */ 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() { if (process.env.NODE_ENV !== 'production') { if (!warnedOnce) { warnedOnce = true; console.warn(['Material-UI: The RootRef component is deprecated.', 'The component relies on the ReactDOM.findDOMNode API which is deprecated in React.StrictMode.', 'Instead, you can get a reference to the underlying DOM node of the components via the `ref` prop.'].join('/n')); } } 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/react-native-web/0.0.0-d48f63060/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/react-native-web/0.13.1/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/esm/Input/Input.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { refType } from '@material-ui/utils'; import InputBase from '../InputBase'; import withStyles from '../styles/withStyles'; export var styles = function styles(theme) { var light = theme.palette.type === 'light'; var bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)'; return { /* Styles applied to the root element. */ root: { position: 'relative' }, /* Styles applied to the root element if the component is a descendant of `FormControl`. */ formControl: { 'label + &': { marginTop: 16 } }, /* Styles applied to the root element if the component is focused. */ focused: {}, /* Styles applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if color secondary. */ colorSecondary: { '&$underline:after': { borderBottomColor: theme.palette.secondary.main } }, /* Styles applied to the root element if `disableUnderline={false}`. */ underline: { '&:after': { borderBottom: "2px solid ".concat(theme.palette.primary.main), left: 0, bottom: 0, // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242 content: '""', position: 'absolute', right: 0, transform: 'scaleX(0)', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut }), pointerEvents: 'none' // Transparent to the hover style. }, '&$focused:after': { transform: 'scaleX(1)' }, '&$error:after': { borderBottomColor: theme.palette.error.main, transform: 'scaleX(1)' // error is always underlined in red }, '&:before': { borderBottom: "1px solid ".concat(bottomLineColor), left: 0, bottom: 0, // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242 content: '"\\00a0"', position: 'absolute', right: 0, transition: theme.transitions.create('border-bottom-color', { duration: theme.transitions.duration.shorter }), pointerEvents: 'none' // Transparent to the hover style. }, '&:hover:not($disabled):before': { borderBottom: "2px solid ".concat(theme.palette.text.primary), // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { borderBottom: "1px solid ".concat(bottomLineColor) } }, '&$disabled:before': { borderBottomStyle: 'dotted' } }, /* Pseudo-class applied to the root element if `error={true}`. */ error: {}, /* Styles applied to the `input` element if `margin="dense"`. */ marginDense: {}, /* Styles applied to the root element if `multiline={true}`. */ multiline: {}, /* Styles applied to the root element if `fullWidth={true}`. */ fullWidth: {}, /* Styles applied to the `input` element. */ input: {}, /* Styles applied to the `input` element if `margin="dense"`. */ inputMarginDense: {}, /* Styles applied to the `input` element if `multiline={true}`. */ inputMultiline: {}, /* Styles applied to the `input` element if `type="search"`. */ inputTypeSearch: {} }; }; var Input = React.forwardRef(function Input(props, ref) { var disableUnderline = props.disableUnderline, classes = props.classes, _props$fullWidth = props.fullWidth, fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth, _props$inputComponent = props.inputComponent, inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent, _props$multiline = props.multiline, multiline = _props$multiline === void 0 ? false : _props$multiline, _props$type = props.type, type = _props$type === void 0 ? 'text' : _props$type, other = _objectWithoutProperties(props, ["disableUnderline", "classes", "fullWidth", "inputComponent", "multiline", "type"]); return React.createElement(InputBase, _extends({ classes: _extends({}, classes, { root: clsx(classes.root, !disableUnderline && classes.underline), underline: null }), fullWidth: fullWidth, inputComponent: inputComponent, multiline: multiline, ref: ref, type: type }, other)); }); process.env.NODE_ENV !== "production" ? Input.propTypes = { /** * This prop helps users to fill forms faster, especially on mobile devices. * The name can be confusing, as it's more like an autofill. * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill). */ autoComplete: PropTypes.string, /** * If `true`, the `input` element will be focused during the first mount. */ autoFocus: PropTypes.bool, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * The CSS class name of the wrapper element. */ 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 default `input` element value. Use when the component is not controlled. */ defaultValue: PropTypes.any, /** * If `true`, the `input` element will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the input will not have an underline. */ disableUnderline: PropTypes.bool, /** * End `InputAdornment` for this component. */ endAdornment: PropTypes.node, /** * If `true`, the input will indicate an error. This is normally obtained via context from * FormControl. */ error: PropTypes.bool, /** * If `true`, the input will take up the full width of its container. */ fullWidth: PropTypes.bool, /** * The id of the `input` element. */ id: PropTypes.string, /** * The component used for the native input. * Either a string to use a DOM element or a component. */ inputComponent: PropTypes.elementType, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. */ inputProps: PropTypes.object, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. */ margin: PropTypes.oneOf(['dense', 'none']), /** * If `true`, a textarea element will be rendered. */ multiline: PropTypes.bool, /** * Name attribute of the `input` element. */ name: PropTypes.string, /** * Callback fired when the value is changed. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: PropTypes.func, /** * The short hint displayed in the input before the user enters a value. */ placeholder: PropTypes.string, /** * It prevents the user from changing the value of the field * (not from interacting with the field). */ readOnly: PropTypes.bool, /** * If `true`, the `input` element will be required. */ required: PropTypes.bool, /** * Number of rows to display when multiline option is set to true. */ rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Maximum number of rows to display when multiline option is set to true. */ rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Start `InputAdornment` for this component. */ startAdornment: PropTypes.node, /** * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types). */ type: PropTypes.string, /** * The value of the `input` element, required for a controlled component. */ value: PropTypes.any } : void 0; Input.muiName = 'Input'; export default withStyles(styles, { name: 'MuiInput' })(Input);
ajax/libs/react-native-web/0.11.7/exports/ScrollView/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 createReactClass from 'create-react-class'; import dismissKeyboard from '../../modules/dismissKeyboard'; import findNodeHandle from '../findNodeHandle'; import invariant from 'fbjs/lib/invariant'; import ScrollResponder from '../../modules/ScrollResponder'; import ScrollViewBase from './ScrollViewBase'; import StyleSheet from '../StyleSheet'; import View from '../View'; import ViewPropTypes from '../ViewPropTypes'; import React from 'react'; import { arrayOf, bool, element, func, number, oneOf } from 'prop-types'; var emptyObject = {}; /* eslint-disable react/prefer-es6-class, react/prop-types */ var ScrollView = createReactClass({ displayName: "ScrollView", propTypes: _objectSpread({}, ViewPropTypes, { contentContainerStyle: ViewPropTypes.style, horizontal: bool, keyboardDismissMode: oneOf(['none', 'interactive', 'on-drag']), onContentSizeChange: func, onScroll: func, pagingEnabled: bool, refreshControl: element, scrollEnabled: bool, scrollEventThrottle: number, stickyHeaderIndices: arrayOf(number), style: ViewPropTypes.style }), mixins: [ScrollResponder.Mixin], getInitialState: function getInitialState() { return this.scrollResponderMixinGetInitialState(); }, flashScrollIndicators: function flashScrollIndicators() { this.scrollResponderFlashScrollIndicators(); }, setNativeProps: function setNativeProps(props) { if (this._scrollViewRef) { this._scrollViewRef.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 findNodeHandle(this._scrollViewRef); }, getInnerViewNode: function getInnerViewNode() { return findNodeHandle(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 }); }, /** * Deprecated, do not use. */ scrollWithoutAnimationTo: function scrollWithoutAnimationTo(y, x) { if (y === void 0) { y = 0; } if (x === void 0) { x = 0; } console.warn('`scrollWithoutAnimationTo` is deprecated. Use `scrollTo` instead'); this.scrollTo({ x: x, y: y, animated: false }); }, 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._setScrollViewRef, style: baseStyle }), contentContainer)); } return React.createElement(ScrollViewClass, _extends({}, props, { ref: this._setScrollViewRef }), 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) { 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; }, _setScrollViewRef: function _setScrollViewRef(component) { this._scrollViewRef = component; } }); var commonStyle = { flexGrow: 1, flexShrink: 1, // Enable hardware compositing in modern browsers. // Creates a new layer with its own backing surface that can significantly // improve scroll performance. transform: [{ translateZ: 0 }], // iOS native scrolling WebkitOverflowScrolling: 'touch' }; var styles = StyleSheet.create({ baseVertical: _objectSpread({}, commonStyle, { flexDirection: 'column', overflowX: 'hidden', overflowY: 'auto' }), baseHorizontal: _objectSpread({}, commonStyle, { flexDirection: 'row', overflowX: 'auto', overflowY: 'hidden' }), contentContainerHorizontal: { flexDirection: 'row' }, stickyHeader: { position: 'sticky', top: 0, zIndex: 10 }, pagingEnabledHorizontal: { scrollSnapType: 'x mandatory' }, pagingEnabledVertical: { scrollSnapType: 'y mandatory' }, pagingEnabledChild: { scrollSnapAlign: 'start' } }); export default ScrollView;
ajax/libs/react-native-web/0.0.0-d48f63060/exports/createElement/index.js
cdnjs/cdnjs
/** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AccessibilityUtil from '../../modules/AccessibilityUtil'; import createDOMProps from '../../modules/createDOMProps'; import React from 'react'; var createElement = function createElement(component, props) { // Use equivalent platform elements where possible. var accessibilityComponent; if (component && component.constructor === String) { accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props); } var Component = accessibilityComponent || component; var domProps = createDOMProps(Component, props); for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } return /*#__PURE__*/React.createElement.apply(React, [Component, domProps].concat(children)); }; export default createElement;
ajax/libs/primereact/7.2.1/gmap/gmap.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var GMap = /*#__PURE__*/function (_Component) { _inherits(GMap, _Component); var _super = _createSuper(GMap); function GMap() { _classCallCheck(this, GMap); return _super.apply(this, arguments); } _createClass(GMap, [{ key: "initMap", value: function initMap() { this.map = new google.maps.Map(this.container, this.props.options); if (this.props.onMapReady) { this.props.onMapReady({ map: this.map }); } this.initOverlays(this.props.overlays); this.bindMapEvent('click', this.props.onMapClick); this.bindMapEvent('dragend', this.props.onMapDragEnd); this.bindMapEvent('zoom_changed', this.props.onZoomChanged); } }, { key: "initOverlays", value: function initOverlays(overlays) { if (overlays) { var _iterator = _createForOfIteratorHelper(overlays), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var overlay = _step.value; overlay.setMap(this.map); this.bindOverlayEvents(overlay); } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } } }, { key: "bindOverlayEvents", value: function bindOverlayEvents(overlay) { var _this = this; overlay.addListener('click', function (event) { if (_this.props.onOverlayClick) { _this.props.onOverlayClick({ originalEvent: event, overlay: overlay, map: _this.map }); } }); if (overlay.getDraggable()) { this.bindDragEvents(overlay); } } }, { key: "bindDragEvents", value: function bindDragEvents(overlay) { this.bindDragEvent(overlay, 'dragstart', this.props.onOverlayDragStart); this.bindDragEvent(overlay, 'drag', this.props.onOverlayDrag); this.bindDragEvent(overlay, 'dragend', this.props.onOverlayDragEnd); } }, { key: "bindMapEvent", value: function bindMapEvent(eventName, callback) { this.map.addListener(eventName, function (event) { if (callback) { callback(event); } }); } }, { key: "bindDragEvent", value: function bindDragEvent(overlay, eventName, callback) { var _this2 = this; overlay.addListener(eventName, function (event) { if (callback) { callback({ originalEvent: event, overlay: overlay, map: _this2.map }); } }); } }, { key: "getMap", value: function getMap() { return this.map; } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState, snapshot) { if (prevProps.overlays !== this.props.overlays) { if (prevProps.overlays) { var _iterator2 = _createForOfIteratorHelper(prevProps.overlays), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var overlay = _step2.value; google.maps.event.clearInstanceListeners(overlay); overlay.setMap(null); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } this.initOverlays(this.props.overlays); } } }, { key: "componentDidMount", value: function componentDidMount() { this.initMap(); } }, { key: "render", value: function render() { var _this3 = this; return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this3.container = el; }, style: this.props.style, className: this.props.className }); } }]); return GMap; }(Component); _defineProperty(GMap, "defaultProps", { options: null, overlays: null, style: null, className: null, onMapReady: null, onMapClick: null, onMapDragEnd: null, onZoomChanged: null, onOverlayDragStart: null, onOverlayDrag: null, onOverlayDragEnd: null, onOverlayClick: null }); export { GMap };
ajax/libs/material-ui/5.0.0-alpha.20/legacy/styles/useTheme.js
cdnjs/cdnjs
import { useTheme as useThemeWithoutDefault } from '@material-ui/styles'; import React from 'react'; import defaultTheme from './defaultTheme'; export default function useTheme() { var theme = useThemeWithoutDefault() || defaultTheme; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks React.useDebugValue(theme); } return theme; }
ajax/libs/primereact/7.0.1/fullcalendar/fullcalendar.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { 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; } 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 FullCalendar = /*#__PURE__*/function (_Component) { _inherits(FullCalendar, _Component); var _super = _createSuper(FullCalendar); function FullCalendar() { _classCallCheck(this, FullCalendar); return _super.apply(this, arguments); } _createClass(FullCalendar, [{ key: "componentDidMount", value: function componentDidMount() { console.warn("FullCalendar component is deprecated. Use FullCalendar component of '@fullcalendar/react' package."); this.config = { theme: true }; if (this.props.options) { for (var prop in this.props.options) { this.config[prop] = this.props.options[prop]; } } this.initialize(); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (!this.calendar) { this.initialize(); } else { if (!ObjectUtils.equals(prevProps.events, this.props.events)) { this.calendar.removeAllEventSources(); this.calendar.addEventSource(this.props.events); } if (!ObjectUtils.equals(prevProps.options, this.props.options)) { for (var prop in this.props.options) { var optionValue = this.props.options[prop]; this.config[prop] = optionValue; this.calendar.setOption(prop, optionValue); } } } } }, { key: "initialize", value: function initialize() { var _this = this; import('@fullcalendar/core').then(function (module) { if (module && module.Calendar) { _this.calendar = new module.Calendar(_this.element, _this.config); _this.calendar.render(); if (_this.props.events) { _this.calendar.removeAllEventSources(); _this.calendar.addEventSource(_this.props.events); } } }); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.calendar) { this.calendar.destroy(); } } }, { key: "render", value: function render() { var _this2 = this; return /*#__PURE__*/React.createElement("div", { id: this.props.id, ref: function ref(el) { return _this2.element = el; }, style: this.props.style, className: this.props.className }); } }]); return FullCalendar; }(Component); _defineProperty(FullCalendar, "defaultProps", { id: null, events: [], style: null, className: null, options: null }); export { FullCalendar };
ajax/libs/material-ui/4.9.2/esm/FormControlLabel/FormControlLabel.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { refType } from '@material-ui/utils'; import { useFormControl } from '../FormControl'; import withStyles from '../styles/withStyles'; import Typography from '../Typography'; import capitalize from '../utils/capitalize'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { display: 'inline-flex', alignItems: 'center', cursor: 'pointer', // For correct alignment with the text. verticalAlign: 'middle', WebkitTapHighlightColor: 'transparent', marginLeft: -11, marginRight: 16, // used for row presentation of radio/checkbox '&$disabled': { cursor: 'default' } }, /* Styles applied to the root element if `labelPlacement="start"`. */ labelPlacementStart: { flexDirection: 'row-reverse', marginLeft: 16, // used for row presentation of radio/checkbox marginRight: -11 }, /* Styles applied to the root element if `labelPlacement="top"`. */ labelPlacementTop: { flexDirection: 'column-reverse', marginLeft: 16 }, /* Styles applied to the root element if `labelPlacement="bottom"`. */ labelPlacementBottom: { flexDirection: 'column', marginLeft: 16 }, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the label's Typography component. */ label: { '&$disabled': { color: theme.palette.text.disabled } } }; }; /** * Drop in replacement of the `Radio`, `Switch` and `Checkbox` component. * Use this component if you want to display an extra label. */ var FormControlLabel = React.forwardRef(function FormControlLabel(props, ref) { var checked = props.checked, classes = props.classes, className = props.className, control = props.control, disabledProp = props.disabled, inputRef = props.inputRef, label = props.label, _props$labelPlacement = props.labelPlacement, labelPlacement = _props$labelPlacement === void 0 ? 'end' : _props$labelPlacement, name = props.name, onChange = props.onChange, value = props.value, other = _objectWithoutProperties(props, ["checked", "classes", "className", "control", "disabled", "inputRef", "label", "labelPlacement", "name", "onChange", "value"]); var muiFormControl = useFormControl(); var disabled = disabledProp; if (typeof disabled === 'undefined' && typeof control.props.disabled !== 'undefined') { disabled = control.props.disabled; } if (typeof disabled === 'undefined' && muiFormControl) { disabled = muiFormControl.disabled; } var controlProps = { disabled: disabled }; ['checked', 'name', 'onChange', 'value', 'inputRef'].forEach(function (key) { if (typeof control.props[key] === 'undefined' && typeof props[key] !== 'undefined') { controlProps[key] = props[key]; } }); return React.createElement("label", _extends({ className: clsx(classes.root, className, labelPlacement !== 'end' && classes["labelPlacement".concat(capitalize(labelPlacement))], disabled && classes.disabled), ref: ref }, other), React.cloneElement(control, controlProps), React.createElement(Typography, { component: "span", className: clsx(classes.label, disabled && classes.disabled) }, label)); }); process.env.NODE_ENV !== "production" ? FormControlLabel.propTypes = { /** * If `true`, the component appears selected. */ checked: 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, /** * A control element. For instance, it can be be a `Radio`, a `Switch` or a `Checkbox`. */ control: PropTypes.element, /** * If `true`, the control will be disabled. */ disabled: PropTypes.bool, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * The text to be used in an enclosing label element. */ label: PropTypes.node, /** * The position of the label. */ labelPlacement: PropTypes.oneOf(['end', 'start', 'top', 'bottom']), /* * @ignore */ name: PropTypes.string, /** * Callback fired when the state is changed. * * @param {object} event The event source of the callback. * You can pull out the new checked state by accessing `event.target.checked` (boolean). */ onChange: PropTypes.func, /** * The value of the component. */ value: PropTypes.any } : void 0; export default withStyles(styles, { name: 'MuiFormControlLabel' })(FormControlLabel);
ajax/libs/primereact/7.1.0/rating/rating.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames } from 'primereact/utils'; import { tip } from 'primereact/tooltip'; 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 Rating = /*#__PURE__*/function (_Component) { _inherits(Rating, _Component); var _super = _createSuper(Rating); function Rating(props) { var _this; _classCallCheck(this, Rating); _this = _super.call(this, props); _this.clear = _this.clear.bind(_assertThisInitialized(_this)); _this.onStarKeyDown = _this.onStarKeyDown.bind(_assertThisInitialized(_this)); _this.onCancelKeyDown = _this.onCancelKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(Rating, [{ key: "rate", value: function rate(event, i) { if (!this.props.readOnly && !this.props.disabled && this.props.onChange) { this.props.onChange({ originalEvent: event, value: i, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: i } }); } event.preventDefault(); } }, { key: "clear", value: function clear(event) { if (!this.props.readOnly && !this.props.disabled && this.props.onChange) { this.props.onChange({ originalEvent: event, value: null, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: null } }); } event.preventDefault(); } }, { key: "shouldComponentUpdate", value: function shouldComponentUpdate(nextProps, nextState) { if (nextProps.value === this.props.value && nextProps.disabled === this.props.disabled) { return false; } return true; } }, { key: "onStarKeyDown", value: function onStarKeyDown(event, value) { if (event.key === 'Enter') { this.rate(event, value); } } }, { key: "onCancelKeyDown", value: function onCancelKeyDown(event) { if (event.key === 'Enter') { this.clear(event); } } }, { key: "getFocusIndex", value: function getFocusIndex() { return this.props.disabled || this.props.readOnly ? null : 0; } }, { 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: "renderStars", value: function renderStars() { var _this2 = this; var starsArray = []; for (var i = 0; i < this.props.stars; i++) { starsArray[i] = i + 1; } var stars = starsArray.map(function (value) { var iconClass = classNames('p-rating-icon', { 'pi pi-star': !_this2.props.value || value > _this2.props.value, 'pi pi-star-fill': value <= _this2.props.value }); return /*#__PURE__*/React.createElement("span", { className: iconClass, onClick: function onClick(e) { return _this2.rate(e, value); }, key: value, tabIndex: _this2.getFocusIndex(), onKeyDown: function onKeyDown(e) { return _this2.onStarKeyDown(e, value); } }); }); return stars; } }, { key: "renderCancelIcon", value: function renderCancelIcon() { if (this.props.cancel) { return /*#__PURE__*/React.createElement("span", { className: "p-rating-icon p-rating-cancel pi pi-ban", onClick: this.clear, tabIndex: this.getFocusIndex(), onKeyDown: this.onCancelKeyDown }); } return null; } }, { key: "render", value: function render() { var _this3 = this; var className = classNames('p-rating', { 'p-disabled': this.props.disabled, 'p-rating-readonly': this.props.readOnly }, this.props.className); var cancelIcon = this.renderCancelIcon(); var stars = this.renderStars(); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this3.element = el; }, id: this.props.id, className: className, style: this.props.style }, cancelIcon, stars); } }]); return Rating; }(Component); _defineProperty(Rating, "defaultProps", { id: null, value: null, disabled: false, readOnly: false, stars: 5, cancel: true, style: null, className: null, tooltip: null, tooltipOptions: null, onChange: null }); export { Rating };
ajax/libs/primereact/7.0.0/utils/utils.esm.js
cdnjs/cdnjs
import React from 'react'; function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest(); } function _typeof(obj) { "@babel/helpers - typeof"; 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 classNames() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (args) { var classes = []; for (var i = 0; i < args.length; i++) { var className = args[i]; if (!className) continue; var type = _typeof(className); if (type === 'string' || type === 'number') { classes.push(className); } else if (type === 'object') { var _classes = Array.isArray(className) ? className : Object.entries(className).map(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), key = _ref2[0], value = _ref2[1]; return !!value ? key : null; }); classes = _classes.length ? classes.concat(_classes.filter(function (c) { return !!c; })) : classes; } } return classes.join(' '); } return undefined; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } var DomHandler = /*#__PURE__*/function () { function DomHandler() { _classCallCheck(this, DomHandler); } _createClass(DomHandler, null, [{ key: "innerWidth", value: function innerWidth(el) { if (el) { var width = el.offsetWidth; var style = getComputedStyle(el); width += parseFloat(style.paddingLeft) + parseFloat(style.paddingRight); return width; } return 0; } }, { key: "width", value: function width(el) { if (el) { var width = el.offsetWidth; var style = getComputedStyle(el); width -= parseFloat(style.paddingLeft) + parseFloat(style.paddingRight); return width; } return 0; } }, { key: "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; 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; if (margin) { var style = getComputedStyle(el); height += parseFloat(style.marginTop) + parseFloat(style.marginBottom); } return height; } return 0; } }, { key: "getClientHeight", value: function getClientHeight(el, margin) { if (el) { var height = el.clientHeight; if (margin) { var style = getComputedStyle(el); height += parseFloat(style.marginTop) + parseFloat(style.marginBottom); } return height; } return 0; } }, { key: "getClientWidth", value: function getClientWidth(el, margin) { if (el) { var width = el.clientWidth; if (margin) { var style = getComputedStyle(el); width += parseFloat(style.marginLeft) + parseFloat(style.marginRight); } return width; } return 0; } }, { key: "getViewport", value: function getViewport() { var win = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], w = win.innerWidth || e.clientWidth || g.clientWidth, h = win.innerHeight || e.clientHeight || g.clientHeight; return { width: w, height: h }; } }, { key: "getOffset", value: function getOffset(el) { if (el) { var rect = el.getBoundingClientRect(); return { top: rect.top + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0), left: rect.left + (window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0) }; } return { top: 'auto', left: 'auto' }; } }, { key: "index", value: function index(element) { if (element) { var children = element.parentNode.childNodes; var num = 0; for (var i = 0; i < children.length; i++) { if (children[i] === element) return num; if (children[i].nodeType === 1) num++; } } return -1; } }, { key: "addMultipleClasses", value: function addMultipleClasses(element, className) { if (element && className) { if (element.classList) { var styles = className.split(' '); for (var i = 0; i < styles.length; i++) { element.classList.add(styles[i]); } } else { var _styles = className.split(' '); for (var _i = 0; _i < _styles.length; _i++) { element.className += ' ' + _styles[_i]; } } } } }, { key: "removeMultipleClasses", value: function removeMultipleClasses(element, className) { if (element && className) { if (element.classList) { var styles = className.split(' '); for (var i = 0; i < styles.length; i++) { element.classList.remove(styles[i]); } } else { var _styles2 = className.split(' '); for (var _i2 = 0; _i2 < _styles2.length; _i2++) { element.className = element.className.replace(new RegExp('(^|\\b)' + _styles2[_i2].split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } } } } }, { key: "addClass", value: function addClass(element, className) { if (element && className) { if (element.classList) element.classList.add(className);else element.className += ' ' + className; } } }, { key: "removeClass", value: function removeClass(element, className) { if (element && className) { if (element.classList) element.classList.remove(className);else element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' '); } } }, { key: "hasClass", value: function hasClass(element, className) { if (element) { if (element.classList) return element.classList.contains(className);else return new RegExp('(^| )' + className + '( |$)', 'gi').test(element.className); } } }, { key: "find", value: function find(element, selector) { return element ? Array.from(element.querySelectorAll(selector)) : []; } }, { key: "findSingle", value: function findSingle(element, selector) { if (element) { return element.querySelector(selector); } return null; } }, { key: "getHeight", value: function getHeight(el) { if (el) { var height = el.offsetHeight; var style = getComputedStyle(el); height -= parseFloat(style.paddingTop) + parseFloat(style.paddingBottom) + parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth); return height; } return 0; } }, { key: "getWidth", value: function getWidth(el) { if (el) { var width = el.offsetWidth; var style = getComputedStyle(el); width -= parseFloat(style.paddingLeft) + parseFloat(style.paddingRight) + parseFloat(style.borderLeftWidth) + parseFloat(style.borderRightWidth); return width; } return 0; } }, { key: "alignOverlay", value: function alignOverlay(overlay, target, appendTo) { var calculateMinWidth = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; if (overlay && target) { if (appendTo === 'self') { this.relativePosition(overlay, target); } else { calculateMinWidth && (overlay.style.minWidth = DomHandler.getOuterWidth(target) + 'px'); this.absolutePosition(overlay, target); } } } }, { key: "absolutePosition", value: function absolutePosition(element, target) { if (element) { var elementDimensions = element.offsetParent ? { width: element.offsetWidth, height: element.offsetHeight } : this.getHiddenElementDimensions(element); var elementOuterHeight = elementDimensions.height; var elementOuterWidth = elementDimensions.width; var targetOuterHeight = target.offsetHeight; var targetOuterWidth = target.offsetWidth; var targetOffset = target.getBoundingClientRect(); var windowScrollTop = this.getWindowScrollTop(); var windowScrollLeft = this.getWindowScrollLeft(); var viewport = this.getViewport(); var top, left; if (targetOffset.top + targetOuterHeight + elementOuterHeight > viewport.height) { top = targetOffset.top + windowScrollTop - elementOuterHeight; if (top < 0) { top = windowScrollTop; } element.style.transformOrigin = 'bottom'; } else { top = targetOuterHeight + targetOffset.top + windowScrollTop; element.style.transformOrigin = 'top'; } if (targetOffset.left + targetOuterWidth + elementOuterWidth > viewport.width) left = Math.max(0, targetOffset.left + windowScrollLeft + targetOuterWidth - elementOuterWidth);else left = targetOffset.left + windowScrollLeft; element.style.top = top + 'px'; element.style.left = left + 'px'; } } }, { key: "relativePosition", value: function relativePosition(element, target) { if (element) { var elementDimensions = element.offsetParent ? { width: element.offsetWidth, height: element.offsetHeight } : this.getHiddenElementDimensions(element); var targetHeight = target.offsetHeight; var targetOffset = target.getBoundingClientRect(); var viewport = this.getViewport(); var top, left; if (targetOffset.top + targetHeight + elementDimensions.height > viewport.height) { top = -1 * elementDimensions.height; if (targetOffset.top + top < 0) { top = -1 * targetOffset.top; } element.style.transformOrigin = 'bottom'; } else { top = targetHeight; element.style.transformOrigin = 'top'; } if (elementDimensions.width > viewport.width) { // element wider then viewport and cannot fit on screen (align at left side of viewport) left = targetOffset.left * -1; } else if (targetOffset.left + elementDimensions.width > viewport.width) { // element wider then viewport but can be fit on screen (align at right side of viewport) left = (targetOffset.left + elementDimensions.width - viewport.width) * -1; } else { // element fits on screen (align with target) left = 0; } element.style.top = top + 'px'; element.style.left = left + 'px'; } } }, { key: "flipfitCollision", value: function flipfitCollision(element, target) { var _this = this; var my = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'left top'; var at = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'left bottom'; var callback = arguments.length > 4 ? arguments[4] : undefined; var targetOffset = target.getBoundingClientRect(); var viewport = this.getViewport(); var myArr = my.split(' '); var atArr = at.split(' '); var getPositionValue = function getPositionValue(arr, isOffset) { return isOffset ? +arr.substring(arr.search(/(\+|-)/g)) || 0 : arr.substring(0, arr.search(/(\+|-)/g)) || arr; }; var position = { my: { x: getPositionValue(myArr[0]), y: getPositionValue(myArr[1] || myArr[0]), offsetX: getPositionValue(myArr[0], true), offsetY: getPositionValue(myArr[1] || myArr[0], true) }, at: { x: getPositionValue(atArr[0]), y: getPositionValue(atArr[1] || atArr[0]), offsetX: getPositionValue(atArr[0], true), offsetY: getPositionValue(atArr[1] || atArr[0], true) } }; var myOffset = { left: function left() { var totalOffset = position.my.offsetX + position.at.offsetX; return totalOffset + targetOffset.left + (position.my.x === 'left' ? 0 : -1 * (position.my.x === 'center' ? _this.getOuterWidth(element) / 2 : _this.getOuterWidth(element))); }, top: function top() { var totalOffset = position.my.offsetY + position.at.offsetY; return totalOffset + targetOffset.top + (position.my.y === 'top' ? 0 : -1 * (position.my.y === 'center' ? _this.getOuterHeight(element) / 2 : _this.getOuterHeight(element))); } }; var alignWithAt = { count: { x: 0, y: 0 }, left: function left() { var left = myOffset.left(); var scrollLeft = DomHandler.getWindowScrollLeft(); element.style.left = left + scrollLeft + 'px'; if (this.count.x === 2) { element.style.left = scrollLeft + 'px'; this.count.x = 0; } else if (left < 0) { this.count.x++; position.my.x = 'left'; position.at.x = 'right'; position.my.offsetX *= -1; position.at.offsetX *= -1; this.right(); } }, right: function right() { var left = myOffset.left() + DomHandler.getOuterWidth(target); var scrollLeft = DomHandler.getWindowScrollLeft(); element.style.left = left + scrollLeft + 'px'; if (this.count.x === 2) { element.style.left = viewport.width - DomHandler.getOuterWidth(element) + scrollLeft + 'px'; this.count.x = 0; } else if (left + DomHandler.getOuterWidth(element) > viewport.width) { this.count.x++; position.my.x = 'right'; position.at.x = 'left'; position.my.offsetX *= -1; position.at.offsetX *= -1; this.left(); } }, top: function top() { var top = myOffset.top(); var scrollTop = DomHandler.getWindowScrollTop(); element.style.top = top + scrollTop + 'px'; if (this.count.y === 2) { element.style.left = scrollTop + 'px'; this.count.y = 0; } else if (top < 0) { this.count.y++; position.my.y = 'top'; position.at.y = 'bottom'; position.my.offsetY *= -1; position.at.offsetY *= -1; this.bottom(); } }, bottom: function bottom() { var top = myOffset.top() + DomHandler.getOuterHeight(target); var scrollTop = DomHandler.getWindowScrollTop(); element.style.top = top + scrollTop + 'px'; if (this.count.y === 2) { element.style.left = viewport.height - DomHandler.getOuterHeight(element) + scrollTop + 'px'; this.count.y = 0; } else if (top + DomHandler.getOuterHeight(target) > viewport.height) { this.count.y++; position.my.y = 'bottom'; position.at.y = 'top'; position.my.offsetY *= -1; position.at.offsetY *= -1; this.top(); } }, center: function center(axis) { if (axis === 'y') { var top = myOffset.top() + DomHandler.getOuterHeight(target) / 2; element.style.top = top + DomHandler.getWindowScrollTop() + 'px'; if (top < 0) { this.bottom(); } else if (top + DomHandler.getOuterHeight(target) > viewport.height) { this.top(); } } else { var left = myOffset.left() + DomHandler.getOuterWidth(target) / 2; element.style.left = left + DomHandler.getWindowScrollLeft() + 'px'; if (left < 0) { this.left(); } else if (left + DomHandler.getOuterWidth(element) > viewport.width) { this.right(); } } } }; alignWithAt[position.at.x]('x'); alignWithAt[position.at.y]('y'); if (this.isFunction(callback)) { callback(position); } } }, { key: "findCollisionPosition", value: function findCollisionPosition(position) { if (position) { var isAxisY = position === 'top' || position === 'bottom'; var myXPosition = position === 'left' ? 'right' : 'left'; var myYPosition = position === 'top' ? 'bottom' : 'top'; if (isAxisY) { return { axis: 'y', my: "center ".concat(myYPosition), at: "center ".concat(position) }; } return { axis: 'x', my: "".concat(myXPosition, " center"), at: "".concat(position, " center") }; } } }, { key: "getParents", value: function getParents(element) { var parents = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; return element['parentNode'] === null ? parents : this.getParents(element.parentNode, parents.concat([element.parentNode])); } }, { key: "getScrollableParents", value: function getScrollableParents(element) { var scrollableParents = []; if (element) { var parents = this.getParents(element); var overflowRegex = /(auto|scroll)/; var overflowCheck = function overflowCheck(node) { var styleDeclaration = node ? getComputedStyle(node) : null; return styleDeclaration && (overflowRegex.test(styleDeclaration.getPropertyValue('overflow')) || overflowRegex.test(styleDeclaration.getPropertyValue('overflowX')) || overflowRegex.test(styleDeclaration.getPropertyValue('overflowY'))); }; var _iterator = _createForOfIteratorHelper(parents), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var parent = _step.value; var scrollSelectors = parent.nodeType === 1 && parent.dataset['scrollselectors']; if (scrollSelectors) { var selectors = scrollSelectors.split(','); var _iterator2 = _createForOfIteratorHelper(selectors), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var selector = _step2.value; var el = this.findSingle(parent, selector); if (el && overflowCheck(el)) { scrollableParents.push(el); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } if (parent.nodeType !== 9 && overflowCheck(parent)) { scrollableParents.push(parent); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } return scrollableParents; } }, { key: "getHiddenElementOuterHeight", value: function getHiddenElementOuterHeight(element) { if (element) { element.style.visibility = 'hidden'; element.style.display = 'block'; var elementHeight = element.offsetHeight; element.style.display = 'none'; element.style.visibility = 'visible'; return elementHeight; } return 0; } }, { key: "getHiddenElementOuterWidth", value: function getHiddenElementOuterWidth(element) { if (element) { element.style.visibility = 'hidden'; element.style.display = 'block'; var elementWidth = element.offsetWidth; element.style.display = 'none'; element.style.visibility = 'visible'; return elementWidth; } return 0; } }, { key: "getHiddenElementDimensions", value: function getHiddenElementDimensions(element) { var dimensions = {}; if (element) { element.style.visibility = 'hidden'; element.style.display = 'block'; dimensions.width = element.offsetWidth; dimensions.height = element.offsetHeight; element.style.display = 'none'; element.style.visibility = 'visible'; } return dimensions; } }, { key: "fadeIn", value: function fadeIn(element, duration) { if (element) { element.style.opacity = 0; var last = +new Date(); var opacity = 0; var tick = function tick() { opacity = +element.style.opacity + (new Date().getTime() - last) / duration; element.style.opacity = opacity; last = +new Date(); if (+opacity < 1) { window.requestAnimationFrame && requestAnimationFrame(tick) || setTimeout(tick, 16); } }; tick(); } } }, { key: "fadeOut", value: function fadeOut(element, duration) { if (element) { var opacity = 1, interval = 50, gap = interval / duration; var fading = setInterval(function () { opacity -= gap; if (opacity <= 0) { opacity = 0; clearInterval(fading); } element.style.opacity = opacity; }, interval); } } }, { key: "getUserAgent", value: function getUserAgent() { return navigator.userAgent; } }, { key: "isIOS", value: function isIOS() { return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window['MSStream']; } }, { key: "isAndroid", value: function isAndroid() { return /(android)/i.test(navigator.userAgent); } }, { key: "isTouchDevice", value: function isTouchDevice() { return 'ontouchstart' in window || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0; } }, { key: "isFunction", value: function isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); } }, { key: "appendChild", value: function appendChild(element, target) { if (this.isElement(target)) target.appendChild(element);else if (target.el && target.el.nativeElement) target.el.nativeElement.appendChild(element);else throw new Error('Cannot append ' + target + ' to ' + element); } }, { key: "removeChild", value: function removeChild(element, target) { if (this.isElement(target)) target.removeChild(element);else if (target.el && target.el.nativeElement) target.el.nativeElement.removeChild(element);else throw new Error('Cannot remove ' + element + ' from ' + target); } }, { key: "isElement", value: function isElement(obj) { return (typeof HTMLElement === "undefined" ? "undefined" : _typeof(HTMLElement)) === "object" ? obj instanceof HTMLElement : obj && _typeof(obj) === "object" && obj !== null && obj.nodeType === 1 && typeof obj.nodeName === "string"; } }, { key: "scrollInView", value: function scrollInView(container, item) { var borderTopValue = getComputedStyle(container).getPropertyValue('borderTopWidth'); var borderTop = borderTopValue ? parseFloat(borderTopValue) : 0; var paddingTopValue = getComputedStyle(container).getPropertyValue('paddingTop'); var paddingTop = paddingTopValue ? parseFloat(paddingTopValue) : 0; var containerRect = container.getBoundingClientRect(); var itemRect = item.getBoundingClientRect(); var offset = itemRect.top + document.body.scrollTop - (containerRect.top + document.body.scrollTop) - borderTop - paddingTop; var scroll = container.scrollTop; var elementHeight = container.clientHeight; var itemHeight = this.getOuterHeight(item); if (offset < 0) { container.scrollTop = scroll + offset; } else if (offset + itemHeight > elementHeight) { container.scrollTop = scroll + offset - elementHeight + itemHeight; } } }, { key: "clearSelection", value: function clearSelection() { if (window.getSelection) { if (window.getSelection().empty) { window.getSelection().empty(); } else if (window.getSelection().removeAllRanges && window.getSelection().rangeCount > 0 && window.getSelection().getRangeAt(0).getClientRects().length > 0) { window.getSelection().removeAllRanges(); } } else if (document['selection'] && document['selection'].empty) { try { document['selection'].empty(); } catch (error) {//ignore IE bug } } } }, { key: "calculateScrollbarWidth", value: function calculateScrollbarWidth(el) { if (el) { var style = getComputedStyle(el); return el.offsetWidth - el.clientWidth - parseFloat(style.borderLeftWidth) - parseFloat(style.borderRightWidth); } else { if (this.calculatedScrollbarWidth != null) return this.calculatedScrollbarWidth; var scrollDiv = document.createElement("div"); scrollDiv.className = "p-scrollbar-measure"; document.body.appendChild(scrollDiv); var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); this.calculatedScrollbarWidth = scrollbarWidth; return scrollbarWidth; } } }, { key: "getBrowser", value: function getBrowser() { if (!this.browser) { var matched = this.resolveUserAgent(); this.browser = {}; if (matched.browser) { this.browser[matched.browser] = true; this.browser['version'] = matched.version; } if (this.browser['chrome']) { this.browser['webkit'] = true; } else if (this.browser['webkit']) { this.browser['safari'] = true; } } return this.browser; } }, { key: "resolveUserAgent", value: function resolveUserAgent() { var ua = navigator.userAgent.toLowerCase(); var match = /(chrome)[ ]([\w.]+)/.exec(ua) || /(webkit)[ ]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ ]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; return { browser: match[1] || "", version: match[2] || "0" }; } }, { key: "isVisible", value: function isVisible(element) { return element && element.offsetParent != null; } }, { key: "isExist", value: function isExist(element) { return element !== null && typeof element !== 'undefined' && element.nodeName; } }, { key: "getFocusableElements", value: function getFocusableElements(element) { var selector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; var focusableElements = DomHandler.find(element, "button:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])".concat(selector, ",\n [href][clientHeight][clientWidth]:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n input:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n select:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n textarea:not([tabindex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n [tabIndex]:not([tabIndex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector, ",\n [contenteditable]:not([tabIndex = \"-1\"]):not([disabled]):not([style*=\"display:none\"]):not([hidden])").concat(selector)); var visibleFocusableElements = []; var _iterator3 = _createForOfIteratorHelper(focusableElements), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var focusableElement = _step3.value; if (getComputedStyle(focusableElement).display !== "none" && getComputedStyle(focusableElement).visibility !== "hidden") visibleFocusableElements.push(focusableElement); } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return visibleFocusableElements; } }, { key: "getFirstFocusableElement", value: function getFirstFocusableElement(element, selector) { var focusableElements = DomHandler.getFocusableElements(element, selector); return focusableElements.length > 0 ? focusableElements[0] : null; } }, { key: "getLastFocusableElement", value: function getLastFocusableElement(element, selector) { var focusableElements = DomHandler.getFocusableElements(element, selector); return focusableElements.length > 0 ? focusableElements[focusableElements.length - 1] : null; } }, { key: "getCursorOffset", value: function getCursorOffset(el, prevText, nextText, currentText) { if (el) { var style = getComputedStyle(el); var ghostDiv = document.createElement('div'); ghostDiv.style.position = 'absolute'; ghostDiv.style.top = '0px'; ghostDiv.style.left = '0px'; ghostDiv.style.visibility = 'hidden'; ghostDiv.style.pointerEvents = 'none'; ghostDiv.style.overflow = style.overflow; ghostDiv.style.width = style.width; ghostDiv.style.height = style.height; ghostDiv.style.padding = style.padding; ghostDiv.style.border = style.border; ghostDiv.style.overflowWrap = style.overflowWrap; ghostDiv.style.whiteSpace = style.whiteSpace; ghostDiv.style.lineHeight = style.lineHeight; ghostDiv.innerHTML = prevText.replace(/\r\n|\r|\n/g, '<br />'); var ghostSpan = document.createElement('span'); ghostSpan.textContent = currentText; ghostDiv.appendChild(ghostSpan); var text = document.createTextNode(nextText); ghostDiv.appendChild(text); document.body.appendChild(ghostDiv); var offsetLeft = ghostSpan.offsetLeft, offsetTop = ghostSpan.offsetTop, clientHeight = ghostSpan.clientHeight; document.body.removeChild(ghostDiv); return { left: Math.abs(offsetLeft - el.scrollLeft), top: Math.abs(offsetTop - el.scrollTop) + clientHeight }; } return { top: 'auto', left: 'auto' }; } }, { key: "invokeElementMethod", value: function invokeElementMethod(element, methodName, args) { element[methodName].apply(element, args); } }, { key: "isClickable", value: function isClickable(element) { var targetNode = element.nodeName; var parentNode = element.parentElement && element.parentElement.nodeName; return targetNode === 'INPUT' || targetNode === 'TEXTAREA' || targetNode === 'BUTTON' || targetNode === 'A' || parentNode === 'INPUT' || parentNode === 'TEXTAREA' || parentNode === 'BUTTON' || parentNode === 'A' || this.hasClass(element, 'p-button') || this.hasClass(element.parentElement, 'p-button') || this.hasClass(element.parentElement, 'p-checkbox') || this.hasClass(element.parentElement, 'p-radiobutton'); } }, { key: "applyStyle", value: function applyStyle(element, style) { if (typeof style === 'string') { element.style.cssText = this.style; } else { for (var prop in this.style) { element.style[prop] = style[prop]; } } } }, { key: "exportCSV", value: function exportCSV(csv, filename) { var blob = new Blob([csv], { type: 'application/csv;charset=utf-8;' }); if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveOrOpenBlob(blob, filename + '.csv'); } else { var link = document.createElement("a"); if (link.download !== undefined) { link.setAttribute('href', URL.createObjectURL(blob)); link.setAttribute('download', filename + '.csv'); link.style.display = 'none'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } else { csv = 'data:text/csv;charset=utf-8,' + csv; window.open(encodeURI(csv)); } } } }]); return DomHandler; }(); var ConnectedOverlayScrollHandler = /*#__PURE__*/function () { function ConnectedOverlayScrollHandler(element) { var listener = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {}; _classCallCheck(this, ConnectedOverlayScrollHandler); this.element = element; this.listener = listener; } _createClass(ConnectedOverlayScrollHandler, [{ key: "bindScrollListener", value: function bindScrollListener() { this.scrollableParents = DomHandler.getScrollableParents(this.element); for (var i = 0; i < this.scrollableParents.length; i++) { this.scrollableParents[i].addEventListener('scroll', this.listener); } } }, { key: "unbindScrollListener", value: function unbindScrollListener() { if (this.scrollableParents) { for (var i = 0; i < this.scrollableParents.length; i++) { this.scrollableParents[i].removeEventListener('scroll', this.listener); } } } }, { key: "destroy", value: function destroy() { this.unbindScrollListener(); this.element = null; this.listener = null; this.scrollableParents = null; } }]); return ConnectedOverlayScrollHandler; }(); function EventBus () { var allHandlers = new Map(); return { on: function on(type, handler) { var handlers = allHandlers.get(type); if (!handlers) handlers = [handler];else handlers.push(handler); allHandlers.set(type, handlers); }, off: function off(type, handler) { var handlers = allHandlers.get(type); handlers && handlers.splice(handlers.indexOf(handler) >>> 0, 1); }, emit: function emit(type, evt) { var handlers = allHandlers.get(type); handlers && handlers.slice().forEach(function (handler) { return handler(evt); }); } }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function mask(el, options) { var defaultOptions = { mask: null, slotChar: '_', autoClear: true, unmask: false, readOnly: false, onComplete: null, onChange: null, onFocus: null, onBlur: null }; options = _objectSpread$1(_objectSpread$1({}, defaultOptions), options); var tests, partialPosition, len, firstNonMaskPos, defs, androidChrome, lastRequiredNonMaskPos, oldVal, focusText, caretTimeoutId, buffer, defaultBuffer; var caret = function caret(first, last) { var range, begin, end; if (!el.offsetParent || el !== document.activeElement) { return; } if (typeof first === 'number') { begin = first; end = typeof last === 'number' ? last : begin; if (el.setSelectionRange) { el.setSelectionRange(begin, end); } else if (el['createTextRange']) { range = el['createTextRange'](); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } } else { if (el.setSelectionRange) { begin = el.selectionStart; end = el.selectionEnd; } else if (document['selection'] && document['selection'].createRange) { range = document['selection'].createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } return { begin: begin, end: end }; } }; var isCompleted = function isCompleted() { for (var i = firstNonMaskPos; i <= lastRequiredNonMaskPos; i++) { if (tests[i] && buffer[i] === getPlaceholder(i)) { return false; } } return true; }; var getPlaceholder = function getPlaceholder(i) { if (i < options.slotChar.length) { return options.slotChar.charAt(i); } return options.slotChar.charAt(0); }; var getValue = function getValue() { return options.unmask ? getUnmaskedValue() : el && el.value; }; var seekNext = function seekNext(pos) { while (++pos < len && !tests[pos]) { } return pos; }; var seekPrev = function seekPrev(pos) { while (--pos >= 0 && !tests[pos]) { } return pos; }; var shiftL = function shiftL(begin, end) { var i, j; if (begin < 0) { return; } for (i = begin, j = seekNext(end); i < len; i++) { if (tests[i]) { if (j < len && tests[i].test(buffer[j])) { buffer[i] = buffer[j]; buffer[j] = getPlaceholder(j); } else { break; } j = seekNext(j); } } writeBuffer(); caret(Math.max(firstNonMaskPos, begin)); }; var shiftR = function shiftR(pos) { var i, c, j, t; for (i = pos, c = getPlaceholder(pos); i < len; i++) { if (tests[i]) { j = seekNext(i); t = buffer[i]; buffer[i] = c; if (j < len && tests[j].test(t)) { c = t; } else { break; } } } }; var handleAndroidInput = function handleAndroidInput(e) { var curVal = el.value; var pos = caret(); if (oldVal && oldVal.length && oldVal.length > curVal.length) { // a deletion or backspace happened checkVal(true); while (pos.begin > 0 && !tests[pos.begin - 1]) { pos.begin--; } if (pos.begin === 0) { while (pos.begin < firstNonMaskPos && !tests[pos.begin]) { pos.begin++; } } caret(pos.begin, pos.begin); } else { checkVal(true); while (pos.begin < len && !tests[pos.begin]) { pos.begin++; } caret(pos.begin, pos.begin); } if (options.onComplete && isCompleted()) { options.onComplete({ originalEvent: e, value: getValue() }); } }; var onBlur = function onBlur(e) { checkVal(); updateModel(e); if (options.onBlur) { options.onBlur(e); } if (el.value !== focusText) { var event = document.createEvent('HTMLEvents'); event.initEvent('change', true, false); el.dispatchEvent(event); } }; var onKeyDown = function onKeyDown(e) { if (options.readOnly) { return; } var k = e.which || e.keyCode, pos, begin, end; var iPhone = /iphone/i.test(DomHandler.getUserAgent()); oldVal = el.value; //backspace, delete, and escape get special treatment if (k === 8 || k === 46 || iPhone && k === 127) { pos = caret(); begin = pos.begin; end = pos.end; if (end - begin === 0) { begin = k !== 46 ? seekPrev(begin) : end = seekNext(begin - 1); end = k === 46 ? seekNext(end) : end; } clearBuffer(begin, end); shiftL(begin, end - 1); updateModel(e); e.preventDefault(); } else if (k === 13) { // enter onBlur(e); updateModel(e); } else if (k === 27) { // escape el.value = focusText; caret(0, checkVal()); updateModel(e); e.preventDefault(); } }; var onKeyPress = function onKeyPress(e) { if (options.readOnly) { return; } var k = e.which || e.keyCode, pos = caret(), p, c, next, completed; if (e.ctrlKey || e.altKey || e.metaKey || k < 32) { //Ignore return; } else if (k && k !== 13) { if (pos.end - pos.begin !== 0) { clearBuffer(pos.begin, pos.end); shiftL(pos.begin, pos.end - 1); } p = seekNext(pos.begin - 1); if (p < len) { c = String.fromCharCode(k); if (tests[p].test(c)) { shiftR(p); buffer[p] = c; writeBuffer(); next = seekNext(p); if (/android/i.test(DomHandler.getUserAgent())) { //Path for CSP Violation on FireFox OS 1.1 var proxy = function proxy() { caret(next); }; setTimeout(proxy, 0); } else { caret(next); } if (pos.begin <= lastRequiredNonMaskPos) { completed = isCompleted(); } } } e.preventDefault(); } updateModel(e); if (options.onComplete && completed) { options.onComplete({ originalEvent: e, value: getValue() }); } }; var clearBuffer = function clearBuffer(start, end) { var i; for (i = start; i < end && i < len; i++) { if (tests[i]) { buffer[i] = getPlaceholder(i); } } }; var writeBuffer = function writeBuffer() { el.value = buffer.join(''); }; var checkVal = function checkVal(allow) { //try to place characters where they belong var test = el.value, lastMatch = -1, i, c, pos; for (i = 0, pos = 0; i < len; i++) { if (tests[i]) { buffer[i] = getPlaceholder(i); while (pos++ < test.length) { c = test.charAt(pos - 1); if (tests[i].test(c)) { buffer[i] = c; lastMatch = i; break; } } if (pos > test.length) { clearBuffer(i + 1, len); break; } } else { if (buffer[i] === test.charAt(pos)) { pos++; } if (i < partialPosition) { lastMatch = i; } } } if (allow) { writeBuffer(); } else if (lastMatch + 1 < partialPosition) { if (options.autoClear || buffer.join('') === defaultBuffer) { // Invalid value. Remove it and replace it with the // mask, which is the default behavior. if (el.value) el.value = ''; clearBuffer(0, len); } else { // Invalid value, but we opt to show the value to the // user and allow them to correct their mistake. writeBuffer(); } } else { writeBuffer(); el.value = el.value.substring(0, lastMatch + 1); } return partialPosition ? i : firstNonMaskPos; }; var onFocus = function onFocus(e) { if (options.readOnly) { return; } clearTimeout(caretTimeoutId); var pos; focusText = el.value; pos = checkVal(); caretTimeoutId = setTimeout(function () { if (el !== document.activeElement) { return; } writeBuffer(); if (pos === options.mask.replace("?", "").length) { caret(0, pos); } else { caret(pos); } }, 10); if (options.onFocus) { options.onFocus(e); } }; var onInput = function onInput(event) { if (androidChrome) handleAndroidInput(event);else handleInputChange(event); }; var handleInputChange = function handleInputChange(e) { if (options.readOnly) { return; } var pos = checkVal(true); caret(pos); updateModel(e); if (options.onComplete && isCompleted()) { options.onComplete({ originalEvent: e, value: getValue() }); } }; var getUnmaskedValue = function getUnmaskedValue() { var unmaskedBuffer = []; for (var i = 0; i < buffer.length; i++) { var c = buffer[i]; if (tests[i] && c !== getPlaceholder(i)) { unmaskedBuffer.push(c); } } return unmaskedBuffer.join(''); }; var updateModel = function updateModel(e) { if (options.onChange) { var val = getValue().replace(options.slotChar, ''); options.onChange({ originalEvent: e, value: defaultBuffer !== val ? val : '' }); } }; var bindEvents = function bindEvents() { el.addEventListener('focus', onFocus); el.addEventListener('blur', onBlur); el.addEventListener('keydown', onKeyDown); el.addEventListener('keypress', onKeyPress); el.addEventListener('input', onInput); el.addEventListener('paste', handleInputChange); }; var unbindEvents = function unbindEvents() { el.removeEventListener('focus', onFocus); el.removeEventListener('blur', onBlur); el.removeEventListener('keydown', onKeyDown); el.removeEventListener('keypress', onKeyPress); el.removeEventListener('input', onInput); el.removeEventListener('paste', handleInputChange); }; var init = function init() { tests = []; partialPosition = options.mask.length; len = options.mask.length; firstNonMaskPos = null; defs = { '9': '[0-9]', 'a': '[A-Za-z]', '*': '[A-Za-z0-9]' }; var ua = DomHandler.getUserAgent(); androidChrome = /chrome/i.test(ua) && /android/i.test(ua); var maskTokens = options.mask.split(''); for (var i = 0; i < maskTokens.length; i++) { var c = maskTokens[i]; if (c === '?') { len--; partialPosition = i; } else if (defs[c]) { tests.push(new RegExp(defs[c])); if (firstNonMaskPos === null) { firstNonMaskPos = tests.length - 1; } if (i < partialPosition) { lastRequiredNonMaskPos = tests.length - 1; } } else { tests.push(null); } } buffer = []; for (var _i = 0; _i < maskTokens.length; _i++) { var _c = maskTokens[_i]; if (_c !== '?') { if (defs[_c]) buffer.push(getPlaceholder(_i));else buffer.push(_c); } } defaultBuffer = buffer.join(''); }; if (el && options.mask) { init(); bindEvents(); } return { init: init, bindEvents: bindEvents, unbindEvents: unbindEvents, updateModel: updateModel, getValue: getValue }; } var ObjectUtils = /*#__PURE__*/function () { function ObjectUtils() { _classCallCheck(this, ObjectUtils); } _createClass(ObjectUtils, null, [{ key: "equals", value: function equals(obj1, obj2, field) { if (field && obj1 && _typeof(obj1) === 'object' && obj2 && _typeof(obj2) === 'object') return this.resolveFieldData(obj1, field) === this.resolveFieldData(obj2, field);else return this.deepEquals(obj1, obj2); } }, { key: "deepEquals", value: function deepEquals(a, b) { if (a === b) return true; if (a && b && _typeof(a) == 'object' && _typeof(b) == 'object') { var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; if (arrA && arrB) { length = a.length; if (length !== b.length) return false; for (i = length; i-- !== 0;) { if (!this.deepEquals(a[i], b[i])) return false; } return true; } if (arrA !== arrB) return false; var dateA = a instanceof Date, dateB = b instanceof Date; if (dateA !== dateB) return false; if (dateA && dateB) return a.getTime() === b.getTime(); var regexpA = a instanceof RegExp, regexpB = b instanceof RegExp; if (regexpA !== regexpB) return false; if (regexpA && regexpB) return a.toString() === b.toString(); var keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) { if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; } for (i = length; i-- !== 0;) { key = keys[i]; if (!this.deepEquals(a[key], b[key])) return false; } return true; } /*eslint no-self-compare: "off"*/ return a !== a && b !== b; } }, { key: "resolveFieldData", value: function resolveFieldData(data, field) { if (data && Object.keys(data).length && field) { if (this.isFunction(field)) { return field(data); } else if (field.indexOf('.') === -1) { return data[field]; } else { var fields = field.split('.'); var value = data; for (var i = 0, len = fields.length; i < len; ++i) { if (value == null) { return null; } value = value[fields[i]]; } return value; } } else { return null; } } }, { key: "isFunction", value: function isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); } }, { key: "findDiffKeys", value: function findDiffKeys(obj1, obj2) { if (!obj1 || !obj2) { return {}; } return Object.keys(obj1).filter(function (key) { return !obj2.hasOwnProperty(key); }).reduce(function (result, current) { result[current] = obj1[current]; return result; }, {}); } }, { key: "reorderArray", value: function reorderArray(value, from, to) { var target; if (value && from !== to) { if (to >= value.length) { target = to - value.length; while (target-- + 1) { value.push(undefined); } } value.splice(to, 0, value.splice(from, 1)[0]); } } }, { key: "findIndexInList", value: function findIndexInList(value, list, dataKey) { var _this = this; if (list) { return dataKey ? list.findIndex(function (item) { return _this.equals(item, value, dataKey); }) : list.findIndex(function (item) { return item === value; }); } return -1; } }, { key: "getJSXElement", value: function getJSXElement(obj) { for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { params[_key - 1] = arguments[_key]; } return this.isFunction(obj) ? obj.apply(void 0, params) : obj; } }, { key: "getPropValue", value: function getPropValue(obj) { for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { params[_key2 - 1] = arguments[_key2]; } return this.isFunction(obj) ? obj.apply(void 0, params) : obj; } }, { key: "getRefElement", value: function getRefElement(ref) { if (ref) { return _typeof(ref) === 'object' && ref.hasOwnProperty('current') ? ref.current : ref; } return null; } }, { key: "removeAccents", value: function removeAccents(str) { if (str && str.search(/[\xC0-\xFF]/g) > -1) { str = str.replace(/[\xC0-\xC5]/g, "A").replace(/[\xC6]/g, "AE").replace(/[\xC7]/g, "C").replace(/[\xC8-\xCB]/g, "E").replace(/[\xCC-\xCF]/g, "I").replace(/[\xD0]/g, "D").replace(/[\xD1]/g, "N").replace(/[\xD2-\xD6\xD8]/g, "O").replace(/[\xD9-\xDC]/g, "U").replace(/[\xDD]/g, "Y").replace(/[\xDE]/g, "P").replace(/[\xE0-\xE5]/g, "a").replace(/[\xE6]/g, "ae").replace(/[\xE7]/g, "c").replace(/[\xE8-\xEB]/g, "e").replace(/[\xEC-\xEF]/g, "i").replace(/[\xF1]/g, "n").replace(/[\xF2-\xF6\xF8]/g, "o").replace(/[\xF9-\xFC]/g, "u").replace(/[\xFE]/g, "p").replace(/[\xFD\xFF]/g, "y"); } return str; } }, { key: "isEmpty", value: function isEmpty(value) { return value === null || value === undefined || value === '' || Array.isArray(value) && value.length === 0 || !(value instanceof Date) && _typeof(value) === 'object' && Object.keys(value).length === 0; } }, { key: "isNotEmpty", value: function isNotEmpty(value) { return !this.isEmpty(value); } }]); return ObjectUtils; }(); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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; } var IconUtils = /*#__PURE__*/function () { function IconUtils() { _classCallCheck(this, IconUtils); } _createClass(IconUtils, null, [{ key: "getJSXIcon", value: function getJSXIcon(icon, iconProps, options) { var content = null; if (icon) { var iconType = _typeof(icon); var className = classNames(iconProps.className, iconType === 'string' && icon); content = /*#__PURE__*/React.createElement("span", _extends({}, iconProps, { className: className })); if (iconType !== 'string') { var defaultContentOptions = _objectSpread({ iconProps: iconProps, element: content }, options); return ObjectUtils.getJSXElement(icon, defaultContentOptions); } } return content; } }]); return IconUtils; }(); var lastId = 0; function UniqueComponentId () { var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'pr_id_'; lastId++; return "".concat(prefix).concat(lastId); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$1(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread(); } function handler() { var zIndexes = []; var generateZIndex = function generateZIndex(key, autoZIndex) { var baseZIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 999; var lastZIndex = getLastZIndex(key, autoZIndex, baseZIndex); var newZIndex = lastZIndex.value + (lastZIndex.key === key ? 0 : baseZIndex) + 1; zIndexes.push({ key: key, value: newZIndex }); return newZIndex; }; var revertZIndex = function revertZIndex(zIndex) { zIndexes = zIndexes.filter(function (obj) { return obj.value !== zIndex; }); }; var getCurrentZIndex = function getCurrentZIndex(key, autoZIndex) { return getLastZIndex(key, autoZIndex).value; }; var getLastZIndex = function getLastZIndex(key, autoZIndex) { var baseZIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; return _toConsumableArray(zIndexes).reverse().find(function (obj) { return autoZIndex ? true : obj.key === key; }) || { key: key, value: baseZIndex }; }; var getZIndex = function getZIndex(el) { return el ? parseInt(el.style.zIndex, 10) || 0 : 0; }; return { get: getZIndex, set: function set(key, el, autoZIndex, baseZIndex) { if (el) { el.style.zIndex = String(generateZIndex(key, autoZIndex, baseZIndex)); } }, clear: function clear(el) { if (el) { revertZIndex(ZIndexUtils.get(el)); el.style.zIndex = ''; } }, getCurrent: function getCurrent(key, autoZIndex) { return getCurrentZIndex(key, autoZIndex); } }; } var ZIndexUtils = handler(); export { ConnectedOverlayScrollHandler, DomHandler, EventBus, IconUtils, ObjectUtils, UniqueComponentId, ZIndexUtils, classNames, mask };
ajax/libs/react-native-web/0.17.4/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) 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 /*#__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.0.0-583e16fa8/vendor/react-native/Animated/createAnimatedComponent.js
cdnjs/cdnjs
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @format */ 'use strict'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } import { AnimatedEvent } from './AnimatedEvent'; import AnimatedProps from './nodes/AnimatedProps'; import React from 'react'; import invariant from 'fbjs/lib/invariant'; import mergeRefs from '../../../modules/mergeRefs'; function createAnimatedComponent(Component, defaultProps) { invariant(typeof Component !== 'function' || Component.prototype && Component.prototype.isReactComponent, '`createAnimatedComponent` does not support stateless functional components; ' + 'use a class component instead.'); var AnimatedComponent = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(AnimatedComponent, _React$Component); function AnimatedComponent(props) { var _this; _this = _React$Component.call(this, props) || this; _this._invokeAnimatedPropsCallbackOnMount = false; _this._eventDetachers = []; _this._animatedPropsCallback = function () { if (_this._component == null) { // AnimatedProps is created in will-mount because it's used in render. // But this callback may be invoked before mount in async mode, // In which case we should defer the setNativeProps() call. // React may throw away uncommitted work in async mode, // So a deferred call won't always be invoked. _this._invokeAnimatedPropsCallbackOnMount = true; } else if (AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY || typeof _this._component.setNativeProps !== 'function') { _this.forceUpdate(); } else if (!_this._propsAnimated.__isNative) { _this._component.setNativeProps(_this._propsAnimated.__getAnimatedValue()); } else { throw new Error('Attempting to run JS driven animation on animated ' + 'node that has been moved to "native" earlier by starting an ' + 'animation with `useNativeDriver: true`'); } }; _this._setComponentRef = mergeRefs(_this.props.forwardedRef, function (ref) { _this._prevComponent = _this._component; _this._component = ref; // TODO: Delete this in a future release. if (ref != null && ref.getNode == null) { ref.getNode = function () { var _ref$constructor$name; console.warn('%s: Calling `getNode()` on the ref of an Animated component ' + 'is no longer necessary. You can now directly use the ref ' + 'instead. This method will be removed in a future release.', (_ref$constructor$name = ref.constructor.name) !== null && _ref$constructor$name !== void 0 ? _ref$constructor$name : '<<anonymous>>'); return ref; }; } }); return _this; } var _proto = AnimatedComponent.prototype; _proto.componentWillUnmount = function componentWillUnmount() { this._propsAnimated && this._propsAnimated.__detach(); this._detachNativeEvents(); }; _proto.UNSAFE_componentWillMount = function UNSAFE_componentWillMount() { this._attachProps(this.props); }; _proto.componentDidMount = function componentDidMount() { if (this._invokeAnimatedPropsCallbackOnMount) { this._invokeAnimatedPropsCallbackOnMount = false; this._animatedPropsCallback(); } this._propsAnimated.setNativeView(this._component); this._attachNativeEvents(); }; _proto._attachNativeEvents = function _attachNativeEvents() { var _this2 = this; // Make sure to get the scrollable node for components that implement // `ScrollResponder.Mixin`. var scrollableNode = this._component && this._component.getScrollableNode ? this._component.getScrollableNode() : this._component; var _loop = function _loop(key) { var prop = _this2.props[key]; if (prop instanceof AnimatedEvent && prop.__isNative) { prop.__attach(scrollableNode, key); _this2._eventDetachers.push(function () { return prop.__detach(scrollableNode, key); }); } }; for (var key in this.props) { _loop(key); } }; _proto._detachNativeEvents = function _detachNativeEvents() { this._eventDetachers.forEach(function (remove) { return remove(); }); this._eventDetachers = []; } // The system is best designed when setNativeProps is implemented. It is // able to avoid re-rendering and directly set the attributes that changed. // However, setNativeProps can only be implemented on leaf native // components. If you want to animate a composite component, you need to // re-render it. In this case, we have a fallback that uses forceUpdate. ; _proto._attachProps = function _attachProps(nextProps) { var oldPropsAnimated = this._propsAnimated; this._propsAnimated = new AnimatedProps(nextProps, this._animatedPropsCallback); // When you call detach, it removes the element from the parent list // of children. If it goes to 0, then the parent also detaches itself // and so on. // An optimization is to attach the new elements and THEN detach the old // ones instead of detaching and THEN attaching. // This way the intermediate state isn't to go to 0 and trigger // this expensive recursive detaching to then re-attach everything on // the very next operation. oldPropsAnimated && oldPropsAnimated.__detach(); }; _proto.UNSAFE_componentWillReceiveProps = function UNSAFE_componentWillReceiveProps(newProps) { this._attachProps(newProps); }; _proto.componentDidUpdate = function componentDidUpdate(prevProps) { if (this._component !== this._prevComponent) { this._propsAnimated.setNativeView(this._component); } if (this._component !== this._prevComponent || prevProps !== this.props) { this._detachNativeEvents(); this._attachNativeEvents(); } }; _proto.render = function render() { var props = this._propsAnimated.__getValue(); return React.createElement(Component, _extends({}, defaultProps, props, { ref: this._setComponentRef // The native driver updates views directly through the UI thread so we // have to make sure the view doesn't get optimized away because it cannot // go through the NativeViewHierarchyManager since it operates on the shadow // thread. , collapsable: false })); }; return AnimatedComponent; }(React.Component); AnimatedComponent.__skipSetNativeProps_FOR_TESTS_ONLY = false; var propTypes = Component.propTypes; return React.forwardRef(function AnimatedComponentWrapper(props, ref) { return React.createElement(AnimatedComponent, _extends({}, props, ref == null ? null : { forwardedRef: ref })); }); } export default createAnimatedComponent;
ajax/libs/react-native-web/0.0.0-20f889ecc/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/primereact/7.2.0/tabview/tabview.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, UniqueComponentId, classNames, ObjectUtils } from 'primereact/utils'; import { Ripple } from 'primereact/ripple'; 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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } 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 _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 } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TabPanel = /*#__PURE__*/function (_Component) { _inherits(TabPanel, _Component); var _super = _createSuper(TabPanel); function TabPanel() { _classCallCheck(this, TabPanel); return _super.apply(this, arguments); } return _createClass(TabPanel); }(Component); _defineProperty(TabPanel, "defaultProps", { header: null, headerTemplate: null, leftIcon: null, rightIcon: null, closable: false, disabled: false, style: null, className: null, headerStyle: null, headerClassName: null, contentStyle: null, contentClassName: null }); var TabView = /*#__PURE__*/function (_Component2) { _inherits(TabView, _Component2); var _super2 = _createSuper(TabView); function TabView(props) { var _this; _classCallCheck(this, TabView); _this = _super2.call(this, props); var state = { id: props.id, backwardIsDisabled: true, forwardIsDisabled: false, hiddenTabs: [] }; if (!_this.props.onTabChange) { state = _objectSpread(_objectSpread({}, state), {}, { activeIndex: props.activeIndex }); } _this.state = state; _this.navBackward = _this.navBackward.bind(_assertThisInitialized(_this)); _this.navForward = _this.navForward.bind(_assertThisInitialized(_this)); _this.onScroll = _this.onScroll.bind(_assertThisInitialized(_this)); return _this; } _createClass(TabView, [{ key: "getActiveIndex", value: function getActiveIndex() { return this.props.onTabChange ? this.props.activeIndex : this.state.activeIndex; } }, { key: "isSelected", value: function isSelected(index) { return index === this.getActiveIndex(); } }, { key: "shouldTabRender", value: function shouldTabRender(tab, index) { return tab && tab.type === TabPanel && this.state.hiddenTabs.every(function (_i) { return _i !== index; }); } }, { key: "findVisibleActiveTab", value: function findVisibleActiveTab(i) { var _this2 = this; var tabsInfo = React.Children.map(this.props.children, function (tab, index) { if (_this2.shouldTabRender(tab, index)) { return { tab: tab, index: index }; } }); return tabsInfo.find(function (_ref) { var tab = _ref.tab, index = _ref.index; return !tab.props.disabled && index >= i; }) || tabsInfo.reverse().find(function (_ref2) { var tab = _ref2.tab, index = _ref2.index; return !tab.props.disabled && i > index; }); } }, { key: "onTabHeaderClose", value: function onTabHeaderClose(event, index) { var _this3 = this; var hiddenTabs = [].concat(_toConsumableArray(this.state.hiddenTabs), [index]); this.setState({ hiddenTabs: hiddenTabs }, function () { var tabInfo = _this3.findVisibleActiveTab(index); tabInfo && _this3.onTabHeaderClick(event, tabInfo.tab, tabInfo.index); }); if (this.props.onTabClose) { this.props.onTabClose({ originalEvent: event, index: index }); } event.preventDefault(); } }, { key: "onTabHeaderClick", value: function onTabHeaderClick(event, tab, index) { if (!tab.props.disabled) { if (this.props.onTabChange) { this.props.onTabChange({ originalEvent: event, index: index }); } else { this.setState({ activeIndex: index }); } } this.updateScrollBar(index); event.preventDefault(); } }, { key: "onKeyDown", value: function onKeyDown(event, tab, index) { if (event.code === 'Enter') { this.onTabHeaderClick(event, tab, index); } } }, { key: "updateInkBar", value: function updateInkBar() { var activeIndex = this.getActiveIndex(); var tabHeader = this["tab_".concat(activeIndex)]; this.inkbar.style.width = DomHandler.getWidth(tabHeader) + 'px'; this.inkbar.style.left = DomHandler.getOffset(tabHeader).left - DomHandler.getOffset(this.nav).left + 'px'; } }, { key: "updateScrollBar", value: function updateScrollBar(index) { var tabHeader = this["tab_".concat(index)]; if (tabHeader) { tabHeader.scrollIntoView({ block: 'nearest' }); } } }, { key: "updateButtonState", value: function updateButtonState() { var content = this.content; var scrollLeft = content.scrollLeft, scrollWidth = content.scrollWidth; var width = DomHandler.getWidth(content); this.setState({ backwardIsDisabled: scrollLeft === 0 }); this.setState({ forwardIsDisabled: scrollLeft === scrollWidth - width }); } }, { key: "onScroll", value: function onScroll(event) { this.props.scrollable && this.updateButtonState(); event.preventDefault(); } }, { key: "getVisibleButtonWidths", value: function getVisibleButtonWidths() { var prevBtn = this.prevBtn; var nextBtn = this.nextBtn; return [prevBtn, nextBtn].reduce(function (acc, el) { return el ? acc + DomHandler.getWidth(el) : acc; }, 0); } }, { key: "navBackward", value: function navBackward() { var content = this.content; var width = DomHandler.getWidth(content) - this.getVisibleButtonWidths(); var pos = content.scrollLeft - width; content.scrollLeft = pos <= 0 ? 0 : pos; } }, { key: "navForward", value: function navForward() { var content = this.content; var width = DomHandler.getWidth(content) - this.getVisibleButtonWidths(); var pos = content.scrollLeft + width; var lastPos = content.scrollWidth - width; content.scrollLeft = pos >= lastPos ? lastPos : pos; } }, { key: "reset", value: function reset() { var state = { backwardIsDisabled: true, forwardIsDisabled: false, hiddenTabs: [] }; if (this.props.onTabChange) { this.props.onTabChange({ index: this.props.activeIndex }); } else { state = _objectSpread(_objectSpread({}, state), {}, { activeIndex: this.props.activeIndex }); } this.setState(state); } }, { key: "componentDidMount", value: function componentDidMount() { if (!this.state.id) { this.setState({ id: UniqueComponentId() }); } this.updateInkBar(); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { this.updateInkBar(); if (prevProps.activeIndex !== this.props.activeIndex) { this.updateScrollBar(this.props.activeIndex); } } }, { key: "renderTabHeader", value: function renderTabHeader(tab, index) { var _this4 = this; var selected = this.isSelected(index); var style = _objectSpread(_objectSpread({}, tab.props.headerStyle || {}), tab.props.style || {}); var className = classNames('p-unselectable-text', { 'p-tabview-selected p-highlight': selected, 'p-disabled': tab.props.disabled }, tab.props.headerClassName, tab.props.className); var id = this.state.id + '_header_' + index; var ariaControls = this.state.id + '_content_' + index; var tabIndex = tab.props.disabled ? null : 0; var leftIconElement = tab.props.leftIcon && /*#__PURE__*/React.createElement("i", { className: tab.props.leftIcon }); var titleElement = /*#__PURE__*/React.createElement("span", { className: "p-tabview-title" }, tab.props.header); var rightIconElement = tab.props.rightIcon && /*#__PURE__*/React.createElement("i", { className: tab.props.rightIcon }); var closableIconElement = tab.props.closable && /*#__PURE__*/React.createElement("i", { className: "p-tabview-close pi pi-times", onClick: function onClick(e) { return _this4.onTabHeaderClose(e, index); } }); var content = /*#__PURE__*/ /* eslint-disable */ React.createElement("a", { role: "tab", className: "p-tabview-nav-link", onClick: function onClick(event) { return _this4.onTabHeaderClick(event, tab, index); }, id: id, onKeyDown: function onKeyDown(event) { return _this4.onKeyDown(event, tab, index); }, "aria-controls": ariaControls, "aria-selected": selected, tabIndex: tabIndex }, leftIconElement, titleElement, rightIconElement, closableIconElement, /*#__PURE__*/React.createElement(Ripple, null)) /* eslint-enable */ ; if (tab.props.headerTemplate) { var defaultContentOptions = { className: 'p-tabview-nav-link', titleClassName: 'p-tabview-title', onClick: function onClick(event) { return _this4.onTabHeaderClick(event, tab, index); }, onKeyDown: function onKeyDown(event) { return _this4.onKeyDown(event, tab, index); }, leftIconElement: leftIconElement, titleElement: titleElement, rightIconElement: rightIconElement, element: content, props: this.props, index: index, selected: selected, ariaControls: ariaControls }; content = ObjectUtils.getJSXElement(tab.props.headerTemplate, defaultContentOptions); } return /*#__PURE__*/React.createElement("li", { ref: function ref(el) { return _this4["tab_".concat(index)] = el; }, className: className, style: style, role: "presentation" }, content); } }, { key: "renderTabHeaders", value: function renderTabHeaders() { var _this5 = this; return React.Children.map(this.props.children, function (tab, index) { if (_this5.shouldTabRender(tab, index)) { return _this5.renderTabHeader(tab, index); } }); } }, { key: "renderNavigator", value: function renderNavigator() { var _this6 = this; var headers = this.renderTabHeaders(); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this6.content = el; }, id: this.props.id, className: "p-tabview-nav-content", style: this.props.style, onScroll: this.onScroll }, /*#__PURE__*/React.createElement("ul", { ref: function ref(el) { return _this6.nav = el; }, className: "p-tabview-nav", role: "tablist" }, headers, /*#__PURE__*/React.createElement("li", { ref: function ref(el) { return _this6.inkbar = el; }, className: "p-tabview-ink-bar" }))); } }, { key: "renderContent", value: function renderContent() { var _this7 = this; var contents = React.Children.map(this.props.children, function (tab, index) { if (_this7.shouldTabRender(tab, index) && (!_this7.props.renderActiveOnly || _this7.isSelected(index))) { return _this7.createContent(tab, index); } }); return /*#__PURE__*/React.createElement("div", { className: "p-tabview-panels" }, contents); } }, { key: "createContent", value: function createContent(tab, index) { var selected = this.isSelected(index); var style = _objectSpread(_objectSpread({}, tab.props.contentStyle || {}), tab.props.style || {}); var className = classNames(tab.props.contentClassName, tab.props.className, 'p-tabview-panel', { 'p-hidden': !selected }); var id = this.state.id + '_content_' + index; var ariaLabelledBy = this.state.id + '_header_' + index; return /*#__PURE__*/React.createElement("div", { id: id, "aria-labelledby": ariaLabelledBy, "aria-hidden": !selected, className: className, style: style, role: "tabpanel" }, !this.props.renderActiveOnly ? tab.props.children : selected && tab.props.children); } }, { key: "renderPrevButton", value: function renderPrevButton() { var _this8 = this; if (this.props.scrollable && !this.state.backwardIsDisabled) { return /*#__PURE__*/React.createElement("button", { ref: function ref(el) { return _this8.prevBtn = el; }, className: "p-tabview-nav-prev p-tabview-nav-btn p-link", onClick: this.navBackward, type: "button" }, /*#__PURE__*/React.createElement("span", { className: "pi pi-chevron-left" }), /*#__PURE__*/React.createElement(Ripple, null)); } return null; } }, { key: "renderNextButton", value: function renderNextButton() { var _this9 = this; if (this.props.scrollable && !this.state.forwardIsDisabled) { return /*#__PURE__*/React.createElement("button", { ref: function ref(el) { return _this9.nextBtn = el; }, className: "p-tabview-nav-next p-tabview-nav-btn p-link", onClick: this.navForward, type: "button" }, /*#__PURE__*/React.createElement("span", { className: "pi pi-chevron-right" }), /*#__PURE__*/React.createElement(Ripple, null)); } } }, { key: "render", value: function render() { var className = classNames('p-tabview p-component', this.props.className, { 'p-tabview-scrollable': this.props.scrollable }); var navigator = this.renderNavigator(); var content = this.renderContent(); var prevButton = this.renderPrevButton(); var nextButton = this.renderNextButton(); return /*#__PURE__*/React.createElement("div", { className: className }, /*#__PURE__*/React.createElement("div", { className: "p-tabview-nav-container" }, prevButton, navigator, nextButton), content); } }]); return TabView; }(Component); _defineProperty(TabView, "defaultProps", { id: null, activeIndex: 0, style: null, className: null, renderActiveOnly: true, onTabChange: null, onTabClose: null, scrollable: false }); export { TabPanel, TabView };
ajax/libs/react-native-web/0.13.5/exports/ScrollView/index.js
cdnjs/cdnjs
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import createReactClass from 'create-react-class'; import dismissKeyboard from '../../modules/dismissKeyboard'; import invariant from 'fbjs/lib/invariant'; import 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.4/esm/ExpansionPanelDetails/ExpansionPanelDetails.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; export var styles = { /* Styles applied to the root element. */ root: { display: 'flex', padding: '8px 24px 24px' } }; var ExpansionPanelDetails = React.forwardRef(function ExpansionPanelDetails(props, ref) { var classes = props.classes, className = props.className, other = _objectWithoutProperties(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.4/es/List/List.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 ListContext from './ListContext'; export const styles = { /* Styles applied to the root element. */ root: { listStyle: 'none', margin: 0, padding: 0, position: 'relative' }, /* Styles applied to the root element if `disablePadding={false}`. */ padding: { paddingTop: 8, paddingBottom: 8 }, /* Styles applied to the root element if dense. */ dense: {}, /* Styles applied to the root element if a `subheader` is provided. */ subheader: { paddingTop: 0 } }; const List = React.forwardRef(function List(props, ref) { const { children, classes, className, component: Component = 'ul', dense = false, disablePadding = false, subheader } = props, other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "component", "dense", "disablePadding", "subheader"]); const context = React.useMemo(() => ({ dense }), [dense]); return React.createElement(ListContext.Provider, { value: context }, React.createElement(Component, _extends({ className: clsx(classes.root, className, dense && classes.dense, !disablePadding && classes.padding, subheader && classes.subheader), ref: ref }, other), subheader, children)); }); process.env.NODE_ENV !== "production" ? List.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * If `true`, compact vertical padding designed for keyboard and mouse input will be used for * the list and list items. * The prop is available to descendant components as the `dense` context. */ dense: PropTypes.bool, /** * If `true`, vertical padding will be removed from the list. */ disablePadding: PropTypes.bool, /** * The content of the subheader, normally `ListSubheader`. */ subheader: PropTypes.node } : void 0; export default withStyles(styles, { name: 'MuiList' })(List);
ajax/libs/primereact/7.1.0/tree/tree.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, ObjectUtils, classNames } from 'primereact/utils'; import { Ripple } from 'primereact/ripple'; 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 _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$2(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } 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 _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$2(arr) || _nonIterableSpread(); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _createForOfIteratorHelper$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 ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var UITreeNode = /*#__PURE__*/function (_Component) { _inherits(UITreeNode, _Component); var _super = _createSuper$1(UITreeNode); function UITreeNode(props) { var _this; _classCallCheck(this, UITreeNode); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onDoubleClick = _this.onDoubleClick.bind(_assertThisInitialized(_this)); _this.onRightClick = _this.onRightClick.bind(_assertThisInitialized(_this)); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this)); _this.onTogglerClick = _this.onTogglerClick.bind(_assertThisInitialized(_this)); _this.onNodeKeyDown = _this.onNodeKeyDown.bind(_assertThisInitialized(_this)); _this.propagateUp = _this.propagateUp.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); _this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_this)); _this.onDragEnter = _this.onDragEnter.bind(_assertThisInitialized(_this)); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this)); _this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this)); _this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this)); _this.onDropPointDragOver = _this.onDropPointDragOver.bind(_assertThisInitialized(_this)); _this.onDropPointDragEnter = _this.onDropPointDragEnter.bind(_assertThisInitialized(_this)); _this.onDropPointDragLeave = _this.onDropPointDragLeave.bind(_assertThisInitialized(_this)); return _this; } _createClass(UITreeNode, [{ key: "isLeaf", value: function isLeaf() { return this.props.isNodeLeaf(this.props.node); } }, { key: "expand", value: function expand(event) { var expandedKeys = this.props.expandedKeys ? _objectSpread$1({}, 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$1({}, this.props.expandedKeys); delete expandedKeys[this.props.node.key]; this.props.onToggle({ originalEvent: event, value: expandedKeys }); this.invokeToggleEvents(event, false); } }, { key: "onTogglerClick", value: function onTogglerClick(event) { if (this.props.disabled) { return; } if (this.isExpanded()) this.collapse(event);else this.expand(event); } }, { 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: "isExpanded", value: function isExpanded() { return (this.props.expandedKeys ? this.props.expandedKeys[this.props.node.key] !== undefined : false) || this.props.node.expanded; } }, { key: "onNodeKeyDown", value: function onNodeKeyDown(event) { if (this.props.disabled) { return; } var nodeElement = event.target.parentElement; if (!DomHandler.hasClass(nodeElement, 'p-treenode')) { return; } switch (event.which) { //down arrow case 40: var listElement = nodeElement.children[1]; if (listElement) { this.focusNode(listElement.children[0]); } else { var nextNodeElement = nodeElement.nextElementSibling; if (nextNodeElement) { this.focusNode(nextNodeElement); } else { var nextSiblingAncestor = this.findNextSiblingOfAncestor(nodeElement); if (nextSiblingAncestor) { this.focusNode(nextSiblingAncestor); } } } event.preventDefault(); break; //up arrow case 38: if (nodeElement.previousElementSibling) { this.focusNode(this.findLastVisibleDescendant(nodeElement.previousElementSibling)); } else { var parentNodeElement = this.getParentNodeElement(nodeElement); if (parentNodeElement) { this.focusNode(parentNodeElement); } } 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: "findNextSiblingOfAncestor", value: function findNextSiblingOfAncestor(nodeElement) { var parentNodeElement = this.getParentNodeElement(nodeElement); if (parentNodeElement) { if (parentNodeElement.nextElementSibling) return parentNodeElement.nextElementSibling;else return this.findNextSiblingOfAncestor(parentNodeElement); } else { return null; } } }, { key: "findLastVisibleDescendant", value: function findLastVisibleDescendant(nodeElement) { var childrenListElement = nodeElement.children[1]; if (childrenListElement) { var lastChildElement = childrenListElement.children[childrenListElement.children.length - 1]; return this.findLastVisibleDescendant(lastChildElement); } else { return nodeElement; } } }, { key: "getParentNodeElement", value: function getParentNodeElement(nodeElement) { var parentNodeElement = nodeElement.parentElement.parentElement; return DomHandler.hasClass(parentNodeElement, 'p-treenode') ? parentNodeElement : null; } }, { key: "focusNode", value: function focusNode(element) { element.children[0].focus(); } }, { key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, node: this.props.node }); } if (event.target.className && event.target.className.constructor === String && event.target.className.indexOf('p-tree-toggler') === 0 || this.props.disabled) { return; } if (this.props.selectionMode && this.props.node.selectable !== false) { var selectionKeys; if (this.isCheckboxSelectionMode()) { var checked = this.isChecked(); selectionKeys = this.props.selectionKeys ? _objectSpread$1({}, 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 }); } } } else { var selected = this.isSelected(); var metaSelection = this.nodeTouched ? false : this.props.metaKeySelection; 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[this.props.node.key]; } if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: this.props.node }); } } else { if (this.isSingleSelectionMode()) { selectionKeys = this.props.node.key; } else if (this.isMultipleSelectionMode()) { selectionKeys = !metaKey ? {} : this.props.selectionKeys ? _objectSpread$1({}, this.props.selectionKeys) : {}; selectionKeys[this.props.node.key] = true; } if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: this.props.node }); } } } else { if (this.isSingleSelectionMode()) { if (selected) { selectionKeys = null; if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: this.props.node }); } } else { selectionKeys = this.props.node.key; if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: this.props.node }); } } } else { if (selected) { selectionKeys = _objectSpread$1({}, this.props.selectionKeys); delete selectionKeys[this.props.node.key]; if (this.props.onUnselect) { this.props.onUnselect({ originalEvent: event, node: this.props.node }); } } else { selectionKeys = this.props.selectionKeys ? _objectSpread$1({}, this.props.selectionKeys) : {}; selectionKeys[this.props.node.key] = true; if (this.props.onSelect) { this.props.onSelect({ originalEvent: event, node: this.props.node }); } } } } } if (this.props.onSelectionChange) { this.props.onSelectionChange({ originalEvent: event, value: selectionKeys }); } } this.nodeTouched = false; } }, { key: "onDoubleClick", value: function onDoubleClick(event) { if (this.props.onDoubleClick) { this.props.onDoubleClick({ originalEvent: event, node: this.props.node }); } } }, { key: "onRightClick", value: function onRightClick(event) { if (this.props.disabled) { return; } DomHandler.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: "propagateUp", value: function propagateUp(event) { var check = event.check; var selectionKeys = event.selectionKeys; var checkedChildCount = 0; var childPartialSelected = false; var _iterator = _createForOfIteratorHelper$1(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 delete selectionKeys[this.props.node.key]; } 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: "isSelected", value: function isSelected() { if (this.props.selectionMode && this.props.selectionKeys) return this.isSingleSelectionMode() ? 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: "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: "isCheckboxSelectionMode", value: function isCheckboxSelectionMode() { return this.props.selectionMode && this.props.selectionMode === 'checkbox'; } }, { key: "onTouchEnd", value: function onTouchEnd() { this.nodeTouched = true; } }, { key: "onDropPoint", value: function onDropPoint(event, position) { event.preventDefault(); if (this.props.node.droppable !== false) { DomHandler.removeClass(event.target, 'p-treenode-droppoint-active'); if (this.props.onDropPoint) { this.props.onDropPoint({ originalEvent: event, path: this.props.path, index: this.props.index, position: position }); } } } }, { key: "onDropPointDragOver", value: function onDropPointDragOver(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) { event.dataTransfer.dropEffect = 'move'; event.preventDefault(); } } }, { key: "onDropPointDragEnter", value: function onDropPointDragEnter(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) { DomHandler.addClass(event.target, 'p-treenode-droppoint-active'); } } }, { key: "onDropPointDragLeave", value: function onDropPointDragLeave(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) { DomHandler.removeClass(event.target, 'p-treenode-droppoint-active'); } } }, { key: "onDrop", value: function onDrop(event) { if (this.props.dragdropScope && this.props.node.droppable !== false) { DomHandler.removeClass(this.contentElement, 'p-treenode-dragover'); event.preventDefault(); event.stopPropagation(); if (this.props.onDrop) { this.props.onDrop({ originalEvent: event, path: this.props.path, index: this.props.index }); } } } }, { key: "onDragOver", value: function onDragOver(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) { event.dataTransfer.dropEffect = 'move'; event.preventDefault(); event.stopPropagation(); } } }, { key: "onDragEnter", value: function onDragEnter(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) { DomHandler.addClass(this.contentElement, 'p-treenode-dragover'); } } }, { key: "onDragLeave", value: function onDragLeave(event) { if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) { var rect = event.currentTarget.getBoundingClientRect(); if (event.nativeEvent.x > rect.left + rect.width || event.nativeEvent.x < rect.left || event.nativeEvent.y >= Math.floor(rect.top + rect.height) || event.nativeEvent.y < rect.top) { DomHandler.removeClass(this.contentElement, 'p-treenode-dragover'); } } } }, { key: "onDragStart", value: function onDragStart(event) { event.dataTransfer.setData("text", this.props.dragdropScope); event.dataTransfer.setData(this.props.dragdropScope, this.props.dragdropScope); if (this.props.onDragStart) { this.props.onDragStart({ originalEvent: event, path: this.props.path, index: this.props.index }); } } }, { key: "onDragEnd", value: function onDragEnd(event) { if (this.props.onDragEnd) { this.props.onDragEnd({ originalEvent: event }); } } }, { key: "renderLabel", value: function renderLabel() { var content = /*#__PURE__*/React.createElement("span", { className: "p-treenode-label" }, this.props.node.label); if (this.props.nodeTemplate) { var defaultContentOptions = { onTogglerClick: this.onTogglerClick, className: 'p-treenode-label', element: content, props: this.props, expanded: this.isExpanded() }; content = ObjectUtils.getJSXElement(this.props.nodeTemplate, this.props.node, defaultContentOptions); } return content; } }, { key: "renderCheckbox", value: function renderCheckbox() { if (this.isCheckboxSelectionMode() && 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, 'p-disabled': this.props.disabled }); 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-component" }, /*#__PURE__*/React.createElement("div", { className: className, role: "checkbox", "aria-checked": checked }, /*#__PURE__*/React.createElement("span", { className: icon }))); } return null; } }, { key: "renderIcon", value: function renderIcon(expanded) { var icon = this.props.node.icon || (expanded ? this.props.node.expandedIcon : this.props.node.collapsedIcon); if (icon) { var className = classNames('p-treenode-icon', icon); return /*#__PURE__*/React.createElement("span", { className: className }); } return null; } }, { key: "renderToggler", value: function renderToggler(expanded) { var iconClassName = classNames('p-tree-toggler-icon pi pi-fw', { 'pi-chevron-right': !expanded, 'pi-chevron-down': expanded }); var content = /*#__PURE__*/React.createElement("button", { type: "button", className: "p-tree-toggler p-link", tabIndex: -1, onClick: this.onTogglerClick }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (this.props.togglerTemplate) { var defaultContentOptions = { onClick: this.onTogglerClick, containerClassName: 'p-tree-toggler p-link', iconClassName: 'p-tree-toggler-icon', element: content, props: this.props, expanded: expanded }; content = ObjectUtils.getJSXElement(this.props.togglerTemplate, this.props.node, defaultContentOptions); } return content; } }, { key: "renderDropPoint", value: function renderDropPoint(position) { var _this2 = this; if (this.props.dragdropScope) { return /*#__PURE__*/React.createElement("li", { className: "p-treenode-droppoint", onDrop: function onDrop(event) { return _this2.onDropPoint(event, position); }, onDragOver: this.onDropPointDragOver, onDragEnter: this.onDropPointDragEnter, onDragLeave: this.onDropPointDragLeave }); } return null; } }, { key: "renderContent", value: function renderContent() { var _this3 = this; var selected = this.isSelected(); var checked = this.isChecked(); var className = classNames('p-treenode-content', this.props.node.className, { 'p-treenode-selectable': this.props.selectionMode && this.props.node.selectable !== false, 'p-highlight': this.isCheckboxSelectionMode() ? checked : selected, 'p-highlight-contextmenu': this.props.contextMenuSelectionKey && this.props.contextMenuSelectionKey === this.props.node.key, 'p-disabled': this.props.disabled }); var expanded = this.isExpanded(); var toggler = this.renderToggler(expanded); var checkbox = this.renderCheckbox(); var icon = this.renderIcon(expanded); var label = this.renderLabel(); var tabIndex = this.props.disabled ? undefined : 0; return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this3.contentElement = el; }, className: className, style: this.props.node.style, onClick: this.onClick, onDoubleClick: this.onDoubleClick, onContextMenu: this.onRightClick, onTouchEnd: this.onTouchEnd, draggable: this.props.dragdropScope && this.props.node.draggable !== false && !this.props.disabled, onDrop: this.onDrop, onDragOver: this.onDragOver, onDragEnter: this.onDragEnter, onDragLeave: this.onDragLeave, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd, tabIndex: tabIndex, onKeyDown: this.onNodeKeyDown, role: "treeitem", "aria-posinset": this.props.index + 1, "aria-expanded": this.isExpanded(), "aria-selected": checked || selected }, toggler, checkbox, icon, label); } }, { key: "renderChildren", value: function renderChildren() { var _this4 = this; if (this.props.node.children && this.props.node.children.length && this.isExpanded()) { return /*#__PURE__*/React.createElement("ul", { className: "p-treenode-children", role: "group" }, this.props.node.children.map(function (childNode, index) { return /*#__PURE__*/React.createElement(UITreeNode, { key: childNode.key || childNode.label, node: childNode, parent: _this4.props.node, index: index, last: index === _this4.props.node.children.length - 1, path: _this4.props.path + '-' + index, disabled: _this4.props.disabled, selectionMode: _this4.props.selectionMode, selectionKeys: _this4.props.selectionKeys, onSelectionChange: _this4.props.onSelectionChange, metaKeySelection: _this4.props.metaKeySelection, propagateSelectionDown: _this4.props.propagateSelectionDown, propagateSelectionUp: _this4.props.propagateSelectionUp, contextMenuSelectionKey: _this4.props.contextMenuSelectionKey, onContextMenuSelectionChange: _this4.props.onContextMenuSelectionChange, onContextMenu: _this4.props.onContextMenu, onExpand: _this4.props.onExpand, onCollapse: _this4.props.onCollapse, onSelect: _this4.props.onSelect, onUnselect: _this4.props.onUnselect, expandedKeys: _this4.props.expandedKeys, onToggle: _this4.props.onToggle, onPropagateUp: _this4.propagateUp, nodeTemplate: _this4.props.nodeTemplate, togglerTemplate: _this4.props.togglerTemplate, isNodeLeaf: _this4.props.isNodeLeaf, dragdropScope: _this4.props.dragdropScope, onDragStart: _this4.props.onDragStart, onDragEnd: _this4.props.onDragEnd, onDrop: _this4.props.onDrop, onDropPoint: _this4.props.onDropPoint }); })); } return null; } }, { key: "renderNode", value: function renderNode() { var className = classNames('p-treenode', { 'p-treenode-leaf': this.isLeaf() }, this.props.node.className); var content = this.renderContent(); var children = this.renderChildren(); return /*#__PURE__*/React.createElement("li", { className: className, style: this.props.node.style }, content, children); } }, { key: "render", value: function render() { var node = this.renderNode(); if (this.props.dragdropScope && !this.props.disabled) { var beforeDropPoint = this.renderDropPoint(-1); var afterDropPoint = this.props.last ? this.renderDropPoint(1) : null; return /*#__PURE__*/React.createElement(React.Fragment, null, beforeDropPoint, node, afterDropPoint); } else { return node; } } }]); return UITreeNode; }(Component); _defineProperty(UITreeNode, "defaultProps", { node: null, index: null, last: null, parent: null, path: null, disabled: false, selectionMode: null, selectionKeys: null, contextMenuSelectionKey: null, metaKeySelection: true, expandedKeys: null, propagateSelectionUp: true, propagateSelectionDown: true, dragdropScope: null, ariaLabel: null, ariaLabelledBy: null, nodeTemplate: null, togglerTemplate: null, isNodeLeaf: null, onSelect: null, onUnselect: null, onExpand: null, onCollapse: null, onToggle: null, onSelectionChange: null, onContextMenuSelectionChange: null, onPropagateUp: null, onDragStart: null, onDragEnd: null, onDrop: null, onDropPoint: null, onContextMenu: null, onNodeClick: null, onNodeDoubleClick: 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 Tree = /*#__PURE__*/function (_Component) { _inherits(Tree, _Component); var _super = _createSuper(Tree); function Tree(props) { var _this; _classCallCheck(this, Tree); _this = _super.call(this, props); _this.state = {}; if (!_this.props.onFilterValueChange) { _this.state['filterValue'] = ''; } if (!_this.props.onToggle) { _this.state['expandedKeys'] = _this.props.expandedKeys; } _this.isNodeLeaf = _this.isNodeLeaf.bind(_assertThisInitialized(_this)); _this.onToggle = _this.onToggle.bind(_assertThisInitialized(_this)); _this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this)); _this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); _this.onDropPoint = _this.onDropPoint.bind(_assertThisInitialized(_this)); _this.onFilterInputChange = _this.onFilterInputChange.bind(_assertThisInitialized(_this)); _this.onFilterInputKeyDown = _this.onFilterInputKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(Tree, [{ key: "getFilterValue", value: function getFilterValue() { return this.props.onFilterValueChange ? this.props.filterValue : this.state.filterValue; } }, { key: "getExpandedKeys", value: function getExpandedKeys() { return this.props.onToggle ? this.props.expandedKeys : this.state.expandedKeys; } }, { key: "getRootNode", value: function getRootNode() { return this.props.filter && this.filteredNodes ? this.filteredNodes : this.props.value; } }, { key: "onToggle", value: function onToggle(event) { if (this.props.onToggle) { this.props.onToggle(event); } else { this.setState({ expandedKeys: event.value }); } } }, { key: "onDragStart", value: function onDragStart(event) { this.dragState = { path: event.path, index: event.index }; } }, { key: "onDragEnd", value: function onDragEnd() { this.dragState = null; } }, { key: "onDrop", value: function onDrop(event) { if (this.validateDropNode(this.dragState.path, event.path)) { var value = JSON.parse(JSON.stringify(this.props.value)); var dragPaths = this.dragState.path.split('-'); dragPaths.pop(); var dragNodeParent = this.findNode(value, dragPaths); var dragNode = dragNodeParent ? dragNodeParent.children[this.dragState.index] : value[this.dragState.index]; var dropNode = this.findNode(value, event.path.split('-')); if (dropNode.children) dropNode.children.push(dragNode);else dropNode.children = [dragNode]; if (dragNodeParent) dragNodeParent.children.splice(this.dragState.index, 1);else value.splice(this.dragState.index, 1); if (this.props.onDragDrop) { this.props.onDragDrop({ originalEvent: event.originalEvent, value: value, dragNode: dragNode, dropNode: dropNode, dropIndex: event.index }); } } } }, { key: "onDropPoint", value: function onDropPoint(event) { if (this.validateDropPoint(event)) { var value = JSON.parse(JSON.stringify(this.props.value)); var dragPaths = this.dragState.path.split('-'); dragPaths.pop(); var dropPaths = event.path.split('-'); dropPaths.pop(); var dragNodeParent = this.findNode(value, dragPaths); var dropNodeParent = this.findNode(value, dropPaths); var dragNode = dragNodeParent ? dragNodeParent.children[this.dragState.index] : value[this.dragState.index]; var siblings = this.areSiblings(this.dragState.path, event.path); if (dragNodeParent) dragNodeParent.children.splice(this.dragState.index, 1);else value.splice(this.dragState.index, 1); if (event.position < 0) { var dropIndex = siblings ? this.dragState.index > event.index ? event.index : event.index - 1 : event.index; if (dropNodeParent) dropNodeParent.children.splice(dropIndex, 0, dragNode);else value.splice(dropIndex, 0, dragNode); } else { if (dropNodeParent) dropNodeParent.children.push(dragNode);else value.push(dragNode); } if (this.props.onDragDrop) { this.props.onDragDrop({ originalEvent: event.originalEvent, value: value, dragNode: dragNode, dropNode: dropNodeParent, dropIndex: event.index }); } } } }, { key: "validateDrop", value: function validateDrop(dragPath, dropPath) { if (!dragPath) { return false; } else { //same node if (dragPath === dropPath) { return false; } //parent dropped on an descendant if (dropPath.indexOf(dragPath) === 0) { return false; } return true; } } }, { key: "validateDropNode", value: function validateDropNode(dragPath, dropPath) { var validateDrop = this.validateDrop(dragPath, dropPath); if (validateDrop) { //child dropped on parent if (dragPath.indexOf('-') > 0 && dragPath.substring(0, dragPath.lastIndexOf('-')) === dropPath) { return false; } return true; } else { return false; } } }, { key: "validateDropPoint", value: function validateDropPoint(event) { var validateDrop = this.validateDrop(this.dragState.path, event.path); if (validateDrop) { //child dropped to next sibling's drop point if (event.position === -1 && this.areSiblings(this.dragState.path, event.path) && this.dragState.index + 1 === event.index) { return false; } return true; } else { return false; } } }, { key: "areSiblings", value: function areSiblings(path1, path2) { if (path1.length === 1 && path2.length === 1) return true;else return path1.substring(0, path1.lastIndexOf('-')) === path2.substring(0, path2.lastIndexOf('-')); } }, { key: "findNode", value: function findNode(value, path) { if (path.length === 0) { return null; } else { var index = parseInt(path[0], 10); var nextSearchRoot = value.children ? value.children[index] : value[index]; if (path.length === 1) { return nextSearchRoot; } else { path.shift(); return this.findNode(nextSearchRoot, path); } } } }, { key: "isNodeLeaf", value: function isNodeLeaf(node) { return node.leaf === false ? false : !(node.children && node.children.length); } }, { key: "onFilterInputKeyDown", value: function onFilterInputKeyDown(event) { //enter if (event.which === 13) { event.preventDefault(); } } }, { key: "onFilterInputChange", value: function onFilterInputChange(event) { this.filterChanged = true; var filterValue = event.target.value; if (this.props.onFilterValueChange) { this.props.onFilterValueChange({ originalEvent: event, value: filterValue }); } else { this.setState({ filterValue: filterValue }); } } }, { key: "filter", value: function filter(value) { this.setState({ filterValue: ObjectUtils.isNotEmpty(value) ? value : '' }, this._filter); } }, { key: "_filter", value: function _filter() { if (!this.filterChanged) { return; } var filterValue = this.getFilterValue(); if (ObjectUtils.isEmpty(filterValue)) { this.filteredNodes = this.props.value; } else { this.filteredNodes = []; var searchFields = this.props.filterBy.split(','); var filterText = filterValue.toLocaleLowerCase(this.props.filterLocale); var isStrictMode = this.props.filterMode === 'strict'; var _iterator = _createForOfIteratorHelper(this.props.value), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var node = _step.value; var copyNode = _objectSpread({}, node); var paramsWithoutNode = { searchFields: searchFields, filterText: filterText, isStrictMode: isStrictMode }; if (isStrictMode && (this.findFilteredNodes(copyNode, paramsWithoutNode) || this.isFilterMatched(copyNode, paramsWithoutNode)) || !isStrictMode && (this.isFilterMatched(copyNode, paramsWithoutNode) || this.findFilteredNodes(copyNode, paramsWithoutNode))) { this.filteredNodes.push(copyNode); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } } this.filterChanged = false; } }, { key: "findFilteredNodes", value: function findFilteredNodes(node, paramsWithoutNode) { if (node) { var matched = false; if (node.children) { var childNodes = _toConsumableArray(node.children); node.children = []; var _iterator2 = _createForOfIteratorHelper(childNodes), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var childNode = _step2.value; var copyChildNode = _objectSpread({}, childNode); if (this.isFilterMatched(copyChildNode, paramsWithoutNode)) { matched = true; node.children.push(copyChildNode); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } if (matched) { node.expanded = true; return true; } } } }, { key: "isFilterMatched", value: function isFilterMatched(node, _ref) { var searchFields = _ref.searchFields, filterText = _ref.filterText, isStrictMode = _ref.isStrictMode; var matched = false; var _iterator3 = _createForOfIteratorHelper(searchFields), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var field = _step3.value; var fieldValue = String(ObjectUtils.resolveFieldData(node, field)).toLocaleLowerCase(this.props.filterLocale); if (fieldValue.indexOf(filterText) > -1) { matched = true; } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } if (!matched || isStrictMode && !this.isNodeLeaf(node)) { matched = this.findFilteredNodes(node, { searchFields: searchFields, filterText: filterText, isStrictMode: isStrictMode }) || matched; } return matched; } }, { key: "renderRootChild", value: function renderRootChild(node, index, last) { return /*#__PURE__*/React.createElement(UITreeNode, { key: node.key || node.label, node: node, index: index, last: last, path: String(index), disabled: this.props.disabled, selectionMode: this.props.selectionMode, selectionKeys: this.props.selectionKeys, onSelectionChange: this.props.onSelectionChange, metaKeySelection: this.props.metaKeySelection, contextMenuSelectionKey: this.props.contextMenuSelectionKey, onContextMenuSelectionChange: this.props.onContextMenuSelectionChange, onContextMenu: this.props.onContextMenu, propagateSelectionDown: this.props.propagateSelectionDown, propagateSelectionUp: this.props.propagateSelectionUp, onExpand: this.props.onExpand, onCollapse: this.props.onCollapse, onSelect: this.props.onSelect, onUnselect: this.props.onUnselect, expandedKeys: this.getExpandedKeys(), onToggle: this.onToggle, nodeTemplate: this.props.nodeTemplate, togglerTemplate: this.props.togglerTemplate, isNodeLeaf: this.isNodeLeaf, dragdropScope: this.props.dragdropScope, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd, onDrop: this.onDrop, onDropPoint: this.onDropPoint, onNodeClick: this.props.onNodeClick, onNodeDoubleClick: this.props.onNodeDoubleClick }); } }, { key: "renderRootChildren", value: function renderRootChildren() { var _this2 = this; if (this.props.filter) { this.filterChanged = true; this._filter(); } var value = this.getRootNode(); return value.map(function (node, index) { return _this2.renderRootChild(node, index, index === value.length - 1); }); } }, { key: "renderModel", value: function renderModel() { if (this.props.value) { var rootNodes = this.renderRootChildren(); var contentClass = classNames('p-tree-container', this.props.contentClassName); return /*#__PURE__*/React.createElement("ul", { className: contentClass, role: "tree", "aria-label": this.props.ariaLabel, "aria-labelledby": this.props.ariaLabelledBy, style: this.props.contentStyle }, rootNodes); } return null; } }, { key: "renderLoader", value: function renderLoader() { if (this.props.loading) { var icon = classNames('p-tree-loading-icon pi-spin', this.props.loadingIcon); return /*#__PURE__*/React.createElement("div", { className: "p-tree-loading-overlay p-component-overlay" }, /*#__PURE__*/React.createElement("i", { className: icon })); } return null; } }, { key: "renderFilter", value: function renderFilter() { if (this.props.filter) { var filterValue = this.getFilterValue(); filterValue = ObjectUtils.isNotEmpty(filterValue) ? filterValue : ''; return /*#__PURE__*/React.createElement("div", { className: "p-tree-filter-container" }, /*#__PURE__*/React.createElement("input", { type: "text", value: filterValue, autoComplete: "off", className: "p-tree-filter p-inputtext p-component", placeholder: this.props.filterPlaceholder, onKeyDown: this.onFilterInputKeyDown, onChange: this.onFilterInputChange, disabled: this.props.disabled }), /*#__PURE__*/React.createElement("span", { className: "p-tree-filter-icon pi pi-search" })); } return null; } }, { key: "renderHeader", value: function renderHeader() { if (this.props.showHeader) { var filterElement = this.renderFilter(); var content = filterElement; if (this.props.header) { var defaultContentOptions = { filterContainerClassName: 'p-tree-filter-container', filterIconClasssName: 'p-tree-filter-icon pi pi-search', filterInput: { className: 'p-tree-filter p-inputtext p-component', onKeyDown: this.onFilterInputKeyDown, onChange: this.onFilterInputChange }, filterElement: filterElement, element: content, props: this.props }; content = ObjectUtils.getJSXElement(this.props.header, defaultContentOptions); } return /*#__PURE__*/React.createElement("div", { className: "p-tree-header" }, content); } return null; } }, { key: "renderFooter", value: function renderFooter() { var content = ObjectUtils.getJSXElement(this.props.footer, this.props); return /*#__PURE__*/React.createElement("div", { className: "p-tree-footer" }, content); } }, { key: "render", value: function render() { var className = classNames('p-tree p-component', this.props.className, { 'p-tree-selectable': this.props.selectionMode, 'p-tree-loading': this.props.loading, 'p-disabled': this.props.disabled }); var loader = this.renderLoader(); var content = this.renderModel(); var header = this.renderHeader(); var footer = this.renderFooter(); return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: className, style: this.props.style }, loader, header, content, footer); } }]); return Tree; }(Component); _defineProperty(Tree, "defaultProps", { id: null, value: null, disabled: false, selectionMode: null, selectionKeys: null, onSelectionChange: null, contextMenuSelectionKey: null, onContextMenuSelectionChange: null, expandedKeys: null, style: null, className: null, contentStyle: null, contentClassName: null, metaKeySelection: true, propagateSelectionUp: true, propagateSelectionDown: true, loading: false, loadingIcon: 'pi pi-spinner', dragdropScope: null, header: null, footer: null, showHeader: true, filter: false, filterValue: null, filterBy: 'label', filterMode: 'lenient', filterPlaceholder: null, filterLocale: undefined, nodeTemplate: null, togglerTemplate: null, onSelect: null, onUnselect: null, onExpand: null, onCollapse: null, onToggle: null, onDragDrop: null, onContextMenu: null, onFilterValueChange: null, onNodeClick: null, onNodeDoubleClick: null }); export { Tree };
ajax/libs/react-native-web/0.13.8/exports/Button/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 StyleSheet from '../StyleSheet'; import TouchableOpacity from '../TouchableOpacity'; import Text from '../Text'; import React from 'react'; export default function Button(props) { var accessibilityLabel = props.accessibilityLabel, color = props.color, disabled = props.disabled, onPress = props.onPress, testID = props.testID, title = props.title; return React.createElement(TouchableOpacity, { accessibilityLabel: accessibilityLabel, accessibilityRole: "button", disabled: disabled, onPress: onPress, style: [styles.button, color && { backgroundColor: color }, disabled && styles.buttonDisabled], testID: testID }, React.createElement(Text, { style: [styles.text, disabled && styles.textDisabled] }, title)); } var styles = StyleSheet.create({ button: { backgroundColor: '#2196F3', borderRadius: 2 }, text: { color: '#fff', fontWeight: '500', padding: 8, textAlign: 'center', textTransform: 'uppercase' }, buttonDisabled: { backgroundColor: '#dfdfdf' }, textDisabled: { color: '#a1a1a1' } });
ajax/libs/react-native-web/0.12.2/exports/YellowBox/index.js
cdnjs/cdnjs
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import React from 'react'; import UnimplementedView from '../../modules/UnimplementedView'; var YellowBox = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(YellowBox, _React$Component); function YellowBox() { return _React$Component.apply(this, arguments) || this; } YellowBox.ignoreWarnings = function ignoreWarnings() {}; var _proto = YellowBox.prototype; _proto.render = function render() { return React.createElement(UnimplementedView, this.props); }; return YellowBox; }(React.Component); export default YellowBox;
ajax/libs/primereact/7.0.0-rc.1/megamenu/megamenu.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { DomHandler, classNames, Ripple, ObjectUtils } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var MegaMenu = /*#__PURE__*/function (_Component) { _inherits(MegaMenu, _Component); var _super = _createSuper(MegaMenu); function MegaMenu(props) { var _this; _classCallCheck(this, MegaMenu); _this = _super.call(this, props); _this.state = { activeItem: null }; _this.onLeafClick = _this.onLeafClick.bind(_assertThisInitialized(_this)); return _this; } _createClass(MegaMenu, [{ key: "onLeafClick", value: function onLeafClick(event, item) { if (item.disabled) { event.preventDefault(); return; } if (!item.url) { event.preventDefault(); } if (item.command) { item.command({ originalEvent: event, item: item }); } this.setState({ activeItem: null }); } }, { key: "onCategoryMouseEnter", value: function onCategoryMouseEnter(event, item) { if (item.disabled) { event.preventDefault(); return; } if (this.state.activeItem) { this.setState({ activeItem: item }); } } }, { key: "onCategoryClick", value: function onCategoryClick(event, item) { if (item.disabled) { event.preventDefault(); return; } if (!item.url) { event.preventDefault(); } if (item.command) { item.command({ originalEvent: event, item: this.props.item }); } if (item.items) { if (this.state.activeItem && this.state.activeItem === item) { this.setState({ activeItem: null }); } else { this.setState({ activeItem: item }); } } event.preventDefault(); } }, { key: "onCategoryKeyDown", value: function onCategoryKeyDown(event, item) { var listItem = event.currentTarget.parentElement; switch (event.which) { //down case 40: if (this.isHorizontal()) this.expandMenu(item);else this.navigateToNextItem(listItem); event.preventDefault(); break; //up case 38: if (this.isVertical()) this.navigateToPrevItem(listItem);else if (item.items && item === this.state.activeItem) this.collapseMenu(); event.preventDefault(); break; //right case 39: if (this.isHorizontal()) this.navigateToNextItem(listItem);else this.expandMenu(item); event.preventDefault(); break; //left case 37: if (this.isHorizontal()) this.navigateToPrevItem(listItem);else if (item.items && item === this.state.activeItem) this.collapseMenu(); event.preventDefault(); break; } } }, { key: "expandMenu", value: function expandMenu(item) { if (item.items) { this.setState({ activeItem: item }); } } }, { key: "collapseMenu", value: function collapseMenu(item) { this.setState({ activeItem: null }); } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return DomHandler.hasClass(nextItem, 'p-disabled') || !DomHandler.hasClass(nextItem, 'p-menuitem') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return DomHandler.hasClass(prevItem, 'p-disabled') || !DomHandler.hasClass(prevItem, 'p-menuitem') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "navigateToNextItem", value: function navigateToNextItem(listItem) { var nextItem = this.findNextItem(listItem); if (nextItem) { nextItem.children[0].focus(); } } }, { key: "navigateToPrevItem", value: function navigateToPrevItem(listItem) { var prevItem = this.findPrevItem(listItem); if (prevItem) { prevItem.children[0].focus(); } } }, { key: "isHorizontal", value: function isHorizontal() { return this.props.orientation === 'horizontal'; } }, { key: "isVertical", value: function isVertical() { return this.props.orientation === 'vertical'; } }, { key: "getColumnClassName", value: function getColumnClassName(category) { var length = category.items ? category.items.length : 0; var columnClass; switch (length) { case 2: columnClass = 'p-megamenu-col-6'; break; case 3: columnClass = 'p-megamenu-col-4'; break; case 4: columnClass = 'p-megamenu-col-3'; break; case 6: columnClass = 'p-megamenu-col-2'; break; default: columnClass = 'p-megamenu-col-12'; break; } return columnClass; } }, { key: "componentDidMount", value: function componentDidMount() { var _this2 = this; if (!this.documentClickListener) { this.documentClickListener = function (event) { if (_this2.container && !_this2.container.contains(event.target)) { _this2.setState({ activeItem: null }); } }; document.addEventListener('click', this.documentClickListener); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.documentClickListener) { document.removeEventListener('click', this.documentClickListener); this.documentClickListener = null; } } }, { key: "renderSeparator", value: function renderSeparator(index) { return /*#__PURE__*/React.createElement("li", { key: 'separator_' + index, className: "p-menu-separator", role: "separator" }); } }, { key: "renderSubmenuIcon", value: function renderSubmenuIcon(item) { if (item.items) { var className = classNames('p-submenu-icon pi', { 'pi-angle-down': this.isHorizontal(), 'pi-angle-right': this.isVertical() }); return /*#__PURE__*/React.createElement("span", { className: className }); } return null; } }, { key: "renderSubmenuItem", value: function renderSubmenuItem(item, index) { var _this3 = this; if (item.separator) { return this.renderSeparator(index); } else { var className = classNames('p-menuitem', item.className); var linkClassName = classNames('p-menuitem-link', { 'p-disabled': item.disabled }); var iconClassName = classNames(item.icon, 'p-menuitem-icon'); var icon = item.icon && /*#__PURE__*/React.createElement("span", { className: iconClassName }); var label = item.label && /*#__PURE__*/React.createElement("span", { className: "p-menuitem-text" }, item.label); var content = /*#__PURE__*/React.createElement("a", { href: item.url || '#', className: linkClassName, target: item.target, onClick: function onClick(event) { return _this3.onLeafClick(event, item); }, role: "menuitem", "aria-disabled": item.disabled }, icon, label, /*#__PURE__*/React.createElement(Ripple, null)); if (item.template) { var defaultContentOptions = { onClick: function onClick(event) { return _this3.onLeafClick(event, item); }, className: linkClassName, labelClassName: 'p-menuitem-text', iconClassName: iconClassName, element: content, props: this.props }; content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions); } return /*#__PURE__*/React.createElement("li", { key: item.label + '_' + index, className: className, style: item.style, role: "none" }, content); } } }, { key: "renderSubmenu", value: function renderSubmenu(submenu) { var _this4 = this; var className = classNames('p-megamenu-submenu-header', { 'p-disabled': submenu.disabled }, submenu.className); var items = submenu.items.map(function (item, index) { return _this4.renderSubmenuItem(item, index); }); return /*#__PURE__*/React.createElement(React.Fragment, { key: submenu.label }, /*#__PURE__*/React.createElement("li", { className: className, style: submenu.style, role: "presentation", "aria-disabled": submenu.disabled }, submenu.label), items); } }, { key: "renderSubmenus", value: function renderSubmenus(column) { var _this5 = this; return column.map(function (submenu, index) { return _this5.renderSubmenu(submenu, index); }); } }, { key: "renderColumn", value: function renderColumn(category, column, index, columnClassName) { var submenus = this.renderSubmenus(column); return /*#__PURE__*/React.createElement("div", { key: category.label + '_column_' + index, className: columnClassName }, /*#__PURE__*/React.createElement("ul", { className: "p-megamenu-submenu", role: "menu" }, submenus)); } }, { key: "renderColumns", value: function renderColumns(category) { var _this6 = this; if (category.items) { var columnClassName = this.getColumnClassName(category); return category.items.map(function (column, index) { return _this6.renderColumn(category, column, index, columnClassName); }); } return null; } }, { key: "renderCategoryPanel", value: function renderCategoryPanel(category) { if (category.items) { var columns = this.renderColumns(category); return /*#__PURE__*/React.createElement("div", { className: "p-megamenu-panel" }, /*#__PURE__*/React.createElement("div", { className: "p-megamenu-grid" }, columns)); } return null; } }, { key: "renderCategory", value: function renderCategory(category, index) { var _this7 = this; var className = classNames('p-menuitem', { 'p-menuitem-active': category === this.state.activeItem }, category.className); var linkClassName = classNames('p-menuitem-link', { 'p-disabled': category.disabled }); var iconClassName = classNames('p-menuitem-icon', category.icon); var icon = category.icon && /*#__PURE__*/React.createElement("span", { className: iconClassName }); var label = category.label && /*#__PURE__*/React.createElement("span", { className: "p-menuitem-text" }, category.label); var itemContent = category.template ? ObjectUtils.getJSXElement(category.template, category) : null; var submenuIcon = this.renderSubmenuIcon(category); var panel = this.renderCategoryPanel(category); return /*#__PURE__*/React.createElement("li", { key: category.label + '_' + index, className: className, style: category.style, onMouseEnter: function onMouseEnter(e) { return _this7.onCategoryMouseEnter(e, category); }, role: "none" }, /*#__PURE__*/React.createElement("a", { href: category.url || '#', className: linkClassName, target: category.target, onClick: function onClick(e) { return _this7.onCategoryClick(e, category); }, onKeyDown: function onKeyDown(e) { return _this7.onCategoryKeyDown(e, category); }, role: "menuitem", "aria-haspopup": category.items != null }, icon, label, itemContent, submenuIcon, /*#__PURE__*/React.createElement(Ripple, null)), panel); } }, { key: "renderMenu", value: function renderMenu() { var _this8 = this; if (this.props.model) { return this.props.model.map(function (item, index) { return _this8.renderCategory(item, index, true); }); } return null; } }, { key: "renderCustomContent", value: function renderCustomContent() { if (this.props.children) { return /*#__PURE__*/React.createElement("div", { className: "p-megamenu-custom" }, this.props.children); } return null; } }, { key: "render", value: function render() { var _this9 = this; var className = classNames('p-megamenu p-component', { 'p-megamenu-horizontal': this.props.orientation === 'horizontal', 'p-megamenu-vertical': this.props.orientation === 'vertical' }, this.props.className); var menu = this.renderMenu(); var customContent = this.renderCustomContent(); return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this9.container = el; }, id: this.props.id, className: className, style: this.props.style }, /*#__PURE__*/React.createElement("ul", { className: "p-megamenu-root-list", role: "menubar" }, menu), customContent); } }]); return MegaMenu; }(Component); _defineProperty(MegaMenu, "defaultProps", { id: null, model: null, style: null, className: null, orientation: 'horizontal' }); export { MegaMenu };
ajax/libs/react-native-web/0.14.1/exports/KeyboardAvoidingView/index.js
cdnjs/cdnjs
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import View from '../View'; import React from 'react'; var KeyboardAvoidingView = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(KeyboardAvoidingView, _React$Component); function KeyboardAvoidingView() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this; _this.frame = null; _this.onLayout = function (event) { _this.frame = event.nativeEvent.layout; }; return _this; } var _proto = KeyboardAvoidingView.prototype; _proto.relativeKeyboardHeight = function relativeKeyboardHeight(keyboardFrame) { var frame = this.frame; if (!frame || !keyboardFrame) { return 0; } var keyboardY = keyboardFrame.screenY - (this.props.keyboardVerticalOffset || 0); return Math.max(frame.y + frame.height - keyboardY, 0); }; _proto.onKeyboardChange = function onKeyboardChange(event) {}; _proto.render = function render() { var _this$props = this.props, behavior = _this$props.behavior, contentContainerStyle = _this$props.contentContainerStyle, keyboardVerticalOffset = _this$props.keyboardVerticalOffset, rest = _objectWithoutPropertiesLoose(_this$props, ["behavior", "contentContainerStyle", "keyboardVerticalOffset"]); return React.createElement(View, _extends({ onLayout: this.onLayout }, rest)); }; return KeyboardAvoidingView; }(React.Component); export default KeyboardAvoidingView;
ajax/libs/react-native-web/0.0.0-da3429ed3/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.11.5/exports/Touchable/index.js
cdnjs/cdnjs
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /* eslint-disable react/prop-types */ /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AccessibilityUtil from '../../modules/AccessibilityUtil'; import BoundingDimensions from './BoundingDimensions'; import findNodeHandle from '../findNodeHandle'; import normalizeColor from 'normalize-css-color'; import Position from './Position'; import React from 'react'; import TouchEventUtils from 'fbjs/lib/TouchEventUtils'; import UIManager from '../UIManager'; import View from '../View'; /** * `Touchable`: Taps done right. * * You hook your `ResponderEventPlugin` events into `Touchable`. `Touchable` * will measure time/geometry and tells you when to give feedback to the user. * * ====================== Touchable Tutorial =============================== * The `Touchable` mixin helps you handle the "press" interaction. It analyzes * the geometry of elements, and observes when another responder (scroll view * etc) has stolen the touch lock. It notifies your component when it should * give feedback to the user. (bouncing/highlighting/unhighlighting). * * - When a touch was activated (typically you highlight) * - When a touch was deactivated (typically you unhighlight) * - When a touch was "pressed" - a touch ended while still within the geometry * of the element, and no other element (like scroller) has "stolen" touch * lock ("responder") (Typically you bounce the element). * * A good tap interaction isn't as simple as you might think. There should be a * slight delay before showing a highlight when starting a touch. If a * subsequent touch move exceeds the boundary of the element, it should * unhighlight, but if that same touch is brought back within the boundary, it * should rehighlight again. A touch can move in and out of that boundary * several times, each time toggling highlighting, but a "press" is only * triggered if that touch ends while within the element's boundary and no * scroller (or anything else) has stolen the lock on touches. * * To create a new type of component that handles interaction using the * `Touchable` mixin, do the following: * * - Initialize the `Touchable` state. * * getInitialState: function() { * return merge(this.touchableGetInitialState(), yourComponentState); * } * * - Choose the rendered component who's touches should start the interactive * sequence. On that rendered node, forward all `Touchable` responder * handlers. You can choose any rendered node you like. Choose a node whose * hit target you'd like to instigate the interaction sequence: * * // In render function: * return ( * <View * onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder} * onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest} * onResponderGrant={this.touchableHandleResponderGrant} * onResponderMove={this.touchableHandleResponderMove} * onResponderRelease={this.touchableHandleResponderRelease} * onResponderTerminate={this.touchableHandleResponderTerminate}> * <View> * Even though the hit detection/interactions are triggered by the * wrapping (typically larger) node, we usually end up implementing * custom logic that highlights this inner one. * </View> * </View> * ); * * - You may set up your own handlers for each of these events, so long as you * also invoke the `touchable*` handlers inside of your custom handler. * * - Implement the handlers on your component class in order to provide * feedback to the user. See documentation for each of these class methods * that you should implement. * * touchableHandlePress: function() { * this.performBounceAnimation(); // or whatever you want to do. * }, * touchableHandleActivePressIn: function() { * this.beginHighlighting(...); // Whatever you like to convey activation * }, * touchableHandleActivePressOut: function() { * this.endHighlighting(...); // Whatever you like to convey deactivation * }, * * - There are more advanced methods you can implement (see documentation below): * touchableGetHighlightDelayMS: function() { * return 20; * } * // In practice, *always* use a predeclared constant (conserve memory). * touchableGetPressRectOffset: function() { * return {top: 20, left: 20, right: 20, bottom: 100}; * } */ /** * Touchable states. */ var States = { NOT_RESPONDER: 'NOT_RESPONDER', // Not the responder RESPONDER_INACTIVE_PRESS_IN: 'RESPONDER_INACTIVE_PRESS_IN', // Responder, inactive, in the `PressRect` RESPONDER_INACTIVE_PRESS_OUT: 'RESPONDER_INACTIVE_PRESS_OUT', // Responder, inactive, out of `PressRect` RESPONDER_ACTIVE_PRESS_IN: 'RESPONDER_ACTIVE_PRESS_IN', // Responder, active, in the `PressRect` RESPONDER_ACTIVE_PRESS_OUT: 'RESPONDER_ACTIVE_PRESS_OUT', // Responder, active, out of `PressRect` RESPONDER_ACTIVE_LONG_PRESS_IN: 'RESPONDER_ACTIVE_LONG_PRESS_IN', // Responder, active, in the `PressRect`, after long press threshold RESPONDER_ACTIVE_LONG_PRESS_OUT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT', // Responder, active, out of `PressRect`, after long press threshold ERROR: 'ERROR' }; /** * Quick lookup map for states that are considered to be "active" */ var IsActive = { RESPONDER_ACTIVE_PRESS_OUT: true, RESPONDER_ACTIVE_PRESS_IN: true }; /** * Quick lookup for states that are considered to be "pressing" and are * therefore eligible to result in a "selection" if the press stops. */ var IsPressingIn = { RESPONDER_INACTIVE_PRESS_IN: true, RESPONDER_ACTIVE_PRESS_IN: true, RESPONDER_ACTIVE_LONG_PRESS_IN: true }; var IsLongPressingIn = { RESPONDER_ACTIVE_LONG_PRESS_IN: true }; /** * Inputs to the state machine. */ var Signals = { DELAY: 'DELAY', RESPONDER_GRANT: 'RESPONDER_GRANT', RESPONDER_RELEASE: 'RESPONDER_RELEASE', RESPONDER_TERMINATED: 'RESPONDER_TERMINATED', ENTER_PRESS_RECT: 'ENTER_PRESS_RECT', LEAVE_PRESS_RECT: 'LEAVE_PRESS_RECT', LONG_PRESS_DETECTED: 'LONG_PRESS_DETECTED' }; /** * Mapping from States x Signals => States */ var Transitions = { NOT_RESPONDER: { DELAY: States.ERROR, RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN, RESPONDER_RELEASE: States.ERROR, RESPONDER_TERMINATED: States.ERROR, ENTER_PRESS_RECT: States.ERROR, LEAVE_PRESS_RECT: States.ERROR, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_INACTIVE_PRESS_IN: { DELAY: States.RESPONDER_ACTIVE_PRESS_IN, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_INACTIVE_PRESS_OUT: { DELAY: States.RESPONDER_ACTIVE_PRESS_OUT, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_ACTIVE_PRESS_IN: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN }, RESPONDER_ACTIVE_PRESS_OUT: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, RESPONDER_ACTIVE_LONG_PRESS_IN: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT, LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN }, RESPONDER_ACTIVE_LONG_PRESS_OUT: { DELAY: States.ERROR, RESPONDER_GRANT: States.ERROR, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN, LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT, LONG_PRESS_DETECTED: States.ERROR }, error: { DELAY: States.NOT_RESPONDER, RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN, RESPONDER_RELEASE: States.NOT_RESPONDER, RESPONDER_TERMINATED: States.NOT_RESPONDER, ENTER_PRESS_RECT: States.NOT_RESPONDER, LEAVE_PRESS_RECT: States.NOT_RESPONDER, LONG_PRESS_DETECTED: States.NOT_RESPONDER } }; // ==== Typical Constants for integrating into UI components ==== // var HIT_EXPAND_PX = 20; // var HIT_VERT_OFFSET_PX = 10; var HIGHLIGHT_DELAY_MS = 130; var PRESS_EXPAND_PX = 20; var LONG_PRESS_THRESHOLD = 500; var LONG_PRESS_DELAY_MS = LONG_PRESS_THRESHOLD - HIGHLIGHT_DELAY_MS; var LONG_PRESS_ALLOWED_MOVEMENT = 10; // Default amount "active" region protrudes beyond box /** * By convention, methods prefixed with underscores are meant to be @private, * and not @protected. Mixers shouldn't access them - not even to provide them * as callback handlers. * * * ========== Geometry ========= * `Touchable` only assumes that there exists a `HitRect` node. The `PressRect` * is an abstract box that is extended beyond the `HitRect`. * * +--------------------------+ * | | - "Start" events in `HitRect` cause `HitRect` * | +--------------------+ | to become the responder. * | | +--------------+ | | - `HitRect` is typically expanded around * | | | | | | the `VisualRect`, but shifted downward. * | | | VisualRect | | | - After pressing down, after some delay, * | | | | | | and before letting up, the Visual React * | | +--------------+ | | will become "active". This makes it eligible * | | HitRect | | for being highlighted (so long as the * | +--------------------+ | press remains in the `PressRect`). * | PressRect o | * +----------------------|---+ * Out Region | * +-----+ This gap between the `HitRect` and * `PressRect` allows a touch to move far away * from the original hit rect, and remain * highlighted, and eligible for a "Press". * Customize this via * `touchableGetPressRectOffset()`. * * * * ======= State Machine ======= * * +-------------+ <---+ RESPONDER_RELEASE * |NOT_RESPONDER| * +-------------+ <---+ RESPONDER_TERMINATED * + * | RESPONDER_GRANT (HitRect) * v * +---------------------------+ DELAY +-------------------------+ T + DELAY +------------------------------+ * |RESPONDER_INACTIVE_PRESS_IN|+-------->|RESPONDER_ACTIVE_PRESS_IN| +------------> |RESPONDER_ACTIVE_LONG_PRESS_IN| * +---------------------------+ +-------------------------+ +------------------------------+ * + ^ + ^ + ^ * |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ * |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT * | | | | | | * v + v + v + * +----------------------------+ DELAY +--------------------------+ +-------------------------------+ * |RESPONDER_INACTIVE_PRESS_OUT|+------->|RESPONDER_ACTIVE_PRESS_OUT| |RESPONDER_ACTIVE_LONG_PRESS_OUT| * +----------------------------+ +--------------------------+ +-------------------------------+ * * T + DELAY => LONG_PRESS_DELAY_MS + DELAY * * Not drawn are the side effects of each transition. The most important side * effect is the `touchableHandlePress` abstract method invocation that occurs * when a responder is released while in either of the "Press" states. * * The other important side effects are the highlight abstract method * invocations (internal callbacks) to be implemented by the mixer. * * * @lends Touchable.prototype */ var TouchableMixin = { // HACK (part 1): basic support for touchable interactions using a keyboard componentDidMount: function componentDidMount() { var _this = this; this._touchableNode = findNodeHandle(this); if (this._touchableNode && this._touchableNode.addEventListener) { this._touchableBlurListener = function (e) { if (_this._isTouchableKeyboardActive) { if (_this.state.touchable.touchState && _this.state.touchable.touchState !== States.NOT_RESPONDER) { _this.touchableHandleResponderTerminate({ nativeEvent: e }); } _this._isTouchableKeyboardActive = false; } }; this._touchableNode.addEventListener('blur', this._touchableBlurListener); } }, /** * Clear all timeouts on unmount */ componentWillUnmount: function componentWillUnmount() { if (this._touchableNode && this._touchableNode.addEventListener) { this._touchableNode.removeEventListener('blur', this._touchableBlurListener); } this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout); this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout); this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout); }, /** * It's prefer that mixins determine state in this way, having the class * explicitly mix the state in the one and only `getInitialState` method. * * @return {object} State object to be placed inside of * `this.state.touchable`. */ touchableGetInitialState: function touchableGetInitialState() { return { touchable: { touchState: undefined, responderID: null } }; }, // ==== Hooks to Gesture Responder system ==== /** * Must return true if embedded in a native platform scroll view. */ touchableHandleResponderTerminationRequest: function touchableHandleResponderTerminationRequest() { return !this.props.rejectResponderTermination; }, /** * Must return true to start the process of `Touchable`. */ touchableHandleStartShouldSetResponder: function touchableHandleStartShouldSetResponder() { return !this.props.disabled; }, /** * Return true to cancel press on long press. */ touchableLongPressCancelsPress: function touchableLongPressCancelsPress() { return true; }, /** * Place as callback for a DOM element's `onResponderGrant` event. */ touchableHandleResponderGrant: function touchableHandleResponderGrant(e) { var dispatchID = e.currentTarget; // Since e is used in a callback invoked on another event loop // (as in setTimeout etc), we need to call e.persist() on the // event to make sure it doesn't get reused in the event object pool. e.persist(); this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout); this.pressOutDelayTimeout = null; this.state.touchable.touchState = States.NOT_RESPONDER; this.state.touchable.responderID = dispatchID; this._receiveSignal(Signals.RESPONDER_GRANT, e); var delayMS = this.touchableGetHighlightDelayMS !== undefined ? Math.max(this.touchableGetHighlightDelayMS(), 0) : HIGHLIGHT_DELAY_MS; delayMS = isNaN(delayMS) ? HIGHLIGHT_DELAY_MS : delayMS; if (delayMS !== 0) { this.touchableDelayTimeout = setTimeout(this._handleDelay.bind(this, e), delayMS); } else { this.state.touchable.positionOnActivate = null; this._handleDelay(e); } var longDelayMS = this.touchableGetLongPressDelayMS !== undefined ? Math.max(this.touchableGetLongPressDelayMS(), 10) : LONG_PRESS_DELAY_MS; longDelayMS = isNaN(longDelayMS) ? LONG_PRESS_DELAY_MS : longDelayMS; this.longPressDelayTimeout = setTimeout(this._handleLongDelay.bind(this, e), longDelayMS + delayMS); }, /** * Place as callback for a DOM element's `onResponderRelease` event. */ touchableHandleResponderRelease: function touchableHandleResponderRelease(e) { this._receiveSignal(Signals.RESPONDER_RELEASE, e); }, /** * Place as callback for a DOM element's `onResponderTerminate` event. */ touchableHandleResponderTerminate: function touchableHandleResponderTerminate(e) { this._receiveSignal(Signals.RESPONDER_TERMINATED, e); }, /** * Place as callback for a DOM element's `onResponderMove` event. */ touchableHandleResponderMove: function touchableHandleResponderMove(e) { // Not enough time elapsed yet, wait for highlight - // this is just a perf optimization. if (this.state.touchable.touchState === States.RESPONDER_INACTIVE_PRESS_IN) { return; } // Measurement may not have returned yet. if (!this.state.touchable.positionOnActivate) { return; } var positionOnActivate = this.state.touchable.positionOnActivate; var dimensionsOnActivate = this.state.touchable.dimensionsOnActivate; var pressRectOffset = this.touchableGetPressRectOffset ? this.touchableGetPressRectOffset() : { left: PRESS_EXPAND_PX, right: PRESS_EXPAND_PX, top: PRESS_EXPAND_PX, bottom: PRESS_EXPAND_PX }; var pressExpandLeft = pressRectOffset.left; var pressExpandTop = pressRectOffset.top; var pressExpandRight = pressRectOffset.right; var pressExpandBottom = pressRectOffset.bottom; var hitSlop = this.touchableGetHitSlop ? this.touchableGetHitSlop() : null; if (hitSlop) { pressExpandLeft += hitSlop.left; pressExpandTop += hitSlop.top; pressExpandRight += hitSlop.right; pressExpandBottom += hitSlop.bottom; } var touch = TouchEventUtils.extractSingleTouch(e.nativeEvent); var pageX = touch && touch.pageX; var pageY = touch && touch.pageY; if (this.pressInLocation) { var movedDistance = this._getDistanceBetweenPoints(pageX, pageY, this.pressInLocation.pageX, this.pressInLocation.pageY); if (movedDistance > LONG_PRESS_ALLOWED_MOVEMENT) { this._cancelLongPressDelayTimeout(); } } var isTouchWithinActive = pageX > positionOnActivate.left - pressExpandLeft && pageY > positionOnActivate.top - pressExpandTop && pageX < positionOnActivate.left + dimensionsOnActivate.width + pressExpandRight && pageY < positionOnActivate.top + dimensionsOnActivate.height + pressExpandBottom; if (isTouchWithinActive) { this._receiveSignal(Signals.ENTER_PRESS_RECT, e); var curState = this.state.touchable.touchState; if (curState === States.RESPONDER_INACTIVE_PRESS_IN) { // fix for t7967420 this._cancelLongPressDelayTimeout(); } } else { this._cancelLongPressDelayTimeout(); this._receiveSignal(Signals.LEAVE_PRESS_RECT, e); } }, // ==== Abstract Application Callbacks ==== /** * Invoked when the item should be highlighted. Mixers should implement this * to visually distinguish the `VisualRect` so that the user knows that * releasing a touch will result in a "selection" (analog to click). * * @abstract * touchableHandleActivePressIn: function, */ /** * Invoked when the item is "active" (in that it is still eligible to become * a "select") but the touch has left the `PressRect`. Usually the mixer will * want to unhighlight the `VisualRect`. If the user (while pressing) moves * back into the `PressRect` `touchableHandleActivePressIn` will be invoked * again and the mixer should probably highlight the `VisualRect` again. This * event will not fire on an `touchEnd/mouseUp` event, only move events while * the user is depressing the mouse/touch. * * @abstract * touchableHandleActivePressOut: function */ /** * Invoked when the item is "selected" - meaning the interaction ended by * letting up while the item was either in the state * `RESPONDER_ACTIVE_PRESS_IN` or `RESPONDER_INACTIVE_PRESS_IN`. * * @abstract * touchableHandlePress: function */ /** * Invoked when the item is long pressed - meaning the interaction ended by * letting up while the item was in `RESPONDER_ACTIVE_LONG_PRESS_IN`. If * `touchableHandleLongPress` is *not* provided, `touchableHandlePress` will * be called as it normally is. If `touchableHandleLongPress` is provided, by * default any `touchableHandlePress` callback will not be invoked. To * override this default behavior, override `touchableLongPressCancelsPress` * to return false. As a result, `touchableHandlePress` will be called when * lifting up, even if `touchableHandleLongPress` has also been called. * * @abstract * touchableHandleLongPress: function */ /** * Returns the number of millis to wait before triggering a highlight. * * @abstract * touchableGetHighlightDelayMS: function */ /** * Returns the amount to extend the `HitRect` into the `PressRect`. Positive * numbers mean the size expands outwards. * * @abstract * touchableGetPressRectOffset: function */ // ==== Internal Logic ==== /** * Measures the `HitRect` node on activation. The Bounding rectangle is with * respect to viewport - not page, so adding the `pageXOffset/pageYOffset` * should result in points that are in the same coordinate system as an * event's `globalX/globalY` data values. * * - Consider caching this for the lifetime of the component, or possibly * being able to share this cache between any `ScrollMap` view. * * @sideeffects * @private */ _remeasureMetricsOnActivation: function _remeasureMetricsOnActivation() { var tag = this.state.touchable.responderID; if (tag == null) { return; } UIManager.measure(tag, this._handleQueryLayout); }, _handleQueryLayout: function _handleQueryLayout(x, y, width, height, globalX, globalY) { // don't do anything if UIManager failed to measure node if (!x && !y && !width && !height && !globalX && !globalY) { return; } this.state.touchable.positionOnActivate && Position.release(this.state.touchable.positionOnActivate); this.state.touchable.dimensionsOnActivate && // $FlowFixMe BoundingDimensions.release(this.state.touchable.dimensionsOnActivate); this.state.touchable.positionOnActivate = Position.getPooled(globalX, globalY); // $FlowFixMe this.state.touchable.dimensionsOnActivate = BoundingDimensions.getPooled(width, height); }, _handleDelay: function _handleDelay(e) { this.touchableDelayTimeout = null; this._receiveSignal(Signals.DELAY, e); }, _handleLongDelay: function _handleLongDelay(e) { this.longPressDelayTimeout = null; var curState = this.state.touchable.touchState; if (curState !== States.RESPONDER_ACTIVE_PRESS_IN && curState !== States.RESPONDER_ACTIVE_LONG_PRESS_IN) { console.error('Attempted to transition from state `' + curState + '` to `' + States.RESPONDER_ACTIVE_LONG_PRESS_IN + '`, which is not supported. This is ' + 'most likely due to `Touchable.longPressDelayTimeout` not being cancelled.'); } else { this._receiveSignal(Signals.LONG_PRESS_DETECTED, e); } }, /** * Receives a state machine signal, performs side effects of the transition * and stores the new state. Validates the transition as well. * * @param {Signals} signal State machine signal. * @throws Error if invalid state transition or unrecognized signal. * @sideeffects */ _receiveSignal: function _receiveSignal(signal, e) { var responderID = this.state.touchable.responderID; var curState = this.state.touchable.touchState; var nextState = Transitions[curState] && Transitions[curState][signal]; if (!responderID && signal === Signals.RESPONDER_RELEASE) { return; } if (!nextState) { throw new Error('Unrecognized signal `' + signal + '` or state `' + curState + '` for Touchable responder `' + responderID + '`'); } if (nextState === States.ERROR) { throw new Error('Touchable cannot transition from `' + curState + '` to `' + signal + '` for responder `' + responderID + '`'); } if (curState !== nextState) { this._performSideEffectsForTransition(curState, nextState, signal, e); this.state.touchable.touchState = nextState; } }, _cancelLongPressDelayTimeout: function _cancelLongPressDelayTimeout() { this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout); this.longPressDelayTimeout = null; }, _isHighlight: function _isHighlight(state) { return state === States.RESPONDER_ACTIVE_PRESS_IN || state === States.RESPONDER_ACTIVE_LONG_PRESS_IN; }, _savePressInLocation: function _savePressInLocation(e) { var touch = TouchEventUtils.extractSingleTouch(e.nativeEvent); var pageX = touch && touch.pageX; var pageY = touch && touch.pageY; this.pressInLocation = { pageX: pageX, pageY: pageY, get locationX() { return touch && touch.locationX; }, get locationY() { return touch && touch.locationY; } }; }, _getDistanceBetweenPoints: function _getDistanceBetweenPoints(aX, aY, bX, bY) { var deltaX = aX - bX; var deltaY = aY - bY; return Math.sqrt(deltaX * deltaX + deltaY * deltaY); }, /** * Will perform a transition between touchable states, and identify any * highlighting or unhighlighting that must be performed for this particular * transition. * * @param {States} curState Current Touchable state. * @param {States} nextState Next Touchable state. * @param {Signal} signal Signal that triggered the transition. * @param {Event} e Native event. * @sideeffects */ _performSideEffectsForTransition: function _performSideEffectsForTransition(curState, nextState, signal, e) { var curIsHighlight = this._isHighlight(curState); var newIsHighlight = this._isHighlight(nextState); var isFinalSignal = signal === Signals.RESPONDER_TERMINATED || signal === Signals.RESPONDER_RELEASE; if (isFinalSignal) { this._cancelLongPressDelayTimeout(); } if (!IsActive[curState] && IsActive[nextState]) { this._remeasureMetricsOnActivation(); } if (IsPressingIn[curState] && signal === Signals.LONG_PRESS_DETECTED) { this.touchableHandleLongPress && this.touchableHandleLongPress(e); } if (newIsHighlight && !curIsHighlight) { this._startHighlight(e); } else if (!newIsHighlight && curIsHighlight) { this._endHighlight(e); } if (IsPressingIn[curState] && signal === Signals.RESPONDER_RELEASE) { var hasLongPressHandler = !!this.props.onLongPress; var pressIsLongButStillCallOnPress = IsLongPressingIn[curState] && ( // We *are* long pressing.. !hasLongPressHandler || // But either has no long handler !this.touchableLongPressCancelsPress()); // or we're told to ignore it. var shouldInvokePress = !IsLongPressingIn[curState] || pressIsLongButStillCallOnPress; if (shouldInvokePress && this.touchableHandlePress) { if (!newIsHighlight && !curIsHighlight) { // we never highlighted because of delay, but we should highlight now this._startHighlight(e); this._endHighlight(e); } this.touchableHandlePress(e); } } this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout); this.touchableDelayTimeout = null; }, _startHighlight: function _startHighlight(e) { this._savePressInLocation(e); this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e); }, _endHighlight: function _endHighlight(e) { var _this2 = this; if (this.touchableHandleActivePressOut) { if (this.touchableGetPressOutDelayMS && this.touchableGetPressOutDelayMS()) { this.pressOutDelayTimeout = setTimeout(function () { _this2.touchableHandleActivePressOut(e); }, this.touchableGetPressOutDelayMS()); } else { this.touchableHandleActivePressOut(e); } } }, // HACK (part 2): basic support for touchable interactions using a keyboard (including // delays and longPress) touchableHandleKeyEvent: function touchableHandleKeyEvent(e) { var ENTER = 13; var SPACE = 32; var type = e.type, which = e.which; if (which === ENTER || which === SPACE) { if (type === 'keydown') { if (!this._isTouchableKeyboardActive) { if (!this.state.touchable.touchState || this.state.touchable.touchState === States.NOT_RESPONDER) { this.touchableHandleResponderGrant(e); this._isTouchableKeyboardActive = true; } } } else if (type === 'keyup') { if (this._isTouchableKeyboardActive) { if (this.state.touchable.touchState && this.state.touchable.touchState !== States.NOT_RESPONDER) { this.touchableHandleResponderRelease(e); this._isTouchableKeyboardActive = false; } } } e.stopPropagation(); // prevent the default behaviour unless the Touchable functions as a link // and Enter is pressed if (!(which === ENTER && AccessibilityUtil.propsToAriaRole(this.props) === 'link')) { e.preventDefault(); } } } }; var Touchable = { Mixin: TouchableMixin, TOUCH_TARGET_DEBUG: false, // Highlights all touchable targets. Toggle with Inspector. /** * Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android). */ renderDebugView: function renderDebugView(_ref) { var color = _ref.color, hitSlop = _ref.hitSlop; if (process.env.NODE_ENV !== 'production') { if (!Touchable.TOUCH_TARGET_DEBUG) { return null; } var debugHitSlopStyle = {}; hitSlop = hitSlop || { top: 0, bottom: 0, left: 0, right: 0 }; for (var key in hitSlop) { debugHitSlopStyle[key] = -hitSlop[key]; } var hexColor = '#' + ('00000000' + normalizeColor(color).toString(16)).substr(-8); return React.createElement(View, { pointerEvents: "none", style: _objectSpread({ position: 'absolute', borderColor: hexColor.slice(0, -2) + '55', // More opaque borderWidth: 1, borderStyle: 'dashed', backgroundColor: hexColor.slice(0, -2) + '0F' }, debugHitSlopStyle) }); } } }; export default Touchable;
ajax/libs/primereact/7.0.0-rc.2/row/row.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Row = /*#__PURE__*/function (_Component) { _inherits(Row, _Component); var _super = _createSuper(Row); function Row() { _classCallCheck(this, Row); return _super.apply(this, arguments); } _createClass(Row, [{ key: "render", value: function render() { return /*#__PURE__*/React.createElement("tr", null, this.props.children); } }]); return Row; }(Component); _defineProperty(Row, "defaultProps", { style: null, className: null }); export { Row };
ajax/libs/material-ui/4.9.4/esm/SnackbarContent/SnackbarContent.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 Paper from '../Paper'; import { emphasize } from '../styles/colorManipulator'; export var styles = function styles(theme) { var emphasis = theme.palette.type === 'light' ? 0.8 : 0.98; var backgroundColor = emphasize(theme.palette.background.default, emphasis); return { /* Styles applied to the root element. */ root: _extends({}, theme.typography.body2, _defineProperty({ color: theme.palette.getContrastText(backgroundColor), backgroundColor: backgroundColor, display: 'flex', alignItems: 'center', flexWrap: 'wrap', padding: '6px 16px', borderRadius: theme.shape.borderRadius, flexGrow: 1 }, theme.breakpoints.up('sm'), { flexGrow: 'initial', minWidth: 288 })), /* Styles applied to the message wrapper element. */ message: { padding: '8px 0' }, /* Styles applied to the action wrapper element if `action` is provided. */ action: { display: 'flex', alignItems: 'center', marginLeft: 'auto', paddingLeft: 16, marginRight: -8 } }; }; var SnackbarContent = React.forwardRef(function SnackbarContent(props, ref) { var action = props.action, classes = props.classes, className = props.className, message = props.message, _props$role = props.role, role = _props$role === void 0 ? 'alert' : _props$role, other = _objectWithoutProperties(props, ["action", "classes", "className", "message", "role"]); return React.createElement(Paper, _extends({ role: role, square: true, elevation: 6, className: clsx(classes.root, className), ref: ref }, other), React.createElement("div", { className: classes.message }, message), action ? React.createElement("div", { className: classes.action }, action) : null); }); process.env.NODE_ENV !== "production" ? SnackbarContent.propTypes = { /** * The action to display. It renders after the message, at the end of the snackbar. */ action: 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 message to display. */ message: PropTypes.node, /** * The ARIA role attribute of the element. */ role: PropTypes.string } : void 0; export default withStyles(styles, { name: 'MuiSnackbarContent' })(SnackbarContent);
ajax/libs/primereact/7.0.0-rc.1/tag/tag.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames } from 'primereact/core'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } 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 Tag = /*#__PURE__*/function (_Component) { _inherits(Tag, _Component); var _super = _createSuper(Tag); function Tag() { _classCallCheck(this, Tag); return _super.apply(this, arguments); } _createClass(Tag, [{ key: "render", value: function render() { var tagClassName = classNames('p-tag p-component', { 'p-tag-info': this.props.severity === 'info', 'p-tag-success': this.props.severity === 'success', 'p-tag-warning': this.props.severity === 'warning', 'p-tag-danger': this.props.severity === 'danger', 'p-tag-rounded': this.props.rounded }, this.props.className); var iconClass = classNames('p-tag-icon', this.props.icon); return /*#__PURE__*/React.createElement("span", { className: tagClassName, style: this.props.style }, this.props.icon && /*#__PURE__*/React.createElement("span", { className: iconClass }), /*#__PURE__*/React.createElement("span", { className: "p-tag-value" }, this.props.value), /*#__PURE__*/React.createElement("span", null, this.props.children)); } }]); return Tag; }(Component); _defineProperty(Tag, "defaultProps", { value: null, severity: null, rounded: false, icon: null, style: null, className: null }); export { Tag };
ajax/libs/material-ui/5.0.0-alpha.19/legacy/styles/useTheme.js
cdnjs/cdnjs
import { useTheme as useThemeWithoutDefault } from '@material-ui/styles'; import React from 'react'; import defaultTheme from './defaultTheme'; export default function useTheme() { var theme = useThemeWithoutDefault() || defaultTheme; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks React.useDebugValue(theme); } return theme; }
ajax/libs/react-big-calendar/0.22.1/react-big-calendar.esm.js
cdnjs/cdnjs
import _extends from '@babel/runtime/helpers/esm/extends'; import _objectWithoutPropertiesLoose from '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose'; import _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { uncontrollable } from 'uncontrollable'; import clsx from 'clsx'; import warning from 'warning'; import invariant from 'invariant'; import _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized'; import { findDOMNode } from 'react-dom'; import { eq, add, startOf, endOf, lte, hours, minutes, seconds, milliseconds, lt, gte, month, max, min, gt, inRange as inRange$1 } from 'date-arithmetic'; import chunk from 'lodash-es/chunk'; import getPosition from 'dom-helpers/position'; import { request, cancel } from 'dom-helpers/animationFrame'; import getOffset from 'dom-helpers/offset'; import getScrollTop from 'dom-helpers/scrollTop'; import getScrollLeft from 'dom-helpers/scrollLeft'; import Overlay from 'react-overlays/Overlay'; import getHeight from 'dom-helpers/height'; import qsa from 'dom-helpers/querySelectorAll'; import contains from 'dom-helpers/contains'; import closest from 'dom-helpers/closest'; import listen from 'dom-helpers/listen'; import findIndex from 'lodash-es/findIndex'; import range$1 from 'lodash-es/range'; import memoize from 'memoize-one'; import _createClass from '@babel/runtime/helpers/esm/createClass'; import sortBy from 'lodash-es/sortBy'; import getWidth from 'dom-helpers/width'; import scrollbarSize from 'dom-helpers/scrollbarSize'; import addClass from 'dom-helpers/addClass'; import removeClass from 'dom-helpers/removeClass'; import omit from 'lodash-es/omit'; import defaults from 'lodash-es/defaults'; import transform from 'lodash-es/transform'; import mapValues from 'lodash-es/mapValues'; function NoopWrapper(props) { return props.children; } var navigate = { PREVIOUS: 'PREV', NEXT: 'NEXT', TODAY: 'TODAY', DATE: 'DATE' }; var views = { MONTH: 'month', WEEK: 'week', WORK_WEEK: 'work_week', DAY: 'day', AGENDA: 'agenda' }; var viewNames = Object.keys(views).map(function (k) { return views[k]; }); var accessor = PropTypes.oneOfType([PropTypes.string, PropTypes.func]); var dateFormat = PropTypes.any; var dateRangeFormat = PropTypes.func; /** * accepts either an array of builtin view names: * * ``` * views={['month', 'day', 'agenda']} * ``` * * or an object hash of the view name and the component (or boolean for builtin) * * ``` * views={{ * month: true, * week: false, * workweek: WorkWeekViewComponent, * }} * ``` */ var views$1 = PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOf(viewNames)), PropTypes.objectOf(function (prop, key) { var isBuiltinView = viewNames.indexOf(key) !== -1 && typeof prop[key] === 'boolean'; if (isBuiltinView) { return null; } else { for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } return PropTypes.elementType.apply(PropTypes, [prop, key].concat(args)); } })]); function notify(handler, args) { handler && handler.apply(null, [].concat(args)); } var localePropType = PropTypes.oneOfType([PropTypes.string, PropTypes.func]); function _format(localizer, formatter, value, format, culture) { var result = typeof format === 'function' ? format(value, culture, localizer) : formatter.call(localizer, value, format, culture); !(result == null || typeof result === 'string') ? process.env.NODE_ENV !== "production" ? invariant(false, '`localizer format(..)` must return a string, null, or undefined') : invariant(false) : void 0; return result; } var DateLocalizer = function DateLocalizer(spec) { var _this = this; !(typeof spec.format === 'function') ? process.env.NODE_ENV !== "production" ? invariant(false, 'date localizer `format(..)` must be a function') : invariant(false) : void 0; !(typeof spec.firstOfWeek === 'function') ? process.env.NODE_ENV !== "production" ? invariant(false, 'date localizer `firstOfWeek(..)` must be a function') : invariant(false) : void 0; this.propType = spec.propType || localePropType; this.startOfWeek = spec.firstOfWeek; this.formats = spec.formats; this.format = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _format.apply(void 0, [_this, spec.format].concat(args)); }; }; function mergeWithDefaults(localizer, culture, formatOverrides, messages) { var formats = _extends({}, localizer.formats, formatOverrides); return _extends({}, localizer, { messages: messages, startOfWeek: function startOfWeek() { return localizer.startOfWeek(culture); }, format: function format(value, _format2) { return localizer.format(value, formats[_format2] || _format2, culture); } }); } var defaultMessages = { date: 'Date', time: 'Time', event: 'Event', allDay: 'All Day', week: 'Week', work_week: 'Work Week', day: 'Day', month: 'Month', previous: 'Back', next: 'Next', yesterday: 'Yesterday', tomorrow: 'Tomorrow', today: 'Today', agenda: 'Agenda', noEventsInRange: 'There are no events in this range.', showMore: function showMore(total) { return "+" + total + " more"; } }; function messages(msgs) { return _extends({}, defaultMessages, msgs); } /* eslint no-fallthrough: off */ var MILLI = { seconds: 1000, minutes: 1000 * 60, hours: 1000 * 60 * 60, day: 1000 * 60 * 60 * 24 }; function firstVisibleDay(date, localizer) { var firstOfMonth = startOf(date, 'month'); return startOf(firstOfMonth, 'week', localizer.startOfWeek()); } function lastVisibleDay(date, localizer) { var endOfMonth = endOf(date, 'month'); return endOf(endOfMonth, 'week', localizer.startOfWeek()); } function visibleDays(date, localizer) { var current = firstVisibleDay(date, localizer), last = lastVisibleDay(date, localizer), days = []; while (lte(current, last, 'day')) { days.push(current); current = add(current, 1, 'day'); } return days; } function ceil(date, unit) { var floor = startOf(date, unit); return eq(floor, date) ? floor : add(floor, 1, unit); } function range(start, end, unit) { if (unit === void 0) { unit = 'day'; } var current = start, days = []; while (lte(current, end, unit)) { days.push(current); current = add(current, 1, unit); } return days; } function merge(date, time) { if (time == null && date == null) return null; if (time == null) time = new Date(); if (date == null) date = new Date(); date = startOf(date, 'day'); date = hours(date, hours(time)); date = minutes(date, minutes(time)); date = seconds(date, seconds(time)); return milliseconds(date, milliseconds(time)); } function isJustDate(date) { return hours(date) === 0 && minutes(date) === 0 && seconds(date) === 0 && milliseconds(date) === 0; } function diff(dateA, dateB, unit) { if (!unit || unit === 'milliseconds') return Math.abs(+dateA - +dateB); // the .round() handles an edge case // with DST where the total won't be exact // since one day in the range may be shorter/longer by an hour return Math.round(Math.abs(+startOf(dateA, unit) / MILLI[unit] - +startOf(dateB, unit) / MILLI[unit])); } var EventCell = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(EventCell, _React$Component); function EventCell() { return _React$Component.apply(this, arguments) || this; } var _proto = EventCell.prototype; _proto.render = function render() { var _this$props = this.props, style = _this$props.style, className = _this$props.className, event = _this$props.event, selected = _this$props.selected, isAllDay = _this$props.isAllDay, onSelect = _this$props.onSelect, _onDoubleClick = _this$props.onDoubleClick, localizer = _this$props.localizer, continuesPrior = _this$props.continuesPrior, continuesAfter = _this$props.continuesAfter, accessors = _this$props.accessors, getters = _this$props.getters, children = _this$props.children, _this$props$component = _this$props.components, Event = _this$props$component.event, EventWrapper = _this$props$component.eventWrapper, slotStart = _this$props.slotStart, slotEnd = _this$props.slotEnd, props = _objectWithoutPropertiesLoose(_this$props, ["style", "className", "event", "selected", "isAllDay", "onSelect", "onDoubleClick", "localizer", "continuesPrior", "continuesAfter", "accessors", "getters", "children", "components", "slotStart", "slotEnd"]); var title = accessors.title(event); var tooltip = accessors.tooltip(event); var end = accessors.end(event); var start = accessors.start(event); var allDay = accessors.allDay(event); var showAsAllDay = isAllDay || allDay || diff(start, ceil(end, 'day'), 'day') > 1; var userProps = getters.eventProp(event, start, end, selected); var content = React.createElement("div", { className: "rbc-event-content", title: tooltip || undefined }, Event ? React.createElement(Event, { event: event, continuesPrior: continuesPrior, continuesAfter: continuesAfter, title: title, isAllDay: allDay, localizer: localizer, slotStart: slotStart, slotEnd: slotEnd }) : title); return React.createElement(EventWrapper, _extends({}, this.props, { type: "date" }), React.createElement("div", _extends({}, props, { tabIndex: 0, style: _extends({}, userProps.style, style), className: clsx('rbc-event', className, userProps.className, { 'rbc-selected': selected, 'rbc-event-allday': showAsAllDay, 'rbc-event-continues-prior': continuesPrior, 'rbc-event-continues-after': continuesAfter }), onClick: function onClick(e) { return onSelect && onSelect(event, e); }, onDoubleClick: function onDoubleClick(e) { return _onDoubleClick && _onDoubleClick(event, e); } }), typeof children === 'function' ? children(content) : content)); }; return EventCell; }(React.Component); EventCell.propTypes = process.env.NODE_ENV !== "production" ? { event: PropTypes.object.isRequired, slotStart: PropTypes.instanceOf(Date), slotEnd: PropTypes.instanceOf(Date), selected: PropTypes.bool, isAllDay: PropTypes.bool, continuesPrior: PropTypes.bool, continuesAfter: PropTypes.bool, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object, onSelect: PropTypes.func, onDoubleClick: PropTypes.func } : {}; function isSelected(event, selected) { if (!event || selected == null) return false; return [].concat(selected).indexOf(event) !== -1; } function slotWidth(rowBox, slots) { var rowWidth = rowBox.right - rowBox.left; var cellWidth = rowWidth / slots; return cellWidth; } function getSlotAtX(rowBox, x, rtl, slots) { var cellWidth = slotWidth(rowBox, slots); return rtl ? slots - 1 - Math.floor((x - rowBox.left) / cellWidth) : Math.floor((x - rowBox.left) / cellWidth); } function pointInBox(box, _ref) { var x = _ref.x, y = _ref.y; return y >= box.top && y <= box.bottom && x >= box.left && x <= box.right; } function dateCellSelection(start, rowBox, box, slots, rtl) { var startIdx = -1; var endIdx = -1; var lastSlotIdx = slots - 1; var cellWidth = slotWidth(rowBox, slots); // cell under the mouse var currentSlot = getSlotAtX(rowBox, box.x, rtl, slots); // Identify row as either the initial row // or the row under the current mouse point var isCurrentRow = rowBox.top < box.y && rowBox.bottom > box.y; var isStartRow = rowBox.top < start.y && rowBox.bottom > start.y; // this row's position relative to the start point var isAboveStart = start.y > rowBox.bottom; var isBelowStart = rowBox.top > start.y; var isBetween = box.top < rowBox.top && box.bottom > rowBox.bottom; // this row is between the current and start rows, so entirely selected if (isBetween) { startIdx = 0; endIdx = lastSlotIdx; } if (isCurrentRow) { if (isBelowStart) { startIdx = 0; endIdx = currentSlot; } else if (isAboveStart) { startIdx = currentSlot; endIdx = lastSlotIdx; } } if (isStartRow) { // select the cell under the initial point startIdx = endIdx = rtl ? lastSlotIdx - Math.floor((start.x - rowBox.left) / cellWidth) : Math.floor((start.x - rowBox.left) / cellWidth); if (isCurrentRow) { if (currentSlot < startIdx) startIdx = currentSlot;else endIdx = currentSlot; //select current range } else if (start.y < box.y) { // the current row is below start row // select cells to the right of the start cell endIdx = lastSlotIdx; } else { // select cells to the left of the start cell startIdx = 0; } } return { startIdx: startIdx, endIdx: endIdx }; } var Popup = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Popup, _React$Component); function Popup() { return _React$Component.apply(this, arguments) || this; } var _proto = Popup.prototype; _proto.componentDidMount = function componentDidMount() { var _this$props = this.props, _this$props$popupOffs = _this$props.popupOffset, popupOffset = _this$props$popupOffs === void 0 ? 5 : _this$props$popupOffs, popperRef = _this$props.popperRef, _getOffset = getOffset(popperRef.current), top = _getOffset.top, left = _getOffset.left, width = _getOffset.width, height = _getOffset.height, viewBottom = window.innerHeight + getScrollTop(window), viewRight = window.innerWidth + getScrollLeft(window), bottom = top + height, right = left + width; if (bottom > viewBottom || right > viewRight) { var topOffset, leftOffset; if (bottom > viewBottom) topOffset = bottom - viewBottom + (popupOffset.y || +popupOffset || 0); if (right > viewRight) leftOffset = right - viewRight + (popupOffset.x || +popupOffset || 0); this.setState({ topOffset: topOffset, leftOffset: leftOffset }); //eslint-disable-line } }; _proto.render = function render() { var _this$props2 = this.props, events = _this$props2.events, selected = _this$props2.selected, getters = _this$props2.getters, accessors = _this$props2.accessors, components = _this$props2.components, onSelect = _this$props2.onSelect, onDoubleClick = _this$props2.onDoubleClick, slotStart = _this$props2.slotStart, slotEnd = _this$props2.slotEnd, localizer = _this$props2.localizer, popperRef = _this$props2.popperRef; var width = this.props.position.width, topOffset = (this.state || {}).topOffset || 0, leftOffset = (this.state || {}).leftOffset || 0; var style = { top: -topOffset, left: -leftOffset, minWidth: width + width / 2 }; return React.createElement("div", { style: _extends({}, this.props.style, style), className: "rbc-overlay", ref: popperRef }, React.createElement("div", { className: "rbc-overlay-header" }, localizer.format(slotStart, 'dayHeaderFormat')), events.map(function (event, idx) { return React.createElement(EventCell, { key: idx, type: "popup", event: event, getters: getters, onSelect: onSelect, accessors: accessors, components: components, onDoubleClick: onDoubleClick, continuesPrior: lt(accessors.end(event), slotStart, 'day'), continuesAfter: gte(accessors.start(event), slotEnd, 'day'), slotStart: slotStart, slotEnd: slotEnd, selected: isSelected(event, selected) }); })); }; return Popup; }(React.Component); Popup.propTypes = process.env.NODE_ENV !== "production" ? { position: PropTypes.object, popupOffset: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ x: PropTypes.number, y: PropTypes.number })]), events: PropTypes.array, selected: PropTypes.object, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, onSelect: PropTypes.func, onDoubleClick: PropTypes.func, slotStart: PropTypes.instanceOf(Date), slotEnd: PropTypes.number, popperRef: PropTypes.oneOfType([PropTypes.func, PropTypes.shape({ current: PropTypes.Element })]) /** * The Overlay component, of react-overlays, creates a ref that is passed to the Popup, and * requires proper ref forwarding to be used without error */ } : {}; var Popup$1 = React.forwardRef(function (props, ref) { return React.createElement(Popup, _extends({ popperRef: ref }, props)); }); function addEventListener(type, handler, target) { if (target === void 0) { target = document; } return listen(target, type, handler, { passive: false }); } function isOverContainer(container, x, y) { return !container || contains(container, document.elementFromPoint(x, y)); } function getEventNodeFromPoint(node, _ref) { var clientX = _ref.clientX, clientY = _ref.clientY; var target = document.elementFromPoint(clientX, clientY); return closest(target, '.rbc-event', node); } function isEvent(node, bounds) { return !!getEventNodeFromPoint(node, bounds); } function getEventCoordinates(e) { var target = e; if (e.touches && e.touches.length) { target = e.touches[0]; } return { clientX: target.clientX, clientY: target.clientY, pageX: target.pageX, pageY: target.pageY }; } var clickTolerance = 5; var clickInterval = 250; var Selection = /*#__PURE__*/ function () { function Selection(node, _temp) { var _ref2 = _temp === void 0 ? {} : _temp, _ref2$global = _ref2.global, global = _ref2$global === void 0 ? false : _ref2$global, _ref2$longPressThresh = _ref2.longPressThreshold, longPressThreshold = _ref2$longPressThresh === void 0 ? 250 : _ref2$longPressThresh; this.isDetached = false; this.container = node; this.globalMouse = !node || global; this.longPressThreshold = longPressThreshold; this._listeners = Object.create(null); this._handleInitialEvent = this._handleInitialEvent.bind(this); this._handleMoveEvent = this._handleMoveEvent.bind(this); this._handleTerminatingEvent = this._handleTerminatingEvent.bind(this); this._keyListener = this._keyListener.bind(this); this._dropFromOutsideListener = this._dropFromOutsideListener.bind(this); this._dragOverFromOutsideListener = this._dragOverFromOutsideListener.bind(this); // Fixes an iOS 10 bug where scrolling could not be prevented on the window. // https://github.com/metafizzy/flickity/issues/457#issuecomment-254501356 this._removeTouchMoveWindowListener = addEventListener('touchmove', function () {}, window); this._removeKeyDownListener = addEventListener('keydown', this._keyListener); this._removeKeyUpListener = addEventListener('keyup', this._keyListener); this._removeDropFromOutsideListener = addEventListener('drop', this._dropFromOutsideListener); this._onDragOverfromOutisde = addEventListener('dragover', this._dragOverFromOutsideListener); this._addInitialEventListener(); } var _proto = Selection.prototype; _proto.on = function on(type, handler) { var handlers = this._listeners[type] || (this._listeners[type] = []); handlers.push(handler); return { remove: function remove() { var idx = handlers.indexOf(handler); if (idx !== -1) handlers.splice(idx, 1); } }; }; _proto.emit = function emit(type) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var result; var handlers = this._listeners[type] || []; handlers.forEach(function (fn) { if (result === undefined) result = fn.apply(void 0, args); }); return result; }; _proto.teardown = function teardown() { this.isDetached = true; this.listeners = Object.create(null); this._removeTouchMoveWindowListener && this._removeTouchMoveWindowListener(); this._removeInitialEventListener && this._removeInitialEventListener(); this._removeEndListener && this._removeEndListener(); this._onEscListener && this._onEscListener(); this._removeMoveListener && this._removeMoveListener(); this._removeKeyUpListener && this._removeKeyUpListener(); this._removeKeyDownListener && this._removeKeyDownListener(); this._removeDropFromOutsideListener && this._removeDropFromOutsideListener(); }; _proto.isSelected = function isSelected(node) { var box = this._selectRect; if (!box || !this.selecting) return false; return objectsCollide(box, getBoundsForNode(node)); }; _proto.filter = function filter(items) { var box = this._selectRect; //not selecting if (!box || !this.selecting) return []; return items.filter(this.isSelected, this); } // Adds a listener that will call the handler only after the user has pressed on the screen // without moving their finger for 250ms. ; _proto._addLongPressListener = function _addLongPressListener(handler, initialEvent) { var _this = this; var timer = null; var removeTouchMoveListener = null; var removeTouchEndListener = null; var handleTouchStart = function handleTouchStart(initialEvent) { timer = setTimeout(function () { cleanup(); handler(initialEvent); }, _this.longPressThreshold); removeTouchMoveListener = addEventListener('touchmove', function () { return cleanup(); }); removeTouchEndListener = addEventListener('touchend', function () { return cleanup(); }); }; var removeTouchStartListener = addEventListener('touchstart', handleTouchStart); var cleanup = function cleanup() { if (timer) { clearTimeout(timer); } if (removeTouchMoveListener) { removeTouchMoveListener(); } if (removeTouchEndListener) { removeTouchEndListener(); } timer = null; removeTouchMoveListener = null; removeTouchEndListener = null; }; if (initialEvent) { handleTouchStart(initialEvent); } return function () { cleanup(); removeTouchStartListener(); }; } // Listen for mousedown and touchstart events. When one is received, disable the other and setup // future event handling based on the type of event. ; _proto._addInitialEventListener = function _addInitialEventListener() { var _this2 = this; var removeMouseDownListener = addEventListener('mousedown', function (e) { _this2._removeInitialEventListener(); _this2._handleInitialEvent(e); _this2._removeInitialEventListener = addEventListener('mousedown', _this2._handleInitialEvent); }); var removeTouchStartListener = addEventListener('touchstart', function (e) { _this2._removeInitialEventListener(); _this2._removeInitialEventListener = _this2._addLongPressListener(_this2._handleInitialEvent, e); }); this._removeInitialEventListener = function () { removeMouseDownListener(); removeTouchStartListener(); }; }; _proto._dropFromOutsideListener = function _dropFromOutsideListener(e) { var _getEventCoordinates = getEventCoordinates(e), pageX = _getEventCoordinates.pageX, pageY = _getEventCoordinates.pageY, clientX = _getEventCoordinates.clientX, clientY = _getEventCoordinates.clientY; this.emit('dropFromOutside', { x: pageX, y: pageY, clientX: clientX, clientY: clientY }); e.preventDefault(); }; _proto._dragOverFromOutsideListener = function _dragOverFromOutsideListener(e) { var _getEventCoordinates2 = getEventCoordinates(e), pageX = _getEventCoordinates2.pageX, pageY = _getEventCoordinates2.pageY, clientX = _getEventCoordinates2.clientX, clientY = _getEventCoordinates2.clientY; this.emit('dragOverFromOutside', { x: pageX, y: pageY, clientX: clientX, clientY: clientY }); e.preventDefault(); }; _proto._handleInitialEvent = function _handleInitialEvent(e) { if (this.isDetached) { return; } var _getEventCoordinates3 = getEventCoordinates(e), clientX = _getEventCoordinates3.clientX, clientY = _getEventCoordinates3.clientY, pageX = _getEventCoordinates3.pageX, pageY = _getEventCoordinates3.pageY; var node = this.container(), collides, offsetData; // Right clicks if (e.which === 3 || e.button === 2 || !isOverContainer(node, clientX, clientY)) return; if (!this.globalMouse && node && !contains(node, e.target)) { var _normalizeDistance = normalizeDistance(0), top = _normalizeDistance.top, left = _normalizeDistance.left, bottom = _normalizeDistance.bottom, right = _normalizeDistance.right; offsetData = getBoundsForNode(node); collides = objectsCollide({ top: offsetData.top - top, left: offsetData.left - left, bottom: offsetData.bottom + bottom, right: offsetData.right + right }, { top: pageY, left: pageX }); if (!collides) return; } var result = this.emit('beforeSelect', this._initialEventData = { isTouch: /^touch/.test(e.type), x: pageX, y: pageY, clientX: clientX, clientY: clientY }); if (result === false) return; switch (e.type) { case 'mousedown': this._removeEndListener = addEventListener('mouseup', this._handleTerminatingEvent); this._onEscListener = addEventListener('keydown', this._handleTerminatingEvent); this._removeMoveListener = addEventListener('mousemove', this._handleMoveEvent); break; case 'touchstart': this._handleMoveEvent(e); this._removeEndListener = addEventListener('touchend', this._handleTerminatingEvent); this._removeMoveListener = addEventListener('touchmove', this._handleMoveEvent); break; default: break; } }; _proto._handleTerminatingEvent = function _handleTerminatingEvent(e) { var _getEventCoordinates4 = getEventCoordinates(e), pageX = _getEventCoordinates4.pageX, pageY = _getEventCoordinates4.pageY; this.selecting = false; this._removeEndListener && this._removeEndListener(); this._removeMoveListener && this._removeMoveListener(); if (!this._initialEventData) return; var inRoot = !this.container || contains(this.container(), e.target); var bounds = this._selectRect; var click = this.isClick(pageX, pageY); this._initialEventData = null; if (e.key === 'Escape') { return this.emit('reset'); } if (!inRoot) { return this.emit('reset'); } if (click && inRoot) { return this._handleClickEvent(e); } // User drag-clicked in the Selectable area if (!click) return this.emit('select', bounds); }; _proto._handleClickEvent = function _handleClickEvent(e) { var _getEventCoordinates5 = getEventCoordinates(e), pageX = _getEventCoordinates5.pageX, pageY = _getEventCoordinates5.pageY, clientX = _getEventCoordinates5.clientX, clientY = _getEventCoordinates5.clientY; var now = new Date().getTime(); if (this._lastClickData && now - this._lastClickData.timestamp < clickInterval) { // Double click event this._lastClickData = null; return this.emit('doubleClick', { x: pageX, y: pageY, clientX: clientX, clientY: clientY }); } // Click event this._lastClickData = { timestamp: now }; return this.emit('click', { x: pageX, y: pageY, clientX: clientX, clientY: clientY }); }; _proto._handleMoveEvent = function _handleMoveEvent(e) { if (this._initialEventData === null || this.isDetached) { return; } var _this$_initialEventDa = this._initialEventData, x = _this$_initialEventDa.x, y = _this$_initialEventDa.y; var _getEventCoordinates6 = getEventCoordinates(e), pageX = _getEventCoordinates6.pageX, pageY = _getEventCoordinates6.pageY; var w = Math.abs(x - pageX); var h = Math.abs(y - pageY); var left = Math.min(pageX, x), top = Math.min(pageY, y), old = this.selecting; // Prevent emitting selectStart event until mouse is moved. // in Chrome on Windows, mouseMove event may be fired just after mouseDown event. if (this.isClick(pageX, pageY) && !old && !(w || h)) { return; } this.selecting = true; this._selectRect = { top: top, left: left, x: pageX, y: pageY, right: left + w, bottom: top + h }; if (!old) { this.emit('selectStart', this._initialEventData); } if (!this.isClick(pageX, pageY)) this.emit('selecting', this._selectRect); e.preventDefault(); }; _proto._keyListener = function _keyListener(e) { this.ctrl = e.metaKey || e.ctrlKey; }; _proto.isClick = function isClick(pageX, pageY) { var _this$_initialEventDa2 = this._initialEventData, x = _this$_initialEventDa2.x, y = _this$_initialEventDa2.y, isTouch = _this$_initialEventDa2.isTouch; return !isTouch && Math.abs(pageX - x) <= clickTolerance && Math.abs(pageY - y) <= clickTolerance; }; return Selection; }(); /** * Resolve the disance prop from either an Int or an Object * @return {Object} */ function normalizeDistance(distance) { if (distance === void 0) { distance = 0; } if (typeof distance !== 'object') distance = { top: distance, left: distance, right: distance, bottom: distance }; return distance; } /** * Given two objects containing "top", "left", "offsetWidth" and "offsetHeight" * properties, determine if they collide. * @param {Object|HTMLElement} a * @param {Object|HTMLElement} b * @return {bool} */ function objectsCollide(nodeA, nodeB, tolerance) { if (tolerance === void 0) { tolerance = 0; } var _getBoundsForNode = getBoundsForNode(nodeA), aTop = _getBoundsForNode.top, aLeft = _getBoundsForNode.left, _getBoundsForNode$rig = _getBoundsForNode.right, aRight = _getBoundsForNode$rig === void 0 ? aLeft : _getBoundsForNode$rig, _getBoundsForNode$bot = _getBoundsForNode.bottom, aBottom = _getBoundsForNode$bot === void 0 ? aTop : _getBoundsForNode$bot; var _getBoundsForNode2 = getBoundsForNode(nodeB), bTop = _getBoundsForNode2.top, bLeft = _getBoundsForNode2.left, _getBoundsForNode2$ri = _getBoundsForNode2.right, bRight = _getBoundsForNode2$ri === void 0 ? bLeft : _getBoundsForNode2$ri, _getBoundsForNode2$bo = _getBoundsForNode2.bottom, bBottom = _getBoundsForNode2$bo === void 0 ? bTop : _getBoundsForNode2$bo; return !( // 'a' bottom doesn't touch 'b' top aBottom - tolerance < bTop || // 'a' top doesn't touch 'b' bottom aTop + tolerance > bBottom || // 'a' right doesn't touch 'b' left aRight - tolerance < bLeft || // 'a' left doesn't touch 'b' right aLeft + tolerance > bRight); } /** * Given a node, get everything needed to calculate its boundaries * @param {HTMLElement} node * @return {Object} */ function getBoundsForNode(node) { if (!node.getBoundingClientRect) return node; var rect = node.getBoundingClientRect(), left = rect.left + pageOffset('left'), top = rect.top + pageOffset('top'); return { top: top, left: left, right: (node.offsetWidth || 0) + left, bottom: (node.offsetHeight || 0) + top }; } function pageOffset(dir) { if (dir === 'left') return window.pageXOffset || document.body.scrollLeft || 0; if (dir === 'top') return window.pageYOffset || document.body.scrollTop || 0; } var BackgroundCells = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(BackgroundCells, _React$Component); function BackgroundCells(props, context) { var _this; _this = _React$Component.call(this, props, context) || this; _this.state = { selecting: false }; return _this; } var _proto = BackgroundCells.prototype; _proto.componentDidMount = function componentDidMount() { this.props.selectable && this._selectable(); }; _proto.componentWillUnmount = function componentWillUnmount() { this._teardownSelectable(); }; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (nextProps.selectable && !this.props.selectable) this._selectable(); if (!nextProps.selectable && this.props.selectable) this._teardownSelectable(); }; _proto.render = function render() { var _this$props = this.props, range = _this$props.range, getNow = _this$props.getNow, getters = _this$props.getters, currentDate = _this$props.date, Wrapper = _this$props.components.dateCellWrapper; var _this$state = this.state, selecting = _this$state.selecting, startIdx = _this$state.startIdx, endIdx = _this$state.endIdx; var current = getNow(); return React.createElement("div", { className: "rbc-row-bg" }, range.map(function (date, index) { var selected = selecting && index >= startIdx && index <= endIdx; var _getters$dayProp = getters.dayProp(date), className = _getters$dayProp.className, style = _getters$dayProp.style; return React.createElement(Wrapper, { key: index, value: date, range: range }, React.createElement("div", { style: style, className: clsx('rbc-day-bg', className, selected && 'rbc-selected-cell', eq(date, current, 'day') && 'rbc-today', currentDate && month(currentDate) !== month(date) && 'rbc-off-range-bg') })); })); }; _proto._selectable = function _selectable() { var _this2 = this; var node = findDOMNode(this); var selector = this._selector = new Selection(this.props.container, { longPressThreshold: this.props.longPressThreshold }); var selectorClicksHandler = function selectorClicksHandler(point, actionType) { if (!isEvent(findDOMNode(_this2), point)) { var rowBox = getBoundsForNode(node); var _this2$props = _this2.props, range = _this2$props.range, rtl = _this2$props.rtl; if (pointInBox(rowBox, point)) { var currentCell = getSlotAtX(rowBox, point.x, rtl, range.length); _this2._selectSlot({ startIdx: currentCell, endIdx: currentCell, action: actionType, box: point }); } } _this2._initial = {}; _this2.setState({ selecting: false }); }; selector.on('selecting', function (box) { var _this2$props2 = _this2.props, range = _this2$props2.range, rtl = _this2$props2.rtl; var startIdx = -1; var endIdx = -1; if (!_this2.state.selecting) { notify(_this2.props.onSelectStart, [box]); _this2._initial = { x: box.x, y: box.y }; } if (selector.isSelected(node)) { var nodeBox = getBoundsForNode(node); var _dateCellSelection = dateCellSelection(_this2._initial, nodeBox, box, range.length, rtl); startIdx = _dateCellSelection.startIdx; endIdx = _dateCellSelection.endIdx; } _this2.setState({ selecting: true, startIdx: startIdx, endIdx: endIdx }); }); selector.on('beforeSelect', function (box) { if (_this2.props.selectable !== 'ignoreEvents') return; return !isEvent(findDOMNode(_this2), box); }); selector.on('click', function (point) { return selectorClicksHandler(point, 'click'); }); selector.on('doubleClick', function (point) { return selectorClicksHandler(point, 'doubleClick'); }); selector.on('select', function (bounds) { _this2._selectSlot(_extends({}, _this2.state, { action: 'select', bounds: bounds })); _this2._initial = {}; _this2.setState({ selecting: false }); notify(_this2.props.onSelectEnd, [_this2.state]); }); }; _proto._teardownSelectable = function _teardownSelectable() { if (!this._selector) return; this._selector.teardown(); this._selector = null; }; _proto._selectSlot = function _selectSlot(_ref) { var endIdx = _ref.endIdx, startIdx = _ref.startIdx, action = _ref.action, bounds = _ref.bounds, box = _ref.box; if (endIdx !== -1 && startIdx !== -1) this.props.onSelectSlot && this.props.onSelectSlot({ start: startIdx, end: endIdx, action: action, bounds: bounds, box: box }); }; return BackgroundCells; }(React.Component); BackgroundCells.propTypes = process.env.NODE_ENV !== "production" ? { date: PropTypes.instanceOf(Date), getNow: PropTypes.func.isRequired, getters: PropTypes.object.isRequired, components: PropTypes.object.isRequired, container: PropTypes.func, dayPropGetter: PropTypes.func, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), longPressThreshold: PropTypes.number, onSelectSlot: PropTypes.func.isRequired, onSelectEnd: PropTypes.func, onSelectStart: PropTypes.func, range: PropTypes.arrayOf(PropTypes.instanceOf(Date)), rtl: PropTypes.bool, type: PropTypes.string } : {}; /* eslint-disable react/prop-types */ var EventRowMixin = { propTypes: { slotMetrics: PropTypes.object.isRequired, selected: PropTypes.object, isAllDay: PropTypes.bool, accessors: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, onSelect: PropTypes.func, onDoubleClick: PropTypes.func }, defaultProps: { segments: [], selected: {} }, renderEvent: function renderEvent(props, event) { var selected = props.selected, _ = props.isAllDay, accessors = props.accessors, getters = props.getters, onSelect = props.onSelect, onDoubleClick = props.onDoubleClick, localizer = props.localizer, slotMetrics = props.slotMetrics, components = props.components; var continuesPrior = slotMetrics.continuesPrior(event); var continuesAfter = slotMetrics.continuesAfter(event); return React.createElement(EventCell, { event: event, getters: getters, localizer: localizer, accessors: accessors, components: components, onSelect: onSelect, onDoubleClick: onDoubleClick, continuesPrior: continuesPrior, continuesAfter: continuesAfter, slotStart: slotMetrics.first, slotEnd: slotMetrics.last, selected: isSelected(event, selected) }); }, renderSpan: function renderSpan(slots, len, key, content) { if (content === void 0) { content = ' '; } var per = Math.abs(len) / slots * 100 + '%'; return React.createElement("div", { key: key, className: "rbc-row-segment" // IE10/11 need max-width. flex-basis doesn't respect box-sizing , style: { WebkitFlexBasis: per, flexBasis: per, maxWidth: per } }, content); } }; var EventRow = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(EventRow, _React$Component); function EventRow() { return _React$Component.apply(this, arguments) || this; } var _proto = EventRow.prototype; _proto.render = function render() { var _this = this; var _this$props = this.props, segments = _this$props.segments, slots = _this$props.slotMetrics.slots, className = _this$props.className; var lastEnd = 1; return React.createElement("div", { className: clsx(className, 'rbc-row') }, segments.reduce(function (row, _ref, li) { var event = _ref.event, left = _ref.left, right = _ref.right, span = _ref.span; var key = '_lvl_' + li; var gap = left - lastEnd; var content = EventRowMixin.renderEvent(_this.props, event); if (gap) row.push(EventRowMixin.renderSpan(slots, gap, key + "_gap")); row.push(EventRowMixin.renderSpan(slots, span, key, content)); lastEnd = right + 1; return row; }, [])); }; return EventRow; }(React.Component); EventRow.propTypes = process.env.NODE_ENV !== "production" ? _extends({ segments: PropTypes.array }, EventRowMixin.propTypes) : {}; EventRow.defaultProps = _extends({}, EventRowMixin.defaultProps); function endOfRange(dateRange, unit) { if (unit === void 0) { unit = 'day'; } return { first: dateRange[0], last: add(dateRange[dateRange.length - 1], 1, unit) }; } function eventSegments(event, range, accessors) { var _endOfRange = endOfRange(range), first = _endOfRange.first, last = _endOfRange.last; var slots = diff(first, last, 'day'); var start = max(startOf(accessors.start(event), 'day'), first); var end = min(ceil(accessors.end(event), 'day'), last); var padding = findIndex(range, function (x) { return eq(x, start, 'day'); }); var span = diff(start, end, 'day'); span = Math.min(span, slots); span = Math.max(span, 1); return { event: event, span: span, left: padding + 1, right: Math.max(padding + span, 1) }; } function eventLevels(rowSegments, limit) { if (limit === void 0) { limit = Infinity; } var i, j, seg, levels = [], extra = []; for (i = 0; i < rowSegments.length; i++) { seg = rowSegments[i]; for (j = 0; j < levels.length; j++) { if (!segsOverlap(seg, levels[j])) break; } if (j >= limit) { extra.push(seg); } else { (levels[j] || (levels[j] = [])).push(seg); } } for (i = 0; i < levels.length; i++) { levels[i].sort(function (a, b) { return a.left - b.left; }); //eslint-disable-line } return { levels: levels, extra: extra }; } function inRange(e, start, end, accessors) { var eStart = startOf(accessors.start(e), 'day'); var eEnd = accessors.end(e); var startsBeforeEnd = lte(eStart, end, 'day'); // when the event is zero duration we need to handle a bit differently var endsAfterStart = !eq(eStart, eEnd, 'minutes') ? gt(eEnd, start, 'minutes') : gte(eEnd, start, 'minutes'); return startsBeforeEnd && endsAfterStart; } function segsOverlap(seg, otherSegs) { return otherSegs.some(function (otherSeg) { return otherSeg.left <= seg.right && otherSeg.right >= seg.left; }); } function sortEvents(evtA, evtB, accessors) { var startSort = +startOf(accessors.start(evtA), 'day') - +startOf(accessors.start(evtB), 'day'); var durA = diff(accessors.start(evtA), ceil(accessors.end(evtA), 'day'), 'day'); var durB = diff(accessors.start(evtB), ceil(accessors.end(evtB), 'day'), 'day'); return startSort || // sort by start Day first Math.max(durB, 1) - Math.max(durA, 1) || // events spanning multiple days go first !!accessors.allDay(evtB) - !!accessors.allDay(evtA) || // then allDay single day events +accessors.start(evtA) - +accessors.start(evtB); // then sort by start time } var isSegmentInSlot = function isSegmentInSlot(seg, slot) { return seg.left <= slot && seg.right >= slot; }; var eventsInSlot = function eventsInSlot(segments, slot) { return segments.filter(function (seg) { return isSegmentInSlot(seg, slot); }).length; }; var EventEndingRow = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(EventEndingRow, _React$Component); function EventEndingRow() { return _React$Component.apply(this, arguments) || this; } var _proto = EventEndingRow.prototype; _proto.render = function render() { var _this$props = this.props, segments = _this$props.segments, slots = _this$props.slotMetrics.slots; var rowSegments = eventLevels(segments).levels[0]; var current = 1, lastEnd = 1, row = []; while (current <= slots) { var key = '_lvl_' + current; var _ref = rowSegments.filter(function (seg) { return isSegmentInSlot(seg, current); })[0] || {}, event = _ref.event, left = _ref.left, right = _ref.right, span = _ref.span; //eslint-disable-line if (!event) { current++; continue; } var gap = Math.max(0, left - lastEnd); if (this.canRenderSlotEvent(left, span)) { var content = EventRowMixin.renderEvent(this.props, event); if (gap) { row.push(EventRowMixin.renderSpan(slots, gap, key + '_gap')); } row.push(EventRowMixin.renderSpan(slots, span, key, content)); lastEnd = current = right + 1; } else { if (gap) { row.push(EventRowMixin.renderSpan(slots, gap, key + '_gap')); } row.push(EventRowMixin.renderSpan(slots, 1, key, this.renderShowMore(segments, current))); lastEnd = current = current + 1; } } return React.createElement("div", { className: "rbc-row" }, row); }; _proto.canRenderSlotEvent = function canRenderSlotEvent(slot, span) { var segments = this.props.segments; return range$1(slot, slot + span).every(function (s) { var count = eventsInSlot(segments, s); return count === 1; }); }; _proto.renderShowMore = function renderShowMore(segments, slot) { var _this = this; var localizer = this.props.localizer; var count = eventsInSlot(segments, slot); return count ? React.createElement("a", { key: 'sm_' + slot, href: "#", className: 'rbc-show-more', onClick: function onClick(e) { return _this.showMore(slot, e); } }, localizer.messages.showMore(count)) : false; }; _proto.showMore = function showMore(slot, e) { e.preventDefault(); this.props.onShowMore(slot, e.target); }; return EventEndingRow; }(React.Component); EventEndingRow.propTypes = process.env.NODE_ENV !== "production" ? _extends({ segments: PropTypes.array, slots: PropTypes.number, onShowMore: PropTypes.func }, EventRowMixin.propTypes) : {}; EventEndingRow.defaultProps = _extends({}, EventRowMixin.defaultProps); var isSegmentInSlot$1 = function isSegmentInSlot(seg, slot) { return seg.left <= slot && seg.right >= slot; }; var isEqual = function isEqual(a, b) { return a.range === b.range && a.events === b.events; }; function getSlotMetrics() { return memoize(function (options) { var range = options.range, events = options.events, maxRows = options.maxRows, minRows = options.minRows, accessors = options.accessors; var _endOfRange = endOfRange(range), first = _endOfRange.first, last = _endOfRange.last; var segments = events.map(function (evt) { return eventSegments(evt, range, accessors); }); var _eventLevels = eventLevels(segments, Math.max(maxRows - 1, 1)), levels = _eventLevels.levels, extra = _eventLevels.extra; while (levels.length < minRows) { levels.push([]); } return { first: first, last: last, levels: levels, extra: extra, range: range, slots: range.length, clone: function clone(args) { var metrics = getSlotMetrics(); return metrics(_extends({}, options, args)); }, getDateForSlot: function getDateForSlot(slotNumber) { return range[slotNumber]; }, getSlotForDate: function getSlotForDate(date) { return range.find(function (r) { return eq(r, date, 'day'); }); }, getEventsForSlot: function getEventsForSlot(slot) { return segments.filter(function (seg) { return isSegmentInSlot$1(seg, slot); }).map(function (seg) { return seg.event; }); }, continuesPrior: function continuesPrior(event) { return lt(accessors.start(event), first, 'day'); }, continuesAfter: function continuesAfter(event) { var eventEnd = accessors.end(event); var singleDayDuration = eq(accessors.start(event), eventEnd, 'minutes'); return singleDayDuration ? gte(eventEnd, last, 'minutes') : gt(eventEnd, last, 'minutes'); } }; }, isEqual); } var DateContentRow = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(DateContentRow, _React$Component); function DateContentRow() { 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.handleSelectSlot = function (slot) { var _this$props = _this.props, range = _this$props.range, onSelectSlot = _this$props.onSelectSlot; onSelectSlot(range.slice(slot.start, slot.end + 1), slot); }; _this.handleShowMore = function (slot, target) { var _this$props2 = _this.props, range = _this$props2.range, onShowMore = _this$props2.onShowMore; var metrics = _this.slotMetrics(_this.props); var row = qsa(findDOMNode(_assertThisInitialized(_this)), '.rbc-row-bg')[0]; var cell; if (row) cell = row.children[slot - 1]; var events = metrics.getEventsForSlot(slot); onShowMore(events, range[slot - 1], cell, slot, target); }; _this.createHeadingRef = function (r) { _this.headingRow = r; }; _this.createEventRef = function (r) { _this.eventRow = r; }; _this.getContainer = function () { var container = _this.props.container; return container ? container() : findDOMNode(_assertThisInitialized(_this)); }; _this.renderHeadingCell = function (date, index) { var _this$props3 = _this.props, renderHeader = _this$props3.renderHeader, getNow = _this$props3.getNow; return renderHeader({ date: date, key: "header_" + index, className: clsx('rbc-date-cell', eq(date, getNow(), 'day') && 'rbc-now') }); }; _this.renderDummy = function () { var _this$props4 = _this.props, className = _this$props4.className, range = _this$props4.range, renderHeader = _this$props4.renderHeader; return React.createElement("div", { className: className }, React.createElement("div", { className: "rbc-row-content" }, renderHeader && React.createElement("div", { className: "rbc-row", ref: _this.createHeadingRef }, range.map(_this.renderHeadingCell)), React.createElement("div", { className: "rbc-row", ref: _this.createEventRef }, React.createElement("div", { className: "rbc-row-segment" }, React.createElement("div", { className: "rbc-event" }, React.createElement("div", { className: "rbc-event-content" }, "\xA0")))))); }; _this.slotMetrics = getSlotMetrics(); return _this; } var _proto = DateContentRow.prototype; _proto.getRowLimit = function getRowLimit() { var eventHeight = getHeight(this.eventRow); var headingHeight = this.headingRow ? getHeight(this.headingRow) : 0; var eventSpace = getHeight(findDOMNode(this)) - headingHeight; return Math.max(Math.floor(eventSpace / eventHeight), 1); }; _proto.render = function render() { var _this$props5 = this.props, date = _this$props5.date, rtl = _this$props5.rtl, range = _this$props5.range, className = _this$props5.className, selected = _this$props5.selected, selectable = _this$props5.selectable, renderForMeasure = _this$props5.renderForMeasure, accessors = _this$props5.accessors, getters = _this$props5.getters, components = _this$props5.components, getNow = _this$props5.getNow, renderHeader = _this$props5.renderHeader, onSelect = _this$props5.onSelect, localizer = _this$props5.localizer, onSelectStart = _this$props5.onSelectStart, onSelectEnd = _this$props5.onSelectEnd, onDoubleClick = _this$props5.onDoubleClick, resourceId = _this$props5.resourceId, longPressThreshold = _this$props5.longPressThreshold, isAllDay = _this$props5.isAllDay; if (renderForMeasure) return this.renderDummy(); var metrics = this.slotMetrics(this.props); var levels = metrics.levels, extra = metrics.extra; var WeekWrapper = components.weekWrapper; var eventRowProps = { selected: selected, accessors: accessors, getters: getters, localizer: localizer, components: components, onSelect: onSelect, onDoubleClick: onDoubleClick, resourceId: resourceId, slotMetrics: metrics }; return React.createElement("div", { className: className }, React.createElement(BackgroundCells, { date: date, getNow: getNow, rtl: rtl, range: range, selectable: selectable, container: this.getContainer, getters: getters, onSelectStart: onSelectStart, onSelectEnd: onSelectEnd, onSelectSlot: this.handleSelectSlot, components: components, longPressThreshold: longPressThreshold }), React.createElement("div", { className: "rbc-row-content" }, renderHeader && React.createElement("div", { className: "rbc-row ", ref: this.createHeadingRef }, range.map(this.renderHeadingCell)), React.createElement(WeekWrapper, _extends({ isAllDay: isAllDay }, eventRowProps), levels.map(function (segs, idx) { return React.createElement(EventRow, _extends({ key: idx, segments: segs }, eventRowProps)); }), !!extra.length && React.createElement(EventEndingRow, _extends({ segments: extra, onShowMore: this.handleShowMore }, eventRowProps))))); }; return DateContentRow; }(React.Component); DateContentRow.propTypes = process.env.NODE_ENV !== "production" ? { date: PropTypes.instanceOf(Date), events: PropTypes.array.isRequired, range: PropTypes.array.isRequired, rtl: PropTypes.bool, resourceId: PropTypes.any, renderForMeasure: PropTypes.bool, renderHeader: PropTypes.func, container: PropTypes.func, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), longPressThreshold: PropTypes.number, onShowMore: PropTypes.func, onSelectSlot: PropTypes.func, onSelect: PropTypes.func, onSelectEnd: PropTypes.func, onSelectStart: PropTypes.func, onDoubleClick: PropTypes.func, dayPropGetter: PropTypes.func, getNow: PropTypes.func.isRequired, isAllDay: PropTypes.bool, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, minRows: PropTypes.number.isRequired, maxRows: PropTypes.number.isRequired } : {}; DateContentRow.defaultProps = { minRows: 0, maxRows: Infinity }; var Header = function Header(_ref) { var label = _ref.label; return React.createElement("span", null, label); }; Header.propTypes = process.env.NODE_ENV !== "production" ? { label: PropTypes.node } : {}; var DateHeader = function DateHeader(_ref) { var label = _ref.label, drilldownView = _ref.drilldownView, onDrillDown = _ref.onDrillDown; if (!drilldownView) { return React.createElement("span", null, label); } return React.createElement("a", { href: "#", onClick: onDrillDown }, label); }; DateHeader.propTypes = process.env.NODE_ENV !== "production" ? { label: PropTypes.node, date: PropTypes.instanceOf(Date), drilldownView: PropTypes.string, onDrillDown: PropTypes.func, isOffRange: PropTypes.bool } : {}; var eventsForWeek = function eventsForWeek(evts, start, end, accessors) { return evts.filter(function (e) { return inRange(e, start, end, accessors); }); }; var MonthView = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(MonthView, _React$Component); function MonthView() { 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.getContainer = function () { return findDOMNode(_assertThisInitialized(_this)); }; _this.renderWeek = function (week, weekIdx) { var _this$props = _this.props, events = _this$props.events, components = _this$props.components, selectable = _this$props.selectable, getNow = _this$props.getNow, selected = _this$props.selected, date = _this$props.date, localizer = _this$props.localizer, longPressThreshold = _this$props.longPressThreshold, accessors = _this$props.accessors, getters = _this$props.getters; var _this$state = _this.state, needLimitMeasure = _this$state.needLimitMeasure, rowLimit = _this$state.rowLimit; events = eventsForWeek(events, week[0], week[week.length - 1], accessors); events.sort(function (a, b) { return sortEvents(a, b, accessors); }); return React.createElement(DateContentRow, { key: weekIdx, ref: weekIdx === 0 ? _this.slotRowRef : undefined, container: _this.getContainer, className: "rbc-month-row", getNow: getNow, date: date, range: week, events: events, maxRows: rowLimit, selected: selected, selectable: selectable, components: components, accessors: accessors, getters: getters, localizer: localizer, renderHeader: _this.readerDateHeading, renderForMeasure: needLimitMeasure, onShowMore: _this.handleShowMore, onSelect: _this.handleSelectEvent, onDoubleClick: _this.handleDoubleClickEvent, onSelectSlot: _this.handleSelectSlot, longPressThreshold: longPressThreshold, rtl: _this.props.rtl }); }; _this.readerDateHeading = function (_ref) { var date = _ref.date, className = _ref.className, props = _objectWithoutPropertiesLoose(_ref, ["date", "className"]); var _this$props2 = _this.props, currentDate = _this$props2.date, getDrilldownView = _this$props2.getDrilldownView, localizer = _this$props2.localizer; var isOffRange = month(date) !== month(currentDate); var isCurrent = eq(date, currentDate, 'day'); var drilldownView = getDrilldownView(date); var label = localizer.format(date, 'dateFormat'); var DateHeaderComponent = _this.props.components.dateHeader || DateHeader; return React.createElement("div", _extends({}, props, { className: clsx(className, isOffRange && 'rbc-off-range', isCurrent && 'rbc-current') }), React.createElement(DateHeaderComponent, { label: label, date: date, drilldownView: drilldownView, isOffRange: isOffRange, onDrillDown: function onDrillDown(e) { return _this.handleHeadingClick(date, drilldownView, e); } })); }; _this.handleSelectSlot = function (range, slotInfo) { _this._pendingSelection = _this._pendingSelection.concat(range); clearTimeout(_this._selectTimer); _this._selectTimer = setTimeout(function () { return _this.selectDates(slotInfo); }); }; _this.handleHeadingClick = function (date, view, e) { e.preventDefault(); _this.clearSelection(); notify(_this.props.onDrillDown, [date, view]); }; _this.handleSelectEvent = function () { _this.clearSelection(); for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } notify(_this.props.onSelectEvent, args); }; _this.handleDoubleClickEvent = function () { _this.clearSelection(); for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } notify(_this.props.onDoubleClickEvent, args); }; _this.handleShowMore = function (events, date, cell, slot, target) { var _this$props3 = _this.props, popup = _this$props3.popup, onDrillDown = _this$props3.onDrillDown, onShowMore = _this$props3.onShowMore, getDrilldownView = _this$props3.getDrilldownView; //cancel any pending selections so only the event click goes through. _this.clearSelection(); if (popup) { var position = getPosition(cell, findDOMNode(_assertThisInitialized(_this))); _this.setState({ overlay: { date: date, events: events, position: position, target: target } }); } else { notify(onDrillDown, [date, getDrilldownView(date) || views.DAY]); } notify(onShowMore, [events, date, slot]); }; _this._bgRows = []; _this._pendingSelection = []; _this.slotRowRef = React.createRef(); _this.state = { rowLimit: 5, needLimitMeasure: true }; return _this; } var _proto = MonthView.prototype; _proto.componentWillReceiveProps = function componentWillReceiveProps(_ref2) { var date = _ref2.date; this.setState({ needLimitMeasure: !eq(date, this.props.date, 'month') }); }; _proto.componentDidMount = function componentDidMount() { var _this2 = this; var running; if (this.state.needLimitMeasure) this.measureRowLimit(this.props); window.addEventListener('resize', this._resizeListener = function () { if (!running) { request(function () { running = false; _this2.setState({ needLimitMeasure: true }); //eslint-disable-line }); } }, false); }; _proto.componentDidUpdate = function componentDidUpdate() { if (this.state.needLimitMeasure) this.measureRowLimit(this.props); }; _proto.componentWillUnmount = function componentWillUnmount() { window.removeEventListener('resize', this._resizeListener, false); }; _proto.render = function render() { var _this$props4 = this.props, date = _this$props4.date, localizer = _this$props4.localizer, className = _this$props4.className, month = visibleDays(date, localizer), weeks = chunk(month, 7); this._weekCount = weeks.length; return React.createElement("div", { className: clsx('rbc-month-view', className) }, React.createElement("div", { className: "rbc-row rbc-month-header" }, this.renderHeaders(weeks[0])), weeks.map(this.renderWeek), this.props.popup && this.renderOverlay()); }; _proto.renderHeaders = function renderHeaders(row) { var _this$props5 = this.props, localizer = _this$props5.localizer, components = _this$props5.components; var first = row[0]; var last = row[row.length - 1]; var HeaderComponent = components.header || Header; return range(first, last, 'day').map(function (day, idx) { return React.createElement("div", { key: 'header_' + idx, className: "rbc-header" }, React.createElement(HeaderComponent, { date: day, localizer: localizer, label: localizer.format(day, 'weekdayFormat') })); }); }; _proto.renderOverlay = function renderOverlay() { var _this3 = this; var overlay = this.state && this.state.overlay || {}; var _this$props6 = this.props, accessors = _this$props6.accessors, localizer = _this$props6.localizer, components = _this$props6.components, getters = _this$props6.getters, selected = _this$props6.selected, popupOffset = _this$props6.popupOffset; return React.createElement(Overlay, { rootClose: true, placement: "bottom", show: !!overlay.position, onHide: function onHide() { return _this3.setState({ overlay: null }); }, target: function target() { return overlay.target; } }, function (_ref3) { var props = _ref3.props; return React.createElement(Popup$1, _extends({}, props, { popupOffset: popupOffset, accessors: accessors, getters: getters, selected: selected, components: components, localizer: localizer, position: overlay.position, events: overlay.events, slotStart: overlay.date, slotEnd: overlay.end, onSelect: _this3.handleSelectEvent, onDoubleClick: _this3.handleDoubleClickEvent })); }); }; _proto.measureRowLimit = function measureRowLimit() { this.setState({ needLimitMeasure: false, rowLimit: this.slotRowRef.current.getRowLimit() }); }; _proto.selectDates = function selectDates(slotInfo) { var slots = this._pendingSelection.slice(); this._pendingSelection = []; slots.sort(function (a, b) { return +a - +b; }); notify(this.props.onSelectSlot, { slots: slots, start: slots[0], end: slots[slots.length - 1], action: slotInfo.action, bounds: slotInfo.bounds, box: slotInfo.box }); }; _proto.clearSelection = function clearSelection() { clearTimeout(this._selectTimer); this._pendingSelection = []; }; return MonthView; }(React.Component); MonthView.propTypes = process.env.NODE_ENV !== "production" ? { events: PropTypes.array.isRequired, date: PropTypes.instanceOf(Date), min: PropTypes.instanceOf(Date), max: PropTypes.instanceOf(Date), step: PropTypes.number, getNow: PropTypes.func.isRequired, scrollToTime: PropTypes.instanceOf(Date), rtl: PropTypes.bool, width: PropTypes.number, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), longPressThreshold: PropTypes.number, onNavigate: PropTypes.func, onSelectSlot: PropTypes.func, onSelectEvent: PropTypes.func, onDoubleClickEvent: PropTypes.func, onShowMore: PropTypes.func, onDrillDown: PropTypes.func, getDrilldownView: PropTypes.func.isRequired, popup: PropTypes.bool, popupOffset: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ x: PropTypes.number, y: PropTypes.number })]) } : {}; MonthView.range = function (date, _ref4) { var localizer = _ref4.localizer; var start = firstVisibleDay(date, localizer); var end = lastVisibleDay(date, localizer); return { start: start, end: end }; }; MonthView.navigate = function (date, action) { switch (action) { case navigate.PREVIOUS: return add(date, -1, 'month'); case navigate.NEXT: return add(date, 1, 'month'); default: return date; } }; MonthView.title = function (date, _ref5) { var localizer = _ref5.localizer; return localizer.format(date, 'monthHeaderFormat'); }; var getDstOffset = function getDstOffset(start, end) { return start.getTimezoneOffset() - end.getTimezoneOffset(); }; var getKey = function getKey(min, max, step, slots) { return "" + +startOf(min, 'minutes') + ("" + +startOf(max, 'minutes')) + (step + "-" + slots); }; function getSlotMetrics$1(_ref) { var start = _ref.min, end = _ref.max, step = _ref.step, timeslots = _ref.timeslots; var key = getKey(start, end, step, timeslots); // if the start is on a DST-changing day but *after* the moment of DST // transition we need to add those extra minutes to our minutesFromMidnight var daystart = startOf(start, 'day'); var daystartdstoffset = getDstOffset(daystart, start); var totalMin = 1 + diff(start, end, 'minutes') + getDstOffset(start, end); var minutesFromMidnight = diff(daystart, start, 'minutes') + daystartdstoffset; var numGroups = Math.ceil(totalMin / (step * timeslots)); var numSlots = numGroups * timeslots; var groups = new Array(numGroups); var slots = new Array(numSlots); // Each slot date is created from "zero", instead of adding `step` to // the previous one, in order to avoid DST oddities for (var grp = 0; grp < numGroups; grp++) { groups[grp] = new Array(timeslots); for (var slot = 0; slot < timeslots; slot++) { var slotIdx = grp * timeslots + slot; var minFromStart = slotIdx * step; // A date with total minutes calculated from the start of the day slots[slotIdx] = groups[grp][slot] = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, minutesFromMidnight + minFromStart, 0, 0); } } // Necessary to be able to select up until the last timeslot in a day var lastSlotMinFromStart = slots.length * step; slots.push(new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, minutesFromMidnight + lastSlotMinFromStart, 0, 0)); function positionFromDate(date) { var diff$1 = diff(start, date, 'minutes') + getDstOffset(start, date); return Math.min(diff$1, totalMin); } return { groups: groups, update: function update(args) { if (getKey(args) !== key) return getSlotMetrics$1(args); return this; }, dateIsInGroup: function dateIsInGroup(date, groupIndex) { var nextGroup = groups[groupIndex + 1]; return inRange$1(date, groups[groupIndex][0], nextGroup ? nextGroup[0] : end, 'minutes'); }, nextSlot: function nextSlot(slot) { var next = slots[Math.min(slots.indexOf(slot) + 1, slots.length - 1)]; // in the case of the last slot we won't a long enough range so manually get it if (next === slot) next = add(slot, step, 'minutes'); return next; }, closestSlotToPosition: function closestSlotToPosition(percent) { var slot = Math.min(slots.length - 1, Math.max(0, Math.floor(percent * numSlots))); return slots[slot]; }, closestSlotFromPoint: function closestSlotFromPoint(point, boundaryRect) { var range = Math.abs(boundaryRect.top - boundaryRect.bottom); return this.closestSlotToPosition((point.y - boundaryRect.top) / range); }, closestSlotFromDate: function closestSlotFromDate(date, offset) { if (offset === void 0) { offset = 0; } if (lt(date, start, 'minutes')) return slots[0]; var diffMins = diff(start, date, 'minutes'); return slots[(diffMins - diffMins % step) / step + offset]; }, startsBeforeDay: function startsBeforeDay(date) { return lt(date, start, 'day'); }, startsAfterDay: function startsAfterDay(date) { return gt(date, end, 'day'); }, startsBefore: function startsBefore(date) { return lt(merge(start, date), start, 'minutes'); }, startsAfter: function startsAfter(date) { return gt(merge(end, date), end, 'minutes'); }, getRange: function getRange(rangeStart, rangeEnd, ignoreMin, ignoreMax) { if (!ignoreMin) rangeStart = min(end, max(start, rangeStart)); if (!ignoreMax) rangeEnd = min(end, max(start, rangeEnd)); var rangeStartMin = positionFromDate(rangeStart); var rangeEndMin = positionFromDate(rangeEnd); var top = rangeEndMin - rangeStartMin < step && !eq(end, rangeEnd) ? (rangeStartMin - step) / (step * numSlots) * 100 : rangeStartMin / (step * numSlots) * 100; return { top: top, height: rangeEndMin / (step * numSlots) * 100 - top, start: positionFromDate(rangeStart), startDate: rangeStart, end: positionFromDate(rangeEnd), endDate: rangeEnd }; }, getCurrentTimePosition: function getCurrentTimePosition(rangeStart) { var rangeStartMin = positionFromDate(rangeStart); var top = rangeStartMin / (step * numSlots) * 100; return top; } }; } var Event = /*#__PURE__*/ function () { function Event(data, _ref) { var accessors = _ref.accessors, slotMetrics = _ref.slotMetrics; var _slotMetrics$getRange = slotMetrics.getRange(accessors.start(data), accessors.end(data)), start = _slotMetrics$getRange.start, startDate = _slotMetrics$getRange.startDate, end = _slotMetrics$getRange.end, endDate = _slotMetrics$getRange.endDate, top = _slotMetrics$getRange.top, height = _slotMetrics$getRange.height; this.start = start; this.end = end; this.startMs = +startDate; this.endMs = +endDate; this.top = top; this.height = height; this.data = data; } /** * The event's width without any overlap. */ _createClass(Event, [{ key: "_width", get: function get() { // The container event's width is determined by the maximum number of // events in any of its rows. if (this.rows) { var columns = this.rows.reduce(function (max, row) { return Math.max(max, row.leaves.length + 1); }, // add itself 0) + 1; // add the container return 100 / columns; } var availableWidth = 100 - this.container._width; // The row event's width is the space left by the container, divided // among itself and its leaves. if (this.leaves) { return availableWidth / (this.leaves.length + 1); } // The leaf event's width is determined by its row's width return this.row._width; } /** * The event's calculated width, possibly with extra width added for * overlapping effect. */ }, { key: "width", get: function get() { var noOverlap = this._width; var overlap = Math.min(100, this._width * 1.7); // Containers can always grow. if (this.rows) { return overlap; } // Rows can grow if they have leaves. if (this.leaves) { return this.leaves.length > 0 ? overlap : noOverlap; } // Leaves can grow unless they're the last item in a row. var leaves = this.row.leaves; var index = leaves.indexOf(this); return index === leaves.length - 1 ? noOverlap : overlap; } }, { key: "xOffset", get: function get() { // Containers have no offset. if (this.rows) return 0; // Rows always start where their container ends. if (this.leaves) return this.container._width; // Leaves are spread out evenly on the space left by its row. var _this$row = this.row, leaves = _this$row.leaves, xOffset = _this$row.xOffset, _width = _this$row._width; var index = leaves.indexOf(this) + 1; return xOffset + index * _width; } }]); return Event; }(); /** * Return true if event a and b is considered to be on the same row. */ function onSameRow(a, b, minimumStartDifference) { return (// Occupies the same start slot. Math.abs(b.start - a.start) < minimumStartDifference || // A's start slot overlaps with b's end slot. b.start > a.start && b.start < a.end ); } function sortByRender(events) { var sortedByTime = sortBy(events, ['startMs', function (e) { return -e.endMs; }]); var sorted = []; while (sortedByTime.length > 0) { var event = sortedByTime.shift(); sorted.push(event); for (var i = 0; i < sortedByTime.length; i++) { var test = sortedByTime[i]; // Still inside this event, look for next. if (event.endMs > test.startMs) continue; // We've found the first event of the next event group. // If that event is not right next to our current event, we have to // move it here. if (i > 0) { var _event = sortedByTime.splice(i, 1)[0]; sorted.push(_event); } // We've already found the next event group, so stop looking. break; } } return sorted; } function getStyledEvents(_ref2) { var events = _ref2.events, minimumStartDifference = _ref2.minimumStartDifference, slotMetrics = _ref2.slotMetrics, accessors = _ref2.accessors; // Create proxy events and order them so that we don't have // to fiddle with z-indexes. var proxies = events.map(function (event) { return new Event(event, { slotMetrics: slotMetrics, accessors: accessors }); }); var eventsInRenderOrder = sortByRender(proxies); // Group overlapping events, while keeping order. // Every event is always one of: container, row or leaf. // Containers can contain rows, and rows can contain leaves. var containerEvents = []; var _loop = function _loop(i) { var event = eventsInRenderOrder[i]; // Check if this event can go into a container event. var container = containerEvents.find(function (c) { return c.end > event.start || Math.abs(event.start - c.start) < minimumStartDifference; }); // Couldn't find a container — that means this event is a container. if (!container) { event.rows = []; containerEvents.push(event); return "continue"; } // Found a container for the event. event.container = container; // Check if the event can be placed in an existing row. // Start looking from behind. var row = null; for (var j = container.rows.length - 1; !row && j >= 0; j--) { if (onSameRow(container.rows[j], event, minimumStartDifference)) { row = container.rows[j]; } } if (row) { // Found a row, so add it. row.leaves.push(event); event.row = row; } else { // Couldn't find a row – that means this event is a row. event.leaves = []; container.rows.push(event); } }; for (var i = 0; i < eventsInRenderOrder.length; i++) { var _ret = _loop(i); if (_ret === "continue") continue; } // Return the original events, along with their styles. return eventsInRenderOrder.map(function (event) { return { event: event.data, style: { top: event.top, height: event.height, width: event.width, xOffset: event.xOffset } }; }); } var TimeSlotGroup = /*#__PURE__*/ function (_Component) { _inheritsLoose(TimeSlotGroup, _Component); function TimeSlotGroup() { return _Component.apply(this, arguments) || this; } var _proto = TimeSlotGroup.prototype; _proto.render = function render() { var _this$props = this.props, renderSlot = _this$props.renderSlot, resource = _this$props.resource, group = _this$props.group, getters = _this$props.getters, _this$props$component = _this$props.components; _this$props$component = _this$props$component === void 0 ? {} : _this$props$component; var _this$props$component2 = _this$props$component.timeSlotWrapper, Wrapper = _this$props$component2 === void 0 ? NoopWrapper : _this$props$component2; return React.createElement("div", { className: "rbc-timeslot-group" }, group.map(function (value, idx) { var slotProps = getters ? getters.slotProp(value, resource) : {}; return React.createElement(Wrapper, { key: idx, value: value, resource: resource }, React.createElement("div", _extends({}, slotProps, { className: clsx('rbc-time-slot', slotProps.className) }), renderSlot && renderSlot(value, idx))); })); }; return TimeSlotGroup; }(Component); TimeSlotGroup.propTypes = process.env.NODE_ENV !== "production" ? { renderSlot: PropTypes.func, group: PropTypes.array.isRequired, resource: PropTypes.any, components: PropTypes.object, getters: PropTypes.object } : {}; /* eslint-disable react/prop-types */ function TimeGridEvent(props) { var _extends2; var style = props.style, className = props.className, event = props.event, accessors = props.accessors, rtl = props.rtl, selected = props.selected, label = props.label, continuesEarlier = props.continuesEarlier, continuesLater = props.continuesLater, getters = props.getters, onClick = props.onClick, onDoubleClick = props.onDoubleClick, _props$components = props.components, Event = _props$components.event, EventWrapper = _props$components.eventWrapper; var title = accessors.title(event); var tooltip = accessors.tooltip(event); var end = accessors.end(event); var start = accessors.start(event); var userProps = getters.eventProp(event, start, end, selected); var height = style.height, top = style.top, width = style.width, xOffset = style.xOffset; var inner = [React.createElement("div", { key: "1", className: "rbc-event-label" }, label), React.createElement("div", { key: "2", className: "rbc-event-content" }, Event ? React.createElement(Event, { event: event, title: title }) : title)]; return React.createElement(EventWrapper, _extends({ type: "time" }, props), React.createElement("div", { onClick: onClick, onDoubleClick: onDoubleClick, style: _extends({}, userProps.style, (_extends2 = { top: top + "%", height: height + "%" }, _extends2[rtl ? 'right' : 'left'] = Math.max(0, xOffset) + "%", _extends2.width = width + "%", _extends2)), title: tooltip ? (typeof label === 'string' ? label + ': ' : '') + tooltip : undefined, className: clsx('rbc-event', className, userProps.className, { 'rbc-selected': selected, 'rbc-event-continues-earlier': continuesEarlier, 'rbc-event-continues-later': continuesLater }) }, inner)); } var DayColumn = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(DayColumn, _React$Component); function DayColumn() { 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.state = { selecting: false, timeIndicatorPosition: null }; _this.intervalTriggered = false; _this.renderEvents = function () { var _this$props = _this.props, events = _this$props.events, rtl = _this$props.rtl, selected = _this$props.selected, accessors = _this$props.accessors, localizer = _this$props.localizer, getters = _this$props.getters, components = _this$props.components, step = _this$props.step, timeslots = _this$props.timeslots; var _assertThisInitialize = _assertThisInitialized(_this), slotMetrics = _assertThisInitialize.slotMetrics; var messages = localizer.messages; var styledEvents = getStyledEvents({ events: events, accessors: accessors, slotMetrics: slotMetrics, minimumStartDifference: Math.ceil(step * timeslots / 2) }); return styledEvents.map(function (_ref, idx) { var event = _ref.event, style = _ref.style; var end = accessors.end(event); var start = accessors.start(event); var format = 'eventTimeRangeFormat'; var label; var startsBeforeDay = slotMetrics.startsBeforeDay(start); var startsAfterDay = slotMetrics.startsAfterDay(end); if (startsBeforeDay) format = 'eventTimeRangeEndFormat';else if (startsAfterDay) format = 'eventTimeRangeStartFormat'; if (startsBeforeDay && startsAfterDay) label = messages.allDay;else label = localizer.format({ start: start, end: end }, format); var continuesEarlier = startsBeforeDay || slotMetrics.startsBefore(start); var continuesLater = startsAfterDay || slotMetrics.startsAfter(end); return React.createElement(TimeGridEvent, { style: style, event: event, label: label, key: 'evt_' + idx, getters: getters, rtl: rtl, components: components, continuesEarlier: continuesEarlier, continuesLater: continuesLater, accessors: accessors, selected: isSelected(event, selected), onClick: function onClick(e) { return _this._select(event, e); }, onDoubleClick: function onDoubleClick(e) { return _this._doubleClick(event, e); } }); }); }; _this._selectable = function () { var node = findDOMNode(_assertThisInitialized(_this)); var selector = _this._selector = new Selection(function () { return findDOMNode(_assertThisInitialized(_this)); }, { longPressThreshold: _this.props.longPressThreshold }); var maybeSelect = function maybeSelect(box) { var onSelecting = _this.props.onSelecting; var current = _this.state || {}; var state = selectionState(box); var start = state.startDate, end = state.endDate; if (onSelecting) { if (eq(current.startDate, start, 'minutes') && eq(current.endDate, end, 'minutes') || onSelecting({ start: start, end: end }) === false) return; } if (_this.state.start !== state.start || _this.state.end !== state.end || _this.state.selecting !== state.selecting) { _this.setState(state); } }; var selectionState = function selectionState(point) { var currentSlot = _this.slotMetrics.closestSlotFromPoint(point, getBoundsForNode(node)); if (!_this.state.selecting) { _this._initialSlot = currentSlot; } var initialSlot = _this._initialSlot; if (lte(initialSlot, currentSlot)) { currentSlot = _this.slotMetrics.nextSlot(currentSlot); } else if (gt(initialSlot, currentSlot)) { initialSlot = _this.slotMetrics.nextSlot(initialSlot); } var selectRange = _this.slotMetrics.getRange(min(initialSlot, currentSlot), max(initialSlot, currentSlot)); return _extends({}, selectRange, { selecting: true, top: selectRange.top + "%", height: selectRange.height + "%" }); }; var selectorClicksHandler = function selectorClicksHandler(box, actionType) { if (!isEvent(findDOMNode(_assertThisInitialized(_this)), box)) { var _selectionState = selectionState(box), startDate = _selectionState.startDate, endDate = _selectionState.endDate; _this._selectSlot({ startDate: startDate, endDate: endDate, action: actionType, box: box }); } _this.setState({ selecting: false }); }; selector.on('selecting', maybeSelect); selector.on('selectStart', maybeSelect); selector.on('beforeSelect', function (box) { if (_this.props.selectable !== 'ignoreEvents') return; return !isEvent(findDOMNode(_assertThisInitialized(_this)), box); }); selector.on('click', function (box) { return selectorClicksHandler(box, 'click'); }); selector.on('doubleClick', function (box) { return selectorClicksHandler(box, 'doubleClick'); }); selector.on('select', function (bounds) { if (_this.state.selecting) { _this._selectSlot(_extends({}, _this.state, { action: 'select', bounds: bounds })); _this.setState({ selecting: false }); } }); selector.on('reset', function () { if (_this.state.selecting) { _this.setState({ selecting: false }); } }); }; _this._teardownSelectable = function () { if (!_this._selector) return; _this._selector.teardown(); _this._selector = null; }; _this._selectSlot = function (_ref2) { var startDate = _ref2.startDate, endDate = _ref2.endDate, action = _ref2.action, bounds = _ref2.bounds, box = _ref2.box; var current = startDate, slots = []; while (lte(current, endDate)) { slots.push(current); current = add(current, _this.props.step, 'minutes'); } notify(_this.props.onSelectSlot, { slots: slots, start: startDate, end: endDate, resourceId: _this.props.resource, action: action, bounds: bounds, box: box }); }; _this._select = function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } notify(_this.props.onSelectEvent, args); }; _this._doubleClick = function () { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } notify(_this.props.onDoubleClickEvent, args); }; _this.slotMetrics = getSlotMetrics$1(_this.props); return _this; } var _proto = DayColumn.prototype; _proto.componentDidMount = function componentDidMount() { this.props.selectable && this._selectable(); if (this.props.isNow) { this.setTimeIndicatorPositionUpdateInterval(); } }; _proto.componentWillUnmount = function componentWillUnmount() { this._teardownSelectable(); this.clearTimeIndicatorInterval(); }; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (nextProps.selectable && !this.props.selectable) this._selectable(); if (!nextProps.selectable && this.props.selectable) this._teardownSelectable(); this.slotMetrics = this.slotMetrics.update(nextProps); }; _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) { var getNowChanged = !eq(prevProps.getNow(), this.props.getNow(), 'minutes'); if (prevProps.isNow !== this.props.isNow || getNowChanged) { this.clearTimeIndicatorInterval(); if (this.props.isNow) { var tail = !getNowChanged && eq(prevProps.date, this.props.date, 'minutes') && prevState.timeIndicatorPosition === this.state.timeIndicatorPosition; this.setTimeIndicatorPositionUpdateInterval(tail); } } else if (this.props.isNow && (!eq(prevProps.min, this.props.min, 'minutes') || !eq(prevProps.max, this.props.max, 'minutes'))) { this.positionTimeIndicator(); } }; /** * @param tail {Boolean} - whether `positionTimeIndicator` call should be * deferred or called upon setting interval (`true` - if deferred); */ _proto.setTimeIndicatorPositionUpdateInterval = function setTimeIndicatorPositionUpdateInterval(tail) { var _this2 = this; if (tail === void 0) { tail = false; } if (!this.intervalTriggered && !tail) { this.positionTimeIndicator(); } this._timeIndicatorTimeout = window.setTimeout(function () { _this2.intervalTriggered = true; _this2.positionTimeIndicator(); _this2.setTimeIndicatorPositionUpdateInterval(); }, 60000); }; _proto.clearTimeIndicatorInterval = function clearTimeIndicatorInterval() { this.intervalTriggered = false; window.clearTimeout(this._timeIndicatorTimeout); }; _proto.positionTimeIndicator = function positionTimeIndicator() { var _this$props2 = this.props, min = _this$props2.min, max = _this$props2.max, getNow = _this$props2.getNow; var current = getNow(); if (current >= min && current <= max) { var top = this.slotMetrics.getCurrentTimePosition(current); this.setState({ timeIndicatorPosition: top }); } else { this.clearTimeIndicatorInterval(); } }; _proto.render = function render() { var _this$props3 = this.props, max = _this$props3.max, rtl = _this$props3.rtl, isNow = _this$props3.isNow, resource = _this$props3.resource, accessors = _this$props3.accessors, localizer = _this$props3.localizer, _this$props3$getters = _this$props3.getters, dayProp = _this$props3$getters.dayProp, getters = _objectWithoutPropertiesLoose(_this$props3$getters, ["dayProp"]), _this$props3$componen = _this$props3.components, EventContainer = _this$props3$componen.eventContainerWrapper, components = _objectWithoutPropertiesLoose(_this$props3$componen, ["eventContainerWrapper"]); var slotMetrics = this.slotMetrics; var _this$state = this.state, selecting = _this$state.selecting, top = _this$state.top, height = _this$state.height, startDate = _this$state.startDate, endDate = _this$state.endDate; var selectDates = { start: startDate, end: endDate }; var _dayProp = dayProp(max), className = _dayProp.className, style = _dayProp.style; return React.createElement("div", { style: style, className: clsx(className, 'rbc-day-slot', 'rbc-time-column', isNow && 'rbc-now', isNow && 'rbc-today', // WHY selecting && 'rbc-slot-selecting') }, slotMetrics.groups.map(function (grp, idx) { return React.createElement(TimeSlotGroup, { key: idx, group: grp, resource: resource, getters: getters, components: components }); }), React.createElement(EventContainer, { localizer: localizer, resource: resource, accessors: accessors, getters: getters, components: components, slotMetrics: slotMetrics }, React.createElement("div", { className: clsx('rbc-events-container', rtl && 'rtl') }, this.renderEvents())), selecting && React.createElement("div", { className: "rbc-slot-selection", style: { top: top, height: height } }, React.createElement("span", null, localizer.format(selectDates, 'selectRangeFormat'))), isNow && React.createElement("div", { className: "rbc-current-time-indicator", style: { top: this.state.timeIndicatorPosition + "%" } })); }; return DayColumn; }(React.Component); DayColumn.propTypes = process.env.NODE_ENV !== "production" ? { events: PropTypes.array.isRequired, step: PropTypes.number.isRequired, date: PropTypes.instanceOf(Date).isRequired, min: PropTypes.instanceOf(Date).isRequired, max: PropTypes.instanceOf(Date).isRequired, getNow: PropTypes.func.isRequired, isNow: PropTypes.bool, rtl: PropTypes.bool, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, showMultiDayTimes: PropTypes.bool, culture: PropTypes.string, timeslots: PropTypes.number, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), eventOffset: PropTypes.number, longPressThreshold: PropTypes.number, onSelecting: PropTypes.func, onSelectSlot: PropTypes.func.isRequired, onSelectEvent: PropTypes.func.isRequired, onDoubleClickEvent: PropTypes.func.isRequired, className: PropTypes.string, dragThroughEvents: PropTypes.bool, resource: PropTypes.any } : {}; DayColumn.defaultProps = { dragThroughEvents: true, timeslots: 2 }; var TimeGutter = /*#__PURE__*/ function (_Component) { _inheritsLoose(TimeGutter, _Component); function TimeGutter() { 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.renderSlot = function (value, idx) { if (idx !== 0) return null; var _this$props = _this.props, localizer = _this$props.localizer, getNow = _this$props.getNow; var isNow = _this.slotMetrics.dateIsInGroup(getNow(), idx); return React.createElement("span", { className: clsx('rbc-label', isNow && 'rbc-now') }, localizer.format(value, 'timeGutterFormat')); }; var _this$props2 = _this.props, min = _this$props2.min, max = _this$props2.max, timeslots = _this$props2.timeslots, step = _this$props2.step; _this.slotMetrics = getSlotMetrics$1({ min: min, max: max, timeslots: timeslots, step: step }); return _this; } var _proto = TimeGutter.prototype; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var min = nextProps.min, max = nextProps.max, timeslots = nextProps.timeslots, step = nextProps.step; this.slotMetrics = this.slotMetrics.update({ min: min, max: max, timeslots: timeslots, step: step }); }; _proto.render = function render() { var _this2 = this; var _this$props3 = this.props, resource = _this$props3.resource, components = _this$props3.components; return React.createElement("div", { className: "rbc-time-gutter rbc-time-column" }, this.slotMetrics.groups.map(function (grp, idx) { return React.createElement(TimeSlotGroup, { key: idx, group: grp, resource: resource, components: components, renderSlot: _this2.renderSlot }); })); }; return TimeGutter; }(Component); TimeGutter.propTypes = process.env.NODE_ENV !== "production" ? { min: PropTypes.instanceOf(Date).isRequired, max: PropTypes.instanceOf(Date).isRequired, timeslots: PropTypes.number.isRequired, step: PropTypes.number.isRequired, getNow: PropTypes.func.isRequired, components: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, resource: PropTypes.string } : {}; var ResourceHeader = function ResourceHeader(_ref) { var label = _ref.label; return React.createElement(React.Fragment, null, label); }; ResourceHeader.propTypes = process.env.NODE_ENV !== "production" ? { label: PropTypes.node, index: PropTypes.number, resource: PropTypes.object } : {}; var TimeGridHeader = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(TimeGridHeader, _React$Component); function TimeGridHeader() { 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.handleHeaderClick = function (date, view, e) { e.preventDefault(); notify(_this.props.onDrillDown, [date, view]); }; _this.renderRow = function (resource) { var _this$props = _this.props, events = _this$props.events, rtl = _this$props.rtl, selectable = _this$props.selectable, getNow = _this$props.getNow, range = _this$props.range, getters = _this$props.getters, localizer = _this$props.localizer, accessors = _this$props.accessors, components = _this$props.components; var resourceId = accessors.resourceId(resource); var eventsToDisplay = resource ? events.filter(function (event) { return accessors.resource(event) === resourceId; }) : events; return React.createElement(DateContentRow, { isAllDay: true, rtl: rtl, getNow: getNow, minRows: 2, range: range, events: eventsToDisplay, resourceId: resourceId, className: "rbc-allday-cell", selectable: selectable, selected: _this.props.selected, components: components, accessors: accessors, getters: getters, localizer: localizer, onSelect: _this.props.onSelectEvent, onDoubleClick: _this.props.onDoubleClickEvent, onSelectSlot: _this.props.onSelectSlot, longPressThreshold: _this.props.longPressThreshold }); }; return _this; } var _proto = TimeGridHeader.prototype; _proto.renderHeaderCells = function renderHeaderCells(range) { var _this2 = this; var _this$props2 = this.props, localizer = _this$props2.localizer, getDrilldownView = _this$props2.getDrilldownView, getNow = _this$props2.getNow, dayProp = _this$props2.getters.dayProp, _this$props2$componen = _this$props2.components.header, HeaderComponent = _this$props2$componen === void 0 ? Header : _this$props2$componen; var today = getNow(); return range.map(function (date, i) { var drilldownView = getDrilldownView(date); var label = localizer.format(date, 'dayFormat'); var _dayProp = dayProp(date), className = _dayProp.className, style = _dayProp.style; var header = React.createElement(HeaderComponent, { date: date, label: label, localizer: localizer }); return React.createElement("div", { key: i, style: style, className: clsx('rbc-header', className, eq(date, today, 'day') && 'rbc-today') }, drilldownView ? React.createElement("a", { href: "#", onClick: function onClick(e) { return _this2.handleHeaderClick(date, drilldownView, e); } }, header) : React.createElement("span", null, header)); }); }; _proto.render = function render() { var _this3 = this; var _this$props3 = this.props, width = _this$props3.width, rtl = _this$props3.rtl, resources = _this$props3.resources, range = _this$props3.range, events = _this$props3.events, getNow = _this$props3.getNow, accessors = _this$props3.accessors, selectable = _this$props3.selectable, components = _this$props3.components, getters = _this$props3.getters, scrollRef = _this$props3.scrollRef, localizer = _this$props3.localizer, isOverflowing = _this$props3.isOverflowing, _this$props3$componen = _this$props3.components, TimeGutterHeader = _this$props3$componen.timeGutterHeader, _this$props3$componen2 = _this$props3$componen.resourceHeader, ResourceHeaderComponent = _this$props3$componen2 === void 0 ? ResourceHeader : _this$props3$componen2; var style = {}; if (isOverflowing) { style[rtl ? 'marginLeft' : 'marginRight'] = scrollbarSize() + "px"; } var groupedEvents = resources.groupEvents(events); return React.createElement("div", { style: style, ref: scrollRef, className: clsx('rbc-time-header', isOverflowing && 'rbc-overflowing') }, React.createElement("div", { className: "rbc-label rbc-time-header-gutter", style: { width: width, minWidth: width, maxWidth: width } }, TimeGutterHeader && React.createElement(TimeGutterHeader, null)), resources.map(function (_ref, idx) { var id = _ref[0], resource = _ref[1]; return React.createElement("div", { className: "rbc-time-header-content", key: id || idx }, resource && React.createElement("div", { className: "rbc-row rbc-row-resource", key: "resource_" + idx }, React.createElement("div", { className: "rbc-header" }, React.createElement(ResourceHeaderComponent, { index: idx, label: accessors.resourceTitle(resource), resource: resource }))), React.createElement("div", { className: "rbc-row rbc-time-header-cell" + (range.length <= 1 ? ' rbc-time-header-cell-single-day' : '') }, _this3.renderHeaderCells(range)), React.createElement(DateContentRow, { isAllDay: true, rtl: rtl, getNow: getNow, minRows: 2, range: range, events: groupedEvents.get(id) || [], resourceId: resource && id, className: "rbc-allday-cell", selectable: selectable, selected: _this3.props.selected, components: components, accessors: accessors, getters: getters, localizer: localizer, onSelect: _this3.props.onSelectEvent, onDoubleClick: _this3.props.onDoubleClickEvent, onSelectSlot: _this3.props.onSelectSlot, longPressThreshold: _this3.props.longPressThreshold })); })); }; return TimeGridHeader; }(React.Component); TimeGridHeader.propTypes = process.env.NODE_ENV !== "production" ? { range: PropTypes.array.isRequired, events: PropTypes.array.isRequired, resources: PropTypes.object, getNow: PropTypes.func.isRequired, isOverflowing: PropTypes.bool, rtl: PropTypes.bool, width: PropTypes.number, localizer: PropTypes.object.isRequired, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), longPressThreshold: PropTypes.number, onSelectSlot: PropTypes.func, onSelectEvent: PropTypes.func, onDoubleClickEvent: PropTypes.func, onDrillDown: PropTypes.func, getDrilldownView: PropTypes.func.isRequired, scrollRef: PropTypes.any } : {}; var NONE = {}; function Resources(resources, accessors) { return { map: function map(fn) { if (!resources) return [fn([NONE, null], 0)]; return resources.map(function (resource, idx) { return fn([accessors.resourceId(resource), resource], idx); }); }, groupEvents: function groupEvents(events) { var eventsByResource = new Map(); if (!resources) { // Return all events if resources are not provided eventsByResource.set(NONE, events); return eventsByResource; } events.forEach(function (event) { var id = accessors.resource(event) || NONE; var resourceEvents = eventsByResource.get(id) || []; resourceEvents.push(event); eventsByResource.set(id, resourceEvents); }); return eventsByResource; } }; } var TimeGrid = /*#__PURE__*/ function (_Component) { _inheritsLoose(TimeGrid, _Component); function TimeGrid(props) { var _this; _this = _Component.call(this, props) || this; _this.handleScroll = function (e) { if (_this.scrollRef.current) { _this.scrollRef.current.scrollLeft = e.target.scrollLeft; } }; _this.handleResize = function () { cancel(_this.rafHandle); _this.rafHandle = request(_this.checkOverflow); }; _this.gutterRef = function (ref) { _this.gutter = ref && findDOMNode(ref); }; _this.handleSelectAlldayEvent = function () { //cancel any pending selections so only the event click goes through. _this.clearSelection(); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } notify(_this.props.onSelectEvent, args); }; _this.handleSelectAllDaySlot = function (slots, slotInfo) { var onSelectSlot = _this.props.onSelectSlot; notify(onSelectSlot, { slots: slots, start: slots[0], end: slots[slots.length - 1], action: slotInfo.action }); }; _this.checkOverflow = function () { if (_this._updatingOverflow) return; var content = _this.contentRef.current; var isOverflowing = content.scrollHeight > content.clientHeight; if (_this.state.isOverflowing !== isOverflowing) { _this._updatingOverflow = true; _this.setState({ isOverflowing: isOverflowing }, function () { _this._updatingOverflow = false; }); } }; _this.memoizedResources = memoize(function (resources, accessors) { return Resources(resources, accessors); }); _this.state = { gutterWidth: undefined, isOverflowing: null }; _this.scrollRef = React.createRef(); _this.contentRef = React.createRef(); return _this; } var _proto = TimeGrid.prototype; _proto.componentWillMount = function componentWillMount() { this.calculateScroll(); }; _proto.componentDidMount = function componentDidMount() { this.checkOverflow(); if (this.props.width == null) { this.measureGutter(); } this.applyScroll(); window.addEventListener('resize', this.handleResize); }; _proto.componentWillUnmount = function componentWillUnmount() { window.removeEventListener('resize', this.handleResize); cancel(this.rafHandle); if (this.measureGutterAnimationFrameRequest) { window.cancelAnimationFrame(this.measureGutterAnimationFrameRequest); } }; _proto.componentDidUpdate = function componentDidUpdate() { if (this.props.width == null) { this.measureGutter(); } this.applyScroll(); //this.checkOverflow() }; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var _this$props = this.props, range = _this$props.range, scrollToTime = _this$props.scrollToTime; // When paginating, reset scroll if (!eq(nextProps.range[0], range[0], 'minute') || !eq(nextProps.scrollToTime, scrollToTime, 'minute')) { this.calculateScroll(nextProps); } }; _proto.renderEvents = function renderEvents(range, events, now) { var _this2 = this; var _this$props2 = this.props, min = _this$props2.min, max = _this$props2.max, components = _this$props2.components, accessors = _this$props2.accessors, localizer = _this$props2.localizer; var resources = this.memoizedResources(this.props.resources, accessors); var groupedEvents = resources.groupEvents(events); return resources.map(function (_ref, i) { var id = _ref[0], resource = _ref[1]; return range.map(function (date, jj) { var daysEvents = (groupedEvents.get(id) || []).filter(function (event) { return inRange$1(date, accessors.start(event), accessors.end(event), 'day'); }); return React.createElement(DayColumn, _extends({}, _this2.props, { localizer: localizer, min: merge(date, min), max: merge(date, max), resource: resource && id, components: components, isNow: eq(date, now, 'day'), key: i + '-' + jj, date: date, events: daysEvents })); }); }); }; _proto.render = function render() { var _this$props3 = this.props, events = _this$props3.events, range = _this$props3.range, width = _this$props3.width, rtl = _this$props3.rtl, selected = _this$props3.selected, getNow = _this$props3.getNow, resources = _this$props3.resources, components = _this$props3.components, accessors = _this$props3.accessors, getters = _this$props3.getters, localizer = _this$props3.localizer, min = _this$props3.min, max = _this$props3.max, showMultiDayTimes = _this$props3.showMultiDayTimes, longPressThreshold = _this$props3.longPressThreshold; width = width || this.state.gutterWidth; var start = range[0], end = range[range.length - 1]; this.slots = range.length; var allDayEvents = [], rangeEvents = []; events.forEach(function (event) { if (inRange(event, start, end, accessors)) { var eStart = accessors.start(event), eEnd = accessors.end(event); if (accessors.allDay(event) || isJustDate(eStart) && isJustDate(eEnd) || !showMultiDayTimes && !eq(eStart, eEnd, 'day')) { allDayEvents.push(event); } else { rangeEvents.push(event); } } }); allDayEvents.sort(function (a, b) { return sortEvents(a, b, accessors); }); return React.createElement("div", { className: clsx('rbc-time-view', resources && 'rbc-time-view-resources') }, React.createElement(TimeGridHeader, { range: range, events: allDayEvents, width: width, rtl: rtl, getNow: getNow, localizer: localizer, selected: selected, resources: this.memoizedResources(resources, accessors), selectable: this.props.selectable, accessors: accessors, getters: getters, components: components, scrollRef: this.scrollRef, isOverflowing: this.state.isOverflowing, longPressThreshold: longPressThreshold, onSelectSlot: this.handleSelectAllDaySlot, onSelectEvent: this.handleSelectAlldayEvent, onDoubleClickEvent: this.props.onDoubleClickEvent, onDrillDown: this.props.onDrillDown, getDrilldownView: this.props.getDrilldownView }), React.createElement("div", { ref: this.contentRef, className: "rbc-time-content", onScroll: this.handleScroll }, React.createElement(TimeGutter, { date: start, ref: this.gutterRef, localizer: localizer, min: merge(start, min), max: merge(start, max), step: this.props.step, getNow: this.props.getNow, timeslots: this.props.timeslots, components: components, className: "rbc-time-gutter" }), this.renderEvents(range, rangeEvents, getNow()))); }; _proto.clearSelection = function clearSelection() { clearTimeout(this._selectTimer); this._pendingSelection = []; }; _proto.measureGutter = function measureGutter() { var _this3 = this; if (this.measureGutterAnimationFrameRequest) { window.cancelAnimationFrame(this.measureGutterAnimationFrameRequest); } this.measureGutterAnimationFrameRequest = window.requestAnimationFrame(function () { var width = getWidth(_this3.gutter); if (width && _this3.state.gutterWidth !== width) { _this3.setState({ gutterWidth: width }); } }); }; _proto.applyScroll = function applyScroll() { if (this._scrollRatio) { var content = this.contentRef.current; content.scrollTop = content.scrollHeight * this._scrollRatio; // Only do this once this._scrollRatio = null; } }; _proto.calculateScroll = function calculateScroll(props) { if (props === void 0) { props = this.props; } var _props = props, min = _props.min, max = _props.max, scrollToTime = _props.scrollToTime; var diffMillis = scrollToTime - startOf(scrollToTime, 'day'); var totalMillis = diff(max, min); this._scrollRatio = diffMillis / totalMillis; }; return TimeGrid; }(Component); TimeGrid.propTypes = process.env.NODE_ENV !== "production" ? { events: PropTypes.array.isRequired, resources: PropTypes.array, step: PropTypes.number, timeslots: PropTypes.number, range: PropTypes.arrayOf(PropTypes.instanceOf(Date)), min: PropTypes.instanceOf(Date), max: PropTypes.instanceOf(Date), getNow: PropTypes.func.isRequired, scrollToTime: PropTypes.instanceOf(Date), showMultiDayTimes: PropTypes.bool, rtl: PropTypes.bool, width: PropTypes.number, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), longPressThreshold: PropTypes.number, onNavigate: PropTypes.func, onSelectSlot: PropTypes.func, onSelectEnd: PropTypes.func, onSelectStart: PropTypes.func, onSelectEvent: PropTypes.func, onDoubleClickEvent: PropTypes.func, onDrillDown: PropTypes.func, getDrilldownView: PropTypes.func.isRequired } : {}; TimeGrid.defaultProps = { step: 30, timeslots: 2, min: startOf(new Date(), 'day'), max: endOf(new Date(), 'day'), scrollToTime: startOf(new Date(), 'day') }; var Day = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Day, _React$Component); function Day() { return _React$Component.apply(this, arguments) || this; } var _proto = Day.prototype; _proto.render = function render() { var _this$props = this.props, date = _this$props.date, props = _objectWithoutPropertiesLoose(_this$props, ["date"]); var range = Day.range(date); return React.createElement(TimeGrid, _extends({}, props, { range: range, eventOffset: 10 })); }; return Day; }(React.Component); Day.propTypes = process.env.NODE_ENV !== "production" ? { date: PropTypes.instanceOf(Date).isRequired } : {}; Day.range = function (date) { return [startOf(date, 'day')]; }; Day.navigate = function (date, action) { switch (action) { case navigate.PREVIOUS: return add(date, -1, 'day'); case navigate.NEXT: return add(date, 1, 'day'); default: return date; } }; Day.title = function (date, _ref) { var localizer = _ref.localizer; return localizer.format(date, 'dayHeaderFormat'); }; var Week = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Week, _React$Component); function Week() { return _React$Component.apply(this, arguments) || this; } var _proto = Week.prototype; _proto.render = function render() { var _this$props = this.props, date = _this$props.date, props = _objectWithoutPropertiesLoose(_this$props, ["date"]); var range = Week.range(date, this.props); return React.createElement(TimeGrid, _extends({}, props, { range: range, eventOffset: 15 })); }; return Week; }(React.Component); Week.propTypes = process.env.NODE_ENV !== "production" ? { date: PropTypes.instanceOf(Date).isRequired } : {}; Week.defaultProps = TimeGrid.defaultProps; Week.navigate = function (date, action) { switch (action) { case navigate.PREVIOUS: return add(date, -1, 'week'); case navigate.NEXT: return add(date, 1, 'week'); default: return date; } }; Week.range = function (date, _ref) { var localizer = _ref.localizer; var firstOfWeek = localizer.startOfWeek(); var start = startOf(date, 'week', firstOfWeek); var end = endOf(date, 'week', firstOfWeek); return range(start, end); }; Week.title = function (date, _ref2) { var localizer = _ref2.localizer; var _Week$range = Week.range(date, { localizer: localizer }), start = _Week$range[0], rest = _Week$range.slice(1); return localizer.format({ start: start, end: rest.pop() }, 'dayRangeHeaderFormat'); }; function workWeekRange(date, options) { return Week.range(date, options).filter(function (d) { return [6, 0].indexOf(d.getDay()) === -1; }); } var WorkWeek = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(WorkWeek, _React$Component); function WorkWeek() { return _React$Component.apply(this, arguments) || this; } var _proto = WorkWeek.prototype; _proto.render = function render() { var _this$props = this.props, date = _this$props.date, props = _objectWithoutPropertiesLoose(_this$props, ["date"]); var range = workWeekRange(date, this.props); return React.createElement(TimeGrid, _extends({}, props, { range: range, eventOffset: 15 })); }; return WorkWeek; }(React.Component); WorkWeek.propTypes = process.env.NODE_ENV !== "production" ? { date: PropTypes.instanceOf(Date).isRequired } : {}; WorkWeek.defaultProps = TimeGrid.defaultProps; WorkWeek.range = workWeekRange; WorkWeek.navigate = Week.navigate; WorkWeek.title = function (date, _ref) { var localizer = _ref.localizer; var _workWeekRange = workWeekRange(date, { localizer: localizer }), start = _workWeekRange[0], rest = _workWeekRange.slice(1); return localizer.format({ start: start, end: rest.pop() }, 'dayRangeHeaderFormat'); }; var Agenda = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Agenda, _React$Component); function Agenda(props) { var _this; _this = _React$Component.call(this, props) || this; _this.renderDay = function (day, events, dayKey) { var _this$props = _this.props, selected = _this$props.selected, getters = _this$props.getters, accessors = _this$props.accessors, localizer = _this$props.localizer, _this$props$component = _this$props.components, Event = _this$props$component.event, AgendaDate = _this$props$component.date; events = events.filter(function (e) { return inRange(e, startOf(day, 'day'), endOf(day, 'day'), accessors); }); return events.map(function (event, idx) { var title = accessors.title(event); var end = accessors.end(event); var start = accessors.start(event); var userProps = getters.eventProp(event, start, end, isSelected(event, selected)); var dateLabel = idx === 0 && localizer.format(day, 'agendaDateFormat'); var first = idx === 0 ? React.createElement("td", { rowSpan: events.length, className: "rbc-agenda-date-cell" }, AgendaDate ? React.createElement(AgendaDate, { day: day, label: dateLabel }) : dateLabel) : false; return React.createElement("tr", { key: dayKey + '_' + idx, className: userProps.className, style: userProps.style }, first, React.createElement("td", { className: "rbc-agenda-time-cell" }, _this.timeRangeLabel(day, event)), React.createElement("td", { className: "rbc-agenda-event-cell" }, Event ? React.createElement(Event, { event: event, title: title }) : title)); }, []); }; _this.timeRangeLabel = function (day, event) { var _this$props2 = _this.props, accessors = _this$props2.accessors, localizer = _this$props2.localizer, components = _this$props2.components; var labelClass = '', TimeComponent = components.time, label = localizer.messages.allDay; var end = accessors.end(event); var start = accessors.start(event); if (!accessors.allDay(event)) { if (eq(start, end)) { label = localizer.format(start, 'agendaTimeFormat'); } else if (eq(start, end, 'day')) { label = localizer.format({ start: start, end: end }, 'agendaTimeRangeFormat'); } else if (eq(day, start, 'day')) { label = localizer.format(start, 'agendaTimeFormat'); } else if (eq(day, end, 'day')) { label = localizer.format(end, 'agendaTimeFormat'); } } if (gt(day, start, 'day')) labelClass = 'rbc-continues-prior'; if (lt(day, end, 'day')) labelClass += ' rbc-continues-after'; return React.createElement("span", { className: labelClass.trim() }, TimeComponent ? React.createElement(TimeComponent, { event: event, day: day, label: label }) : label); }; _this._adjustHeader = function () { if (!_this.tbodyRef.current) return; var header = _this.headerRef.current; var firstRow = _this.tbodyRef.current.firstChild; if (!firstRow) return; var isOverflowing = _this.contentRef.current.scrollHeight > _this.contentRef.current.clientHeight; var widths = _this._widths || []; _this._widths = [getWidth(firstRow.children[0]), getWidth(firstRow.children[1])]; if (widths[0] !== _this._widths[0] || widths[1] !== _this._widths[1]) { _this.dateColRef.current.style.width = _this._widths[0] + 'px'; _this.timeColRef.current.style.width = _this._widths[1] + 'px'; } if (isOverflowing) { addClass(header, 'rbc-header-overflowing'); header.style.marginRight = scrollbarSize() + 'px'; } else { removeClass(header, 'rbc-header-overflowing'); } }; _this.headerRef = React.createRef(); _this.dateColRef = React.createRef(); _this.timeColRef = React.createRef(); _this.contentRef = React.createRef(); _this.tbodyRef = React.createRef(); return _this; } var _proto = Agenda.prototype; _proto.componentDidMount = function componentDidMount() { this._adjustHeader(); }; _proto.componentDidUpdate = function componentDidUpdate() { this._adjustHeader(); }; _proto.render = function render() { var _this2 = this; var _this$props3 = this.props, length = _this$props3.length, date = _this$props3.date, events = _this$props3.events, accessors = _this$props3.accessors, localizer = _this$props3.localizer; var messages = localizer.messages; var end = add(date, length, 'day'); var range$1 = range(date, end, 'day'); events = events.filter(function (event) { return inRange(event, date, end, accessors); }); events.sort(function (a, b) { return +accessors.start(a) - +accessors.start(b); }); return React.createElement("div", { className: "rbc-agenda-view" }, events.length !== 0 ? React.createElement(React.Fragment, null, React.createElement("table", { ref: this.headerRef, className: "rbc-agenda-table" }, React.createElement("thead", null, React.createElement("tr", null, React.createElement("th", { className: "rbc-header", ref: this.dateColRef }, messages.date), React.createElement("th", { className: "rbc-header", ref: this.timeColRef }, messages.time), React.createElement("th", { className: "rbc-header" }, messages.event)))), React.createElement("div", { className: "rbc-agenda-content", ref: this.contentRef }, React.createElement("table", { className: "rbc-agenda-table" }, React.createElement("tbody", { ref: this.tbodyRef }, range$1.map(function (day, idx) { return _this2.renderDay(day, events, idx); }))))) : React.createElement("span", { className: "rbc-agenda-empty" }, messages.noEventsInRange)); }; return Agenda; }(React.Component); Agenda.propTypes = process.env.NODE_ENV !== "production" ? { events: PropTypes.array, date: PropTypes.instanceOf(Date), length: PropTypes.number.isRequired, selected: PropTypes.object, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired } : {}; Agenda.defaultProps = { length: 30 }; Agenda.range = function (start, _ref) { var _ref$length = _ref.length, length = _ref$length === void 0 ? Agenda.defaultProps.length : _ref$length; var end = add(start, length, 'day'); return { start: start, end: end }; }; Agenda.navigate = function (date, action, _ref2) { var _ref2$length = _ref2.length, length = _ref2$length === void 0 ? Agenda.defaultProps.length : _ref2$length; switch (action) { case navigate.PREVIOUS: return add(date, -length, 'day'); case navigate.NEXT: return add(date, length, 'day'); default: return date; } }; Agenda.title = function (start, _ref3) { var _ref3$length = _ref3.length, length = _ref3$length === void 0 ? Agenda.defaultProps.length : _ref3$length, localizer = _ref3.localizer; var end = add(start, length, 'day'); return localizer.format({ start: start, end: end }, 'agendaHeaderFormat'); }; var _VIEWS; var VIEWS = (_VIEWS = {}, _VIEWS[views.MONTH] = MonthView, _VIEWS[views.WEEK] = Week, _VIEWS[views.WORK_WEEK] = WorkWeek, _VIEWS[views.DAY] = Day, _VIEWS[views.AGENDA] = Agenda, _VIEWS); function moveDate(View, _ref) { var action = _ref.action, date = _ref.date, today = _ref.today, props = _objectWithoutPropertiesLoose(_ref, ["action", "date", "today"]); View = typeof View === 'string' ? VIEWS[View] : View; switch (action) { case navigate.TODAY: date = today || new Date(); break; case navigate.DATE: break; default: !(View && typeof View.navigate === 'function') ? process.env.NODE_ENV !== "production" ? invariant(false, 'Calendar View components must implement a static `.navigate(date, action)` method.s') : invariant(false) : void 0; date = View.navigate(date, action, props); } return date; } var Toolbar = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Toolbar, _React$Component); function Toolbar() { 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.navigate = function (action) { _this.props.onNavigate(action); }; _this.view = function (view) { _this.props.onView(view); }; return _this; } var _proto = Toolbar.prototype; _proto.render = function render() { var _this$props = this.props, messages = _this$props.localizer.messages, label = _this$props.label; return React.createElement("div", { className: "rbc-toolbar" }, React.createElement("span", { className: "rbc-btn-group" }, React.createElement("button", { type: "button", onClick: this.navigate.bind(null, navigate.TODAY) }, messages.today), React.createElement("button", { type: "button", onClick: this.navigate.bind(null, navigate.PREVIOUS) }, messages.previous), React.createElement("button", { type: "button", onClick: this.navigate.bind(null, navigate.NEXT) }, messages.next)), React.createElement("span", { className: "rbc-toolbar-label" }, label), React.createElement("span", { className: "rbc-btn-group" }, this.viewNamesGroup(messages))); }; _proto.viewNamesGroup = function viewNamesGroup(messages) { var _this2 = this; var viewNames = this.props.views; var view = this.props.view; if (viewNames.length > 1) { return viewNames.map(function (name) { return React.createElement("button", { type: "button", key: name, className: clsx({ 'rbc-active': view === name }), onClick: _this2.view.bind(null, name) }, messages[name]); }); } }; return Toolbar; }(React.Component); Toolbar.propTypes = process.env.NODE_ENV !== "production" ? { view: PropTypes.string.isRequired, views: PropTypes.arrayOf(PropTypes.string).isRequired, label: PropTypes.node.isRequired, localizer: PropTypes.object, onNavigate: PropTypes.func.isRequired, onView: PropTypes.func.isRequired } : {}; /** * Retrieve via an accessor-like property * * accessor(obj, 'name') // => retrieves obj['name'] * accessor(data, func) // => retrieves func(data) * ... otherwise null */ function accessor$1(data, field) { var value = null; if (typeof field === 'function') value = field(data);else if (typeof field === 'string' && typeof data === 'object' && data != null && field in data) value = data[field]; return value; } var wrapAccessor = function wrapAccessor(acc) { return function (data) { return accessor$1(data, acc); }; }; function viewNames$1(_views) { return !Array.isArray(_views) ? Object.keys(_views) : _views; } function isValidView(view, _ref) { var _views = _ref.views; var names = viewNames$1(_views); return names.indexOf(view) !== -1; } /** * react-big-calendar is a full featured Calendar component for managing events and dates. It uses * modern `flexbox` for layout, making it super responsive and performant. Leaving most of the layout heavy lifting * to the browser. __note:__ The default styles use `height: 100%` which means your container must set an explicit * height (feel free to adjust the styles to suit your specific needs). * * Big Calendar is unopiniated about editing and moving events, preferring to let you implement it in a way that makes * the most sense to your app. It also tries not to be prescriptive about your event data structures, just tell it * how to find the start and end datetimes and you can pass it whatever you want. * * One thing to note is that, `react-big-calendar` treats event start/end dates as an _exclusive_ range. * which means that the event spans up to, but not including, the end date. In the case * of displaying events on whole days, end dates are rounded _up_ to the next day. So an * event ending on `Apr 8th 12:00:00 am` will not appear on the 8th, whereas one ending * on `Apr 8th 12:01:00 am` will. If you want _inclusive_ ranges consider providing a * function `endAccessor` that returns the end date + 1 day for those events that end at midnight. */ var Calendar = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Calendar, _React$Component); function Calendar() { 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.getViews = function () { var views = _this.props.views; if (Array.isArray(views)) { return transform(views, function (obj, name) { return obj[name] = VIEWS[name]; }, {}); } if (typeof views === 'object') { return mapValues(views, function (value, key) { if (value === true) { return VIEWS[key]; } return value; }); } return VIEWS; }; _this.getView = function () { var views = _this.getViews(); return views[_this.props.view]; }; _this.getDrilldownView = function (date) { var _this$props = _this.props, view = _this$props.view, drilldownView = _this$props.drilldownView, getDrilldownView = _this$props.getDrilldownView; if (!getDrilldownView) return drilldownView; return getDrilldownView(date, view, Object.keys(_this.getViews())); }; _this.handleRangeChange = function (date, viewComponent, view) { var _this$props2 = _this.props, onRangeChange = _this$props2.onRangeChange, localizer = _this$props2.localizer; if (onRangeChange) { if (viewComponent.range) { onRangeChange(viewComponent.range(date, { localizer: localizer }), view); } else { process.env.NODE_ENV !== "production" ? warning(true, 'onRangeChange prop not supported for this view') : void 0; } } }; _this.handleNavigate = function (action, newDate) { var _this$props3 = _this.props, view = _this$props3.view, date = _this$props3.date, getNow = _this$props3.getNow, onNavigate = _this$props3.onNavigate, props = _objectWithoutPropertiesLoose(_this$props3, ["view", "date", "getNow", "onNavigate"]); var ViewComponent = _this.getView(); var today = getNow(); date = moveDate(ViewComponent, _extends({}, props, { action: action, date: newDate || date || today, today: today })); onNavigate(date, view, action); _this.handleRangeChange(date, ViewComponent); }; _this.handleViewChange = function (view) { if (view !== _this.props.view && isValidView(view, _this.props)) { _this.props.onView(view); } var views = _this.getViews(); _this.handleRangeChange(_this.props.date || _this.props.getNow(), views[view], view); }; _this.handleSelectEvent = function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } notify(_this.props.onSelectEvent, args); }; _this.handleDoubleClickEvent = function () { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } notify(_this.props.onDoubleClickEvent, args); }; _this.handleSelectSlot = function (slotInfo) { notify(_this.props.onSelectSlot, slotInfo); }; _this.handleDrillDown = function (date, view) { var onDrillDown = _this.props.onDrillDown; if (onDrillDown) { onDrillDown(date, view, _this.drilldownView); return; } if (view) _this.handleViewChange(view); _this.handleNavigate(navigate.DATE, date); }; _this.state = { context: _this.getContext(_this.props) }; return _this; } var _proto = Calendar.prototype; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { this.setState({ context: this.getContext(nextProps) }); }; _proto.getContext = function getContext(_ref2) { var startAccessor = _ref2.startAccessor, endAccessor = _ref2.endAccessor, allDayAccessor = _ref2.allDayAccessor, tooltipAccessor = _ref2.tooltipAccessor, titleAccessor = _ref2.titleAccessor, resourceAccessor = _ref2.resourceAccessor, resourceIdAccessor = _ref2.resourceIdAccessor, resourceTitleAccessor = _ref2.resourceTitleAccessor, eventPropGetter = _ref2.eventPropGetter, slotPropGetter = _ref2.slotPropGetter, dayPropGetter = _ref2.dayPropGetter, view = _ref2.view, views = _ref2.views, localizer = _ref2.localizer, culture = _ref2.culture, _ref2$messages = _ref2.messages, messages$1 = _ref2$messages === void 0 ? {} : _ref2$messages, _ref2$components = _ref2.components, components = _ref2$components === void 0 ? {} : _ref2$components, _ref2$formats = _ref2.formats, formats = _ref2$formats === void 0 ? {} : _ref2$formats; var names = viewNames$1(views); var msgs = messages(messages$1); return { viewNames: names, localizer: mergeWithDefaults(localizer, culture, formats, msgs), getters: { eventProp: function eventProp() { return eventPropGetter && eventPropGetter.apply(void 0, arguments) || {}; }, slotProp: function slotProp() { return slotPropGetter && slotPropGetter.apply(void 0, arguments) || {}; }, dayProp: function dayProp() { return dayPropGetter && dayPropGetter.apply(void 0, arguments) || {}; } }, components: defaults(components[view] || {}, omit(components, names), { eventWrapper: NoopWrapper, eventContainerWrapper: NoopWrapper, dateCellWrapper: NoopWrapper, weekWrapper: NoopWrapper, timeSlotWrapper: NoopWrapper }), accessors: { start: wrapAccessor(startAccessor), end: wrapAccessor(endAccessor), allDay: wrapAccessor(allDayAccessor), tooltip: wrapAccessor(tooltipAccessor), title: wrapAccessor(titleAccessor), resource: wrapAccessor(resourceAccessor), resourceId: wrapAccessor(resourceIdAccessor), resourceTitle: wrapAccessor(resourceTitleAccessor) } }; }; _proto.render = function render() { var _this$props4 = this.props, view = _this$props4.view, toolbar = _this$props4.toolbar, events = _this$props4.events, style = _this$props4.style, className = _this$props4.className, elementProps = _this$props4.elementProps, current = _this$props4.date, getNow = _this$props4.getNow, length = _this$props4.length, showMultiDayTimes = _this$props4.showMultiDayTimes, onShowMore = _this$props4.onShowMore, _0 = _this$props4.components, _1 = _this$props4.formats, _2 = _this$props4.messages, _3 = _this$props4.culture, props = _objectWithoutPropertiesLoose(_this$props4, ["view", "toolbar", "events", "style", "className", "elementProps", "date", "getNow", "length", "showMultiDayTimes", "onShowMore", "components", "formats", "messages", "culture"]); current = current || getNow(); var View = this.getView(); var _this$state$context = this.state.context, accessors = _this$state$context.accessors, components = _this$state$context.components, getters = _this$state$context.getters, localizer = _this$state$context.localizer, viewNames = _this$state$context.viewNames; var CalToolbar = components.toolbar || Toolbar; var label = View.title(current, { localizer: localizer, length: length }); return React.createElement("div", _extends({}, elementProps, { className: clsx(className, 'rbc-calendar', props.rtl && 'rbc-rtl'), style: style }), toolbar && React.createElement(CalToolbar, { date: current, view: view, views: viewNames, label: label, onView: this.handleViewChange, onNavigate: this.handleNavigate, localizer: localizer }), React.createElement(View, _extends({}, props, { events: events, date: current, getNow: getNow, length: length, localizer: localizer, getters: getters, components: components, accessors: accessors, showMultiDayTimes: showMultiDayTimes, getDrilldownView: this.getDrilldownView, onNavigate: this.handleNavigate, onDrillDown: this.handleDrillDown, onSelectEvent: this.handleSelectEvent, onDoubleClickEvent: this.handleDoubleClickEvent, onSelectSlot: this.handleSelectSlot, onShowMore: onShowMore }))); } /** * * @param date * @param viewComponent * @param {'month'|'week'|'work_week'|'day'|'agenda'} [view] - optional * parameter. It appears when range change on view changing. It could be handy * when you need to have both: range and view type at once, i.e. for manage rbc * state via url */ ; return Calendar; }(React.Component); Calendar.defaultProps = { elementProps: {}, popup: false, toolbar: true, view: views.MONTH, views: [views.MONTH, views.WEEK, views.DAY, views.AGENDA], step: 30, length: 30, drilldownView: views.DAY, titleAccessor: 'title', tooltipAccessor: 'title', allDayAccessor: 'allDay', startAccessor: 'start', endAccessor: 'end', resourceAccessor: 'resourceId', resourceIdAccessor: 'id', resourceTitleAccessor: 'title', longPressThreshold: 250, getNow: function getNow() { return new Date(); } }; Calendar.propTypes = process.env.NODE_ENV !== "production" ? { localizer: PropTypes.object.isRequired, /** * Props passed to main calendar `<div>`. * */ elementProps: PropTypes.object, /** * The current date value of the calendar. Determines the visible view range. * If `date` is omitted then the result of `getNow` is used; otherwise the * current date is used. * * @controllable onNavigate */ date: PropTypes.instanceOf(Date), /** * The current view of the calendar. * * @default 'month' * @controllable onView */ view: PropTypes.string, /** * The initial view set for the Calendar. * @type Calendar.Views ('month'|'week'|'work_week'|'day'|'agenda') * @default 'month' */ defaultView: PropTypes.string, /** * An array of event objects to display on the calendar. Events objects * can be any shape, as long as the Calendar knows how to retrieve the * following details of the event: * * - start time * - end time * - title * - whether its an "all day" event or not * - any resource the event may be related to * * Each of these properties can be customized or generated dynamically by * setting the various "accessor" props. Without any configuration the default * event should look like: * * ```js * Event { * title: string, * start: Date, * end: Date, * allDay?: boolean * resource?: any, * } * ``` */ events: PropTypes.arrayOf(PropTypes.object), /** * Accessor for the event title, used to display event information. Should * resolve to a `renderable` value. * * ```js * string | (event: Object) => string * ``` * * @type {(func|string)} */ titleAccessor: accessor, /** * Accessor for the event tooltip. Should * resolve to a `renderable` value. Removes the tooltip if null. * * ```js * string | (event: Object) => string * ``` * * @type {(func|string)} */ tooltipAccessor: accessor, /** * Determines whether the event should be considered an "all day" event and ignore time. * Must resolve to a `boolean` value. * * ```js * string | (event: Object) => boolean * ``` * * @type {(func|string)} */ allDayAccessor: accessor, /** * The start date/time of the event. Must resolve to a JavaScript `Date` object. * * ```js * string | (event: Object) => Date * ``` * * @type {(func|string)} */ startAccessor: accessor, /** * The end date/time of the event. Must resolve to a JavaScript `Date` object. * * ```js * string | (event: Object) => Date * ``` * * @type {(func|string)} */ endAccessor: accessor, /** * Returns the id of the `resource` that the event is a member of. This * id should match at least one resource in the `resources` array. * * ```js * string | (event: Object) => Date * ``` * * @type {(func|string)} */ resourceAccessor: accessor, /** * An array of resource objects that map events to a specific resource. * Resource objects, like events, can be any shape or have any properties, * but should be uniquly identifiable via the `resourceIdAccessor`, as * well as a "title" or name as provided by the `resourceTitleAccessor` prop. */ resources: PropTypes.arrayOf(PropTypes.object), /** * Provides a unique identifier for each resource in the `resources` array * * ```js * string | (resource: Object) => any * ``` * * @type {(func|string)} */ resourceIdAccessor: accessor, /** * Provides a human readable name for the resource object, used in headers. * * ```js * string | (resource: Object) => any * ``` * * @type {(func|string)} */ resourceTitleAccessor: accessor, /** * Determines the current date/time which is highlighted in the views. * * The value affects which day is shaded and which time is shown as * the current time. It also affects the date used by the Today button in * the toolbar. * * Providing a value here can be useful when you are implementing time zones * using the `startAccessor` and `endAccessor` properties. * * @type {func} * @default () => new Date() */ getNow: PropTypes.func, /** * Callback fired when the `date` value changes. * * @controllable date */ onNavigate: PropTypes.func, /** * Callback fired when the `view` value changes. * * @controllable view */ onView: PropTypes.func, /** * Callback fired when date header, or the truncated events links are clicked * */ onDrillDown: PropTypes.func, /** * * ```js * (dates: Date[] | { start: Date; end: Date }, view?: 'month'|'week'|'work_week'|'day'|'agenda') => void * ``` * * Callback fired when the visible date range changes. Returns an Array of dates * or an object with start and end dates for BUILTIN views. Optionally new `view` * will be returned when callback called after view change. * * Custom views may return something different. */ onRangeChange: PropTypes.func, /** * A callback fired when a date selection is made. Only fires when `selectable` is `true`. * * ```js * ( * slotInfo: { * start: Date, * end: Date, * slots: Array<Date>, * action: "select" | "click" | "doubleClick", * bounds: ?{ // For "select" action * x: number, * y: number, * top: number, * right: number, * left: number, * bottom: number, * }, * box: ?{ // For "click" or "doubleClick" actions * clientX: number, * clientY: number, * x: number, * y: number, * }, * } * ) => any * ``` */ onSelectSlot: PropTypes.func, /** * Callback fired when a calendar event is selected. * * ```js * (event: Object, e: SyntheticEvent) => any * ``` * * @controllable selected */ onSelectEvent: PropTypes.func, /** * Callback fired when a calendar event is clicked twice. * * ```js * (event: Object, e: SyntheticEvent) => void * ``` */ onDoubleClickEvent: PropTypes.func, /** * Callback fired when dragging a selection in the Time views. * * Returning `false` from the handler will prevent a selection. * * ```js * (range: { start: Date, end: Date }) => ?boolean * ``` */ onSelecting: PropTypes.func, /** * Callback fired when a +{count} more is clicked * * ```js * (events: Object, date: Date) => any * ``` */ onShowMore: PropTypes.func, /** * The selected event, if any. */ selected: PropTypes.object, /** * An array of built-in view names to allow the calendar to display. * accepts either an array of builtin view names, * * ```jsx * views={['month', 'day', 'agenda']} * ``` * or an object hash of the view name and the component (or boolean for builtin). * * ```jsx * views={{ * month: true, * week: false, * myweek: WorkWeekViewComponent, * }} * ``` * * Custom views can be any React component, that implements the following * interface: * * ```js * interface View { * static title(date: Date, { formats: DateFormat[], culture: string?, ...props }): string * static navigate(date: Date, action: 'PREV' | 'NEXT' | 'DATE'): Date * } * ``` * * @type Views ('month'|'week'|'work_week'|'day'|'agenda') * @View ['month', 'week', 'day', 'agenda'] */ views: views$1, /** * The string name of the destination view for drill-down actions, such * as clicking a date header, or the truncated events links. If * `getDrilldownView` is also specified it will be used instead. * * Set to `null` to disable drill-down actions. * * ```js * <Calendar * drilldownView="agenda" * /> * ``` */ drilldownView: PropTypes.string, /** * Functionally equivalent to `drilldownView`, but accepts a function * that can return a view name. It's useful for customizing the drill-down * actions depending on the target date and triggering view. * * Return `null` to disable drill-down actions. * * ```js * <Calendar * getDrilldownView={(targetDate, currentViewName, configuredViewNames) => * if (currentViewName === 'month' && configuredViewNames.includes('week')) * return 'week' * * return null; * }} * /> * ``` */ getDrilldownView: PropTypes.func, /** * Determines the end date from date prop in the agenda view * date prop + length (in number of days) = end date */ length: PropTypes.number, /** * Determines whether the toolbar is displayed */ toolbar: PropTypes.bool, /** * Show truncated events in an overlay when you click the "+_x_ more" link. */ popup: PropTypes.bool, /** * Distance in pixels, from the edges of the viewport, the "show more" overlay should be positioned. * * ```jsx * <Calendar popupOffset={30}/> * <Calendar popupOffset={{x: 30, y: 20}}/> * ``` */ popupOffset: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ x: PropTypes.number, y: PropTypes.number })]), /** * Allows mouse selection of ranges of dates/times. * * The 'ignoreEvents' option prevents selection code from running when a * drag begins over an event. Useful when you want custom event click or drag * logic */ selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), /** * Specifies the number of miliseconds the user must press and hold on the screen for a touch * to be considered a "long press." Long presses are used for time slot selection on touch * devices. * * @type {number} * @default 250 */ longPressThreshold: PropTypes.number, /** * Determines the selectable time increments in week and day views */ step: PropTypes.number, /** * The number of slots per "section" in the time grid views. Adjust with `step` * to change the default of 1 hour long groups, with 30 minute slots. */ timeslots: PropTypes.number, /** *Switch the calendar to a `right-to-left` read direction. */ rtl: PropTypes.bool, /** * Optionally provide a function that returns an object of className or style props * to be applied to the the event node. * * ```js * ( * event: Object, * start: Date, * end: Date, * isSelected: boolean * ) => { className?: string, style?: Object } * ``` */ eventPropGetter: PropTypes.func, /** * Optionally provide a function that returns an object of className or style props * to be applied to the the time-slot node. Caution! Styles that change layout or * position may break the calendar in unexpected ways. * * ```js * (date: Date, resourceId: (number|string)) => { className?: string, style?: Object } * ``` */ slotPropGetter: PropTypes.func, /** * Optionally provide a function that returns an object of className or style props * to be applied to the the day background. Caution! Styles that change layout or * position may break the calendar in unexpected ways. * * ```js * (date: Date) => { className?: string, style?: Object } * ``` */ dayPropGetter: PropTypes.func, /** * Support to show multi-day events with specific start and end times in the * main time grid (rather than in the all day header). * * **Note: This may cause calendars with several events to look very busy in * the week and day views.** */ showMultiDayTimes: PropTypes.bool, /** * Constrains the minimum _time_ of the Day and Week views. */ min: PropTypes.instanceOf(Date), /** * Constrains the maximum _time_ of the Day and Week views. */ max: PropTypes.instanceOf(Date), /** * Determines how far down the scroll pane is initially scrolled down. */ scrollToTime: PropTypes.instanceOf(Date), /** * Specify a specific culture code for the Calendar. * * **Note: it's generally better to handle this globally via your i18n library.** */ culture: PropTypes.string, /** * Localizer specific formats, tell the Calendar how to format and display dates. * * `format` types are dependent on the configured localizer; both Moment and Globalize * accept strings of tokens according to their own specification, such as: `'DD mm yyyy'`. * * ```jsx * let formats = { * dateFormat: 'dd', * * dayFormat: (date, , localizer) => * localizer.format(date, 'DDD', culture), * * dayRangeHeaderFormat: ({ start, end }, culture, localizer) => * localizer.format(start, { date: 'short' }, culture) + ' – ' + * localizer.format(end, { date: 'short' }, culture) * } * * <Calendar formats={formats} /> * ``` * * All localizers accept a function of * the form `(date: Date, culture: ?string, localizer: Localizer) -> string` */ formats: PropTypes.shape({ /** * Format for the day of the month heading in the Month view. * e.g. "01", "02", "03", etc */ dateFormat: dateFormat, /** * A day of the week format for Week and Day headings, * e.g. "Wed 01/04" * */ dayFormat: dateFormat, /** * Week day name format for the Month week day headings, * e.g: "Sun", "Mon", "Tue", etc * */ weekdayFormat: dateFormat, /** * The timestamp cell formats in Week and Time views, e.g. "4:00 AM" */ timeGutterFormat: dateFormat, /** * Toolbar header format for the Month view, e.g "2015 April" * */ monthHeaderFormat: dateFormat, /** * Toolbar header format for the Week views, e.g. "Mar 29 - Apr 04" */ dayRangeHeaderFormat: dateRangeFormat, /** * Toolbar header format for the Day view, e.g. "Wednesday Apr 01" */ dayHeaderFormat: dateFormat, /** * Toolbar header format for the Agenda view, e.g. "4/1/2015 – 5/1/2015" */ agendaHeaderFormat: dateRangeFormat, /** * A time range format for selecting time slots, e.g "8:00am – 2:00pm" */ selectRangeFormat: dateRangeFormat, agendaDateFormat: dateFormat, agendaTimeFormat: dateFormat, agendaTimeRangeFormat: dateRangeFormat, /** * Time range displayed on events. */ eventTimeRangeFormat: dateRangeFormat, /** * An optional event time range for events that continue onto another day */ eventTimeRangeStartFormat: dateFormat, /** * An optional event time range for events that continue from another day */ eventTimeRangeEndFormat: dateFormat }), /** * Customize how different sections of the calendar render by providing custom Components. * In particular the `Event` component can be specified for the entire calendar, or you can * provide an individual component for each view type. * * ```jsx * let components = { * event: MyEvent, // used by each view (Month, Day, Week) * eventWrapper: MyEventWrapper, * eventContainerWrapper: MyEventContainerWrapper, * dateCellWrapper: MyDateCellWrapper, * timeSlotWrapper: MyTimeSlotWrapper, * timeGutterHeader: MyTimeGutterWrapper, * toolbar: MyToolbar, * agenda: { * event: MyAgendaEvent // with the agenda view use a different component to render events * time: MyAgendaTime, * date: MyAgendaDate, * }, * day: { * header: MyDayHeader, * event: MyDayEvent, * }, * week: { * header: MyWeekHeader, * event: MyWeekEvent, * }, * month: { * header: MyMonthHeader, * dateHeader: MyMonthDateHeader, * event: MyMonthEvent, * } * } * <Calendar components={components} /> * ``` */ components: PropTypes.shape({ event: PropTypes.elementType, eventWrapper: PropTypes.elementType, eventContainerWrapper: PropTypes.elementType, dateCellWrapper: PropTypes.elementType, timeSlotWrapper: PropTypes.elementType, timeGutterHeader: PropTypes.elementType, resourceHeader: PropTypes.elementType, toolbar: PropTypes.elementType, agenda: PropTypes.shape({ date: PropTypes.elementType, time: PropTypes.elementType, event: PropTypes.elementType }), day: PropTypes.shape({ header: PropTypes.elementType, event: PropTypes.elementType }), week: PropTypes.shape({ header: PropTypes.elementType, event: PropTypes.elementType }), month: PropTypes.shape({ header: PropTypes.elementType, dateHeader: PropTypes.elementType, event: PropTypes.elementType }) }), /** * String messages used throughout the component, override to provide localizations */ messages: PropTypes.shape({ allDay: PropTypes.node, previous: PropTypes.node, next: PropTypes.node, today: PropTypes.node, month: PropTypes.node, week: PropTypes.node, day: PropTypes.node, agenda: PropTypes.node, date: PropTypes.node, time: PropTypes.node, event: PropTypes.node, noEventsInRange: PropTypes.node, showMore: PropTypes.func }) } : {}; var Calendar$1 = uncontrollable(Calendar, { view: 'onView', date: 'onNavigate', selected: 'onSelectEvent' }); var dateRangeFormat$1 = function dateRangeFormat(_ref, culture, local) { var start = _ref.start, end = _ref.end; return local.format(start, 'L', culture) + ' – ' + local.format(end, 'L', culture); }; var timeRangeFormat = function timeRangeFormat(_ref2, culture, local) { var start = _ref2.start, end = _ref2.end; return local.format(start, 'LT', culture) + ' – ' + local.format(end, 'LT', culture); }; var timeRangeStartFormat = function timeRangeStartFormat(_ref3, culture, local) { var start = _ref3.start; return local.format(start, 'LT', culture) + ' – '; }; var timeRangeEndFormat = function timeRangeEndFormat(_ref4, culture, local) { var end = _ref4.end; return ' – ' + local.format(end, 'LT', culture); }; var weekRangeFormat = function weekRangeFormat(_ref5, culture, local) { var start = _ref5.start, end = _ref5.end; return local.format(start, 'MMMM DD', culture) + ' – ' + local.format(end, eq(start, end, 'month') ? 'DD' : 'MMMM DD', culture); }; var formats = { dateFormat: 'DD', dayFormat: 'DD ddd', weekdayFormat: 'ddd', selectRangeFormat: timeRangeFormat, eventTimeRangeFormat: timeRangeFormat, eventTimeRangeStartFormat: timeRangeStartFormat, eventTimeRangeEndFormat: timeRangeEndFormat, timeGutterFormat: 'LT', monthHeaderFormat: 'MMMM YYYY', dayHeaderFormat: 'dddd MMM DD', dayRangeHeaderFormat: weekRangeFormat, agendaHeaderFormat: dateRangeFormat$1, agendaDateFormat: 'ddd MMM DD', agendaTimeFormat: 'LT', agendaTimeRangeFormat: timeRangeFormat }; function moment (moment) { var locale = function locale(m, c) { return c ? m.locale(c) : m; }; return new DateLocalizer({ formats: formats, firstOfWeek: function firstOfWeek(culture) { var data = culture ? moment.localeData(culture) : moment.localeData(); return data ? data.firstDayOfWeek() : 0; }, format: function format(value, _format, culture) { return locale(moment(value), culture).format(_format); } }); } var dateRangeFormat$2 = function dateRangeFormat(_ref, culture, local) { var start = _ref.start, end = _ref.end; return local.format(start, 'd', culture) + ' – ' + local.format(end, 'd', culture); }; var timeRangeFormat$1 = function timeRangeFormat(_ref2, culture, local) { var start = _ref2.start, end = _ref2.end; return local.format(start, 't', culture) + ' – ' + local.format(end, 't', culture); }; var timeRangeStartFormat$1 = function timeRangeStartFormat(_ref3, culture, local) { var start = _ref3.start; return local.format(start, 't', culture) + ' – '; }; var timeRangeEndFormat$1 = function timeRangeEndFormat(_ref4, culture, local) { var end = _ref4.end; return ' – ' + local.format(end, 't', culture); }; var weekRangeFormat$1 = function weekRangeFormat(_ref5, culture, local) { var start = _ref5.start, end = _ref5.end; return local.format(start, 'MMM dd', culture) + ' – ' + local.format(end, eq(start, end, 'month') ? 'dd' : 'MMM dd', culture); }; var formats$1 = { dateFormat: 'dd', dayFormat: 'ddd dd/MM', weekdayFormat: 'ddd', selectRangeFormat: timeRangeFormat$1, eventTimeRangeFormat: timeRangeFormat$1, eventTimeRangeStartFormat: timeRangeStartFormat$1, eventTimeRangeEndFormat: timeRangeEndFormat$1, timeGutterFormat: 't', monthHeaderFormat: 'Y', dayHeaderFormat: 'dddd MMM dd', dayRangeHeaderFormat: weekRangeFormat$1, agendaHeaderFormat: dateRangeFormat$2, agendaDateFormat: 'ddd MMM dd', agendaTimeFormat: 't', agendaTimeRangeFormat: timeRangeFormat$1 }; function oldGlobalize (globalize) { function getCulture(culture) { return culture ? globalize.findClosestCulture(culture) : globalize.culture(); } function firstOfWeek(culture) { culture = getCulture(culture); return culture && culture.calendar.firstDay || 0; } return new DateLocalizer({ firstOfWeek: firstOfWeek, formats: formats$1, format: function format(value, _format, culture) { return globalize.format(value, _format, culture); } }); } var dateRangeFormat$3 = function dateRangeFormat(_ref, culture, local) { var start = _ref.start, end = _ref.end; return local.format(start, { date: 'short' }, culture) + ' – ' + local.format(end, { date: 'short' }, culture); }; var timeRangeFormat$2 = function timeRangeFormat(_ref2, culture, local) { var start = _ref2.start, end = _ref2.end; return local.format(start, { time: 'short' }, culture) + ' – ' + local.format(end, { time: 'short' }, culture); }; var timeRangeStartFormat$2 = function timeRangeStartFormat(_ref3, culture, local) { var start = _ref3.start; return local.format(start, { time: 'short' }, culture) + ' – '; }; var timeRangeEndFormat$2 = function timeRangeEndFormat(_ref4, culture, local) { var end = _ref4.end; return ' – ' + local.format(end, { time: 'short' }, culture); }; var weekRangeFormat$2 = function weekRangeFormat(_ref5, culture, local) { var start = _ref5.start, end = _ref5.end; return local.format(start, 'MMM dd', culture) + ' – ' + local.format(end, eq(start, end, 'month') ? 'dd' : 'MMM dd', culture); }; var formats$2 = { dateFormat: 'dd', dayFormat: 'eee dd/MM', weekdayFormat: 'eee', selectRangeFormat: timeRangeFormat$2, eventTimeRangeFormat: timeRangeFormat$2, eventTimeRangeStartFormat: timeRangeStartFormat$2, eventTimeRangeEndFormat: timeRangeEndFormat$2, timeGutterFormat: { time: 'short' }, monthHeaderFormat: 'MMMM yyyy', dayHeaderFormat: 'eeee MMM dd', dayRangeHeaderFormat: weekRangeFormat$2, agendaHeaderFormat: dateRangeFormat$3, agendaDateFormat: 'eee MMM dd', agendaTimeFormat: { time: 'short' }, agendaTimeRangeFormat: timeRangeFormat$2 }; function globalize (globalize) { var locale = function locale(culture) { return culture ? globalize(culture) : globalize; }; // return the first day of the week from the locale data. Defaults to 'world' // territory if no territory is derivable from CLDR. // Failing to use CLDR supplemental (not loaded?), revert to the original // method of getting first day of week. function firstOfWeek(culture) { try { var days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; var cldr = locale(culture).cldr; var territory = cldr.attributes.territory; var weekData = cldr.get('supplemental').weekData; var firstDay = weekData.firstDay[territory || '001']; return days.indexOf(firstDay); } catch (e) { process.env.NODE_ENV !== "production" ? warning(true, "Failed to accurately determine first day of the week.\n Is supplemental data loaded into CLDR?") : void 0; // maybe cldr supplemental is not loaded? revert to original method var date = new Date(); //cldr-data doesn't seem to be zero based var localeDay = Math.max(parseInt(locale(culture).formatDate(date, { raw: 'e' }), 10) - 1, 0); return Math.abs(date.getDay() - localeDay); } } if (!globalize.load) return oldGlobalize(globalize); return new DateLocalizer({ firstOfWeek: firstOfWeek, formats: formats$2, format: function format(value, _format, culture) { _format = typeof _format === 'string' ? { raw: _format } : _format; return locale(culture).formatDate(value, _format); } }); } var components = { eventWrapper: NoopWrapper, timeSlotWrapper: NoopWrapper, dateCellWrapper: NoopWrapper }; export { Calendar$1 as Calendar, DateLocalizer, navigate as Navigate, views as Views, components, globalize as globalizeLocalizer, moment as momentLocalizer, moveDate as move };
ajax/libs/primereact/6.6.0/datatable/datatable.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { Paginator } from 'primereact/paginator'; import { DomHandler, classNames, OverlayService, ObjectUtils, Ripple, FilterUtils } from 'primereact/core'; import { InputText } from 'primereact/inputtext'; 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 _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$2(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } 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 _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$2(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$c(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$c(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$c() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var ScrollableView = /*#__PURE__*/function (_Component) { _inherits(ScrollableView, _Component); var _super = _createSuper$c(ScrollableView); function ScrollableView(props) { var _this; _classCallCheck(this, ScrollableView); _this = _super.call(this, props); _this.onHeaderScroll = _this.onHeaderScroll.bind(_assertThisInitialized(_this)); _this.onBodyScroll = _this.onBodyScroll.bind(_assertThisInitialized(_this)); return _this; } _createClass(ScrollableView, [{ key: "componentDidMount", value: function componentDidMount() { this.setScrollHeight(); if (!this.props.frozen) { var scrollBarWidth = DomHandler.calculateScrollbarWidth(); this.scrollHeaderBox.style.marginRight = scrollBarWidth + 'px'; if (this.scrollFooterBox) { this.scrollFooterBox.style.marginRight = scrollBarWidth + 'px'; } } else { this.scrollBody.style.paddingBottom = DomHandler.calculateScrollbarWidth() + 'px'; } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState, snapshot) { if (this.props.scrollHeight !== prevProps.scrollHeight) { this.setScrollHeight(); } if (!this.props.frozen && this.props.virtualScroll) { this.virtualScroller.style.height = this.props.totalRecords * this.props.virtualRowHeight + 'px'; } if (this.virtualScrollCallback && !this.props.loading) { this.virtualScrollCallback(); this.virtualScrollCallback = null; } } }, { key: "setScrollHeight", value: function setScrollHeight() { if (this.props.scrollHeight) { var frozenView = this.container.previousElementSibling; if (frozenView) { var frozenScrollBody = DomHandler.findSingle(frozenView, '.p-datatable-scrollable-body'); this.scrollBody.style.maxHeight = frozenScrollBody.style.maxHeight; } else { 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.getOuterHeight(datatableContainer); var relativeHeight = DomHandler.getOuterHeight(datatableContainer.parentElement) * parseInt(this.props.scrollHeight, 10) / 100; var staticHeight = containerHeight - 100; //total height of headers, footers, paginators var scrollBodyHeight = relativeHeight - staticHeight; if (this.props.frozen) { scrollBodyHeight -= DomHandler.calculateScrollbarWidth(); } 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.hasClass(el, 'p-datatable')) { el = el.parentElement; } return el; } else { return null; } } }, { key: "onHeaderScroll", value: function onHeaderScroll() { this.scrollHeader.scrollLeft = 0; } }, { key: "onBodyScroll", value: function onBodyScroll() { var _this2 = this; var frozenView = this.container.previousElementSibling; var frozenScrollBody; if (frozenView) { frozenScrollBody = DomHandler.findSingle(frozenView, '.p-datatable-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; } if (this.props.virtualScroll) { var viewport = DomHandler.getClientHeight(this.scrollBody); var tableHeight = DomHandler.getOuterHeight(this.scrollTable); var pageHeight = this.props.virtualRowHeight * this.props.rows; var virtualTableHeight = DomHandler.getOuterHeight(this.virtualScroller); var pageCount = virtualTableHeight / pageHeight || 1; var scrollBodyTop = this.scrollTable.style.top || '0'; if (this.scrollBody.scrollTop + viewport > parseFloat(scrollBodyTop) + tableHeight || this.scrollBody.scrollTop < parseFloat(scrollBodyTop)) { if (this.loadingTable) { this.loadingTable.style.display = 'table'; this.loadingTable.style.top = this.scrollBody.scrollTop + 'px'; } var page = Math.floor(this.scrollBody.scrollTop * pageCount / this.scrollBody.scrollHeight) + 1; if (this.props.onVirtualScroll) { this.props.onVirtualScroll({ page: page }); this.virtualScrollCallback = function () { if (_this2.loadingTable) { _this2.loadingTable.style.display = 'none'; } _this2.scrollTable.style.top = (page - 1) * pageHeight + 'px'; }; } } } } }, { key: "renderColGroup", value: function renderColGroup() { if (this.props.columns && this.props.columns.length) { return /*#__PURE__*/React.createElement("colgroup", { className: "p-datatable-scrollable-colgroup" }, this.props.columns.map(function (col, i) { return /*#__PURE__*/React.createElement("col", { key: col.props.field + '_' + i, style: col.props.headerStyle || col.props.style, className: col.props.headerClassName || col.props.className }); })); } else { return null; } } }, { key: "renderLoadingTable", value: function renderLoadingTable(colGroup) { var _this3 = this; if (this.props.virtualScroll) { return /*#__PURE__*/React.createElement("table", { ref: function ref(el) { return _this3.loadingTable = el; }, style: { top: '0', display: 'none' }, className: "p-datatable-scrollable-body-table p-datatable-loading-virtual-table p-datatable-virtual-table" }, colGroup, this.props.loadingBody); } else { return null; } } }, { key: "render", value: function render() { var _this4 = this; var className = classNames('p-datatable-scrollable-view', { 'p-datatable-frozen-view': this.props.frozen, 'p-datatable-unfrozen-view': !this.props.frozen && this.props.frozenWidth }); var tableBodyClassName = classNames('p-datatable-scrollable-body-table', this.props.tableClassName, { 'p-datatable-virtual-table': this.props.virtualScroll }); var tableHeaderClassName = classNames('p-datatable-scrollable-header-table', this.props.tableClassName); var tableFooterClassName = classNames('p-datatable-scrollable-footer-table', this.props.tableClassName); var tableBodyStyle = Object.assign({ top: '0' }, this.props.tableStyle); var width = this.props.columns ? this.props.frozen ? this.props.frozenWidth : 'calc(100% - ' + this.props.frozenWidth + ')' : 0; var left = this.props.frozen ? null : this.props.frozenWidth; var colGroup = this.renderColGroup(); var loadingTable = this.renderLoadingTable(colGroup); 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) { _this4.container = el; } }, /*#__PURE__*/React.createElement("div", { className: "p-datatable-scrollable-header", ref: function ref(el) { _this4.scrollHeader = el; }, onScroll: this.onHeaderScroll }, /*#__PURE__*/React.createElement("div", { className: "p-datatable-scrollable-header-box", ref: function ref(el) { _this4.scrollHeaderBox = el; } }, /*#__PURE__*/React.createElement("table", { className: tableHeaderClassName, style: this.props.tableStyle }, colGroup, this.props.header, this.props.frozenBody))), /*#__PURE__*/React.createElement("div", { className: "p-datatable-scrollable-body", ref: function ref(el) { _this4.scrollBody = el; }, style: scrollableBodyStyle, onScroll: this.onBodyScroll }, /*#__PURE__*/React.createElement("table", { ref: function ref(el) { return _this4.scrollTable = el; }, style: tableBodyStyle, className: tableBodyClassName }, colGroup, this.props.body), loadingTable, /*#__PURE__*/React.createElement("div", { className: "p-datatable-virtual-scroller", ref: function ref(el) { _this4.virtualScroller = el; } })), /*#__PURE__*/React.createElement("div", { className: "p-datatable-scrollable-footer", ref: function ref(el) { _this4.scrollFooter = el; } }, /*#__PURE__*/React.createElement("div", { className: "p-datatable-scrollable-footer-box", ref: function ref(el) { _this4.scrollFooterBox = el; } }, /*#__PURE__*/React.createElement("table", { className: tableFooterClassName, style: this.props.tableStyle }, colGroup, this.props.footer)))); } }]); return ScrollableView; }(Component); _defineProperty(ScrollableView, "defaultProps", { header: null, body: null, footer: null, columns: null, frozen: null, frozenWidth: null, frozenBody: null, virtualScroll: false, virtualRowHeight: null, rows: null, totalRecords: null, loading: false, tableStyle: null, tableClassName: null, onVirtualScroll: null }); 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 _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$b(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$b(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$b() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var RowRadioButton = /*#__PURE__*/function (_Component) { _inherits(RowRadioButton, _Component); var _super = _createSuper$b(RowRadioButton); function RowRadioButton(props) { var _this; _classCallCheck(this, RowRadioButton); _this = _super.call(this, props); _this.state = { focused: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onChange = _this.onChange.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(RowRadioButton, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, data: this.props.rowData }); } this.input.focus(); } }, { key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onChange", value: function onChange(event) { this.onClick(event); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.code === 'Space') { this.onClick(event); event.preventDefault(); } } }, { key: "render", value: function render() { var _this2 = this; var className = classNames('p-radiobutton-box p-component p-clickable', { 'p-highlight': this.props.selected, 'p-focus': this.state.focused }); var name = "".concat(this.props.tableId ? this.props.tableId + '_' : '', "dt_radio"); return /*#__PURE__*/React.createElement("div", { className: "p-radiobutton p-component" }, /*#__PURE__*/React.createElement("div", { className: "p-hidden-accessible" }, /*#__PURE__*/React.createElement("input", { name: name, ref: function ref(el) { return _this2.input = el; }, type: "radio", checked: this.props.selected, onFocus: this.onFocus, onBlur: this.onBlur, onChange: this.onChange, onKeyDown: this.onKeyDown })), /*#__PURE__*/React.createElement("div", { className: className, onClick: this.onClick, role: "radio", "aria-checked": this.props.selected }, /*#__PURE__*/React.createElement("div", { className: "p-radiobutton-icon p-clickable" }))); } }]); return RowRadioButton; }(Component); _defineProperty(RowRadioButton, "defaultProps", { rowData: null, onClick: null, selected: false }); function _createSuper$a(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$a(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$a() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var RowCheckbox = /*#__PURE__*/function (_Component) { _inherits(RowCheckbox, _Component); var _super = _createSuper$a(RowCheckbox); function RowCheckbox(props) { var _this; _classCallCheck(this, RowCheckbox); _this = _super.call(this, props); _this.state = { focused: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(RowCheckbox, [{ key: "onClick", value: function onClick(event) { if (!this.props.disabled) { this.setState({ focused: true }); if (this.props.onClick) { this.props.onClick({ originalEvent: event, data: this.props.rowData, checked: this.props.selected }); } } } }, { key: "onFocus", value: function onFocus() { this.setState({ focused: true }); } }, { key: "onBlur", value: function onBlur() { this.setState({ focused: false }); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.code === 'Space') { this.onClick(event); event.preventDefault(); } } }, { key: "render", value: function render() { var className = classNames('p-checkbox-box p-component p-clickable', { 'p-highlight': this.props.selected, 'p-disabled': this.props.disabled, 'p-focus': this.state.focused }); var iconClassName = classNames('p-checkbox-icon p-clickable', { 'pi pi-check': this.props.selected }); var tabIndex = this.props.disabled ? null : '0'; return /*#__PURE__*/React.createElement("div", { className: "p-checkbox p-component", onClick: this.onClick }, /*#__PURE__*/React.createElement("div", { className: className, role: "checkbox", "aria-checked": this.props.selected, tabIndex: tabIndex, onKeyDown: this.onKeyDown, onFocus: this.onFocus, onBlur: this.onBlur }, /*#__PURE__*/React.createElement("span", { className: iconClassName }))); } }]); return RowCheckbox; }(Component); _defineProperty(RowCheckbox, "defaultProps", { rowData: null, onClick: null, disabled: false }); function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$3(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$9(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$9(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$9() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var BodyCell = /*#__PURE__*/function (_Component) { _inherits(BodyCell, _Component); var _super = _createSuper$9(BodyCell); function BodyCell(props) { var _this; _classCallCheck(this, BodyCell); _this = _super.call(this, props); _this.state = { editing: _this.props.editing }; _this.onExpanderClick = _this.onExpanderClick.bind(_assertThisInitialized(_this)); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this)); _this.onMouseUp = _this.onMouseUp.bind(_assertThisInitialized(_this)); _this.onEditorFocus = _this.onEditorFocus.bind(_assertThisInitialized(_this)); return _this; } _createClass(BodyCell, [{ key: "onExpanderClick", value: function onExpanderClick(event) { if (this.props.onRowToggle) { this.props.onRowToggle({ originalEvent: event, data: this.props.rowData }); } event.preventDefault(); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (this.props.editMode !== 'row') { if (event.which === 13 || event.which === 9) { // tab || enter this.switchCellToViewMode(event, true); } if (event.which === 27) { // escape this.switchCellToViewMode(event, false); } } if (this.props.allowCellSelection) { var cell = event.currentTarget; switch (event.which) { //left arrow case 37: var prevCell = this.findPrevSelectableCell(cell); if (prevCell) { this.changeTabIndex(cell, prevCell); prevCell.focus(); } event.preventDefault(); break; //right arrow case 39: var nextCell = this.findNextSelectableCell(cell); if (nextCell) { this.changeTabIndex(cell, nextCell); nextCell.focus(); } event.preventDefault(); break; //up arrow case 38: var prevRow = this.findPrevSelectableRow(cell.parentElement); if (prevRow) { var upCell = prevRow.children[this.props.index]; this.changeTabIndex(cell, upCell); upCell.focus(); } event.preventDefault(); break; //down arrow case 40: var nextRow = this.findNextSelectableRow(cell.parentElement); if (nextRow) { var downCell = nextRow.children[this.props.index]; this.changeTabIndex(cell, downCell); downCell.focus(); } event.preventDefault(); break; //enter or space case 13: // @deprecated case 32: this.onClick(event); event.preventDefault(); break; } } } }, { key: "onClick", value: function onClick(event) { var _this2 = this; if (this.props.editMode !== 'row' && this.props.editor && !this.state.editing && (this.props.selectOnEdit || !this.props.selectOnEdit && this.props.selected)) { this.selfClick = true; if (this.props.onBeforeEditorShow) { this.props.onBeforeEditorShow({ originalEvent: event, columnProps: this.props }); } this.setState({ editing: true }, function () { if (_this2.props.onEditorInit) { _this2.props.onEditorInit({ originalEvent: event, columnProps: _this2.props }); } if (_this2.props.editorValidatorEvent === 'click') { _this2.bindDocumentEditListener(); _this2.overlayEventListener = function (e) { if (!_this2.isOutsideClicked(e.target)) { _this2.selfClick = true; } }; OverlayService.on('overlay-click', _this2.overlayEventListener); } if (_this2.props.onEditingCellChange) { _this2.props.onEditingCellChange({ rowIndex: _this2.props.rowIndex, cellIndex: _this2.props.index, editing: true }); } }); } if (this.props.allowCellSelection && this.props.onClick) { this.props.onClick({ originalEvent: event, value: ObjectUtils.resolveFieldData(this.props.rowData, this.props.field), field: this.props.field, rowData: this.props.rowData, rowIndex: this.props.rowIndex, cellIndex: this.props.index, selected: this.isSelected() }); } } }, { key: "onBlur", value: function onBlur(event) { this.selfClick = false; if (this.props.editMode !== 'row' && this.state.editing && this.props.editorValidatorEvent === 'blur') { this.switchCellToViewMode(event, true); } } }, { key: "onMouseDown", value: function onMouseDown(event) { if (this.props.onMouseDown) { this.props.onMouseDown({ originalEvent: event, value: ObjectUtils.resolveFieldData(this.props.rowData, this.props.field), field: this.props.field, rowData: this.props.rowData, rowIndex: this.props.rowIndex, cellIndex: this.props.index, selected: this.isSelected() }); } } }, { key: "onMouseUp", value: function onMouseUp(event) { if (this.props.onMouseUp) { this.props.onMouseUp({ originalEvent: event, value: ObjectUtils.resolveFieldData(this.props.rowData, this.props.field), field: this.props.field, rowData: this.props.rowData, rowIndex: this.props.rowIndex, cellIndex: this.props.index, selected: this.isSelected() }); } } }, { key: "onEditorFocus", value: function onEditorFocus(event) { this.onClick(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, true); } _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: "closeCell", value: function closeCell(event) { var _this4 = this; if (this.props.onBeforeEditorHide) { this.props.onBeforeEditorHide({ originalEvent: event, columnProps: this.props }); } /* 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; if (_this4.props.onEditingCellChange) { _this4.props.onEditingCellChange({ rowIndex: _this4.props.rowIndex, cellIndex: _this4.props.index, editing: false }); } }); }, 1); } }, { key: "switchCellToViewMode", value: function switchCellToViewMode(event, submit) { var params = { originalEvent: event, columnProps: this.props }; if (!submit && this.props.onEditorCancel) { this.props.onEditorCancel(params); } var valid = true; if (this.props.editorValidator) { valid = this.props.editorValidator(params); } if (valid) { if (submit && this.props.onEditorSubmit) { this.props.onEditorSubmit(params); } this.closeCell(event); } } }, { key: "findNextSelectableCell", value: function findNextSelectableCell(cell) { var nextCell = cell.nextElementSibling; if (nextCell) { return DomHandler.hasClass(nextCell, 'p-selectable-cell') ? nextCell : this.findNextSelectableRow(nextCell); } return null; } }, { key: "findPrevSelectableCell", value: function findPrevSelectableCell(cell) { var prevCell = cell.previousElementSibling; if (prevCell) { return DomHandler.hasClass(prevCell, 'p-selectable-cell') ? prevCell : this.findPrevSelectableRow(prevCell); } return null; } }, { key: "findNextSelectableRow", value: function findNextSelectableRow(row) { var nextRow = row.nextElementSibling; if (nextRow) { return DomHandler.hasClass(nextRow, 'p-selectable-row') ? nextRow : this.findNextSelectableRow(nextRow); } return null; } }, { key: "findPrevSelectableRow", value: function findPrevSelectableRow(row) { var prevRow = row.previousElementSibling; if (prevRow) { return DomHandler.hasClass(prevRow, 'p-selectable-row') ? prevRow : this.findPrevSelectableRow(prevRow); } return null; } }, { key: "changeTabIndex", value: function changeTabIndex(currentCell, nextCell) { if (currentCell && nextCell) { currentCell.tabIndex = -1; nextCell.tabIndex = 0; } } }, { key: "getTabIndex", value: function getTabIndex(cellSelected) { return this.props.allowCellSelection ? cellSelected ? 0 : this.props.rowIndex === 0 && this.props.index === 0 ? 0 : -1 : null; } }, { key: "isSelected", value: function isSelected() { if (this.props.selection) { return this.props.selection instanceof Array ? this.findIndexInSelection() > -1 : this.equals(this.props.selection); } return false; } }, { key: "equals", value: function equals(selectedCell) { return (selectedCell.rowIndex === this.props.rowIndex || selectedCell.rowData === this.props.rowData) && (selectedCell.field === this.props.field || selectedCell.cellIndex === this.props.index); } }, { key: "findIndexInSelection", value: function findIndexInSelection() { var _this5 = this; return this.props.selection ? this.props.selection.findIndex(function (d) { return _this5.equals(d); }) : -1; } }, { key: "unbindDocumentEditListener", value: function unbindDocumentEditListener() { if (this.documentEditListener) { document.removeEventListener('click', this.documentEditListener); this.documentEditListener = null; this.selfClick = false; } } }, { key: "componentDidUpdate", value: function componentDidUpdate() { var _this6 = this; if (this.props.editMode !== 'row' && this.container && this.props.editor) { clearTimeout(this.tabindexTimeout); this.tabindexTimeout = setTimeout(function () { if (_this6.state.editing) { var focusable = DomHandler.findSingle(_this6.container, 'input'); if (focusable && document.activeElement !== focusable && !focusable.hasAttribute('data-isCellEditing')) { focusable.setAttribute('data-isCellEditing', true); focusable.focus(); } _this6.keyHelper.tabIndex = -1; } else if (_this6.keyHelper) { _this6.keyHelper.setAttribute('tabindex', 0); } }, 1); } } }, { 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 _this7 = this; var content, editorKeyHelper; var cellSelected = this.props.allowCellSelection && this.isSelected(); var cellClassName = null; if (this.props.cellClassName) { var cellData = ObjectUtils.resolveFieldData(this.props.rowData, this.props.field); cellClassName = this.props.cellClassName(cellData, _objectSpread$3(_objectSpread$3({}, this.props), { rowData: this.props.rowData })); } var className = classNames(this.props.bodyClassName || this.props.className, cellClassName, { 'p-selection-column': this.props.selectionMode, 'p-selectable-cell': this.props.allowCellSelection, 'p-highlight': cellSelected, 'p-editable-column': this.props.editor, 'p-cell-editing': this.state.editing && this.props.editor }); var tabIndex = this.getTabIndex(cellSelected); if (this.props.expander) { var iconClassName = classNames('p-row-toggler-icon pi pi-fw p-clickable', { 'pi-chevron-down': this.props.expanded, 'pi-chevron-right': !this.props.expanded }); var ariaControls = "".concat(this.props.tableId ? this.props.tableId + '_' : '', "content_").concat(this.props.rowIndex, "_expanded"); var expanderProps = { onClick: this.onExpanderClick, className: 'p-row-toggler p-link', iconClassName: iconClassName }; content = /*#__PURE__*/React.createElement("button", { type: "button", onClick: expanderProps.onClick, className: expanderProps.className, "aria-expanded": this.props.expanded, "aria-controls": ariaControls }, /*#__PURE__*/React.createElement("span", { className: expanderProps.iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); if (this.props.body) { expanderProps['element'] = content; content = this.props.body(this.props.rowData, _objectSpread$3(_objectSpread$3({}, this.props), { expander: expanderProps })); } } else if (this.props.selectionMode) { var showSelection = true; if (this.props.showSelectionElement) { showSelection = this.props.showSelectionElement(this.props.rowData); } if (showSelection) { if (this.props.selectionMode === 'single') content = /*#__PURE__*/React.createElement(RowRadioButton, { onClick: this.props.onRadioClick, rowData: this.props.rowData, selected: this.props.selected, tableId: this.props.tableId });else content = /*#__PURE__*/React.createElement(RowCheckbox, { onClick: this.props.onCheckboxClick, rowData: this.props.rowData, selected: this.props.selected }); } } else if (this.props.rowReorder) { var showReorder = true; if (this.props.showRowReorderElement) { showReorder = this.props.showRowReorderElement(this.props.rowData); } if (showReorder) { var reorderIcon = classNames('p-datatable-reorderablerow-handle', this.props.rowReorderIcon); content = /*#__PURE__*/React.createElement("i", { className: reorderIcon }); } } else if (this.props.rowEditor) { var rowEditorProps = {}; if (this.state.editing) { rowEditorProps = { editing: true, onSaveClick: this.props.onRowEditSave, saveClassName: 'p-row-editor-save p-link', saveIconClassName: 'p-row-editor-save-icon pi pi-fw pi-check p-clickable', onCancelClick: this.props.onRowEditCancel, cancelClassName: 'p-row-editor-cancel p-link', cancelIconClassName: 'p-row-editor-cancel-icon pi pi-fw pi-times p-clickable' }; content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("button", { type: "button", onClick: rowEditorProps.onSaveClick, className: rowEditorProps.saveClassName }, /*#__PURE__*/React.createElement("span", { className: rowEditorProps.saveIconClassName }), /*#__PURE__*/React.createElement(Ripple, null)), /*#__PURE__*/React.createElement("button", { type: "button", onClick: rowEditorProps.onCancelClick, className: rowEditorProps.cancelClassName }, /*#__PURE__*/React.createElement("span", { className: rowEditorProps.cancelIconClassName }), /*#__PURE__*/React.createElement(Ripple, null))); } else { rowEditorProps = { editing: false, onInitClick: this.props.onRowEditInit, initClassName: 'p-row-editor-init p-link', initIconClassName: 'p-row-editor-init-icon pi pi-fw pi-pencil p-clickable' }; content = /*#__PURE__*/React.createElement("button", { type: "button", onClick: rowEditorProps.onInitClick, className: rowEditorProps.initClassName }, /*#__PURE__*/React.createElement("span", { className: rowEditorProps.initIconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); } if (this.props.body) { rowEditorProps['element'] = content; content = this.props.body(this.props.rowData, _objectSpread$3(_objectSpread$3({}, this.props), { rowEditor: rowEditorProps })); } } else { if (this.state.editing && this.props.editor) { content = this.props.editor(this.props); } else { if (this.props.body) content = this.props.body(this.props.rowData, this.props);else content = ObjectUtils.resolveFieldData(this.props.rowData, this.props.field); } } if (this.props.editMode !== 'row') { /* eslint-disable */ editorKeyHelper = this.props.editor && /*#__PURE__*/React.createElement("a", { tabIndex: "0", ref: function ref(el) { _this7.keyHelper = el; }, className: "p-cell-editor-key-helper p-hidden-accessible", onFocus: this.onEditorFocus }, /*#__PURE__*/React.createElement("span", null)); /* eslint-enable */ } return /*#__PURE__*/React.createElement("td", { ref: function ref(el) { _this7.container = el; }, role: "cell", tabIndex: tabIndex, className: className, style: this.props.bodyStyle || this.props.style, onClick: this.onClick, onKeyDown: this.onKeyDown, rowSpan: this.props.rowSpan, onBlur: this.onBlur, onMouseDown: this.onMouseDown, onMouseUp: this.onMouseUp }, editorKeyHelper, content); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { if (nextProps.editMode === 'row' && nextProps.editing !== prevState.editing) { return { editing: nextProps.editing }; } return null; } }]); return BodyCell; }(Component); function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$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 BodyRow = /*#__PURE__*/function (_Component) { _inherits(BodyRow, _Component); var _super = _createSuper$8(BodyRow); function BodyRow(props) { var _this; _classCallCheck(this, BodyRow); _this = _super.call(this, props); if (!_this.props.isRowEditingControlled) { _this.state = { editing: false }; } _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onDoubleClick = _this.onDoubleClick.bind(_assertThisInitialized(_this)); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this)); _this.onRightClick = _this.onRightClick.bind(_assertThisInitialized(_this)); _this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this)); _this.onMouseUp = _this.onMouseUp.bind(_assertThisInitialized(_this)); _this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this)); _this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_this)); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onRowEditInit = _this.onRowEditInit.bind(_assertThisInitialized(_this)); _this.onRowEditSave = _this.onRowEditSave.bind(_assertThisInitialized(_this)); _this.onRowEditCancel = _this.onRowEditCancel.bind(_assertThisInitialized(_this)); _this.updateEditingState = _this.updateEditingState.bind(_assertThisInitialized(_this)); return _this; } _createClass(BodyRow, [{ key: "getEditing", value: function getEditing() { return this.props.isRowEditingControlled ? this.props.editing : this.state.editing; } }, { key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex }); } } }, { key: "onDoubleClick", value: function onDoubleClick(event) { if (this.props.onDoubleClick) { this.props.onDoubleClick({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex }); } } }, { key: "onTouchEnd", value: function onTouchEnd(event) { if (this.props.onTouchEnd) { this.props.onTouchEnd(event); } } }, { key: "onRightClick", value: function onRightClick(event) { if (this.props.onRightClick) { this.props.onRightClick({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex }); } } }, { key: "onMouseDown", value: function onMouseDown(event) { if (DomHandler.hasClass(event.target, 'p-datatable-reorderablerow-handle')) event.currentTarget.draggable = true;else event.currentTarget.draggable = false; if (this.props.onMouseDown) { this.props.onMouseDown({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex }); } } }, { key: "onMouseUp", value: function onMouseUp(event) { if (this.props.onMouseUp) { this.props.onMouseUp({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex }); } } }, { key: "onDragEnd", value: function onDragEnd(event) { if (this.props.onDragEnd) { this.props.onDragEnd(event); } event.currentTarget.draggable = false; } }, { key: "onDragOver", value: function onDragOver(event) { if (this.props.onDragOver) { this.props.onDragOver({ originalEvent: event, rowElement: this.container }); } event.preventDefault(); } }, { key: "onDragLeave", value: function onDragLeave(event) { if (this.props.onDragLeave) { this.props.onDragLeave({ originalEvent: event, rowElement: this.container }); } } }, { key: "onDrop", value: function onDrop(event) { if (this.props.onDrop) { this.props.onDrop({ originalEvent: event, rowElement: this.container }); } event.preventDefault(); } }, { key: "onKeyDown", value: function onKeyDown(event) { if (this.isFocusable() && !this.props.allowCellSelection) { var target = event.target, row = event.currentTarget; switch (event.which) { //down arrow case 40: var nextRow = this.findNextSelectableRow(row); if (nextRow) { this.changeTabIndex(row, nextRow); nextRow.focus(); } event.preventDefault(); break; //up arrow case 38: var prevRow = this.findPrevSelectableRow(row); if (prevRow) { this.changeTabIndex(row, prevRow); prevRow.focus(); } event.preventDefault(); break; //enter case 13: // @deprecated this.onClick(event); event.preventDefault(); break; //space case 32: if (target.nodeName !== 'INPUT' && target.nodeName !== 'TEXTAREA' && !target.readOnly) { this.onClick(event); event.preventDefault(); } break; } } } }, { key: "changeTabIndex", value: function changeTabIndex(currentRow, nextRow) { if (currentRow && nextRow) { currentRow.tabIndex = -1; nextRow.tabIndex = 0; } } }, { key: "findNextSelectableRow", value: function findNextSelectableRow(row) { var nextRow = row.nextElementSibling; if (nextRow) { if (DomHandler.hasClass(nextRow, 'p-selectable-row')) return nextRow;else return this.findNextSelectableRow(nextRow); } else { return null; } } }, { key: "findPrevSelectableRow", value: function findPrevSelectableRow(row) { var prevRow = row.previousElementSibling; if (prevRow) { if (DomHandler.hasClass(prevRow, 'p-selectable-row')) return prevRow;else return this.findPrevSelectableRow(prevRow); } else { return null; } } }, { key: "updateEditingState", value: function updateEditingState(event, editing) { if (this.props.isRowEditingControlled) { this.props.onRowEditingToggle({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex }); } else { this.setState({ editing: editing }); } } }, { key: "onRowEditInit", value: function onRowEditInit(event) { if (this.props.onRowEditInit) { this.props.onRowEditInit({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex }); } this.updateEditingState(event, true); event.preventDefault(); } }, { key: "onRowEditSave", value: function onRowEditSave(event) { var valid = true; if (this.props.rowEditorValidator) { valid = this.props.rowEditorValidator(this.props.rowData); } if (this.props.onRowEditSave) { this.props.onRowEditSave({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex, valid: valid }); } if (valid) { this.updateEditingState(event, false); } event.preventDefault(); } }, { key: "onRowEditCancel", value: function onRowEditCancel(event) { if (this.props.onRowEditCancel) { this.props.onRowEditCancel({ originalEvent: event, data: this.props.rowData, index: this.props.rowIndex }); } this.updateEditingState(event, false); event.preventDefault(); } }, { key: "isFocusable", value: function isFocusable() { return this.props.selectionMode && this.props.selectionModeInColumn !== 'single' && this.props.selectionModeInColumn !== 'multiple'; } }, { key: "getTabIndex", value: function getTabIndex() { return this.isFocusable() && !this.props.allowCellSelection ? this.props.rowIndex === 0 ? 0 : -1 : null; } }, { key: "render", value: function render() { var _this2 = this; var columns = React.Children.toArray(this.props.children); var conditionalClassNames = { 'p-highlight': !this.props.allowCellSelection && this.props.selected, 'p-highlight-contextmenu': this.props.contextMenuSelected, 'p-selectable-row': this.props.allowRowSelection, 'p-row-odd': this.props.rowIndex % 2 !== 0 }; if (this.props.rowClassName) { var rowClassNameCondition = this.props.rowClassName(this.props.rowData); conditionalClassNames = _objectSpread$2(_objectSpread$2({}, conditionalClassNames), rowClassNameCondition); } var className = classNames(conditionalClassNames); var style = this.props.virtualScroll ? { height: this.props.virtualRowHeight } : {}; var hasRowSpanGrouping = this.props.rowGroupMode === 'rowspan'; var tabIndex = this.getTabIndex(); var cells = []; for (var i = 0; i < columns.length; i++) { var column = columns[i]; var rowSpan = void 0; if (hasRowSpanGrouping) { if (this.props.sortField === column.props.field) { if (this.props.groupRowSpan) { rowSpan = this.props.groupRowSpan; className += ' p-datatable-rowspan-group'; } else { continue; } } } var editing = this.getEditing(); var cell = /*#__PURE__*/React.createElement(BodyCell, _extends({ tableId: this.props.tableId, key: i }, column.props, { value: this.props.value, rowSpan: rowSpan, rowData: this.props.rowData, index: i, rowIndex: this.props.rowIndex, onRowToggle: this.props.onRowToggle, expanded: this.props.expanded, onRadioClick: this.props.onRadioClick, onCheckboxClick: this.props.onCheckboxClick, selected: this.props.selected, selection: this.props.selection, selectOnEdit: this.props.selectOnEdit, editMode: this.props.editMode, editing: editing, onRowEditInit: this.onRowEditInit, onRowEditSave: this.onRowEditSave, onRowEditCancel: this.onRowEditCancel, onMouseDown: this.props.onCellMouseDown, onMouseUp: this.props.onCellMouseUp, showRowReorderElement: this.props.showRowReorderElement, showSelectionElement: this.props.showSelectionElement, allowCellSelection: this.props.allowCellSelection, onClick: this.props.onCellClick, onEditingCellChange: this.props.onEditingCellChange, cellClassName: this.props.cellClassName })); cells.push(cell); } return /*#__PURE__*/React.createElement("tr", { role: "row", tabIndex: tabIndex, ref: function ref(el) { _this2.container = el; }, className: className, onClick: this.onClick, onDoubleClick: this.onDoubleClick, onTouchEnd: this.onTouchEnd, onContextMenu: this.onRightClick, onMouseDown: this.onMouseDown, onMouseUp: this.onMouseUp, onDragStart: this.props.onDragStart, onDragEnd: this.onDragEnd, onDragOver: this.onDragOver, onDragLeave: this.onDragLeave, onDrop: this.onDrop, style: style, onKeyDown: this.onKeyDown }, cells); } }]); return BodyRow; }(Component); 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 RowTogglerButton = /*#__PURE__*/function (_Component) { _inherits(RowTogglerButton, _Component); var _super = _createSuper$7(RowTogglerButton); function RowTogglerButton(props) { var _this; _classCallCheck(this, RowTogglerButton); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); return _this; } _createClass(RowTogglerButton, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, data: this.props.rowData }); } } }, { key: "render", value: function render() { var iconClassName = classNames('p-row-toggler-icon pi pi-fw p-clickable', { 'pi-chevron-down': this.props.expanded, 'pi-chevron-right': !this.props.expanded }); return /*#__PURE__*/React.createElement("button", { type: "button", onClick: this.onClick, className: "p-row-toggler p-link" }, /*#__PURE__*/React.createElement("span", { className: iconClassName }), /*#__PURE__*/React.createElement(Ripple, null)); } }]); return RowTogglerButton; }(Component); _defineProperty(RowTogglerButton, "defaultProps", { rowData: null, onClick: null, expanded: false }); var _excluded = ["originalEvent"]; function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper$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 TableBody = /*#__PURE__*/function (_Component) { _inherits(TableBody, _Component); var _super = _createSuper$6(TableBody); function TableBody(props) { var _this; _classCallCheck(this, TableBody); _this = _super.call(this, props); _this.onRowClick = _this.onRowClick.bind(_assertThisInitialized(_this)); _this.onRowRightClick = _this.onRowRightClick.bind(_assertThisInitialized(_this)); _this.onRowTouchEnd = _this.onRowTouchEnd.bind(_assertThisInitialized(_this)); _this.onRowToggle = _this.onRowToggle.bind(_assertThisInitialized(_this)); _this.onRowEditingToggle = _this.onRowEditingToggle.bind(_assertThisInitialized(_this)); _this.onRadioClick = _this.onRadioClick.bind(_assertThisInitialized(_this)); _this.onCheckboxClick = _this.onCheckboxClick.bind(_assertThisInitialized(_this)); _this.onDragSelectionMouseMove = _this.onDragSelectionMouseMove.bind(_assertThisInitialized(_this)); _this.onDragSelectionMouseUp = _this.onDragSelectionMouseUp.bind(_assertThisInitialized(_this)); _this.onRowDragEnd = _this.onRowDragEnd.bind(_assertThisInitialized(_this)); _this.onRowDragLeave = _this.onRowDragLeave.bind(_assertThisInitialized(_this)); _this.onRowDrop = _this.onRowDrop.bind(_assertThisInitialized(_this)); _this.onRowMouseDown = _this.onRowMouseDown.bind(_assertThisInitialized(_this)); _this.onRowMouseUp = _this.onRowMouseUp.bind(_assertThisInitialized(_this)); _this.onCellClick = _this.onCellClick.bind(_assertThisInitialized(_this)); _this.onCellMouseDown = _this.onCellMouseDown.bind(_assertThisInitialized(_this)); _this.onCellMouseUp = _this.onCellMouseUp.bind(_assertThisInitialized(_this)); return _this; } _createClass(TableBody, [{ key: "onRowClick", value: function onRowClick(event) { if (this.allowCellSelection() || !this.allowSelection(event)) { return; } this.props.onRowClick && this.props.onRowClick(event); if (this.allowRowSelection()) { if (this.allowRangeSelection(event)) { this.onRangeSelection(event); } else { var toggleable = this.isRadioSelectionModeInColumn() || this.isCheckboxSelectionModeInColumn() || this.allowMetaKeySelection(event); this.anchorRowIndex = event.index; this.rangeRowIndex = event.index; this.anchorRowFirst = this.props.first; if (this.isSingleSelection()) { this.onSingleSelection(_objectSpread$1(_objectSpread$1({}, event), {}, { toggleable: toggleable, type: 'row' })); } else { this.onMultipleSelection(_objectSpread$1(_objectSpread$1({}, event), {}, { toggleable: toggleable, type: 'row' })); } } } else { this.focusOnElement(event.originalEvent); } this.rowTouched = false; } }, { key: "onCellClick", value: function onCellClick(event) { if (!this.allowSelection(event)) { return; } this.props.onCellClick && this.props.onCellClick(event); if (this.allowCellSelection()) { if (this.allowRangeSelection(event)) { this.onRangeSelection(event); } else { var toggleable = this.allowMetaKeySelection(event); var originalEvent = event.originalEvent, data = _objectWithoutProperties(event, _excluded); this.anchorRowIndex = event.rowIndex; this.rangeRowIndex = event.rowIndex; this.anchorRowFirst = this.props.first; this.anchorCellIndex = event.cellIndex; if (this.isSingleSelection()) { this.onSingleSelection({ originalEvent: originalEvent, data: data, toggleable: toggleable, type: 'cell' }); } else { this.onMultipleSelection({ originalEvent: originalEvent, data: data, toggleable: toggleable, type: 'cell' }); } } } this.rowTouched = false; } }, { key: "onSingleSelection", value: function onSingleSelection(_ref) { var originalEvent = _ref.originalEvent, data = _ref.data, toggleable = _ref.toggleable, type = _ref.type; var selected = this.isSelected(data); var selection = this.props.selection; if (selected) { if (toggleable) { selection = null; this.onUnselect({ originalEvent: originalEvent, data: data, type: type }); } } else { selection = data; this.onSelect({ originalEvent: originalEvent, data: data, type: type }); } this.focusOnElement(originalEvent, true); if (this.props.onSelectionChange && selection !== this.props.selection) { this.props.onSelectionChange({ originalEvent: originalEvent, value: selection }); } } }, { key: "onMultipleSelection", value: function onMultipleSelection(_ref2) { var _this2 = this; var originalEvent = _ref2.originalEvent, data = _ref2.data, toggleable = _ref2.toggleable, type = _ref2.type; var selected = this.isSelected(data); var selection = this.props.selection || []; if (selected) { if (toggleable) { var selectionIndex = this.findIndexInSelection(data); selection = this.props.selection.filter(function (val, i) { return i !== selectionIndex; }); this.onUnselect({ originalEvent: originalEvent, data: data, type: type }); } else if (selection.length) { this.props.selection.forEach(function (d) { return _this2.onUnselect({ originalEvent: originalEvent, data: d, type: type }); }); selection = [data]; this.onSelect({ originalEvent: originalEvent, data: data, type: type }); } } else { selection = toggleable && this.isMultipleSelection() ? [].concat(_toConsumableArray(selection), [data]) : [data]; this.onSelect({ originalEvent: originalEvent, data: data, type: type }); } this.focusOnElement(originalEvent, true); if (this.props.onSelectionChange && selection !== this.props.selection) { this.props.onSelectionChange({ originalEvent: originalEvent, value: selection }); } } }, { key: "onRangeSelection", value: function onRangeSelection(event) { DomHandler.clearSelection(); this.rangeRowIndex = this.allowCellSelection() ? event.rowIndex : event.index; var selectionInRange = this.selectRange(event); var selection = this.isMultipleSelection() ? _toConsumableArray(new Set([].concat(_toConsumableArray(this.props.selection || []), _toConsumableArray(selectionInRange)))) : selectionInRange; if (this.props.onSelectionChange && selection !== this.props.selection) { this.props.onSelectionChange({ originalEvent: event.originalEvent, value: selection }); } this.anchorRowIndex = this.rangeRowIndex; this.anchorCellIndex = event.cellIndex; this.focusOnElement(event.originalEvent, false); } }, { key: "selectRange", value: function selectRange(event) { var rangeStart, rangeEnd; var isLazyAndPaginator = this.props.lazy && this.props.paginator; if (isLazyAndPaginator) { this.anchorRowIndex += this.anchorRowFirst; this.rangeRowIndex += this.props.first; } if (this.rangeRowIndex > this.anchorRowIndex) { rangeStart = this.anchorRowIndex; rangeEnd = this.rangeRowIndex; } else if (this.rangeRowIndex < this.anchorRowIndex) { rangeStart = this.rangeRowIndex; rangeEnd = this.anchorRowIndex; } else { rangeStart = rangeEnd = this.rangeRowIndex; } if (isLazyAndPaginator) { rangeStart = Math.max(rangeStart - this.props.first, 0); rangeEnd -= this.props.first; } return this.allowCellSelection() ? this.selectRangeOnCell(event, rangeStart, rangeEnd) : this.selectRangeOnRow(event, rangeStart, rangeEnd); } }, { key: "selectRangeOnRow", value: function selectRangeOnRow(event, rowRangeStart, rowRangeEnd) { var value = this.props.value; var selection = []; for (var i = rowRangeStart; i <= rowRangeEnd; i++) { var rangeRowData = value[i]; selection.push(rangeRowData); this.onSelect({ originalEvent: event.originalEvent, data: rangeRowData, type: 'row' }); } return selection; } }, { key: "selectRangeOnCell", value: function selectRangeOnCell(event, rowRangeStart, rowRangeEnd) { var cellRangeStart, cellRangeEnd, cellIndex = event.cellIndex; if (cellIndex > this.anchorCellIndex) { cellRangeStart = this.anchorCellIndex; cellRangeEnd = cellIndex; } else if (cellIndex < this.anchorCellIndex) { cellRangeStart = cellIndex; cellRangeEnd = this.anchorCellIndex; } else { cellRangeStart = cellRangeEnd = cellIndex; } var value = this.props.value; var selection = []; for (var i = rowRangeStart; i <= rowRangeEnd; i++) { var rowData = value[i]; var columns = React.Children.toArray(this.props.children); for (var j = cellRangeStart; j <= cellRangeEnd; j++) { var field = columns[j].props.field; var rangeRowData = { value: ObjectUtils.resolveFieldData(rowData, field), field: field, rowData: rowData, rowIndex: i, cellIndex: j, selected: true }; selection.push(rangeRowData); this.onSelect({ originalEvent: event.originalEvent, data: rangeRowData, type: 'cell' }); } } return selection; } }, { key: "onSelect", value: function onSelect(event) { if (this.allowCellSelection()) this.props.onCellSelect && this.props.onCellSelect(_objectSpread$1(_objectSpread$1({ originalEvent: event.originalEvent }, event.data), {}, { type: event.type }));else this.props.onRowSelect && this.props.onRowSelect(event); } }, { key: "onUnselect", value: function onUnselect(event) { if (this.allowCellSelection()) this.props.onCellUnselect && this.props.onCellUnselect(_objectSpread$1(_objectSpread$1({ originalEvent: event.originalEvent }, event.data), {}, { type: event.type }));else this.props.onRowUnselect && this.props.onRowUnselect(event); } }, { key: "enableDragSelection", value: function enableDragSelection(event) { if (this.props.dragSelection && !this.dragSelectionHelper) { this.dragSelectionHelper = document.createElement('div'); DomHandler.addClass(this.dragSelectionHelper, 'p-datatable-drag-selection-helper'); this.initialDragPosition = { x: event.clientX, y: event.clientY }; this.dragSelectionHelper.style.top = "".concat(event.pageY, "px"); this.dragSelectionHelper.style.left = "".concat(event.pageX, "px"); this.bindDragSelectionEvents(); } } }, { key: "bindDragSelectionEvents", value: function bindDragSelectionEvents() { document.addEventListener('mousemove', this.onDragSelectionMouseMove); document.addEventListener('mouseup', this.onDragSelectionMouseUp); document.body.appendChild(this.dragSelectionHelper); } }, { key: "unbindDragSelectionEvents", value: function unbindDragSelectionEvents() { this.onDragSelectionMouseUp(); } }, { key: "onDragSelectionMouseMove", value: function onDragSelectionMouseMove(event) { var _this$initialDragPosi = this.initialDragPosition, x = _this$initialDragPosi.x, y = _this$initialDragPosi.y; var dx = event.clientX - x; var dy = event.clientY - y; if (dy < 0) this.dragSelectionHelper.style.top = "".concat(event.pageY + 5, "px"); if (dx < 0) this.dragSelectionHelper.style.left = "".concat(event.pageX + 5, "px"); this.dragSelectionHelper.style.height = "".concat(Math.abs(dy), "px"); this.dragSelectionHelper.style.width = "".concat(Math.abs(dx), "px"); event.preventDefault(); } }, { key: "onDragSelectionMouseUp", value: function onDragSelectionMouseUp() { if (this.dragSelectionHelper) { this.dragSelectionHelper.remove(); this.dragSelectionHelper = null; } document.removeEventListener('mousemove', this.onDragSelectionMouseMove); document.removeEventListener('mouseup', this.onDragSelectionMouseUp); } }, { key: "onRowMouseDown", value: function onRowMouseDown(event) { DomHandler.clearSelection(); if (this.allowRowDrag(event)) { this.enableDragSelection(event.originalEvent); this.anchorRowIndex = event.index; this.rangeRowIndex = event.index; this.anchorRowFirst = this.props.first; } } }, { key: "onRowMouseUp", value: function onRowMouseUp(event) { var isSameRow = event.index === this.anchorRowIndex; if (this.allowRowDrag(event) && !isSameRow) { this.onRangeSelection(event); } } }, { key: "onCellMouseDown", value: function onCellMouseDown(event) { if (this.allowCellDrag(event)) { this.enableDragSelection(event.originalEvent); this.anchorRowIndex = event.rowIndex; this.rangeRowIndex = event.rowIndex; this.anchorRowFirst = this.props.first; this.anchorCellIndex = event.cellIndex; } } }, { key: "onCellMouseUp", value: function onCellMouseUp(event) { var isSameCell = event.rowIndex === this.anchorRowIndex && event.cellIndex === this.anchorCellIndex; if (this.allowCellDrag(event) && !isSameCell) { this.onRangeSelection(event); } } }, { key: "onRowTouchEnd", value: function onRowTouchEnd(event) { this.rowTouched = true; } }, { key: "onRowRightClick", value: function onRowRightClick(event) { if (this.props.onContextMenu) { DomHandler.clearSelection(); if (this.props.onContextMenuSelectionChange) { this.props.onContextMenuSelectionChange({ originalEvent: event.originalEvent, value: event.data }); } if (this.props.onContextMenu) { this.props.onContextMenu({ originalEvent: event.originalEvent, data: event.data }); } event.originalEvent.preventDefault(); } } }, { key: "onRadioClick", value: function onRadioClick(event) { this.onSingleSelection(_objectSpread$1(_objectSpread$1({}, event), {}, { toggleable: true, type: 'radio' })); } }, { key: "onCheckboxClick", value: function onCheckboxClick(event) { this.onMultipleSelection(_objectSpread$1(_objectSpread$1({}, event), {}, { toggleable: true, type: 'checkbox' })); } }, { key: "allowDrag", value: function allowDrag(event) { return this.props.dragSelection && this.isMultipleSelection() && !event.originalEvent.shiftKey; } }, { key: "allowRowDrag", value: function allowRowDrag(event) { return !this.allowCellSelection() && this.allowDrag(event); } }, { key: "allowCellDrag", value: function allowCellDrag(event) { return this.allowCellSelection() && this.allowDrag(event); } }, { key: "allowSelection", value: function allowSelection(event) { var targetNode = event.originalEvent.target.nodeName; if (targetNode === 'INPUT' || targetNode === 'BUTTON' || targetNode === 'A' || DomHandler.hasClass(event.originalEvent.target, 'p-clickable')) { return false; } return true; } }, { key: "allowMetaKeySelection", value: function allowMetaKeySelection(event) { return !this.rowTouched && (!this.props.metaKeySelection || this.props.metaKeySelection && (event.originalEvent.metaKey || event.originalEvent.ctrlKey)); } }, { key: "allowRangeSelection", value: function allowRangeSelection(event) { return this.isMultipleSelection() && event.originalEvent.shiftKey && this.anchorRowIndex !== null; } }, { key: "allowRowSelection", value: function allowRowSelection() { return (this.props.selectionMode || this.props.selectionModeInColumn) && !this.isRadioOnlySelection() && !this.isCheckboxOnlySelection(); } }, { key: "allowCellSelection", value: function allowCellSelection() { return this.props.cellSelection && !this.isRadioSelectionModeInColumn() && !this.isCheckboxSelectionModeInColumn(); } }, { key: "isRadioSelectionMode", value: function isRadioSelectionMode() { return this.props.selectionMode === 'radiobutton'; } }, { key: "isCheckboxSelectionMode", value: function isCheckboxSelectionMode() { return this.props.selectionMode === 'checkbox'; } }, { key: "isRadioSelectionModeInColumn", value: function isRadioSelectionModeInColumn() { return this.props.selectionModeInColumn === 'single'; } }, { key: "isCheckboxSelectionModeInColumn", value: function isCheckboxSelectionModeInColumn() { return this.props.selectionModeInColumn === 'multiple'; } }, { key: "isSingleSelection", value: function isSingleSelection() { return this.props.selectionMode === 'single' && !this.isCheckboxSelectionModeInColumn() || !this.isRadioSelectionMode() && this.isRadioSelectionModeInColumn(); } }, { key: "isMultipleSelection", value: function isMultipleSelection() { return this.props.selectionMode === 'multiple' && !this.isRadioSelectionModeInColumn() || this.isCheckboxSelectionModeInColumn(); } }, { key: "isRadioOnlySelection", value: function isRadioOnlySelection() { return this.isRadioSelectionMode() && this.isRadioSelectionModeInColumn(); } }, { key: "isCheckboxOnlySelection", value: function isCheckboxOnlySelection() { return this.isCheckboxSelectionMode() && this.isCheckboxSelectionModeInColumn(); } }, { key: "isSelected", value: function isSelected(rowData) { if (rowData && this.props.selection) { return this.props.selection instanceof Array ? this.findIndexInSelection(rowData) > -1 : this.equals(rowData, this.props.selection); } return false; } }, { key: "isContextMenuSelected", value: function isContextMenuSelected(rowData) { if (rowData && this.props.contextMenuSelection) { return this.equals(rowData, this.props.contextMenuSelection); } return false; } }, { key: "focusOnElement", value: function focusOnElement(event, isFocused) { var target = event.currentTarget; if (!this.allowCellSelection()) { if (this.isCheckboxSelectionModeInColumn()) { var checkbox = DomHandler.findSingle(target, 'td.p-selection-column .p-checkbox-box'); checkbox && checkbox.focus(); } else if (this.isRadioSelectionModeInColumn()) { var radio = DomHandler.findSingle(target, 'td.p-selection-column input[type="radio"]'); radio && radio.focus(); } } !isFocused && target && target.focus(); } }, { key: "equals", value: function equals(data1, data2) { if (this.allowCellSelection()) return (data1.rowIndex === data2.rowIndex || data1.rowData === data2.rowData) && (data1.field === data2.field || data1.cellIndex === data2.cellIndex);else return this.compareSelectionBy === 'equals' ? data1 === data2 : ObjectUtils.equals(data1, data2, this.props.dataKey); } }, { key: "findIndexInSelection", value: function findIndexInSelection(data) { var _this3 = this; return this.props.selection ? this.props.selection.findIndex(function (d) { return _this3.equals(data, d); }) : -1; } }, { key: "onRowToggle", value: function onRowToggle(event) { var expandedRows; var dataKey = this.props.dataKey; if (dataKey) { var dataKeyValue = String(ObjectUtils.resolveFieldData(event.data, dataKey)); expandedRows = this.props.expandedRows ? _objectSpread$1({}, this.props.expandedRows) : {}; if (expandedRows[dataKeyValue] != null) { delete expandedRows[dataKeyValue]; if (this.props.onRowCollapse) { this.props.onRowCollapse({ originalEvent: event, data: event.data }); } } else { expandedRows[dataKeyValue] = true; if (this.props.onRowExpand) { this.props.onRowExpand({ originalEvent: event, data: event.data }); } } } else { var expandedRowIndex = this.findRowIndex(this.props.expandedRows, event.data); expandedRows = this.props.expandedRows ? _toConsumableArray(this.props.expandedRows) : []; if (expandedRowIndex !== -1) { expandedRows = expandedRows.filter(function (val, i) { return i !== expandedRowIndex; }); if (this.props.onRowCollapse) { this.props.onRowCollapse({ originalEvent: event, data: event.data }); } } else { expandedRows.push(event.data); if (this.props.onRowExpand) { this.props.onRowExpand({ originalEvent: event, data: event.data }); } } } if (this.props.onRowToggle) { this.props.onRowToggle({ data: expandedRows }); } } }, { key: "findRowIndex", value: function findRowIndex(rows, row) { return rows ? rows.findIndex(function (r) { return ObjectUtils.equals(row, r); }) : -1; } }, { key: "isRowExpanded", value: function isRowExpanded(row) { var dataKey = this.props.dataKey; if (dataKey) { var dataKeyValue = String(ObjectUtils.resolveFieldData(row, dataKey)); return this.props.expandedRows && this.props.expandedRows[dataKeyValue] != null; } else { return this.findRowIndex(this.props.expandedRows, row) !== -1; } } }, { key: "onRowEditingToggle", value: function onRowEditingToggle(event) { var editingRows; var dataKey = this.props.dataKey; if (dataKey) { var dataKeyValue = String(ObjectUtils.resolveFieldData(event.data, dataKey)); editingRows = this.props.editingRows ? _objectSpread$1({}, this.props.editingRows) : {}; if (editingRows[dataKeyValue] != null) delete editingRows[dataKeyValue];else editingRows[dataKeyValue] = true; } else { var editingRowIndex = this.findRowIndex(this.props.editingRows, event.data); editingRows = this.props.editingRows ? _toConsumableArray(this.props.editingRows) : []; if (editingRowIndex !== -1) editingRows = editingRows.filter(function (val, i) { return i !== editingRowIndex; });else editingRows.push(event.data); } if (this.props.onRowEditChange) { this.props.onRowEditChange({ originalEvent: event.originalEvent, data: editingRows, index: event.rowIndex }); } } }, { key: "isRowEditing", value: function isRowEditing(row) { var dataKey = this.props.dataKey; if (dataKey) { var dataKeyValue = String(ObjectUtils.resolveFieldData(row, dataKey)); return this.props.editingRows && this.props.editingRows[dataKeyValue] != null; } else { return this.findRowIndex(this.props.editingRows, row) !== -1; } } }, { key: "isSelectionEnabled", value: function isSelectionEnabled() { if (this.props.selectionMode || this.props.selectionModeInColumn != null) { return true; } else { if (Array.isArray(this.props.children)) { for (var i = 0; i < this.props.children.length; i++) { if (this.props.children[i].props.selectionMode) { return true; } } } else { return this.props.children && this.props.children.selectionMode != null; } } return false; } }, { key: "onRowDragStart", value: function onRowDragStart(event, index) { this.rowDragging = true; this.draggedRowIndex = index; event.dataTransfer.setData('text', 'b'); // For firefox } }, { key: "onRowDragEnd", value: function onRowDragEnd(event, index) { this.rowDragging = false; this.draggedRowIndex = null; this.droppedRowIndex = null; } }, { key: "onRowDragOver", value: function onRowDragOver(event, index) { if (this.rowDragging && this.draggedRowIndex !== index) { var rowElement = event.rowElement; var rowY = DomHandler.getOffset(rowElement).top + DomHandler.getWindowScrollTop(); var pageY = event.originalEvent.pageY; var rowMidY = rowY + DomHandler.getOuterHeight(rowElement) / 2; var prevRowElement = rowElement.previousElementSibling; if (pageY < rowMidY) { DomHandler.removeClass(rowElement, 'p-datatable-dragpoint-bottom'); this.droppedRowIndex = index; if (prevRowElement) DomHandler.addClass(prevRowElement, 'p-datatable-dragpoint-bottom');else DomHandler.addClass(rowElement, 'p-datatable-dragpoint-top'); } else { if (prevRowElement) DomHandler.removeClass(prevRowElement, 'p-datatable-dragpoint-bottom');else DomHandler.addClass(rowElement, 'p-datatable-dragpoint-top'); this.droppedRowIndex = index + 1; DomHandler.addClass(rowElement, 'p-datatable-dragpoint-bottom'); } } } }, { key: "onRowDragLeave", value: function onRowDragLeave(event) { var rowElement = event.rowElement; var prevRowElement = rowElement.previousElementSibling; if (prevRowElement) { DomHandler.removeClass(prevRowElement, 'p-datatable-dragpoint-bottom'); } DomHandler.removeClass(rowElement, 'p-datatable-dragpoint-bottom'); DomHandler.removeClass(rowElement, 'p-datatable-dragpoint-top'); } }, { key: "onRowDrop", value: function onRowDrop(event) { if (this.droppedRowIndex != null) { var dropIndex = this.draggedRowIndex > this.droppedRowIndex ? this.droppedRowIndex : this.droppedRowIndex === 0 ? 0 : this.droppedRowIndex - 1; var val = _toConsumableArray(this.props.value); ObjectUtils.reorderArray(val, this.draggedRowIndex, dropIndex); if (this.props.onRowReorder) { this.props.onRowReorder({ originalEvent: event, value: val, dragIndex: this.draggedRowIndex, dropIndex: this.droppedRowIndex }); } } //cleanup this.onRowDragLeave(event); this.onRowDragEnd(event); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this.props.dragSelection) { this.unbindDragSelectionEvents(); } } }, { key: "renderRowGroupHeader", value: function renderRowGroupHeader(rowData, index) { var content = null; if (this.props.rowGroupMode === 'subheader' && this.props.expandableRowGroups) { content = /*#__PURE__*/React.createElement(RowTogglerButton, { onClick: this.onRowToggle, rowData: rowData, expanded: this.isRowExpanded(rowData) }); } return /*#__PURE__*/React.createElement("tr", { role: "row", key: index + '_rowgroupheader', className: "p-rowgroup-header" }, /*#__PURE__*/React.createElement("td", { role: "cell", colSpan: React.Children.count(this.props.children) }, content, /*#__PURE__*/React.createElement("span", { className: "p-rowgroup-header-name" }, this.props.rowGroupHeaderTemplate(rowData, index)))); } }, { key: "renderRowGroupFooter", value: function renderRowGroupFooter(rowData, index) { return /*#__PURE__*/React.createElement("tr", { role: "row", key: index + '_rowgroupfooter', className: "p-rowgroup-footer" }, this.props.rowGroupFooterTemplate(rowData, index)); } }, { key: "render", value: function render() { var _this4 = this; var rows; if (this.props.children) { var rpp = this.props.rows || 0; var first = this.props.first || 0; var selectionEnabled = this.isSelectionEnabled(); var rowGroupMode = this.props.rowGroupMode; var hasSubheaderGrouping = rowGroupMode && rowGroupMode === 'subheader'; var rowSpanGrouping = rowGroupMode && rowGroupMode === 'rowspan'; var rowGroupHeaderExpanded = false; if (this.props.value && this.props.value.length) { rows = []; var startIndex = this.props.lazy ? 0 : this.props.value.length > first ? first : 0; var endIndex = this.props.virtualScroll ? startIndex + rpp * 2 : startIndex + rpp || this.props.value.length; var _loop = function _loop(i) { if (i >= _this4.props.value.length) { return "break"; } var rowData = _this4.props.value[i]; var expanded = _this4.isRowExpanded(rowData); var editing = _this4.isRowEditing(rowData); var selected = selectionEnabled ? _this4.isSelected(_this4.props.value[i]) : false; var contextMenuSelected = _this4.isContextMenuSelected(rowData); var groupRowSpan = void 0; //header row group if (hasSubheaderGrouping) { var currentRowFieldData = ObjectUtils.resolveFieldData(rowData, _this4.props.groupField); var previousRowFieldData = ObjectUtils.resolveFieldData(_this4.props.value[i - 1], _this4.props.groupField); if (i === 0 || currentRowFieldData !== previousRowFieldData) { rows.push(_this4.renderRowGroupHeader(rowData, i)); rowGroupHeaderExpanded = expanded; } } if (rowSpanGrouping) { var rowSpanIndex = i; var _currentRowFieldData = ObjectUtils.resolveFieldData(rowData, _this4.props.sortField); var shouldCountRowSpan = i === startIndex || ObjectUtils.resolveFieldData(_this4.props.value[i - 1], _this4.props.sortField) !== _currentRowFieldData; if (shouldCountRowSpan) { var nextRowFieldData = _currentRowFieldData; groupRowSpan = 0; while (_currentRowFieldData === nextRowFieldData) { groupRowSpan++; var nextRowData = _this4.props.value[++rowSpanIndex]; if (nextRowData) { nextRowFieldData = ObjectUtils.resolveFieldData(nextRowData, _this4.props.sortField); } else { break; } } } } var isRowGroupExpanded = _this4.props.expandableRowGroups && hasSubheaderGrouping && rowGroupHeaderExpanded; if (!_this4.props.expandableRowGroups || isRowGroupExpanded) { //row content var bodyRow = /*#__PURE__*/React.createElement(BodyRow, { tableId: _this4.props.tableId, key: i, value: _this4.props.value, rowData: rowData, rowIndex: i, onClick: _this4.onRowClick, onDoubleClick: _this4.props.onRowDoubleClick, onRightClick: _this4.onRowRightClick, onTouchEnd: _this4.onRowTouchEnd, onMouseDown: _this4.onRowMouseDown, onMouseUp: _this4.onRowMouseUp, onCellMouseDown: _this4.onCellMouseDown, onCellMouseUp: _this4.onCellMouseUp, onRowToggle: _this4.onRowToggle, expanded: expanded, selectionMode: _this4.props.selectionMode, selectOnEdit: _this4.props.selectOnEdit, onRadioClick: _this4.onRadioClick, onCheckboxClick: _this4.onCheckboxClick, selected: selected, contextMenuSelected: contextMenuSelected, rowClassName: _this4.props.rowClassName, cellClassName: _this4.props.cellClassName, sortField: _this4.props.sortField, rowGroupMode: _this4.props.rowGroupMode, groupRowSpan: groupRowSpan, onDragStart: function onDragStart(e) { return _this4.onRowDragStart(e, i); }, onDragEnd: _this4.onRowDragEnd, onDragOver: function onDragOver(e) { return _this4.onRowDragOver(e, i); }, onDragLeave: _this4.onRowDragLeave, onDrop: _this4.onRowDrop, virtualScroll: _this4.props.virtualScroll, virtualRowHeight: _this4.props.virtualRowHeight, editMode: _this4.props.editMode, editing: editing, isRowEditingControlled: !!_this4.props.onRowEditChange, rowEditorValidator: _this4.props.rowEditorValidator, onRowEditInit: _this4.props.onRowEditInit, onRowEditSave: _this4.props.onRowEditSave, onRowEditCancel: _this4.props.onRowEditCancel, onRowEditingToggle: _this4.onRowEditingToggle, showRowReorderElement: _this4.props.showRowReorderElement, showSelectionElement: _this4.props.showSelectionElement, onSelectionChange: _this4.props.onSelectionChange, selectionModeInColumn: _this4.props.selectionModeInColumn, dragSelection: _this4.props.dragSelection, selection: _this4.props.selection, allowRowSelection: _this4.allowRowSelection(), allowCellSelection: _this4.allowCellSelection(), onCellClick: _this4.onCellClick, onEditingCellChange: _this4.props.onEditingCellChange }, _this4.props.children); rows.push(bodyRow); } //row expansion if (expanded && !(hasSubheaderGrouping && _this4.props.expandableRowGroups)) { var expandedRowContent = _this4.props.rowExpansionTemplate(rowData); var id = "".concat(_this4.props.tableId ? _this4.props.tableId + '_' : '', "content_").concat(i, "_expanded"); var expandedRow = /*#__PURE__*/React.createElement("tr", { key: id, id: id, role: "row", className: "p-row-expanded" }, /*#__PURE__*/React.createElement("td", { role: "cell", colSpan: _this4.props.children.length }, expandedRowContent)); rows.push(expandedRow); } //footer row group if (hasSubheaderGrouping && (!_this4.props.expandableRowGroups || isRowGroupExpanded)) { var _currentRowFieldData2 = ObjectUtils.resolveFieldData(rowData, _this4.props.groupField); var _nextRowFieldData = ObjectUtils.resolveFieldData(_this4.props.value[i + 1], _this4.props.groupField); if (i === _this4.props.value.length - 1 || _currentRowFieldData2 !== _nextRowFieldData) { rows.push(_this4.renderRowGroupFooter(rowData, i)); } } }; for (var i = startIndex; i < endIndex; i++) { var _ret = _loop(i); if (_ret === "break") break; } } else { var emptyMessage = this.props.emptyMessage; rows = !this.props.loading && emptyMessage !== null ? /*#__PURE__*/React.createElement("tr", { role: "row", className: "p-datatable-emptymessage" }, /*#__PURE__*/React.createElement("td", { role: "cell", colSpan: this.props.children.length }, typeof emptyMessage === 'function' ? emptyMessage(this.props.frozen) : emptyMessage)) : null; } } return /*#__PURE__*/React.createElement("tbody", { className: "p-datatable-tbody" }, rows); } }]); return TableBody; }(Component); function _createSuper$5(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$5(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$5() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var FooterCell = /*#__PURE__*/function (_Component) { _inherits(FooterCell, _Component); var _super = _createSuper$5(FooterCell); function FooterCell() { _classCallCheck(this, FooterCell); return _super.apply(this, arguments); } _createClass(FooterCell, [{ key: "render", value: function render() { var className = this.props.footerClassName || this.props.className; var footer = ObjectUtils.getJSXElement(this.props.footer, this.props); return /*#__PURE__*/React.createElement("td", { role: "cell", className: className, style: this.props.footerStyle || this.props.style, colSpan: this.props.colSpan, rowSpan: this.props.rowSpan }, footer); } }]); return FooterCell; }(Component); function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var TableFooter = /*#__PURE__*/function (_Component) { _inherits(TableFooter, _Component); var _super = _createSuper$4(TableFooter); function TableFooter() { _classCallCheck(this, TableFooter); return _super.apply(this, arguments); } _createClass(TableFooter, [{ key: "createFooterCells", value: function createFooterCells(root, column, i) { var children = React.Children.toArray(root.props.children); return React.Children.map(children, function (column, i) { return /*#__PURE__*/React.createElement(FooterCell, _extends({ key: i }, column.props)); }); } }, { key: "render", value: function render() { var _this = this; var content; if (this.props.columnGroup) { var rows = React.Children.toArray(this.props.columnGroup.props.children); content = rows.map(function (row, i) { return /*#__PURE__*/React.createElement("tr", { key: i, role: "row" }, _this.createFooterCells(row)); }); } else { content = /*#__PURE__*/React.createElement("tr", { role: "row" }, this.createFooterCells(this)); } return /*#__PURE__*/React.createElement("tfoot", { className: "p-datatable-tfoot" }, content); } }]); return TableFooter; }(Component); 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 HeaderCell = /*#__PURE__*/function (_Component) { _inherits(HeaderCell, _Component); var _super = _createSuper$3(HeaderCell); function HeaderCell(props) { var _this; _classCallCheck(this, HeaderCell); _this = _super.call(this, props); _this.state = { filterValue: '', badgeVisible: false }; _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onFilterChange = _this.onFilterChange.bind(_assertThisInitialized(_this)); _this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this)); _this.onResizerMouseDown = _this.onResizerMouseDown.bind(_assertThisInitialized(_this)); _this.onResizerClick = _this.onResizerClick.bind(_assertThisInitialized(_this)); _this.onResizerDoubleClick = _this.onResizerDoubleClick.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); _this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this)); _this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_this)); _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this)); _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this)); return _this; } _createClass(HeaderCell, [{ key: "onClick", value: function onClick(event) { var _this$props$columnPro = this.props.columnProps, field = _this$props$columnPro.field, sortField = _this$props$columnPro.sortField, sortable = _this$props$columnPro.sortable, sortFunction = _this$props$columnPro.sortFunction; if (!this.isSortableDisabled()) { var targetNode = event.target; if (DomHandler.hasClass(targetNode, 'p-sortable-column') || DomHandler.hasClass(targetNode, 'p-column-title') || DomHandler.hasClass(targetNode, 'p-sortable-column-icon') || DomHandler.hasClass(targetNode.parentElement, 'p-sortable-column-icon')) { this.props.onSort({ originalEvent: event, sortField: sortField || field, sortFunction: sortFunction, sortable: sortable, sortableDisabledFields: this.props.sortableDisabledFields }); DomHandler.clearSelection(); } } } }, { key: "onFilterChange", value: function onFilterChange(e) { var _this2 = this; var filterValue = e.target.value; if (this.props.columnProps.filter && this.props.onFilter) { if (this.filterTimeout) { clearTimeout(this.filterTimeout); } this.filterTimeout = setTimeout(function () { _this2.props.onFilter({ value: filterValue, field: _this2.props.columnProps.filterField || _this2.props.columnProps.field, matchMode: _this2.props.columnProps.filterMatchMode }); _this2.filterTimeout = null; }, this.props.filterDelay); } this.setState({ filterValue: filterValue }); } }, { key: "onResizerMouseDown", value: function onResizerMouseDown(event) { if (this.props.resizableColumns && this.props.onColumnResizeStart) { this.props.onColumnResizeStart({ originalEvent: event, columnEl: event.target.parentElement, columnProps: this.props.columnProps }); event.preventDefault(); } } }, { key: "onResizerClick", value: function onResizerClick(event) { if (this.props.resizableColumns && this.props.onColumnResizerClick) { this.props.onColumnResizerClick({ originalEvent: event, element: event.currentTarget.parentElement, column: this.props.columnProps }); event.preventDefault(); } } }, { key: "onResizerDoubleClick", value: function onResizerDoubleClick(event) { if (this.props.resizableColumns && this.props.onColumnResizerDoubleClick) { this.props.onColumnResizerDoubleClick({ originalEvent: event, element: event.currentTarget.parentElement, column: this.props.columnProps }); event.preventDefault(); } } }, { key: "onMouseDown", value: function onMouseDown(event) { if (this.props.reorderableColumns && this.props.columnProps.reorderable) { if (event.target.nodeName !== 'INPUT') this.el.draggable = true;else if (event.target.nodeName === 'INPUT') this.el.draggable = false; } } }, { key: "onKeyDown", value: function onKeyDown(event) { if (event.key === 'Enter' && event.currentTarget === this.el) { this.onClick(event); event.preventDefault(); } } }, { key: "onDragStart", value: function onDragStart(event) { if (this.props.onDragStart) { this.props.onDragStart({ originalEvent: event, column: this.props.columnProps }); } } }, { key: "onDragOver", value: function onDragOver(event) { if (this.props.onDragOver) { this.props.onDragOver({ originalEvent: event, column: this.props.columnProps }); } } }, { key: "onDragLeave", value: function onDragLeave(event) { if (this.props.onDragLeave) { this.props.onDragLeave({ originalEvent: event, column: this.props.columnProps }); } } }, { key: "onDrop", value: function onDrop(event) { if (this.props.onDrop) { this.props.onDrop({ originalEvent: event, column: this.props.columnProps }); } } }, { key: "getMultiSortMetaDataIndex", value: function getMultiSortMetaDataIndex() { if (this.props.multiSortMeta) { var columnSortField = this.props.columnProps.sortField || this.props.columnProps.field; for (var i = 0; i < this.props.multiSortMeta.length; i++) { if (this.props.multiSortMeta[i].field === columnSortField) { return i; } } } return -1; } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var prevColumnProps = prevProps.columnProps; var columnProps = this.props.columnProps; var filterField = columnProps.filterField || columnProps.field; if (prevColumnProps.sortableDisabled !== columnProps.sortableDisabled || prevColumnProps.sortable !== columnProps.sortable) { this.props.onSortableChange(); } if (this.state.filterValue && prevProps.filters && prevProps.filters[filterField] && (!this.props.filters || !this.props.filters[filterField])) { this.setState({ filterValue: '' }); } } }, { key: "getAriaSort", value: function getAriaSort(sorted, sortOrder) { if (this.props.columnProps.sortable) { var sortIcon = sorted ? sortOrder < 0 ? 'pi-sort-amount-down' : 'pi-sort-amount-up-alt' : 'pi-sort-alt'; if (sortIcon === 'pi-sort-amount-down') return 'descending';else if (sortIcon === 'pi-sort-amount-up-alt') return 'ascending';else return 'none'; } else { return null; } } }, { key: "isSortableDisabled", value: function isSortableDisabled() { return !this.props.columnProps.sortable || this.props.columnProps.sortable && (this.props.allSortableDisabled || this.props.columnProps.sortableDisabled); } }, { key: "isSingleSorted", value: function isSingleSorted() { return this.props.sortField !== null ? this.props.columnProps.field === this.props.sortField || this.props.columnProps.sortField === this.props.sortField : false; } }, { key: "renderSortIcon", value: function renderSortIcon(sorted, sortOrder) { if (this.props.columnProps.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: "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: "render", value: function render() { var _this3 = this; var filterElement, headerCheckbox; if (this.props.columnProps.filter && this.props.renderOptions.renderFilter) { filterElement = this.props.columnProps.filterElement || /*#__PURE__*/React.createElement(InputText, { onChange: this.onFilterChange, type: this.props.columnProps.filterType, value: this.state.filterValue, className: "p-column-filter", placeholder: this.props.columnProps.filterPlaceholder, maxLength: this.props.columnProps.filterMaxLength }); } if (this.props.columnProps.selectionMode === 'multiple' && this.props.renderOptions.renderHeaderCheckbox) { headerCheckbox = /*#__PURE__*/React.createElement(RowCheckbox, { onClick: this.props.onHeaderCheckboxClick, selected: this.props.headerCheckboxSelected, disabled: !this.props.value || this.props.value.length === 0 }); } if (this.props.renderOptions.filterOnly) { return /*#__PURE__*/React.createElement("th", { ref: function ref(el) { return _this3.el = el; }, role: "columnheader", className: classNames('p-filter-column', this.props.columnProps.filterHeaderClassName), style: this.props.columnProps.filterHeaderStyle || this.props.columnProps.style, colSpan: this.props.columnProps.colSpan, rowSpan: this.props.columnProps.rowSpan }, filterElement, headerCheckbox); } else { var sortMetaDataIndex = this.getMultiSortMetaDataIndex(); var multiSortMetaData = sortMetaDataIndex !== -1 ? this.props.multiSortMeta[sortMetaDataIndex] : null; var singleSorted = this.isSingleSorted(); var multipleSorted = multiSortMetaData !== null; var sortOrder = 0; var resizer = this.props.resizableColumns && /*#__PURE__*/React.createElement("span", { className: "p-column-resizer p-clickable", onMouseDown: this.onResizerMouseDown, onClick: this.onResizerClick, onDoubleClick: this.onResizerDoubleClick }); if (singleSorted) sortOrder = this.props.sortOrder;else if (multipleSorted) sortOrder = multiSortMetaData.order; var sorted = this.props.columnProps.sortable && (singleSorted || multipleSorted); var isSortableDisabled = this.isSortableDisabled(); var className = classNames({ 'p-sortable-column': this.props.columnProps.sortable, 'p-highlight': sorted, 'p-sortable-disabled': isSortableDisabled, 'p-resizable-column': this.props.resizableColumns, 'p-selection-column': this.props.columnProps.selectionMode }, this.props.columnProps.headerClassName || this.props.columnProps.className); var sortIconElement = this.renderSortIcon(sorted, sortOrder); var ariaSortData = this.getAriaSort(sorted, sortOrder); var sortBadge = this.renderSortBadge(sortMetaDataIndex); var tabIndex = this.props.columnProps.sortable && !isSortableDisabled ? this.props.tabIndex : null; return /*#__PURE__*/React.createElement("th", { ref: function ref(el) { return _this3.el = el; }, role: "columnheader", tabIndex: tabIndex, className: className, style: this.props.columnProps.headerStyle || this.props.columnProps.style, onClick: this.onClick, onMouseDown: this.onMouseDown, onKeyDown: this.onKeyDown, colSpan: this.props.columnProps.colSpan, rowSpan: this.props.columnProps.rowSpan, "aria-sort": ariaSortData, onDragStart: this.onDragStart, onDragOver: this.onDragOver, onDragLeave: this.onDragLeave, onDrop: this.onDrop }, resizer, /*#__PURE__*/React.createElement("span", { className: "p-column-title" }, this.props.columnProps.header), sortIconElement, sortBadge, filterElement, headerCheckbox); } } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { return { badgeVisible: nextProps.multiSortMeta && nextProps.multiSortMeta.length > 1 }; } }]); return HeaderCell; }(Component); 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$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 TableHeader = /*#__PURE__*/function (_Component) { _inherits(TableHeader, _Component); var _super = _createSuper$2(TableHeader); function TableHeader(props) { var _this; _classCallCheck(this, TableHeader); _this = _super.call(this, props); _this.state = { sortableDisabledFields: [], allSortableDisabled: false }; _this.onSortableChange = _this.onSortableChange.bind(_assertThisInitialized(_this)); return _this; } _createClass(TableHeader, [{ key: "createHeaderCells", value: function createHeaderCells(columns, renderOptions) { var _this2 = this; return React.Children.map(columns, function (column, i) { return /*#__PURE__*/React.createElement(HeaderCell, { key: column.props.columnKey || column.props.field || i, allSortableDisabled: _this2.isAllSortableDisabled(), onSortableChange: _this2.onSortableChange, columnProps: column.props, value: _this2.props.value, onSort: _this2.props.onSort, sortableDisabledFields: _this2.state.sortableDisabledFields, sortMode: _this2.props.sortMode, sortField: _this2.props.sortField, sortOrder: _this2.props.sortOrder, multiSortMeta: _this2.props.multiSortMeta, resizableColumns: _this2.props.resizableColumns, onColumnResizeStart: _this2.props.onColumnResizeStart, onColumnResizerClick: _this2.props.onColumnResizerClick, onColumnResizerDoubleClick: _this2.props.onColumnResizerDoubleClick, filterDelay: _this2.props.filterDelay, onFilter: _this2.props.onFilter, renderOptions: renderOptions, onHeaderCheckboxClick: _this2.props.onHeaderCheckboxClick, headerCheckboxSelected: _this2.props.headerCheckboxSelected, reorderableColumns: _this2.props.reorderableColumns, onDragStart: _this2.props.onColumnDragStart, onDragOver: _this2.props.onColumnDragOver, onDragLeave: _this2.props.onColumnDragLeave, onDrop: _this2.props.onColumnDrop, filters: _this2.props.filters, tabIndex: _this2.props.tabIndex }); }); } }, { key: "hasColumnFilter", value: function hasColumnFilter(columns) { if (columns) { var _iterator = _createForOfIteratorHelper$1(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: "isSingleSort", value: function isSingleSort() { return this.props.sortMode === 'single'; } }, { key: "isMultipleSort", value: function isMultipleSort() { return this.props.sortMode === 'multiple'; } }, { key: "isAllSortableDisabled", value: function isAllSortableDisabled() { return this.isSingleSort() && this.state.allSortableDisabled; } }, { key: "isColumnSorted", value: function isColumnSorted(column) { return this.props.sortField !== null ? column.props.field === this.props.sortField || column.props.sortField === this.props.sortField : false; } }, { key: "updateSortableDisabled", value: function updateSortableDisabled() { var _this3 = this; if (this.isSingleSort() || this.isMultipleSort() && this.props.onSort) { var sortableDisabledFields = []; var allSortableDisabled = false; React.Children.forEach(this.props.children, function (column) { if (column.props.sortableDisabled) { sortableDisabledFields.push(column.props.sortField || column.props.field); if (!allSortableDisabled && _this3.isColumnSorted(column)) { allSortableDisabled = true; } } }); this.setState({ sortableDisabledFields: sortableDisabledFields, allSortableDisabled: allSortableDisabled }); } } }, { key: "onSortableChange", value: function onSortableChange() { this.updateSortableDisabled(); } }, { key: "componentDidMount", value: function componentDidMount() { this.updateSortableDisabled(); } }, { key: "render", value: function render() { var _this4 = this; var content; if (this.props.columnGroup) { var rows = React.Children.toArray(this.props.columnGroup.props.children); content = rows.map(function (row, i) { return /*#__PURE__*/React.createElement("tr", { key: i, role: "row" }, _this4.createHeaderCells(React.Children.toArray(row.props.children), { filterOnly: false, renderFilter: true, renderHeaderCheckbox: true })); }); } else { var columns = React.Children.toArray(this.props.children); if (this.hasColumnFilter(columns)) { content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("tr", { role: "row" }, this.createHeaderCells(columns, { filterOnly: false, renderFilter: false, renderHeaderCheckbox: false })), /*#__PURE__*/React.createElement("tr", { role: "row" }, this.createHeaderCells(columns, { filterOnly: true, renderFilter: true, renderHeaderCheckbox: true }))); } else { content = /*#__PURE__*/React.createElement("tr", { role: "row" }, this.createHeaderCells(columns, { filterOnly: false, renderFilter: false, renderHeaderCheckbox: true })); } } return /*#__PURE__*/React.createElement("thead", { className: "p-datatable-thead" }, content); } }]); return TableHeader; }(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 TableLoadingBody = /*#__PURE__*/function (_Component) { _inherits(TableLoadingBody, _Component); var _super = _createSuper$1(TableLoadingBody); function TableLoadingBody() { _classCallCheck(this, TableLoadingBody); return _super.apply(this, arguments); } _createClass(TableLoadingBody, [{ key: "renderRow", value: function renderRow(index) { var cells = []; for (var i = 0; i < this.props.columns.length; i++) { cells.push( /*#__PURE__*/React.createElement("td", { key: i }, this.props.columns[i].props.loadingBody())); } return /*#__PURE__*/React.createElement("tr", { key: index }, cells); } }, { key: "renderRows", value: function renderRows() { var rows = []; for (var i = 0; i < this.props.rows; i++) { rows.push(this.renderRow(i)); } return rows; } }, { key: "render", value: function render() { var rows = this.renderRows(); return /*#__PURE__*/React.createElement("tbody", { className: "p-datatable-tbody" }, rows); } }]); return TableLoadingBody; }(Component); function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var DataTable = /*#__PURE__*/function (_Component) { _inherits(DataTable, _Component); var _super = _createSuper(DataTable); function DataTable(props) { var _this; _classCallCheck(this, DataTable); _this = _super.call(this, props); _this.state = { d_rows: props.rows, editingCells: [] }; if (!_this.props.onPage) { _this.state.first = props.first; _this.state.rows = props.rows; } if (!_this.props.onSort) { _this.state.sortField = props.sortField; _this.state.sortOrder = props.sortOrder; _this.state.multiSortMeta = props.multiSortMeta; } if (!_this.props.onFilter) { _this.state.filters = props.filters; } if (_this.isStateful()) { _this.restoreState(_this.state); } _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.onHeaderCheckboxClick = _this.onHeaderCheckboxClick.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)); _this.onVirtualScroll = _this.onVirtualScroll.bind(_assertThisInitialized(_this)); _this.onEditingCellChange = _this.onEditingCellChange.bind(_assertThisInitialized(_this)); return _this; } _createClass(DataTable, [{ 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: "getStorage", value: function getStorage() { switch (this.props.stateStorage) { case 'local': return window.localStorage; case 'session': return window.sessionStorage; case 'custom': return null; default: throw new Error(this.props.stateStorage + ' is not a valid value for the state storage, supported values are "local", "session" and "custom".'); } } }, { key: "isCustomStateStorage", value: function isCustomStateStorage() { return this.props.stateStorage === 'custom'; } }, { key: "isStateful", value: function isStateful() { return this.props.stateKey != null || this.isCustomStateStorage(); } }, { key: "saveState", value: function saveState() { var state = {}; if (this.props.paginator) { state.first = this.getFirst(); state.rows = this.getRows(); } var sortField = this.getSortField(); if (sortField) { state.sortField = sortField; state.sortOrder = this.getSortOrder(); } var multiSortMeta = this.getMultiSortMeta(); if (multiSortMeta) { state.multiSortMeta = multiSortMeta; } if (this.hasFilter()) { state.filters = this.getFilters(); } if (this.props.resizableColumns) { this.saveColumnWidths(state); } if (this.props.reorderableColumns) { state.columnOrder = this.state.columnOrder; } if (this.props.expandedRows) { state.expandedRows = this.props.expandedRows; } if (this.props.selection && this.props.onSelectionChange) { state.selection = this.props.selection; } if (this.isCustomStateStorage()) { if (this.props.customSaveState) { this.props.customSaveState(state); } } else { var storage = this.getStorage(); if (Object.keys(state).length) { storage.setItem(this.props.stateKey, JSON.stringify(state)); } } if (this.props.onStateSave) { this.props.onStateSave(state); } } }, { key: "clearState", value: function clearState() { var storage = this.getStorage(); if (storage && this.props.stateKey) { storage.removeItem(this.props.stateKey); } } }, { key: "restoreState", value: function restoreState(state) { var restoredState = {}; if (this.isCustomStateStorage()) { if (this.props.customRestoreState) { restoredState = this.props.customRestoreState(); } } else { var storage = this.getStorage(); var stateString = storage.getItem(this.props.stateKey); if (stateString) { restoredState = JSON.parse(stateString); } } this._restoreState(restoredState, state); } }, { key: "restoreTableState", value: function restoreTableState(restoredState) { var state = this._restoreState(restoredState); if (state && Object.keys(state).length) { this.setState(state); } } }, { key: "_restoreState", value: function _restoreState(restoredState) { var _this2 = this; var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (restoredState && Object.keys(restoredState).length) { if (this.props.paginator) { if (this.props.onPage) { var getOnPageParams = function getOnPageParams(first, rows) { var totalRecords = _this2.getTotalRecords(_this2.processData()); var pageCount = Math.ceil(totalRecords / rows) || 1; var page = Math.floor(first / rows); return { first: first, rows: rows, page: page, pageCount: pageCount }; }; this.props.onPage(getOnPageParams(restoredState.first, restoredState.rows)); } else { state.first = restoredState.first; state.rows = restoredState.rows; } } if (restoredState.sortField) { if (this.props.onSort) { this.props.onSort({ sortField: restoredState.sortField, sortOrder: restoredState.sortOrder }); } else { state.sortField = restoredState.sortField; state.sortOrder = restoredState.sortOrder; } } if (restoredState.multiSortMeta) { if (this.props.onSort) { this.props.onSort({ multiSortMeta: restoredState.multiSortMeta }); } else { state.multiSortMeta = restoredState.multiSortMeta; } } if (restoredState.filters) { if (this.props.onFilter) { this.props.onFilter({ filters: restoredState.filters }); } else { state.filters = restoredState.filters; } } if (this.props.resizableColumns) { this.columnWidthsState = restoredState.columnWidths; this.tableWidthState = restoredState.tableWidth; } if (this.props.reorderableColumns) { state.columnOrder = restoredState.columnOrder; } if (restoredState.expandedRows && this.props.onRowToggle) { this.props.onRowToggle({ data: restoredState.expandedRows }); } if (restoredState.selection && this.props.onSelectionChange) { this.props.onSelectionChange({ value: restoredState.selection }); } if (this.props.onStateRestore) { this.props.onStateRestore(restoredState); } } return state; } }, { key: "saveColumnWidths", value: function saveColumnWidths(state) { var widths = []; var headers = DomHandler.find(this.container, '.p-datatable-thead > tr > th.p-resizable-column'); headers.map(function (header) { return widths.push(DomHandler.getOuterWidth(header)); }); state.columnWidths = widths.join(','); if (this.props.columnResizeMode === 'expand') { state.tableWidth = this.props.scrollable ? DomHandler.findSingle(this.container, '.p-datatable-scrollable-header-table').style.width : DomHandler.getOuterWidth(this.table) + 'px'; } } }, { key: "restoreColumnWidths", value: function restoreColumnWidths() { if (this.columnWidthsState) { var widths = this.columnWidthsState.split(','); if (this.props.columnResizeMode === 'expand' && this.tableWidthState) { if (this.props.scrollable) { this.setScrollableItemsWidthOnExpandResize(null, this.tableWidthState, 0); } else { this.table.style.width = this.tableWidthState; this.container.style.width = this.tableWidthState; } } if (this.props.scrollable) { var headerCols = DomHandler.find(this.container, '.p-datatable-scrollable-header-table > colgroup > col'); var bodyCols = DomHandler.find(this.container, '.p-datatable-scrollable-body-table > colgroup > col'); headerCols.map(function (col, index) { return col.style.width = widths[index] + 'px'; }); bodyCols.map(function (col, index) { return col.style.width = widths[index] + 'px'; }); } else { var headers = DomHandler.find(this.table, '.p-datatable-thead > tr > th'); headers.map(function (header, index) { return header.style.width = widths[index] + 'px'; }); } } } }, { key: "onPageChange", value: function onPageChange(event) { if (this.props.onPage) this.props.onPage(event);else this.setState({ first: event.first, rows: event.rows }); if (this.props.onValueChange) { this.props.onValueChange(this.processData()); } } }, { key: "createPaginator", value: function createPaginator(position, totalRecords, data) { 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: "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; var sortableDisabledFields = event.sortableDisabledFields; multiSortMeta = _toConsumableArray(this.getMultiSortMeta() || []); var sortMeta = multiSortMeta.find(function (sortMeta) { return sortMeta.field === sortField; }); sortOrder = sortMeta ? this.getCalculatedSortOrder(sortMeta.order) : sortOrder; var newMetaData = { field: sortField, order: sortOrder }; if (sortOrder) { multiSortMeta = metaKey ? multiSortMeta : multiSortMeta.filter(function (meta) { return sortableDisabledFields.some(function (field) { return field === meta.field; }); }); this.addSortMeta(newMetaData, multiSortMeta); } else if (this.props.removableSort) { this.removeSortMeta(newMetaData, multiSortMeta); } eventMeta = { multiSortMeta: multiSortMeta }; } else { sortOrder = this.getSortField() === sortField ? this.getCalculatedSortOrder(this.getSortOrder()) : sortOrder; if (this.props.removableSort) { sortField = sortOrder ? sortField : null; } eventMeta = { sortField: sortField, sortOrder: sortOrder }; } if (this.props.onSort) { this.props.onSort(eventMeta); } else { eventMeta.first = 0; this.setState(eventMeta); } if (this.props.onValueChange) { this.props.onValueChange(this.processData({ sortField: sortField, sortOrder: sortOrder, multiSortMeta: multiSortMeta })); } } }, { key: "getCalculatedSortOrder", value: function getCalculatedSortOrder(currentOrder) { return this.props.removableSort ? this.props.defaultSortOrder === currentOrder ? currentOrder * -1 : 0 : currentOrder * -1; } }, { key: "addSortMeta", value: function addSortMeta(meta, multiSortMeta) { var index = -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, sortField, sortOrder) { var value = _toConsumableArray(data); if (this.columnSortable && this.columnSortFunction) { value = this.columnSortFunction({ field: this.getSortField(), order: this.getSortOrder() }); } else { value.sort(function (data1, data2) { var value1 = ObjectUtils.resolveFieldData(data1, sortField); var value2 = ObjectUtils.resolveFieldData(data2, sortField); var result = null; if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2, undefined, { numeric: true });else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0; return sortOrder * result; }); } return value; } }, { key: "sortMultiple", value: function sortMultiple(data, multiSortMeta) { var _this3 = this; var value = _toConsumableArray(data); if (this.columnSortable && this.columnSortFunction) { var meta = multiSortMeta.find(function (meta) { return meta.field === _this3.columnField; }); var field = this.columnField; var order = meta ? meta.order : this.defaultSortOrder; value = this.columnSortFunction({ field: field, order: order }); } else { value.sort(function (data1, data2) { return _this3.multisortField(data1, data2, multiSortMeta, 0); }); } return value; } }, { key: "multisortField", value: function multisortField(data1, data2, multiSortMeta, index) { var value1 = ObjectUtils.resolveFieldData(data1, multiSortMeta[index].field); var value2 = ObjectUtils.resolveFieldData(data2, multiSortMeta[index].field); var result = null; if (typeof value1 === 'string' || value1 instanceof String) { if (value1.localeCompare && value1 !== value2) { return multiSortMeta[index].order * value1.localeCompare(value2, undefined, { numeric: true }); } } else { result = value1 < value2 ? -1 : 1; } if (value1 === value2) { return multiSortMeta.length - 1 > index ? this.multisortField(data1, data2, multiSortMeta, index + 1) : 0; } return multiSortMeta[index].order * result; } }, { key: "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 }); } if (this.props.onValueChange) { this.props.onValueChange(this.processData({ filters: newFilters })); } } }, { key: "hasFilter", value: function hasFilter() { var filters = this.getFilters() || this.props.globalFilter; 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: "hasFooter", value: function hasFooter() { if (this.props.children) { if (this.props.footerColumnGroup) { return true; } else { return this.hasChildrenFooter(this.props.children); } } else { return false; } } }, { key: "hasChildrenFooter", value: function hasChildrenFooter(children) { var hasFooter = false; if (children) { if (children instanceof Array) { for (var i = 0; i < children.length; i++) { hasFooter = hasFooter || this.hasChildrenFooter(children[i]); } } else { return children.props && children.props.footer !== null; } } return hasFooter; } }, { key: "onColumnResizeStart", value: function onColumnResizeStart(event) { var containerLeft = DomHandler.getOffset(this.container).left; this.resizeColumn = event.columnEl; this.resizeColumnProps = event.columnProps; this.columnResizing = true; this.lastResizerHelperX = event.originalEvent.pageX - containerLeft + this.container.scrollLeft; this.bindColumnResizeEvents(); } }, { key: "onColumnResize", value: function onColumnResize(event) { var containerLeft = DomHandler.getOffset(this.container).left; DomHandler.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.findSingle(scrollableView, 'table.p-datatable-scrollable-body-table'); var scrollableHeaderTable = DomHandler.findSingle(scrollableView, 'table.p-datatable-scrollable-header-table'); var scrollableFooterTable = DomHandler.findSingle(scrollableView, 'table.p-datatable-scrollable-footer-table'); var resizeColumnIndex = DomHandler.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) { this.setScrollableItemsWidthOnExpandResize(this.resizeColumn, newColumnWidth, delta); } 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 }); } if (this.isStateful()) { this.saveState(); } } this.resizerHelper.style.display = 'none'; this.resizeColumn = null; this.resizeColumnProps = null; DomHandler.removeClass(this.container, 'p-unselectable-text'); this.unbindColumnResizeEvents(); } }, { key: "setScrollableItemsWidthOnExpandResize", value: function setScrollableItemsWidthOnExpandResize(column, newColumnWidth, delta) { var scrollableView = column ? this.findParentScrollableView(column) : this.container; var scrollableBody = DomHandler.findSingle(scrollableView, '.p-datatable-scrollable-body'); var scrollableHeader = DomHandler.findSingle(scrollableView, '.p-datatable-scrollable-header'); var scrollableFooter = DomHandler.findSingle(scrollableView, '.p-datatable-scrollable-footer'); var scrollableBodyTable = DomHandler.findSingle(scrollableBody, 'table.p-datatable-scrollable-body-table'); var scrollableHeaderTable = DomHandler.findSingle(scrollableHeader, 'table.p-datatable-scrollable-header-table'); var scrollableFooterTable = DomHandler.findSingle(scrollableFooter, 'table.p-datatable-scrollable-footer-table'); var scrollableBodyTableWidth = column ? scrollableBodyTable.offsetWidth + delta : newColumnWidth; var scrollableHeaderTableWidth = column ? scrollableHeaderTable.offsetWidth + delta : newColumnWidth; var isContainerInViewport = this.container.offsetWidth >= scrollableBodyTableWidth; var setWidth = function setWidth(container, table, width, isContainerInViewport) { if (container && table) { container.style.width = isContainerInViewport ? width + DomHandler.calculateScrollbarWidth(scrollableBody) + 'px' : 'auto'; table.style.width = width + 'px'; } }; setWidth(scrollableBody, scrollableBodyTable, scrollableBodyTableWidth, isContainerInViewport); setWidth(scrollableHeader, scrollableHeaderTable, scrollableHeaderTableWidth, isContainerInViewport); setWidth(scrollableFooter, scrollableFooterTable, scrollableHeaderTableWidth, isContainerInViewport); if (column) { var resizeColumnIndex = DomHandler.index(column); this.resizeColGroup(scrollableHeaderTable, resizeColumnIndex, newColumnWidth, null); this.resizeColGroup(scrollableBodyTable, resizeColumnIndex, newColumnWidth, null); this.resizeColGroup(scrollableFooterTable, resizeColumnIndex, newColumnWidth, null); } } }, { key: "findParentScrollableView", value: function findParentScrollableView(column) { if (column) { var parent = column.parentElement; while (parent && !DomHandler.hasClass(parent, 'p-datatable-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: "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: "onColumnDragStart", value: function onColumnDragStart(e) { var event = e.originalEvent, column = e.column; if (this.columnResizing) { event.preventDefault(); return; } this.iconWidth = DomHandler.getHiddenElementOuterWidth(this.reorderIndicatorUp); this.iconHeight = DomHandler.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.getOffset(this.container); var dropHeaderOffset = DomHandler.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.index(this.draggedColumnEl); var dropIndex = DomHandler.index(this.findParentHeader(event.currentTarget)); var allowDrop = dragIndex !== dropIndex; if (allowDrop && (dropIndex - dragIndex === 1 && this.dropPosition === -1 || dragIndex - dropIndex === 1 && this.dropPosition === 1)) { allowDrop = false; } if (allowDrop) { var columns = this.state.columnOrder ? this.getColumns() : React.Children.toArray(this.props.children); var isSameColumn = function isSameColumn(col1, col2) { return col1.columnKey || col2.columnKey ? ObjectUtils.equals(col1, col2, 'columnKey') : ObjectUtils.equals(col1, col2, 'field'); }; var dragColIndex = columns.findIndex(function (child) { return isSameColumn(child.props, _this5.draggedColumn); }); var dropColIndex = columns.findIndex(function (child) { return isSameColumn(child.props, 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({ originalEvent: event, 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: "onVirtualScroll", value: function onVirtualScroll(event) { var _this6 = this; if (this.virtualScrollTimer) { clearTimeout(this.virtualScrollTimer); } this.virtualScrollTimer = setTimeout(function () { if (_this6.props.onVirtualScroll) { _this6.props.onVirtualScroll({ first: (event.page - 1) * _this6.props.rows, rows: _this6.props.virtualScroll ? _this6.props.rows * 2 : _this6.props.rows }); } }, this.props.virtualScrollDelay); } }, { key: "hasEditingCell", value: function hasEditingCell() { return this.state.editingCells && this.state.editingCells.length !== 0; } }, { key: "onEditingCellChange", value: function onEditingCellChange(event) { var _this7 = this; var rowIndex = event.rowIndex, cellIndex = event.cellIndex, editing = event.editing; var editingCells = _toConsumableArray(this.state.editingCells); if (editing) editingCells.push({ rowIndex: rowIndex, cellIndex: cellIndex });else editingCells = editingCells.filter(function (cell) { return !(cell.rowIndex === rowIndex && cell.cellIndex === cellIndex); }); this.setState({ editingCells: editingCells }, function () { _this7.props.onValueChange && _this7.props.onValueChange(_this7.processData()); }); } }, { key: "exportCSV", value: function exportCSV(options) { var _this8 = this; var data; var csv = "\uFEFF"; var columns = this.getColumns(); if (options && options.selectionOnly) { data = this.props.selection || []; } else { data = [].concat(_toConsumableArray(this.props.frozenValue || []), _toConsumableArray(this.processData() || [])); } //headers columns.forEach(function (column, i) { var _column$props = column.props, field = _column$props.field, header = _column$props.header, exportable = _column$props.exportable; if (exportable && field) { csv += '"' + (header || field) + '"'; if (i < columns.length - 1) { csv += _this8.props.csvSeparator; } } }); //body data.forEach(function (record) { csv += '\n'; columns.forEach(function (column, i) { var _column$props2 = column.props, field = _column$props2.field, exportable = _column$props2.exportable; if (exportable && field) { var cellData = ObjectUtils.resolveFieldData(record, field); if (cellData != null) cellData = _this8.props.exportFunction ? _this8.props.exportFunction({ data: cellData, field: field }) : String(cellData).replace(/"/g, '""');else cellData = ''; csv += '"' + cellData + '"'; if (i < columns.length - 1) { csv += _this8.props.csvSeparator; } } }); }); var blob = new Blob([csv], { type: 'application/csv;charset=utf-8;' }); if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveOrOpenBlob(blob, this.props.exportFilename + '.csv'); } else { var link = document.createElement("a"); if (link.download !== undefined) { link.setAttribute('href', URL.createObjectURL(blob)); link.setAttribute('download', this.props.exportFilename + '.csv'); link.style.display = 'none'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } else { csv = 'data:text/csv;charset=utf-8,' + csv; window.open(encodeURI(csv)); } } } }, { key: "closeEditingCell", value: function closeEditingCell() { if (this.props.editMode !== "row") { document.body.click(); } } }, { key: "onHeaderCheckboxClick", value: function onHeaderCheckboxClick(event) { var originalEvent = event.originalEvent; var selection; if (!event.checked) { var visibleData = this.hasFilter() ? this.processData() : this.props.value; selection = _toConsumableArray(visibleData); this.props.onAllRowsSelect && this.props.onAllRowsSelect({ originalEvent: originalEvent, data: selection, type: 'all' }); } else { selection = []; this.props.onAllRowsUnselect && this.props.onAllRowsUnselect({ originalEvent: originalEvent, data: selection, type: 'all' }); } if (this.props.onSelectionChange) { this.props.onSelectionChange({ originalEvent: originalEvent, value: selection }); } } }, { key: "filterLocal", value: function filterLocal(value, localFilters) { var filteredValue = []; var filters = localFilters || this.getFilters(); var columns = React.Children.toArray(this.props.children); for (var i = 0; i < value.length; i++) { var localMatch = true; var globalMatch = false; for (var j = 0; j < columns.length; j++) { var col = columns[j]; var columnField = col.props.filterField || col.props.field; var filterMeta = filters ? filters[columnField] : null; //local if (filterMeta) { var filterValue = filterMeta.value; var dataFieldValue = ObjectUtils.resolveFieldData(value[i], columnField); var filterMatchMode = filterMeta.matchMode || col.props.filterMatchMode; var filterConstraint = filterMatchMode === 'custom' ? col.props.filterFunction : FilterUtils[filterMatchMode]; var options = { rowData: value[i], filters: filters, props: this.props, column: { filterMeta: filterMeta, filterField: columnField, props: col.props } }; if (filterConstraint !== null && !filterConstraint(dataFieldValue, filterValue, this.props.filterLocale, options)) { localMatch = false; } if (!localMatch) { break; } } if (!col.props.excludeGlobalFilter && this.props.globalFilter && !globalMatch) { globalMatch = FilterUtils['contains'](ObjectUtils.resolveFieldData(value[i], columnField), this.props.globalFilter, this.props.filterLocale); } } var matches = localMatch; if (this.props.globalFilter) { matches = localMatch && globalMatch; } if (matches) { filteredValue.push(value[i]); } } if (filteredValue.length === value.length) { filteredValue = value; } return filteredValue; } }, { key: "processData", value: function processData(localState) { var data = this.props.value; if (!this.props.lazy && !this.hasEditingCell()) { if (data && data.length) { var sortField = localState && localState.sortField || this.getSortField(); var sortOrder = localState && localState.sortOrder || this.getSortOrder(); var multiSortMeta = localState && localState.multiSortMeta || this.getMultiSortMeta(); if (sortField || multiSortMeta && multiSortMeta.length) { if (this.props.sortMode === 'single') data = this.sortSingle(data, sortField, sortOrder);else if (this.props.sortMode === 'multiple') data = this.sortMultiple(data, multiSortMeta); } var localFilters = localState && localState.filters || this.getFilters(); if (localFilters || this.props.globalFilter) { data = this.filterLocal(data, localFilters); } } } return data; } }, { key: "isAllSelected", value: function isAllSelected() { var visibleData = this.hasFilter() ? this.processData() : this.props.value; if (this.props.lazy) { return this.props.selection && this.props.totalRecords && this.props.selection.length === this.props.totalRecords; } return this.props.selection && visibleData && visibleData.length && this.props.selection.length === visibleData.length; } }, { key: "getFrozenColumns", value: function getFrozenColumns(columns) { var frozenColumns = null; var _iterator2 = _createForOfIteratorHelper(columns), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var col = _step2.value; if (col.props.frozen) { frozenColumns = frozenColumns || []; frozenColumns.push(col); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return frozenColumns; } }, { key: "getScrollableColumns", value: function getScrollableColumns(columns) { var scrollableColumns = null; var _iterator3 = _createForOfIteratorHelper(columns), _step3; try { for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { var col = _step3.value; if (!col.props.frozen) { scrollableColumns = scrollableColumns || []; scrollableColumns.push(col); } } } catch (err) { _iterator3.e(err); } finally { _iterator3.f(); } return scrollableColumns; } }, { key: "getSelectionModeInColumn", value: function getSelectionModeInColumn(columns) { if (Array.isArray(columns)) { var _iterator4 = _createForOfIteratorHelper(columns), _step4; try { for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { var col = _step4.value; if (col.props.selectionMode) return col.props.selectionMode; } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } } return null; } }, { key: "createTableHeader", value: function createTableHeader(value, columns, columnGroup) { return /*#__PURE__*/React.createElement(TableHeader, { value: value, sortMode: this.props.sortMode, onSort: this.onSort, sortField: this.getSortField(), sortOrder: this.getSortOrder(), multiSortMeta: this.getMultiSortMeta(), columnGroup: columnGroup, resizableColumns: this.props.resizableColumns, onColumnResizeStart: this.onColumnResizeStart, onColumnResizerClick: this.props.onColumnResizerClick, onColumnResizerDoubleClick: this.props.onColumnResizerDoubleClick, onFilter: this.onFilter, filterDelay: this.props.filterDelay, onHeaderCheckboxClick: this.onHeaderCheckboxClick, headerCheckboxSelected: this.isAllSelected(), reorderableColumns: this.props.reorderableColumns, onColumnDragStart: this.onColumnDragStart, filters: this.getFilters(), onColumnDragOver: this.onColumnDragOver, onColumnDragLeave: this.onColumnDragLeave, onColumnDrop: this.onColumnDrop, tabIndex: this.props.tabIndex }, columns); } }, { key: "createTableBody", value: function createTableBody(value, columns, frozen, selectionModeInColumn) { return /*#__PURE__*/React.createElement(TableBody, { tableId: this.props.id, value: value, first: this.getFirst(), rows: this.getRows(), lazy: this.props.lazy, paginator: this.props.paginator, dataKey: this.props.dataKey, compareSelectionBy: this.props.compareSelectionBy, selectionMode: this.props.selectionMode, selection: this.props.selection, metaKeySelection: this.props.metaKeySelection, frozen: frozen, selectionModeInColumn: selectionModeInColumn, onSelectionChange: this.props.onSelectionChange, onRowClick: this.props.onRowClick, onRowDoubleClick: this.props.onRowDoubleClick, onRowSelect: this.props.onRowSelect, onRowUnselect: this.props.onRowUnselect, contextMenuSelection: this.props.contextMenuSelection, onContextMenuSelectionChange: this.props.onContextMenuSelectionChange, onContextMenu: this.props.onContextMenu, expandedRows: this.props.expandedRows, onRowToggle: this.props.onRowToggle, rowExpansionTemplate: this.props.rowExpansionTemplate, selectOnEdit: this.props.selectOnEdit, onRowExpand: this.props.onRowExpand, onRowCollapse: this.props.onRowCollapse, emptyMessage: this.props.emptyMessage, virtualScroll: this.props.virtualScroll, virtualRowHeight: this.props.virtualRowHeight, loading: this.props.loading, groupField: this.props.groupField, rowGroupMode: this.props.rowGroupMode, rowGroupHeaderTemplate: this.props.rowGroupHeaderTemplate, rowGroupFooterTemplate: this.props.rowGroupFooterTemplate, sortField: this.getSortField(), rowClassName: this.props.rowClassName, cellClassName: this.props.cellClassName, onRowReorder: this.props.onRowReorder, editMode: this.props.editMode, editingRows: this.props.editingRows, rowEditorValidator: this.props.rowEditorValidator, onRowEditInit: this.props.onRowEditInit, onRowEditSave: this.props.onRowEditSave, onRowEditCancel: this.props.onRowEditCancel, onRowEditChange: this.props.onRowEditChange, expandableRowGroups: this.props.expandableRowGroups, showRowReorderElement: this.props.showRowReorderElement, showSelectionElement: this.props.showSelectionElement, dragSelection: this.props.dragSelection, cellSelection: this.props.cellSelection, onCellClick: this.props.onCellClick, onCellSelect: this.props.onCellSelect, onCellUnselect: this.props.onCellUnselect, onEditingCellChange: this.onEditingCellChange }, columns); } }, { key: "createTableLoadingBody", value: function createTableLoadingBody(columns) { if (this.props.virtualScroll) { return /*#__PURE__*/React.createElement(TableLoadingBody, { columns: columns, rows: this.getRows() }); } else { return null; } } }, { key: "createTableFooter", value: function createTableFooter(columns, columnGroup) { if (this.hasFooter()) return /*#__PURE__*/React.createElement(TableFooter, { columnGroup: columnGroup }, columns);else return null; } }, { key: "createScrollableView", value: function createScrollableView(value, columns, frozen, headerColumnGroup, footerColumnGroup, totalRecords, selectionModeInColumn) { return /*#__PURE__*/React.createElement(ScrollableView, { columns: columns, header: this.createTableHeader(value, columns, headerColumnGroup), body: this.createTableBody(value, columns, frozen, selectionModeInColumn), loadingBody: this.createTableLoadingBody(columns), frozenBody: this.props.frozenValue ? this.createTableBody(this.props.frozenValue, columns, true, selectionModeInColumn) : null, footer: this.createTableFooter(columns, footerColumnGroup), tableStyle: this.props.tableStyle, tableClassName: this.props.tableClassName, scrollHeight: this.props.scrollHeight, frozen: frozen, frozenWidth: this.props.frozenWidth, virtualScroll: this.props.virtualScroll, virtualRowHeight: this.props.virtualRowHeight, rows: this.props.rows, totalRecords: totalRecords, onVirtualScroll: this.onVirtualScroll, loading: this.props.loading }); } }, { 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 _iterator5 = _createForOfIteratorHelper(this.state.columnOrder), _step5; try { for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { var columnKey = _step5.value; var column = this.findColumnByKey(columns, columnKey); if (column) { orderedColumns.push(column); } } } catch (err) { _iterator5.e(err); } finally { _iterator5.f(); } return [].concat(orderedColumns, _toConsumableArray(columns.filter(function (item) { return orderedColumns.indexOf(item) < 0; }))); } else { return columns; } } return null; } }, { 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: "getTotalRecords", value: function getTotalRecords(data) { return this.props.lazy ? this.props.totalRecords : data ? data.length : 0; } }, { key: "reset", value: function reset() { var state = {}; if (!this.props.onPage) { state.first = this.props.first; state.rows = this.props.rows; } if (!this.props.onSort) { state.sortField = this.props.sortField; state.sortOrder = this.props.sortOrder; state.multiSortMeta = this.props.multiSortMeta; } if (!this.props.onFilter) { state.filters = this.props.filters; } this.resetColumnOrder(); if (Object.keys(state).length) { this.setState(state); } } }, { key: "resetColumnOrder", value: function resetColumnOrder() { var columns = React.Children.toArray(this.props.children); var columnOrder = []; var _iterator6 = _createForOfIteratorHelper(columns), _step6; try { for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) { var column = _step6.value; columnOrder.push(column.props.columnKey || column.props.field); } } catch (err) { _iterator6.e(err); } finally { _iterator6.f(); } this.setState({ columnOrder: columnOrder }); } }, { key: "renderLoader", value: function renderLoader() { var iconClassName = classNames('p-datatable-loading-icon pi-spin', this.props.loadingIcon); return /*#__PURE__*/React.createElement("div", { className: "p-datatable-loading-overlay p-component-overlay" }, /*#__PURE__*/React.createElement("i", { className: iconClassName })); } }, { key: "componentDidMount", value: function componentDidMount() { if (this.isStateful() && this.props.resizableColumns) { this.restoreColumnWidths(); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps, prevState) { if (this.isStateful()) { this.saveState(); } if (prevProps.globalFilter !== this.props.globalFilter) { this.filter(this.props.globalFilter, 'globalFilter', 'contains'); } } }, { key: "render", value: function render() { var _this9 = this; var value = this.processData(); var columns = this.getColumns(); var totalRecords = this.getTotalRecords(value); var selectionModeInColumn = this.getSelectionModeInColumn(columns); var className = classNames('p-datatable p-component', { 'p-datatable-resizable': this.props.resizableColumns, 'p-datatable-resizable-fit': this.props.resizableColumns && this.props.columnResizeMode === 'fit', 'p-datatable-scrollable': this.props.scrollable, 'p-datatable-virtual-scrollable': this.props.virtualScroll, 'p-datatable-striped': this.props.stripedRows, 'p-datatable-gridlines': this.props.showGridlines, 'p-datatable-auto-layout': this.props.autoLayout, 'p-datatable-hoverable-rows': this.props.rowHover || this.props.selectionMode || selectionModeInColumn }, this.props.className); 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 headerFacet = this.props.header && /*#__PURE__*/React.createElement("div", { className: "p-datatable-header" }, this.props.header); var footerFacet = this.props.footer && /*#__PURE__*/React.createElement("div", { className: "p-datatable-footer" }, this.props.footer); var resizeHelper = this.props.resizableColumns && /*#__PURE__*/React.createElement("div", { ref: function ref(el) { _this9.resizerHelper = el; }, className: "p-column-resizer-helper p-highlight", style: { display: 'none' } }); var tableContent = null; var resizeIndicatorUp = this.props.reorderableColumns && /*#__PURE__*/React.createElement("span", { ref: function ref(el) { _this9.reorderIndicatorUp = el; }, className: "pi pi-arrow-down p-datatable-reorder-indicator-up", style: { position: 'absolute', display: 'none' } }); var resizeIndicatorDown = this.props.reorderableColumns && /*#__PURE__*/React.createElement("span", { ref: function ref(el) { _this9.reorderIndicatorDown = el; }, className: "pi pi-arrow-up p-datatable-reorder-indicator-down", style: { position: 'absolute', display: 'none' } }); var loader; if (this.props.loading) { loader = this.renderLoader(); } if (Array.isArray(columns)) { if (this.props.scrollable) { 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, totalRecords, selectionModeInColumn); } scrollableView = this.createScrollableView(value, scrollableColumns, false, this.props.headerColumnGroup, this.props.footerColumnGroup, totalRecords, selectionModeInColumn); tableContent = /*#__PURE__*/React.createElement("div", { className: "p-datatable-scrollable-wrapper" }, frozenView, scrollableView); } else { var tableHeader = this.createTableHeader(value, columns, this.props.headerColumnGroup); var tableBody = this.createTableBody(value, columns, false, selectionModeInColumn); var tableFooter = this.createTableFooter(columns, this.props.footerColumnGroup); tableContent = /*#__PURE__*/React.createElement("div", { className: "p-datatable-wrapper" }, /*#__PURE__*/React.createElement("table", { style: this.props.tableStyle, role: "grid", className: this.props.tableClassName, ref: function ref(el) { _this9.table = el; } }, tableHeader, tableFooter, tableBody)); } } return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: className, style: this.props.style, ref: function ref(el) { _this9.container = el; }, "data-scrollselectors": ".p-datatable-scrollable-body, .p-datatable-unfrozen-view .p-datatable-scrollable-body" }, loader, headerFacet, paginatorTop, tableContent, paginatorBottom, footerFacet, resizeHelper, resizeIndicatorUp, resizeIndicatorDown); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { if (nextProps.rows !== prevState.d_rows && !nextProps.onPage) { return { rows: nextProps.rows, d_rows: nextProps.rows }; } return null; } }]); return DataTable; }(Component); _defineProperty(DataTable, "defaultProps", { id: null, value: null, header: null, footer: null, style: null, className: null, tableStyle: null, tableClassName: null, paginator: false, paginatorPosition: 'bottom', alwaysShowPaginator: true, paginatorClassName: null, paginatorTemplate: 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown', paginatorLeft: null, paginatorRight: null, paginatorDropdownAppendTo: null, pageLinkSize: 5, rowsPerPageOptions: null, currentPageReportTemplate: '({currentPage} of {totalPages})', first: 0, rows: null, totalRecords: null, lazy: false, sortField: null, sortOrder: null, multiSortMeta: null, sortMode: 'single', defaultSortOrder: 1, removableSort: false, emptyMessage: 'No records found', selectionMode: null, dragSelection: false, cellSelection: false, selection: null, onSelectionChange: null, contextMenuSelection: null, onContextMenuSelectionChange: null, compareSelectionBy: 'deepEquals', dataKey: null, metaKeySelection: true, selectOnEdit: true, headerColumnGroup: null, footerColumnGroup: null, frozenHeaderColumnGroup: null, frozenFooterColumnGroup: null, rowExpansionTemplate: null, expandedRows: null, onRowToggle: null, resizableColumns: false, columnResizeMode: 'fit', reorderableColumns: false, filters: null, globalFilter: null, filterDelay: 300, filterLocale: undefined, scrollable: false, scrollHeight: null, virtualScroll: false, virtualScrollDelay: 150, virtualRowHeight: 28, frozenWidth: null, frozenValue: null, csvSeparator: ',', exportFilename: 'download', rowGroupMode: null, autoLayout: false, rowClassName: null, cellClassName: null, rowGroupHeaderTemplate: null, rowGroupFooterTemplate: null, loading: false, loadingIcon: 'pi pi-spinner', tabIndex: 0, stateKey: null, stateStorage: 'session', groupField: null, editMode: 'cell', editingRows: null, expandableRowGroups: false, rowHover: false, showGridlines: false, stripedRows: false, showSelectionElement: null, showRowReorderElement: null, onColumnResizeEnd: null, onColumnResizerClick: null, onColumnResizerDoubleClick: null, onSort: null, onPage: null, onFilter: null, onVirtualScroll: null, onAllRowsSelect: null, onAllRowsUnselect: null, onRowClick: null, onRowDoubleClick: null, onRowSelect: null, onRowUnselect: null, onRowExpand: null, onRowCollapse: null, onContextMenu: null, onColReorder: null, onCellClick: null, onCellSelect: null, onCellUnselect: null, onRowReorder: null, onValueChange: null, rowEditorValidator: null, onRowEditInit: null, onRowEditSave: null, onRowEditCancel: null, onRowEditChange: null, exportFunction: null, customSaveState: null, customRestoreState: null, onStateSave: null, onStateRestore: null }); export { DataTable };
ajax/libs/material-ui/4.9.2/es/FilledInput/FilledInput.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { refType } from '@material-ui/utils'; import InputBase from '../InputBase'; import withStyles from '../styles/withStyles'; export const styles = theme => { const light = theme.palette.type === 'light'; const bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)'; const backgroundColor = light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)'; return { /* Styles applied to the root element. */ root: { position: 'relative', backgroundColor, borderTopLeftRadius: theme.shape.borderRadius, borderTopRightRadius: theme.shape.borderRadius, transition: theme.transitions.create('background-color', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut }), '&:hover': { backgroundColor: light ? 'rgba(0, 0, 0, 0.13)' : 'rgba(255, 255, 255, 0.13)', // Reset on touch devices, it doesn't add specificity '@media (hover: none)': { backgroundColor } }, '&$focused': { backgroundColor: light ? 'rgba(0, 0, 0, 0.09)' : 'rgba(255, 255, 255, 0.09)' }, '&$disabled': { backgroundColor: light ? 'rgba(0, 0, 0, 0.12)' : 'rgba(255, 255, 255, 0.12)' } }, /* Styles applied to the root element if color secondary. */ colorSecondary: { '&$underline:after': { borderBottomColor: theme.palette.secondary.main } }, /* Styles applied to the root element if `disableUnderline={false}`. */ underline: { '&:after': { borderBottom: `2px solid ${theme.palette.primary.main}`, left: 0, bottom: 0, // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242 content: '""', position: 'absolute', right: 0, transform: 'scaleX(0)', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut }), pointerEvents: 'none' // Transparent to the hover style. }, '&$focused:after': { transform: 'scaleX(1)' }, '&$error:after': { borderBottomColor: theme.palette.error.main, transform: 'scaleX(1)' // error is always underlined in red }, '&:before': { borderBottom: `1px solid ${bottomLineColor}`, left: 0, bottom: 0, // Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242 content: '"\\00a0"', position: 'absolute', right: 0, transition: theme.transitions.create('border-bottom-color', { duration: theme.transitions.duration.shorter }), pointerEvents: 'none' // Transparent to the hover style. }, '&:hover:before': { borderBottom: `1px solid ${theme.palette.text.primary}` }, '&$disabled:before': { borderBottomStyle: 'dotted' } }, /* Pseudo-class applied to the root element if the component is focused. */ focused: {}, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the root element if `startAdornment` is provided. */ adornedStart: { paddingLeft: 12 }, /* Styles applied to the root element if `endAdornment` is provided. */ adornedEnd: { paddingRight: 12 }, /* Pseudo-class applied to the root element if `error={true}`. */ error: {}, /* Styles applied to the `input` element if `margin="dense"`. */ marginDense: {}, /* Styles applied to the root element if `multiline={true}`. */ multiline: { padding: '27px 12px 10px', '&$marginDense': { paddingTop: 23, paddingBottom: 6 } }, /* Styles applied to the `input` element. */ input: { padding: '27px 12px 10px', '&:-webkit-autofill': { WebkitBoxShadow: theme.palette.type === 'dark' ? '0 0 0 100px #266798 inset' : null, WebkitTextFillColor: theme.palette.type === 'dark' ? '#fff' : null, borderTopLeftRadius: 'inherit', borderTopRightRadius: 'inherit' } }, /* Styles applied to the `input` element if `margin="dense"`. */ inputMarginDense: { paddingTop: 23, paddingBottom: 6 }, /* Styles applied to the `input` if in `<FormControl hiddenLabel />`. */ inputHiddenLabel: { paddingTop: 18, paddingBottom: 19, '&$inputMarginDense': { paddingTop: 10, paddingBottom: 11 } }, /* Styles applied to the `input` element if `multiline={true}`. */ inputMultiline: { padding: 0 }, /* Styles applied to the `input` element if `startAdornment` is provided. */ inputAdornedStart: { paddingLeft: 0 }, /* Styles applied to the `input` element if `endAdornment` is provided. */ inputAdornedEnd: { paddingRight: 0 } }; }; const FilledInput = React.forwardRef(function FilledInput(props, ref) { const { disableUnderline, classes, fullWidth = false, inputComponent = 'input', multiline = false, type = 'text' } = props, other = _objectWithoutPropertiesLoose(props, ["disableUnderline", "classes", "fullWidth", "inputComponent", "multiline", "type"]); return React.createElement(InputBase, _extends({ classes: _extends({}, classes, { root: clsx(classes.root, !disableUnderline && classes.underline), underline: null }), fullWidth: fullWidth, inputComponent: inputComponent, multiline: multiline, ref: ref, type: type }, other)); }); process.env.NODE_ENV !== "production" ? FilledInput.propTypes = { /** * This prop helps users to fill forms faster, especially on mobile devices. * The name can be confusing, as it's more like an autofill. * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill). */ autoComplete: PropTypes.string, /** * If `true`, the `input` element will be focused during the first mount. */ autoFocus: PropTypes.bool, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * The CSS class name of the wrapper element. */ 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 default `input` element value. Use when the component is not controlled. */ defaultValue: PropTypes.any, /** * If `true`, the `input` element will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the input will not have an underline. */ disableUnderline: PropTypes.bool, /** * End `InputAdornment` for this component. */ endAdornment: PropTypes.node, /** * If `true`, the input will indicate an error. This is normally obtained via context from * FormControl. */ error: PropTypes.bool, /** * If `true`, the input will take up the full width of its container. */ fullWidth: PropTypes.bool, /** * The id of the `input` element. */ id: PropTypes.string, /** * The component used for the native input. * Either a string to use a DOM element or a component. */ inputComponent: PropTypes.elementType, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. */ inputProps: PropTypes.object, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. */ margin: PropTypes.oneOf(['dense', 'none']), /** * If `true`, a textarea element will be rendered. */ multiline: PropTypes.bool, /** * Name attribute of the `input` element. */ name: PropTypes.string, /** * Callback fired when the value is changed. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: PropTypes.func, /** * The short hint displayed in the input before the user enters a value. */ placeholder: PropTypes.string, /** * It prevents the user from changing the value of the field * (not from interacting with the field). */ readOnly: PropTypes.bool, /** * If `true`, the `input` element will be required. */ required: PropTypes.bool, /** * Number of rows to display when multiline option is set to true. */ rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Maximum number of rows to display when multiline option is set to true. */ rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Start `InputAdornment` for this component. */ startAdornment: PropTypes.node, /** * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types). */ type: PropTypes.string, /** * The value of the `input` element, required for a controlled component. */ value: PropTypes.any } : void 0; FilledInput.muiName = 'Input'; export default withStyles(styles, { name: 'MuiFilledInput' })(FilledInput);
ajax/libs/react-native-web/0.11.5/vendor/react-native/SwipeableRow/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 SwipeableRow * */ 'use strict'; import Animated from '../../../exports/Animated'; import I18nManager from '../../../exports/I18nManager'; import PanResponder from '../../../exports/PanResponder'; import React from 'react'; import PropTypes from 'prop-types'; import StyleSheet from '../../../exports/StyleSheet'; /* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error * found when Flow v0.54 was deployed. To see the error delete this comment and * run Flow. */ import TimerMixin from 'react-timer-mixin'; import View from '../../../exports/View'; import createReactClass from 'create-react-class'; import emptyFunction from 'fbjs/lib/emptyFunction'; var isRTL = function isRTL() { return I18nManager.isRTL; }; // NOTE: Eventually convert these consts to an input object of configurations // Position of the left of the swipable item when closed var CLOSED_LEFT_POSITION = 0; // Minimum swipe distance before we recognize it as such var HORIZONTAL_SWIPE_DISTANCE_THRESHOLD = 10; // Minimum swipe speed before we fully animate the user's action (open/close) var HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD = 0.3; // Factor to divide by to get slow speed; i.e. 4 means 1/4 of full speed var SLOW_SPEED_SWIPE_FACTOR = 4; // Time, in milliseconds, of how long the animated swipe should be var SWIPE_DURATION = 300; /** * On SwipeableListView mount, the 1st item will bounce to show users it's * possible to swipe */ var ON_MOUNT_BOUNCE_DELAY = 700; var ON_MOUNT_BOUNCE_DURATION = 400; // Distance left of closed position to bounce back when right-swiping from closed var RIGHT_SWIPE_BOUNCE_BACK_DISTANCE = 30; var RIGHT_SWIPE_BOUNCE_BACK_DURATION = 300; /** * Max distance of right swipe to allow (right swipes do functionally nothing). * Must be multiplied by SLOW_SPEED_SWIPE_FACTOR because gestureState.dx tracks * how far the finger swipes, and not the actual animation distance. */ var RIGHT_SWIPE_THRESHOLD = 30 * SLOW_SPEED_SWIPE_FACTOR; /** * Creates a swipable row that allows taps on the main item and a custom View * on the item hidden behind the row. Typically this should be used in * conjunction with SwipeableListView for additional functionality, but can be * used in a normal ListView. See the renderRow for SwipeableListView to see how * to use this component separately. */ var SwipeableRow = createReactClass({ displayName: 'SwipeableRow', _panResponder: {}, _previousLeft: CLOSED_LEFT_POSITION, mixins: [TimerMixin], propTypes: { children: PropTypes.any, isOpen: PropTypes.bool, preventSwipeRight: PropTypes.bool, maxSwipeDistance: PropTypes.number.isRequired, onOpen: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, onSwipeEnd: PropTypes.func.isRequired, onSwipeStart: PropTypes.func.isRequired, // Should bounce the row on mount shouldBounceOnMount: PropTypes.bool, /** * A ReactElement that is unveiled when the user swipes */ slideoutView: PropTypes.node.isRequired, /** * The minimum swipe distance required before fully animating the swipe. If * the user swipes less than this distance, the item will return to its * previous (open/close) position. */ swipeThreshold: PropTypes.number.isRequired }, getInitialState: function getInitialState() { return { currentLeft: new Animated.Value(this._previousLeft), /** * In order to render component A beneath component B, A must be rendered * before B. However, this will cause "flickering", aka we see A briefly * then B. To counter this, _isSwipeableViewRendered flag is used to set * component A to be transparent until component B is loaded. */ isSwipeableViewRendered: false, rowHeight: null }; }, getDefaultProps: function getDefaultProps() { return { isOpen: false, preventSwipeRight: false, maxSwipeDistance: 0, onOpen: emptyFunction, onClose: emptyFunction, onSwipeEnd: emptyFunction, onSwipeStart: emptyFunction, swipeThreshold: 30 }; }, UNSAFE_componentWillMount: function UNSAFE_componentWillMount() { this._panResponder = PanResponder.create({ onMoveShouldSetPanResponderCapture: this._handleMoveShouldSetPanResponderCapture, onPanResponderGrant: this._handlePanResponderGrant, onPanResponderMove: this._handlePanResponderMove, onPanResponderRelease: this._handlePanResponderEnd, onPanResponderTerminationRequest: this._onPanResponderTerminationRequest, onPanResponderTerminate: this._handlePanResponderEnd, onShouldBlockNativeResponder: function onShouldBlockNativeResponder(event, gestureState) { return false; } }); }, componentDidMount: function componentDidMount() { var _this = this; if (this.props.shouldBounceOnMount) { /** * Do the on mount bounce after a delay because if we animate when other * components are loading, the animation will be laggy */ this.setTimeout(function () { _this._animateBounceBack(ON_MOUNT_BOUNCE_DURATION); }, ON_MOUNT_BOUNCE_DELAY); } }, UNSAFE_componentWillReceiveProps: function UNSAFE_componentWillReceiveProps(nextProps) { /** * We do not need an "animateOpen(noCallback)" because this animation is * handled internally by this component. */ if (this.props.isOpen && !nextProps.isOpen) { this._animateToClosedPosition(); } }, render: function render() { // The view hidden behind the main view var slideOutView; if (this.state.isSwipeableViewRendered && this.state.rowHeight) { slideOutView = React.createElement(View, { style: [styles.slideOutContainer, { height: this.state.rowHeight }] }, this.props.slideoutView); } // The swipeable item var swipeableView = React.createElement(Animated.View, { onLayout: this._onSwipeableViewLayout, style: { transform: [{ translateX: this.state.currentLeft }] } }, this.props.children); return React.createElement(View, this._panResponder.panHandlers, slideOutView, swipeableView); }, close: function close() { this.props.onClose(); this._animateToClosedPosition(); }, _onSwipeableViewLayout: function _onSwipeableViewLayout(event) { this.setState({ isSwipeableViewRendered: true, rowHeight: event.nativeEvent.layout.height }); }, _handleMoveShouldSetPanResponderCapture: function _handleMoveShouldSetPanResponderCapture(event, gestureState) { // Decides whether a swipe is responded to by this component or its child return gestureState.dy < 10 && this._isValidSwipe(gestureState); }, _handlePanResponderGrant: function _handlePanResponderGrant(event, gestureState) {}, _handlePanResponderMove: function _handlePanResponderMove(event, gestureState) { if (this._isSwipingExcessivelyRightFromClosedPosition(gestureState)) { return; } this.props.onSwipeStart(); if (this._isSwipingRightFromClosed(gestureState)) { this._swipeSlowSpeed(gestureState); } else { this._swipeFullSpeed(gestureState); } }, _isSwipingRightFromClosed: function _isSwipingRightFromClosed(gestureState) { var gestureStateDx = isRTL() ? -gestureState.dx : gestureState.dx; return this._previousLeft === CLOSED_LEFT_POSITION && gestureStateDx > 0; }, _swipeFullSpeed: function _swipeFullSpeed(gestureState) { this.state.currentLeft.setValue(this._previousLeft + gestureState.dx); }, _swipeSlowSpeed: function _swipeSlowSpeed(gestureState) { this.state.currentLeft.setValue(this._previousLeft + gestureState.dx / SLOW_SPEED_SWIPE_FACTOR); }, _isSwipingExcessivelyRightFromClosedPosition: function _isSwipingExcessivelyRightFromClosedPosition(gestureState) { /** * We want to allow a BIT of right swipe, to allow users to know that * swiping is available, but swiping right does not do anything * functionally. */ var gestureStateDx = isRTL() ? -gestureState.dx : gestureState.dx; return this._isSwipingRightFromClosed(gestureState) && gestureStateDx > RIGHT_SWIPE_THRESHOLD; }, _onPanResponderTerminationRequest: function _onPanResponderTerminationRequest(event, gestureState) { return false; }, _animateTo: function _animateTo(toValue, duration, callback) { var _this2 = this; if (duration === void 0) { duration = SWIPE_DURATION; } if (callback === void 0) { callback = emptyFunction; } Animated.timing(this.state.currentLeft, { duration: duration, toValue: toValue, useNativeDriver: true }).start(function () { _this2._previousLeft = toValue; callback(); }); }, _animateToOpenPosition: function _animateToOpenPosition() { var maxSwipeDistance = isRTL() ? -this.props.maxSwipeDistance : this.props.maxSwipeDistance; this._animateTo(-maxSwipeDistance); }, _animateToOpenPositionWith: function _animateToOpenPositionWith(speed, distMoved) { /** * Ensure the speed is at least the set speed threshold to prevent a slow * swiping animation */ speed = speed > HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD ? speed : HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD; /** * Calculate the duration the row should take to swipe the remaining distance * at the same speed the user swiped (or the speed threshold) */ var duration = Math.abs((this.props.maxSwipeDistance - Math.abs(distMoved)) / speed); var maxSwipeDistance = isRTL() ? -this.props.maxSwipeDistance : this.props.maxSwipeDistance; this._animateTo(-maxSwipeDistance, duration); }, _animateToClosedPosition: function _animateToClosedPosition(duration) { if (duration === void 0) { duration = SWIPE_DURATION; } this._animateTo(CLOSED_LEFT_POSITION, duration); }, _animateToClosedPositionDuringBounce: function _animateToClosedPositionDuringBounce() { this._animateToClosedPosition(RIGHT_SWIPE_BOUNCE_BACK_DURATION); }, _animateBounceBack: function _animateBounceBack(duration) { /** * When swiping right, we want to bounce back past closed position on release * so users know they should swipe right to get content. */ var swipeBounceBackDistance = isRTL() ? -RIGHT_SWIPE_BOUNCE_BACK_DISTANCE : RIGHT_SWIPE_BOUNCE_BACK_DISTANCE; this._animateTo(-swipeBounceBackDistance, duration, this._animateToClosedPositionDuringBounce); }, // Ignore swipes due to user's finger moving slightly when tapping _isValidSwipe: function _isValidSwipe(gestureState) { if (this.props.preventSwipeRight && this._previousLeft === CLOSED_LEFT_POSITION && gestureState.dx > 0) { return false; } return Math.abs(gestureState.dx) > HORIZONTAL_SWIPE_DISTANCE_THRESHOLD; }, _shouldAnimateRemainder: function _shouldAnimateRemainder(gestureState) { /** * If user has swiped past a certain distance, animate the rest of the way * if they let go */ return Math.abs(gestureState.dx) > this.props.swipeThreshold || gestureState.vx > HORIZONTAL_FULL_SWIPE_SPEED_THRESHOLD; }, _handlePanResponderEnd: function _handlePanResponderEnd(event, gestureState) { var horizontalDistance = isRTL() ? -gestureState.dx : gestureState.dx; if (this._isSwipingRightFromClosed(gestureState)) { this.props.onOpen(); this._animateBounceBack(RIGHT_SWIPE_BOUNCE_BACK_DURATION); } else if (this._shouldAnimateRemainder(gestureState)) { if (horizontalDistance < 0) { // Swiped left this.props.onOpen(); this._animateToOpenPositionWith(gestureState.vx, horizontalDistance); } else { // Swiped right this.props.onClose(); this._animateToClosedPosition(); } } else { if (this._previousLeft === CLOSED_LEFT_POSITION) { this._animateToClosedPosition(); } else { this._animateToOpenPosition(); } } this.props.onSwipeEnd(); } }); var styles = StyleSheet.create({ slideOutContainer: { bottom: 0, left: 0, position: 'absolute', right: 0, top: 0 } }); export default SwipeableRow;
ajax/libs/react-instantsearch/5.2.2/Connectors.js
cdnjs/cdnjs
/*! React InstantSearch 5.2.2 | © Algolia, inc. | https://community.algolia.com/react-instantsearch */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Connectors = {}),global.React)); }(this, (function (exports,React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } function nextTick(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; var title = 'browser'; var platform = 'browser'; var browser = true; var env = {}; var argv = []; var version = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; var config = {}; function noop() {} var on = noop; var addListener = noop; var once = noop; var off = noop; var removeListener = noop; var removeAllListeners = noop; var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); } function cwd () { return '/' } function chdir (dir) { throw new Error('process.chdir is not supported'); }function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function(){ return (new Date()).getTime() }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp){ var clocktime = performanceNow.call(performance)*1e-3; var seconds = Math.floor(clocktime); var nanoseconds = Math.floor((clocktime%1)*1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds<0) { seconds--; nanoseconds += 1e9; } } return [seconds,nanoseconds] } var startTime = new Date(); function uptime() { var currentTime = new Date(); var dif = currentTime - startTime; return dif / 1000; } var process = { nextTick: nextTick, title: title, browser: browser, env: env, argv: argv, version: version, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime }; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; var emptyFunction_1 = emptyFunction; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } var invariant_1 = invariant; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret; var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret_1) { // It is still safe when called from React. return; } invariant_1( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); } shim.isRequired = shim; function getShim() { return shim; } // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim }; ReactPropTypes.checkPropTypes = emptyFunction_1; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var propTypes = createCommonjsModule(function (module) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = factoryWithThrowingShims(); } }); /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } var _listCacheClear = listCacheClear; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } var eq_1 = eq; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq_1(array[length][0], key)) { return length; } } return -1; } var _assocIndexOf = assocIndexOf; /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } var _listCacheDelete = listCacheDelete; /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = _assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } var _listCacheGet = listCacheGet; /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return _assocIndexOf(this.__data__, key) > -1; } var _listCacheHas = listCacheHas; /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } var _listCacheSet = listCacheSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = _listCacheClear; ListCache.prototype['delete'] = _listCacheDelete; ListCache.prototype.get = _listCacheGet; ListCache.prototype.has = _listCacheHas; ListCache.prototype.set = _listCacheSet; var _ListCache = ListCache; /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new _ListCache; this.size = 0; } var _stackClear = stackClear; /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } var _stackDelete = stackDelete; /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } var _stackGet = stackGet; /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } var _stackHas = stackHas; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var _freeGlobal = freeGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = _freeGlobal || freeSelf || Function('return this')(); var _root = root; /** Built-in value references. */ var Symbol$1 = _root.Symbol; var _Symbol = Symbol$1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty$1.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; } catch (e) {} var result = nativeObjectToString.call(value); { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var _getRawTag = getRawTag; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$1.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } var _objectToString = objectToString; /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag$1 && symToStringTag$1 in Object(value)) ? _getRawTag(value) : _objectToString(value); } var _baseGetTag = baseGetTag; /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } var isObject_1 = isObject; /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject_1(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = _baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_1 = isFunction; /** Used to detect overreaching core-js shims. */ var coreJsData = _root['__core-js_shared__']; var _coreJsData = coreJsData; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } var _isMasked = isMasked; /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } var _toSource = toSource; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto$1 = Function.prototype, objectProto$2 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$1 = funcProto$1.toString; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$2.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject_1(value) || _isMasked(value)) { return false; } var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; return pattern.test(_toSource(value)); } var _baseIsNative = baseIsNative; /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } var _getValue = getValue; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = _getValue(object, key); return _baseIsNative(value) ? value : undefined; } var _getNative = getNative; /* Built-in method references that are verified to be native. */ var Map = _getNative(_root, 'Map'); var _Map = Map; /* Built-in method references that are verified to be native. */ var nativeCreate = _getNative(Object, 'create'); var _nativeCreate = nativeCreate; /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; this.size = 0; } var _hashClear = hashClear; /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } var _hashDelete = hashDelete; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$3.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (_nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty$3.call(data, key) ? data[key] : undefined; } var _hashGet = hashGet; /** Used for built-in method references. */ var objectProto$4 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$4 = objectProto$4.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$4.call(data, key); } var _hashHas = hashHas; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; return this; } var _hashSet = hashSet; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = _hashClear; Hash.prototype['delete'] = _hashDelete; Hash.prototype.get = _hashGet; Hash.prototype.has = _hashHas; Hash.prototype.set = _hashSet; var _Hash = Hash; /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new _Hash, 'map': new (_Map || _ListCache), 'string': new _Hash }; } var _mapCacheClear = mapCacheClear; /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } var _isKeyable = isKeyable; /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } var _getMapData = getMapData; /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = _getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } var _mapCacheDelete = mapCacheDelete; /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return _getMapData(this, key).get(key); } var _mapCacheGet = mapCacheGet; /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return _getMapData(this, key).has(key); } var _mapCacheHas = mapCacheHas; /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = _getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } var _mapCacheSet = mapCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = _mapCacheClear; MapCache.prototype['delete'] = _mapCacheDelete; MapCache.prototype.get = _mapCacheGet; MapCache.prototype.has = _mapCacheHas; MapCache.prototype.set = _mapCacheSet; var _MapCache = MapCache; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof _ListCache) { var pairs = data.__data__; if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new _MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } var _stackSet = stackSet; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new _ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = _stackClear; Stack.prototype['delete'] = _stackDelete; Stack.prototype.get = _stackGet; Stack.prototype.has = _stackHas; Stack.prototype.set = _stackSet; var _Stack = Stack; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED$2); return this; } var _setCacheAdd = setCacheAdd; /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } var _setCacheHas = setCacheHas; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new _MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; SetCache.prototype.has = _setCacheHas; var _SetCache = SetCache; /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } var _arraySome = arraySome; /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } var _cacheHas = cacheHas; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!_arraySome(other, function(othValue, othIndex) { if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } var _equalArrays = equalArrays; /** Built-in value references. */ var Uint8Array = _root.Uint8Array; var _Uint8Array = Uint8Array; /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } var _mapToArray = mapToArray; /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } var _setToArray = setToArray; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$1 = 1, COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol ? _Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq_1(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = _mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; convert || (convert = _setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } var _equalByTag = equalByTag; /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } var _arrayPush = arrayPush; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; var isArray_1 = isArray; /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); } var _baseGetAllKeys = baseGetAllKeys; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } var _arrayFilter = arrayFilter; /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } var stubArray_1 = stubArray; /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable = objectProto$5.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { if (object == null) { return []; } object = Object(object); return _arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; var _getSymbols = getSymbols; /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } var _baseTimes = baseTimes; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } var isObjectLike_1 = isObjectLike; /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike_1(value) && _baseGetTag(value) == argsTag; } var _baseIsArguments = baseIsArguments; /** Used for built-in method references. */ var objectProto$6 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$5 = objectProto$6.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { return isObjectLike_1(value) && hasOwnProperty$5.call(value, 'callee') && !propertyIsEnumerable$1.call(value, 'callee'); }; var isArguments_1 = isArguments; /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } var stubFalse_1 = stubFalse; var isBuffer_1 = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse_1; module.exports = isBuffer; }); /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } var _isIndex = isIndex; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; } var isLength_1 = isLength; /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]', arrayTag = '[object Array]', boolTag$1 = '[object Boolean]', dateTag$1 = '[object Date]', errorTag$1 = '[object Error]', funcTag$1 = '[object Function]', mapTag$1 = '[object Map]', numberTag$1 = '[object Number]', objectTag = '[object Object]', regexpTag$1 = '[object RegExp]', setTag$1 = '[object Set]', stringTag$1 = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag$1 = '[object ArrayBuffer]', dataViewTag$1 = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag$1] = typedArrayTags[boolTag$1] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag$1] = typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$1] = typedArrayTags[numberTag$1] = typedArrayTags[objectTag] = typedArrayTags[regexpTag$1] = typedArrayTags[setTag$1] = typedArrayTags[stringTag$1] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; } var _baseIsTypedArray = baseIsTypedArray; /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } var _baseUnary = baseUnary; var _nodeUtil = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && _freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; }); /* Node.js helper references. */ var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; var isTypedArray_1 = isTypedArray; /** Used for built-in method references. */ var objectProto$7 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$6 = objectProto$7.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty$6.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. _isIndex(key, length) ))) { result.push(key); } } return result; } var _arrayLikeKeys = arrayLikeKeys; /** Used for built-in method references. */ var objectProto$8 = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$8; return value === proto; } var _isPrototype = isPrototype; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var _overArg = overArg; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = _overArg(Object.keys, Object); var _nativeKeys = nativeKeys; /** Used for built-in method references. */ var objectProto$9 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$7 = objectProto$9.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$7.call(object, key) && key != 'constructor') { result.push(key); } } return result; } var _baseKeys = baseKeys; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength_1(value.length) && !isFunction_1(value); } var isArrayLike_1 = isArrayLike; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); } var keys_1 = keys; /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return _baseGetAllKeys(object, keys_1, _getSymbols); } var _getAllKeys = getAllKeys; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$2 = 1; /** Used for built-in method references. */ var objectProto$a = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$8 = objectProto$a.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, objProps = _getAllKeys(object), objLength = objProps.length, othProps = _getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } var _equalObjects = equalObjects; /* Built-in method references that are verified to be native. */ var DataView = _getNative(_root, 'DataView'); var _DataView = DataView; /* Built-in method references that are verified to be native. */ var Promise$1 = _getNative(_root, 'Promise'); var _Promise = Promise$1; /* Built-in method references that are verified to be native. */ var Set = _getNative(_root, 'Set'); var _Set = Set; /* Built-in method references that are verified to be native. */ var WeakMap = _getNative(_root, 'WeakMap'); var _WeakMap = WeakMap; /** `Object#toString` result references. */ var mapTag$2 = '[object Map]', objectTag$1 = '[object Object]', promiseTag = '[object Promise]', setTag$2 = '[object Set]', weakMapTag$1 = '[object WeakMap]'; var dataViewTag$2 = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = _toSource(_DataView), mapCtorString = _toSource(_Map), promiseCtorString = _toSource(_Promise), setCtorString = _toSource(_Set), weakMapCtorString = _toSource(_WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2) || (_Map && getTag(new _Map) != mapTag$2) || (_Promise && getTag(_Promise.resolve()) != promiseTag) || (_Set && getTag(new _Set) != setTag$2) || (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) { getTag = function(value) { var result = _baseGetTag(value), Ctor = result == objectTag$1 ? value.constructor : undefined, ctorString = Ctor ? _toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag$2; case mapCtorString: return mapTag$2; case promiseCtorString: return promiseTag; case setCtorString: return setTag$2; case weakMapCtorString: return weakMapTag$1; } } return result; }; } var _getTag = getTag; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$3 = 1; /** `Object#toString` result references. */ var argsTag$2 = '[object Arguments]', arrayTag$1 = '[object Array]', objectTag$2 = '[object Object]'; /** Used for built-in method references. */ var objectProto$b = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$9 = objectProto$b.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray_1(object), othIsArr = isArray_1(other), objTag = objIsArr ? arrayTag$1 : _getTag(object), othTag = othIsArr ? arrayTag$1 : _getTag(other); objTag = objTag == argsTag$2 ? objectTag$2 : objTag; othTag = othTag == argsTag$2 ? objectTag$2 : othTag; var objIsObj = objTag == objectTag$2, othIsObj = othTag == objectTag$2, isSameTag = objTag == othTag; if (isSameTag && isBuffer_1(object)) { if (!isBuffer_1(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new _Stack); return (objIsArr || isTypedArray_1(object)) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new _Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new _Stack); return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); } var _baseIsEqualDeep = baseIsEqualDeep; /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } var _baseIsEqual = baseIsEqual; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$4 = 1, COMPARE_UNORDERED_FLAG$2 = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result )) { return false; } } } return true; } var _baseIsMatch = baseIsMatch; /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject_1(value); } var _isStrictComparable = isStrictComparable; /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys_1(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, _isStrictComparable(value)]; } return result; } var _getMatchData = getMatchData; /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } var _matchesStrictComparable = matchesStrictComparable; /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = _getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return _matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || _baseIsMatch(object, source, matchData); }; } var _baseMatches = baseMatches; /** `Object#toString` result references. */ var symbolTag$1 = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$1); } var isSymbol_1 = isSymbol; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray_1(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } var _isKey = isKey; /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || _MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = _MapCache; var memoize_1 = memoize; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize_1(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var _memoizeCapped = memoizeCapped; /** Used to match property names within property paths. */ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = _memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); var _stringToPath = stringToPath; /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } var _arrayMap = arrayMap; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined, symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray_1(value)) { // Recursively convert values (susceptible to call stack limits). return _arrayMap(value, baseToString) + ''; } if (isSymbol_1(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } var _baseToString = baseToString; /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : _baseToString(value); } var toString_1 = toString; /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray_1(value)) { return value; } return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); } var _castPath = castPath; /** Used as references for various `Number` constants. */ var INFINITY$1 = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol_1(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; } var _toKey = toKey; /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = _castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[_toKey(path[index++])]; } return (index && index == length) ? object : undefined; } var _baseGet = baseGet; /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : _baseGet(object, path); return result === undefined ? defaultValue : result; } var get_1 = get; /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } var _baseHasIn = baseHasIn; /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = _castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = _toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); } var _hasPath = hasPath; /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && _hasPath(object, path, _baseHasIn); } var hasIn_1 = hasIn; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$5 = 1, COMPARE_UNORDERED_FLAG$3 = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (_isKey(path) && _isStrictComparable(srcValue)) { return _matchesStrictComparable(_toKey(path), srcValue); } return function(object) { var objValue = get_1(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); }; } var _baseMatchesProperty = baseMatchesProperty; /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } var identity_1 = identity; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } var _baseProperty = baseProperty; /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return _baseGet(object, path); }; } var _basePropertyDeep = basePropertyDeep; /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); } var property_1 = property; /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity_1; } if (typeof value == 'object') { return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value); } return property_1(value); } var _baseIteratee = baseIteratee; /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike_1(collection)) { var iteratee = _baseIteratee(predicate, 3); collection = keys_1(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } var _createFind = createFind; /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } var _baseFindIndex = baseFindIndex; /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol_1(value)) { return NAN; } if (isObject_1(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject_1(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } var toNumber_1 = toNumber; /** Used as references for various `Number` constants. */ var INFINITY$2 = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber_1(value); if (value === INFINITY$2 || value === -INFINITY$2) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } var toFinite_1 = toFinite; /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite_1(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } var toInteger_1 = toInteger; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return _baseFindIndex(array, _baseIteratee(predicate, 3), index); } var findIndex_1 = findIndex; /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = _createFind(findIndex_1); var find_1 = find; /** `Object#toString` result references. */ var mapTag$3 = '[object Map]', setTag$3 = '[object Set]'; /** Used for built-in method references. */ var objectProto$c = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$a = objectProto$c.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike_1(value) && (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) { return !value.length; } var tag = _getTag(value); if (tag == mapTag$3 || tag == setTag$3) { return !value.size; } if (_isPrototype(value)) { return !_baseKeys(value).length; } for (var key in value) { if (hasOwnProperty$a.call(value, key)) { return false; } } return true; } var isEmpty_1 = isEmpty; /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } var _arrayEach = arrayEach; var defineProperty = (function() { try { var func = _getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); var _defineProperty = defineProperty; /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && _defineProperty) { _defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } var _baseAssignValue = baseAssignValue; /** Used for built-in method references. */ var objectProto$d = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$b = objectProto$d.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty$b.call(object, key) && eq_1(objValue, value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignValue = assignValue; /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { _baseAssignValue(object, key, newValue); } else { _assignValue(object, key, newValue); } } return object; } var _copyObject = copyObject; /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && _copyObject(source, keys_1(source), object); } var _baseAssign = baseAssign; /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } var _nativeKeysIn = nativeKeysIn; /** Used for built-in method references. */ var objectProto$e = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$c = objectProto$e.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject_1(object)) { return _nativeKeysIn(object); } var isProto = _isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty$c.call(object, key)))) { result.push(key); } } return result; } var _baseKeysIn = baseKeysIn; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn$1(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object); } var keysIn_1 = keysIn$1; /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && _copyObject(source, keysIn_1(source), object); } var _baseAssignIn = baseAssignIn; var _cloneBuffer = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; }); /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } var _copyArray = copyArray; /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return _copyObject(source, _getSymbols(source), object); } var _copySymbols = copySymbols; /** Built-in value references. */ var getPrototype = _overArg(Object.getPrototypeOf, Object); var _getPrototype = getPrototype; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols$1 = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) { var result = []; while (object) { _arrayPush(result, _getSymbols(object)); object = _getPrototype(object); } return result; }; var _getSymbolsIn = getSymbolsIn; /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return _copyObject(source, _getSymbolsIn(source), object); } var _copySymbolsIn = copySymbolsIn; /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn); } var _getAllKeysIn = getAllKeysIn; /** Used for built-in method references. */ var objectProto$f = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$d = objectProto$f.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty$d.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } var _initCloneArray = initCloneArray; /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new _Uint8Array(result).set(new _Uint8Array(arrayBuffer)); return result; } var _cloneArrayBuffer = cloneArrayBuffer; /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } var _cloneDataView = cloneDataView; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } var _cloneRegExp = cloneRegExp; /** Used to convert symbols to primitives and strings. */ var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined, symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {}; } var _cloneSymbol = cloneSymbol; /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } var _cloneTypedArray = cloneTypedArray; /** `Object#toString` result references. */ var boolTag$2 = '[object Boolean]', dateTag$2 = '[object Date]', mapTag$4 = '[object Map]', numberTag$2 = '[object Number]', regexpTag$2 = '[object RegExp]', setTag$4 = '[object Set]', stringTag$2 = '[object String]', symbolTag$2 = '[object Symbol]'; var arrayBufferTag$2 = '[object ArrayBuffer]', dataViewTag$3 = '[object DataView]', float32Tag$1 = '[object Float32Array]', float64Tag$1 = '[object Float64Array]', int8Tag$1 = '[object Int8Array]', int16Tag$1 = '[object Int16Array]', int32Tag$1 = '[object Int32Array]', uint8Tag$1 = '[object Uint8Array]', uint8ClampedTag$1 = '[object Uint8ClampedArray]', uint16Tag$1 = '[object Uint16Array]', uint32Tag$1 = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag$2: return _cloneArrayBuffer(object); case boolTag$2: case dateTag$2: return new Ctor(+object); case dataViewTag$3: return _cloneDataView(object, isDeep); case float32Tag$1: case float64Tag$1: case int8Tag$1: case int16Tag$1: case int32Tag$1: case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: return _cloneTypedArray(object, isDeep); case mapTag$4: return new Ctor; case numberTag$2: case stringTag$2: return new Ctor(object); case regexpTag$2: return _cloneRegExp(object); case setTag$4: return new Ctor; case symbolTag$2: return _cloneSymbol(object); } } var _initCloneByTag = initCloneByTag; /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject_1(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); var _baseCreate = baseCreate; /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !_isPrototype(object)) ? _baseCreate(_getPrototype(object)) : {}; } var _initCloneObject = initCloneObject; /** `Object#toString` result references. */ var mapTag$5 = '[object Map]'; /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike_1(value) && _getTag(value) == mapTag$5; } var _baseIsMap = baseIsMap; /* Node.js helper references. */ var nodeIsMap = _nodeUtil && _nodeUtil.isMap; /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap; var isMap_1 = isMap; /** `Object#toString` result references. */ var setTag$5 = '[object Set]'; /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike_1(value) && _getTag(value) == setTag$5; } var _baseIsSet = baseIsSet; /* Node.js helper references. */ var nodeIsSet = _nodeUtil && _nodeUtil.isSet; /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet; var isSet_1 = isSet; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag$3 = '[object Arguments]', funcTag$2 = '[object Function]', genTag$1 = '[object GeneratorFunction]', objectTag$3 = '[object Object]'; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject_1(value)) { return value; } var isArr = isArray_1(value); if (isArr) { result = _initCloneArray(value); if (!isDeep) { return _copyArray(value, result); } } else { var tag = _getTag(value), isFunc = tag == funcTag$2 || tag == genTag$1; if (isBuffer_1(value)) { return _cloneBuffer(value, isDeep); } if (tag == objectTag$3 || tag == argsTag$3 || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : _initCloneObject(value); if (!isDeep) { return isFlat ? _copySymbolsIn(value, _baseAssignIn(result, value)) : _copySymbols(value, _baseAssign(result, value)); } } else { { return object ? value : {}; } result = _initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new _Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet_1(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); return result; } if (isMap_1(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var keysFunc = isFull ? (isFlat ? _getAllKeysIn : _getAllKeys) : (isFlat ? keysIn : keys_1); var props = isArr ? undefined : keysFunc(value); _arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var _baseClone = baseClone; /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } var last_1 = last; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } var _baseSlice = baseSlice; /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1)); } var _parent = parent; /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = _castPath(path, object); object = _parent(object, path); return object == null || delete object[_toKey(last_1(path))]; } var _baseUnset = baseUnset; /** `Object#toString` result references. */ var objectTag$4 = '[object Object]'; /** Used for built-in method references. */ var funcProto$2 = Function.prototype, objectProto$g = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$2 = funcProto$2.toString; /** Used to check objects for own properties. */ var hasOwnProperty$e = objectProto$g.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString$2.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$4) { return false; } var proto = _getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$e.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString; } var isPlainObject_1 = isPlainObject; /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject_1(value) ? undefined : value; } var _customOmitClone = customOmitClone; /** Built-in value references. */ var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } var _isFlattenable = isFlattenable; /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = _isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { _arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } var _baseFlatten = baseFlatten; /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? _baseFlatten(array, 1) : []; } var flatten_1 = flatten; /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } var _apply = apply; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$1 = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax$1(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax$1(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return _apply(func, this, otherArgs); }; } var _overRest = overRest; /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } var constant_1 = constant; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !_defineProperty ? identity_1 : function(func, string) { return _defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant_1(string), 'writable': true }); }; var _baseSetToString = baseSetToString; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } var _shortOut = shortOut; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = _shortOut(_baseSetToString); var _setToString = setToString; /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return _setToString(_overRest(func, undefined, flatten_1), func + ''); } var _flatRest = flatRest; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$1 = 1, CLONE_FLAT_FLAG$1 = 2, CLONE_SYMBOLS_FLAG$1 = 4; /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = _flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = _arrayMap(paths, function(path) { path = _castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); _copyObject(object, _getAllKeysIn(object), result); if (isDeep) { result = _baseClone(result, CLONE_DEEP_FLAG$1 | CLONE_FLAT_FLAG$1 | CLONE_SYMBOLS_FLAG$1, _customOmitClone); } var length = paths.length; while (length--) { _baseUnset(result, paths[length]); } return result; }); var omit_1 = omit; /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } var _baseIsNaN = baseIsNaN; /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } var _strictIndexOf = strictIndexOf; /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex); } var _baseIndexOf = baseIndexOf; /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && _baseIndexOf(array, value, 0) > -1; } var _arrayIncludes = arrayIncludes; /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } var _arrayIncludesWith = arrayIncludesWith; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? _arrayIncludesWith : _arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = _arrayMap(array, _baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new _SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? _cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? _cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } var _baseIntersection = baseIntersection; /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return _setToString(_overRest(func, start, identity_1), func + ''); } var _baseRest = baseRest; /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike_1(value) && isArrayLike_1(value); } var isArrayLikeObject_1 = isArrayLikeObject; /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject_1(value) ? value : []; } var _castArrayLikeObject = castArrayLikeObject; /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = _baseRest(function(arrays) { var mapped = _arrayMap(arrays, _castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? _baseIntersection(mapped) : []; }); var intersection_1 = intersection; /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } var _createBaseFor = createBaseFor; /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = _createBaseFor(); var _baseFor = baseFor; /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && _baseFor(object, iteratee, keys_1); } var _baseForOwn = baseForOwn; /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity_1; } var _castFunction = castFunction; /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && _baseForOwn(object, _castFunction(iteratee)); } var forOwn_1 = forOwn; /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike_1(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } var _createBaseEach = createBaseEach; /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = _createBaseEach(_baseForOwn); var _baseEach = baseEach; /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray_1(collection) ? _arrayEach : _baseEach; return func(collection, _castFunction(iteratee)); } var forEach_1 = forEach; /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; _baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } var _baseFilter = baseFilter; /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray_1(collection) ? _arrayFilter : _baseFilter; return func(collection, _baseIteratee(predicate, 3)); } var filter_1 = filter; /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike_1(collection) ? Array(collection.length) : []; _baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } var _baseMap = baseMap; /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray_1(collection) ? _arrayMap : _baseMap; return func(collection, _baseIteratee(iteratee, 3)); } var map_1 = map; /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } var _arrayReduce = arrayReduce; /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } var _baseReduce = baseReduce; /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray_1(collection) ? _arrayReduce : _baseReduce, initAccum = arguments.length < 3; return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEach); } var reduce_1 = reduce; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$2 = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$2(length + index, 0); } return _baseIndexOf(array, value, index); } var indexOf_1 = indexOf; /** `Object#toString` result references. */ var numberTag$4 = '[object Number]'; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike_1(value) && _baseGetTag(value) == numberTag$4); } var isNumber_1 = isNumber; /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN$1(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber_1(value) && value != +value; } var _isNaN = isNaN$1; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return _baseIsEqual(value, other); } var isEqual_1 = isEqual; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } var isUndefined_1 = isUndefined; /** `Object#toString` result references. */ var stringTag$4 = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$4); } var isString_1 = isString; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : _baseSlice(array, start, end); } var _castSlice = castSlice; /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsEndIndex = charsEndIndex; /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsStartIndex = charsStartIndex; /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } var _asciiToArray = asciiToArray; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } var _hasUnicode = hasUnicode; /** Used to compose unicode character classes. */ var rsAstralRange$1 = '\\ud800-\\udfff', rsComboMarksRange$1 = '\\u0300-\\u036f', reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, rsVarRange$1 = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange$1 + ']', rsCombo = '[' + rsComboRange$1 + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange$1 + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsZWJ$1 = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange$1 + ']?', rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } var _unicodeToArray = unicodeToArray; /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return _hasUnicode(string) ? _unicodeToArray(string) : _asciiToArray(string); } var _stringToArray = stringToArray; /** Used to match leading and trailing whitespace. */ var reTrim$1 = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString_1(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim$1, ''); } if (!string || !(chars = _baseToString(chars))) { return string; } var strSymbols = _stringToArray(string), chrSymbols = _stringToArray(chars), start = _charsStartIndex(strSymbols, chrSymbols), end = _charsEndIndex(strSymbols, chrSymbols) + 1; return _castSlice(strSymbols, start, end).join(''); } var trim_1 = trim; /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject_1(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike_1(object) && _isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq_1(object[index], value); } return false; } var _isIterateeCall = isIterateeCall; /** Used for built-in method references. */ var objectProto$h = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$f = objectProto$h.hasOwnProperty; /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = _baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && _isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn_1(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq_1(value, objectProto$h[key]) && !hasOwnProperty$f.call(object, key))) { object[key] = source[key]; } } } return object; }); var defaults_1 = defaults; /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq_1(object[key], value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignMergeValue = assignMergeValue; /** * Gets the value at `key`, unless `key` is "__proto__". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { return key == '__proto__' ? undefined : object[key]; } var _safeGet = safeGet; /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return _copyObject(value, keysIn_1(value)); } var toPlainObject_1 = toPlainObject; /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = _safeGet(object, key), srcValue = _safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { _assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray_1(srcValue), isBuff = !isArr && isBuffer_1(srcValue), isTyped = !isArr && !isBuff && isTypedArray_1(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray_1(objValue)) { newValue = objValue; } else if (isArrayLikeObject_1(objValue)) { newValue = _copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = _cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = _cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject_1(srcValue) || isArguments_1(srcValue)) { newValue = objValue; if (isArguments_1(objValue)) { newValue = toPlainObject_1(objValue); } else if (!isObject_1(objValue) || (srcIndex && isFunction_1(objValue))) { newValue = _initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } _assignMergeValue(object, key, newValue); } var _baseMergeDeep = baseMergeDeep; /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } _baseFor(source, function(srcValue, key) { if (isObject_1(srcValue)) { stack || (stack = new _Stack); _baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(_safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } _assignMergeValue(object, key, newValue); } }, keysIn_1); } var _baseMerge = baseMerge; /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return _baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && _isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } var _createAssigner = createAssigner; /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = _createAssigner(function(object, source, srcIndex) { _baseMerge(object, source, srcIndex); }); var merge_1 = merge; function valToNumber(v) { if (isNumber_1(v)) { return v; } else if (isString_1(v)) { return parseFloat(v); } else if (Array.isArray(v)) { return map_1(v, valToNumber); } throw new Error('The value should be a number, a parseable string or an array of those.'); } var valToNumber_1 = valToNumber; function filterState(state, filters) { var partialState = {}; var attributeFilters = filter_1(filters, function(f) { return f.indexOf('attribute:') !== -1; }); var attributes = map_1(attributeFilters, function(aF) { return aF.split(':')[1]; }); if (indexOf_1(attributes, '*') === -1) { forEach_1(attributes, function(attr) { if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) { if (!partialState.facetsRefinements) partialState.facetsRefinements = {}; partialState.facetsRefinements[attr] = state.facetsRefinements[attr]; } if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) { if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {}; partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr]; } if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) { if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {}; partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr]; } var numericRefinements = state.getNumericRefinements(attr); if (!isEmpty_1(numericRefinements)) { if (!partialState.numericRefinements) partialState.numericRefinements = {}; partialState.numericRefinements[attr] = state.numericRefinements[attr]; } }); } else { if (!isEmpty_1(state.numericRefinements)) { partialState.numericRefinements = state.numericRefinements; } if (!isEmpty_1(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements; if (!isEmpty_1(state.disjunctiveFacetsRefinements)) { partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements; } if (!isEmpty_1(state.hierarchicalFacetsRefinements)) { partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements; } } var searchParameters = filter_1( filters, function(f) { return f.indexOf('attribute:') === -1; } ); forEach_1( searchParameters, function(parameterKey) { partialState[parameterKey] = state[parameterKey]; } ); return partialState; } var filterState_1 = filterState; /** * Functions to manipulate refinement lists * * The RefinementList is not formally defined through a prototype but is based * on a specific structure. * * @module SearchParameters.refinementList * * @typedef {string[]} SearchParameters.refinementList.Refinements * @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList */ var lib = { /** * Adds a refinement to a RefinementList * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement, if the value is not a string it will be converted * @return {RefinementList} a new and updated refinement list */ addRefinement: function addRefinement(refinementList, attribute, value) { if (lib.isRefined(refinementList, attribute, value)) { return refinementList; } var valueAsString = '' + value; var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString); var mod = {}; mod[attribute] = facetRefinement; return defaults_1({}, mod, refinementList); }, /** * Removes refinement(s) for an attribute: * - if the value is specified removes the refinement for the value on the attribute * - if no value is specified removes all the refinements for this attribute * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} [value] the value of the refinement * @return {RefinementList} a new and updated refinement lst */ removeRefinement: function removeRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) { return lib.clearRefinement(refinementList, attribute); } var valueAsString = '' + value; return lib.clearRefinement(refinementList, function(v, f) { return attribute === f && valueAsString === v; }); }, /** * Toggles the refinement value for an attribute. * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement * @return {RefinementList} a new and updated list */ toggleRefinement: function toggleRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) throw new Error('toggleRefinement should be used with a value'); if (lib.isRefined(refinementList, attribute, value)) { return lib.removeRefinement(refinementList, attribute, value); } return lib.addRefinement(refinementList, attribute, value); }, /** * Clear all or parts of a RefinementList. Depending on the arguments, three * kinds of behavior can happen: * - if no attribute is provided: clears the whole list * - if an attribute is provided as a string: clears the list for the specific attribute * - if an attribute is provided as a function: discards the elements for which the function returns true * @param {RefinementList} refinementList the initial list * @param {string} [attribute] the attribute or function to discard * @param {string} [refinementType] optional parameter to give more context to the attribute function * @return {RefinementList} a new and updated refinement list */ clearRefinement: function clearRefinement(refinementList, attribute, refinementType) { if (isUndefined_1(attribute)) { if (isEmpty_1(refinementList)) return refinementList; return {}; } else if (isString_1(attribute)) { if (isEmpty_1(refinementList[attribute])) return refinementList; return omit_1(refinementList, attribute); } else if (isFunction_1(attribute)) { var hasChanged = false; var newRefinementList = reduce_1(refinementList, function(memo, values, key) { var facetList = filter_1(values, function(value) { return !attribute(value, key, refinementType); }); if (!isEmpty_1(facetList)) { if (facetList.length !== values.length) hasChanged = true; memo[key] = facetList; } else hasChanged = true; return memo; }, {}); if (hasChanged) return newRefinementList; return refinementList; } }, /** * Test if the refinement value is used for the attribute. If no refinement value * is provided, test if the refinementList contains any refinement for the * given attribute. * @param {RefinementList} refinementList the list of refinement * @param {string} attribute name of the attribute * @param {string} [refinementValue] value of the filter/refinement * @return {boolean} */ isRefined: function isRefined(refinementList, attribute, refinementValue) { var indexOf = indexOf_1; var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (isUndefined_1(refinementValue) || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return indexOf(refinementList[attribute], refinementValueAsString) !== -1; } }; var RefinementList = lib; /** * like _.find but using _.isEqual to be able to use it * to find arrays. * @private * @param {any[]} array array to search into * @param {any} searchedValue the value we're looking for * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find_1(array, function(currentValue) { return isEqual_1(currentValue, searchedValue); }); } /** * The facet list is the structure used to store the list of values used to * filter a single attribute. * @typedef {string[]} SearchParameters.FacetList */ /** * Structure to store numeric filters with the operator as the key. The supported operators * are `=`, `>`, `<`, `>=`, `<=` and `!=`. * @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList */ /** * SearchParameters is the data structure that contains all the information * usable for making a search to Algolia API. It doesn't do the search itself, * nor does it contains logic about the parameters. * It is an immutable object, therefore it has been created in a way that each * changes does not change the object itself but returns a copy with the * modification. * This object should probably not be instantiated outside of the helper. It will * be provided when needed. This object is documented for reference as you'll * get it from events generated by the {@link AlgoliaSearchHelper}. * If need be, instantiate the Helper from the factory function {@link SearchParameters.make} * @constructor * @classdesc contains all the parameters of a search * @param {object|SearchParameters} newParameters existing parameters or partial object * for the properties of a new SearchParameters * @see SearchParameters.make * @example <caption>SearchParameters of the first query in * <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption> { "query": "", "disjunctiveFacets": [ "customerReviewCount", "category", "salePrice_range", "manufacturer" ], "maxValuesPerFacet": 30, "page": 0, "hitsPerPage": 10, "facets": [ "type", "shipping" ] } */ function SearchParameters(newParameters) { var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {}; /** * Targeted index. This parameter is mandatory. * @member {string} */ this.index = params.index || ''; // Query /** * Query string of the instant search. The empty string is a valid query. * @member {string} * @see https://www.algolia.com/doc/rest#param-query */ this.query = params.query || ''; // Facets /** * This attribute contains the list of all the conjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.facets = params.facets || []; /** * This attribute contains the list of all the disjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.disjunctiveFacets = params.disjunctiveFacets || []; /** * This attribute contains the list of all the hierarchical facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * Hierarchical facets are a sub type of disjunctive facets that * let you filter faceted attributes hierarchically. * @member {string[]|object[]} */ this.hierarchicalFacets = params.hierarchicalFacets || []; // Refinements /** * This attribute contains all the filters that need to be * applied on the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsRefinements = params.facetsRefinements || {}; /** * This attribute contains all the filters that need to be * excluded from the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters excluded for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsExcludes = params.facetsExcludes || {}; /** * This attribute contains all the filters that need to be * applied on the disjunctive facets. Each facet must be properly * defined in the `disjunctiveFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {}; /** * This attribute contains all the filters that need to be * applied on the numeric attributes. * * The key is the name of the attribute, and the value is the * filters to apply to this attribute. * * When querying algolia, the values stored in this attribute will * be translated into the `numericFilters` attribute. * @member {Object.<string, SearchParameters.OperatorList>} */ this.numericRefinements = params.numericRefinements || {}; /** * This attribute contains all the tags used to refine the query. * * When querying algolia, the values stored in this attribute will * be translated into the `tagFilters` attribute. * @member {string[]} */ this.tagRefinements = params.tagRefinements || []; /** * This attribute contains all the filters that need to be * applied on the hierarchical facets. Each facet must be properly * defined in the `hierarchicalFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. The FacetList values * are structured as a string that contain the values for each level * separated by the configured separator. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {}; /** * Contains the numeric filters in the raw format of the Algolia API. Setting * this parameter is not compatible with the usage of numeric filters methods. * @see https://www.algolia.com/doc/javascript#numericFilters * @member {string} */ this.numericFilters = params.numericFilters; /** * Contains the tag filters in the raw format of the Algolia API. Setting this * parameter is not compatible with the of the add/remove/toggle methods of the * tag api. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.tagFilters = params.tagFilters; /** * Contains the optional tag filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalTagFilters = params.optionalTagFilters; /** * Contains the optional facet filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalFacetFilters = params.optionalFacetFilters; // Misc. parameters /** * Number of hits to be returned by the search API * @member {number} * @see https://www.algolia.com/doc/rest#param-hitsPerPage */ this.hitsPerPage = params.hitsPerPage; /** * Number of values for each faceted attribute * @member {number} * @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet */ this.maxValuesPerFacet = params.maxValuesPerFacet; /** * The current page number * @member {number} * @see https://www.algolia.com/doc/rest#param-page */ this.page = params.page || 0; /** * How the query should be treated by the search engine. * Possible values: prefixAll, prefixLast, prefixNone * @see https://www.algolia.com/doc/rest#param-queryType * @member {string} */ this.queryType = params.queryType; /** * How the typo tolerance behave in the search engine. * Possible values: true, false, min, strict * @see https://www.algolia.com/doc/rest#param-typoTolerance * @member {string} */ this.typoTolerance = params.typoTolerance; /** * Number of characters to wait before doing one character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo * @member {number} */ this.minWordSizefor1Typo = params.minWordSizefor1Typo; /** * Number of characters to wait before doing a second character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos * @member {number} */ this.minWordSizefor2Typos = params.minWordSizefor2Typos; /** * Configure the precision of the proximity ranking criterion * @see https://www.algolia.com/doc/rest#param-minProximity */ this.minProximity = params.minProximity; /** * Should the engine allow typos on numerics. * @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens * @member {boolean} */ this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens; /** * Should the plurals be ignored * @see https://www.algolia.com/doc/rest#param-ignorePlurals * @member {boolean} */ this.ignorePlurals = params.ignorePlurals; /** * Restrict which attribute is searched. * @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes * @member {string} */ this.restrictSearchableAttributes = params.restrictSearchableAttributes; /** * Enable the advanced syntax. * @see https://www.algolia.com/doc/rest#param-advancedSyntax * @member {boolean} */ this.advancedSyntax = params.advancedSyntax; /** * Enable the analytics * @see https://www.algolia.com/doc/rest#param-analytics * @member {boolean} */ this.analytics = params.analytics; /** * Tag of the query in the analytics. * @see https://www.algolia.com/doc/rest#param-analyticsTags * @member {string} */ this.analyticsTags = params.analyticsTags; /** * Enable the synonyms * @see https://www.algolia.com/doc/rest#param-synonyms * @member {boolean} */ this.synonyms = params.synonyms; /** * Should the engine replace the synonyms in the highlighted results. * @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight * @member {boolean} */ this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight; /** * Add some optional words to those defined in the dashboard * @see https://www.algolia.com/doc/rest#param-optionalWords * @member {string} */ this.optionalWords = params.optionalWords; /** * Possible values are "lastWords" "firstWords" "allOptional" "none" (default) * @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults * @member {string} */ this.removeWordsIfNoResults = params.removeWordsIfNoResults; /** * List of attributes to retrieve * @see https://www.algolia.com/doc/rest#param-attributesToRetrieve * @member {string} */ this.attributesToRetrieve = params.attributesToRetrieve; /** * List of attributes to highlight * @see https://www.algolia.com/doc/rest#param-attributesToHighlight * @member {string} */ this.attributesToHighlight = params.attributesToHighlight; /** * Code to be embedded on the left part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPreTag * @member {string} */ this.highlightPreTag = params.highlightPreTag; /** * Code to be embedded on the right part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPostTag * @member {string} */ this.highlightPostTag = params.highlightPostTag; /** * List of attributes to snippet * @see https://www.algolia.com/doc/rest#param-attributesToSnippet * @member {string} */ this.attributesToSnippet = params.attributesToSnippet; /** * Enable the ranking informations in the response, set to 1 to activate * @see https://www.algolia.com/doc/rest#param-getRankingInfo * @member {number} */ this.getRankingInfo = params.getRankingInfo; /** * Remove duplicates based on the index setting attributeForDistinct * @see https://www.algolia.com/doc/rest#param-distinct * @member {boolean|number} */ this.distinct = params.distinct; /** * Center of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundLatLng * @member {string} */ this.aroundLatLng = params.aroundLatLng; /** * Center of the search, retrieve from the user IP. * @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP * @member {boolean} */ this.aroundLatLngViaIP = params.aroundLatLngViaIP; /** * Radius of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundRadius * @member {number} */ this.aroundRadius = params.aroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundPrecision * @member {number} */ this.minimumAroundRadius = params.minimumAroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-minimumAroundRadius * @member {number} */ this.aroundPrecision = params.aroundPrecision; /** * Geo search inside a box. * @see https://www.algolia.com/doc/rest#param-insideBoundingBox * @member {string} */ this.insideBoundingBox = params.insideBoundingBox; /** * Geo search inside a polygon. * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.insidePolygon = params.insidePolygon; /** * Allows to specify an ellipsis character for the snippet when we truncate the text * (added before and after if truncated). * The default value is an empty string and we recommend to set it to "…" * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.snippetEllipsisText = params.snippetEllipsisText; /** * Allows to specify some attributes name on which exact won't be applied. * Attributes are separated with a comma (for example "name,address" ), you can also use a * JSON string array encoding (for example encodeURIComponent('["name","address"]') ). * By default the list is empty. * @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes * @member {string|string[]} */ this.disableExactOnAttributes = params.disableExactOnAttributes; /** * Applies 'exact' on single word queries if the word contains at least 3 characters * and is not a stop word. * Can take two values: true or false. * By default, its set to false. * @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery * @member {boolean} */ this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery; // Undocumented parameters, still needed otherwise we fail this.offset = params.offset; this.length = params.length; var self = this; forOwn_1(params, function checkForUnknownParameter(paramValue, paramName) { if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) { self[paramName] = paramValue; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = keys_1(new SearchParameters()); /** * @private * @param {object} partialState full or part of a state * @return {object} a new object with the number keys as number */ SearchParameters._parseNumbers = function(partialState) { // Do not reparse numbers in SearchParameters, they ought to be parsed already if (partialState instanceof SearchParameters) return partialState; var numbers = {}; var numberKeys = [ 'aroundPrecision', 'aroundRadius', 'getRankingInfo', 'minWordSizefor2Typos', 'minWordSizefor1Typo', 'page', 'maxValuesPerFacet', 'distinct', 'minimumAroundRadius', 'hitsPerPage', 'minProximity' ]; forEach_1(numberKeys, function(k) { var value = partialState[k]; if (isString_1(value)) { var parsedValue = parseFloat(value); numbers[k] = _isNaN(parsedValue) ? value : parsedValue; } }); // there's two formats of insideBoundingBox, we need to parse // the one which is an array of float geo rectangles if (Array.isArray(partialState.insideBoundingBox)) { numbers.insideBoundingBox = partialState.insideBoundingBox.map(function(geoRect) { return geoRect.map(function(value) { return parseFloat(value); }); }); } if (partialState.numericRefinements) { var numericRefinements = {}; forEach_1(partialState.numericRefinements, function(operators, attribute) { numericRefinements[attribute] = {}; forEach_1(operators, function(values, operator) { var parsedValues = map_1(values, function(v) { if (Array.isArray(v)) { return map_1(v, function(vPrime) { if (isString_1(vPrime)) { return parseFloat(vPrime); } return vPrime; }); } else if (isString_1(v)) { return parseFloat(v); } return v; }); numericRefinements[attribute][operator] = parsedValues; }); }); numbers.numericRefinements = numericRefinements; } return merge_1({}, partialState, numbers); }; /** * Factory for SearchParameters * @param {object|SearchParameters} newParameters existing parameters or partial * object for the properties of a new SearchParameters * @return {SearchParameters} frozen instance of SearchParameters */ SearchParameters.make = function makeSearchParameters(newParameters) { var instance = new SearchParameters(newParameters); forEach_1(newParameters.hierarchicalFacets, function(facet) { if (facet.rootPath) { var currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) { instance = instance.clearRefinements(facet.name); } // get it again in case it has been cleared currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length === 0) { instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath); } } }); return instance; }; /** * Validates the new parameters based on the previous state * @param {SearchParameters} currentState the current state * @param {object|SearchParameters} parameters the new parameters to set * @return {Error|null} Error if the modification is invalid, null otherwise */ SearchParameters.validate = function(currentState, parameters) { var params = parameters || {}; if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) { return new Error( '[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' + 'an error, if it is really what you want, you should first clear the tags with clearTags method.'); } if (currentState.tagRefinements.length > 0 && params.tagFilters) { return new Error( '[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' + 'an error, if it is not, you should first clear the tags with clearTags method.'); } if (currentState.numericFilters && params.numericRefinements && !isEmpty_1(params.numericRefinements)) { return new Error( "[Numeric filters] Can't switch from the advanced to the managed API. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } if (!isEmpty_1(currentState.numericRefinements) && params.numericFilters) { return new Error( "[Numeric filters] Can't switch from the managed API to the advanced. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } return null; }; SearchParameters.prototype = { constructor: SearchParameters, /** * Remove all refinements (disjunctive + conjunctive + excludes + numeric filters) * @method * @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {SearchParameters} */ clearRefinements: function clearRefinements(attribute) { var clear = RefinementList.clearRefinement; var patch = { numericRefinements: this._clearNumericRefinements(attribute), facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'), facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'), disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'), hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet') }; if (patch.numericRefinements === this.numericRefinements && patch.facetsRefinements === this.facetsRefinements && patch.facetsExcludes === this.facetsExcludes && patch.disjunctiveFacetsRefinements === this.disjunctiveFacetsRefinements && patch.hierarchicalFacetsRefinements === this.hierarchicalFacetsRefinements) { return this; } return this.setQueryParameters(patch); }, /** * Remove all the refined tags from the SearchParameters * @method * @return {SearchParameters} */ clearTags: function clearTags() { if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this; return this.setQueryParameters({ tagFilters: undefined, tagRefinements: [] }); }, /** * Set the index. * @method * @param {string} index the index name * @return {SearchParameters} */ setIndex: function setIndex(index) { if (index === this.index) return this; return this.setQueryParameters({ index: index }); }, /** * Query setter * @method * @param {string} newQuery value for the new query * @return {SearchParameters} */ setQuery: function setQuery(newQuery) { if (newQuery === this.query) return this; return this.setQueryParameters({ query: newQuery }); }, /** * Page setter * @method * @param {number} newPage new page number * @return {SearchParameters} */ setPage: function setPage(newPage) { if (newPage === this.page) return this; return this.setQueryParameters({ page: newPage }); }, /** * Facets setter * The facets are the simple facets, used for conjunctive (and) faceting. * @method * @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting * @return {SearchParameters} */ setFacets: function setFacets(facets) { return this.setQueryParameters({ facets: facets }); }, /** * Disjunctive facets setter * Change the list of disjunctive (or) facets the helper chan handle. * @method * @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting * @return {SearchParameters} */ setDisjunctiveFacets: function setDisjunctiveFacets(facets) { return this.setQueryParameters({ disjunctiveFacets: facets }); }, /** * HitsPerPage setter * Hits per page represents the number of hits retrieved for this query * @method * @param {number} n number of hits retrieved per page of results * @return {SearchParameters} */ setHitsPerPage: function setHitsPerPage(n) { if (this.hitsPerPage === n) return this; return this.setQueryParameters({ hitsPerPage: n }); }, /** * typoTolerance setter * Set the value of typoTolerance * @method * @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict") * @return {SearchParameters} */ setTypoTolerance: function setTypoTolerance(typoTolerance) { if (this.typoTolerance === typoTolerance) return this; return this.setQueryParameters({ typoTolerance: typoTolerance }); }, /** * Add a numeric filter for a given attribute * When value is an array, they are combined with OR * When value is a single value, it will combined with AND * @method * @param {string} attribute attribute to set the filter on * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number | number[]} value value of the filter * @return {SearchParameters} * @example * // for price = 50 or 40 * searchparameter.addNumericRefinement('price', '=', [50, 40]); * @example * // for size = 38 and 40 * searchparameter.addNumericRefinement('size', '=', 38); * searchparameter.addNumericRefinement('size', '=', 40); */ addNumericRefinement: function(attribute, operator, v) { var value = valToNumber_1(v); if (this.isNumericRefined(attribute, operator, value)) return this; var mod = merge_1({}, this.numericRefinements); mod[attribute] = merge_1({}, mod[attribute]); if (mod[attribute][operator]) { // Array copy mod[attribute][operator] = mod[attribute][operator].slice(); // Add the element. Concat can't be used here because value can be an array. mod[attribute][operator].push(value); } else { mod[attribute][operator] = [value]; } return this.setQueryParameters({ numericRefinements: mod }); }, /** * Get the list of conjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getConjunctiveRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsRefinements[facetName] || []; }, /** * Get the list of disjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getDisjunctiveRefinements: function(facetName) { if (!this.isDisjunctiveFacet(facetName)) { throw new Error( facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ); } return this.disjunctiveFacetsRefinements[facetName] || []; }, /** * Get the list of hierarchical refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getHierarchicalRefinement: function(facetName) { // we send an array but we currently do not support multiple // hierarchicalRefinements for a hierarchicalFacet return this.hierarchicalFacetsRefinements[facetName] || []; }, /** * Get the list of exclude refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getExcludeRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsExcludes[facetName] || []; }, /** * Remove all the numeric filter for a given (attribute, operator) * @method * @param {string} attribute attribute to set the filter on * @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number} [number] the value to be removed * @return {SearchParameters} */ removeNumericRefinement: function(attribute, operator, paramValue) { if (paramValue !== undefined) { var paramValueAsNumber = valToNumber_1(paramValue); if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator && isEqual_1(value.val, paramValueAsNumber); }) }); } else if (operator !== undefined) { if (!this.isNumericRefined(attribute, operator)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator; }) }); } if (!this.isNumericRefined(attribute)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute; }) }); }, /** * Get the list of numeric refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {SearchParameters.OperatorList[]} list of refinements */ getNumericRefinements: function(facetName) { return this.numericRefinements[facetName] || {}; }, /** * Return the current refinement for the (attribute, operator) * @param {string} attribute attribute in the record * @param {string} operator operator applied on the refined values * @return {Array.<number|number[]>} refined values */ getNumericRefinement: function(attribute, operator) { return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator]; }, /** * Clear numeric filters. * @method * @private * @param {string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {Object.<string, OperatorList>} */ _clearNumericRefinements: function _clearNumericRefinements(attribute) { if (isUndefined_1(attribute)) { if (isEmpty_1(this.numericRefinements)) return this.numericRefinements; return {}; } else if (isString_1(attribute)) { if (isEmpty_1(this.numericRefinements[attribute])) return this.numericRefinements; return omit_1(this.numericRefinements, attribute); } else if (isFunction_1(attribute)) { var hasChanged = false; var newNumericRefinements = reduce_1(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach_1(operators, function(values, operator) { var outValues = []; forEach_1(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty_1(outValues)) { if (outValues.length !== values.length) hasChanged = true; operatorList[operator] = outValues; } else hasChanged = true; }); if (!isEmpty_1(operatorList)) memo[key] = operatorList; return memo; }, {}); if (hasChanged) return newNumericRefinements; return this.numericRefinements; } }, /** * Add a facet to the facets attribute of the helper configuration, if it * isn't already present. * @method * @param {string} facet facet name to add * @return {SearchParameters} */ addFacet: function addFacet(facet) { if (this.isConjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ facets: this.facets.concat([facet]) }); }, /** * Add a disjunctive facet to the disjunctiveFacets attribute of the helper * configuration, if it isn't already present. * @method * @param {string} facet disjunctive facet name to add * @return {SearchParameters} */ addDisjunctiveFacet: function addDisjunctiveFacet(facet) { if (this.isDisjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.concat([facet]) }); }, /** * Add a hierarchical facet to the hierarchicalFacets attribute of the helper * configuration. * @method * @param {object} hierarchicalFacet hierarchical facet to add * @return {SearchParameters} * @throws will throw an error if a hierarchical facet with the same name was already declared */ addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) { if (this.isHierarchicalFacet(hierarchicalFacet.name)) { throw new Error( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`'); } return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) }); }, /** * Add a refinement on a "normal" facet * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addFacetRefinement: function addFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) }); }, /** * Exclude a value from a "normal" facet * @method * @param {string} facet attribute to apply the exclusion on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addExcludeRefinement: function addExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) }); }, /** * Adds a refinement on a disjunctive facet. * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * addTagRefinement adds a tag to the list used to filter the results * @param {string} tag tag to be added * @return {SearchParameters} */ addTagRefinement: function addTagRefinement(tag) { if (this.isTagRefined(tag)) return this; var modification = { tagRefinements: this.tagRefinements.concat(tag) }; return this.setQueryParameters(modification); }, /** * Remove a facet from the facets attribute of the helper configuration, if it * is present. * @method * @param {string} facet facet name to remove * @return {SearchParameters} */ removeFacet: function removeFacet(facet) { if (!this.isConjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ facets: filter_1(this.facets, function(f) { return f !== facet; }) }); }, /** * Remove a disjunctive facet from the disjunctiveFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet disjunctive facet name to remove * @return {SearchParameters} */ removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) { if (!this.isDisjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: filter_1(this.disjunctiveFacets, function(f) { return f !== facet; }) }); }, /** * Remove a hierarchical facet from the hierarchicalFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet hierarchical facet name to remove * @return {SearchParameters} */ removeHierarchicalFacet: function removeHierarchicalFacet(facet) { if (!this.isHierarchicalFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: filter_1(this.hierarchicalFacets, function(f) { return f.name !== facet; }) }); }, /** * Remove a refinement set on facet. If a value is provided, it will clear the * refinement for the given value, otherwise it will clear all the refinement * values for the faceted attribute. * @method * @param {string} facet name of the attribute used for faceting * @param {string} [value] value used to filter * @return {SearchParameters} */ removeFacetRefinement: function removeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) }); }, /** * Remove a negative refinement on a facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeExcludeRefinement: function removeExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) }); }, /** * Remove a refinement on a disjunctive facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Remove a tag from the list of tag refinements * @method * @param {string} tag the tag to remove * @return {SearchParameters} */ removeTagRefinement: function removeTagRefinement(tag) { if (!this.isTagRefined(tag)) return this; var modification = { tagRefinements: filter_1(this.tagRefinements, function(t) { return t !== tag; }) }; return this.setQueryParameters(modification); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper * @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement} */ toggleRefinement: function toggleRefinement(facet, value) { return this.toggleFacetRefinement(facet, value); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper */ toggleFacetRefinement: function toggleFacetRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleConjunctiveFacetRefinement(facet, value); } else if (this.isDisjunctiveFacet(facet)) { return this.toggleDisjunctiveFacetRefinement(facet, value); } throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.toggleRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet)); var mod = {}; var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined && this.hierarchicalFacetsRefinements[facet].length > 0 && ( // remove current refinement: // refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0] === value || // remove a parent refinement of the current refinement: // - refinement was 'beer > IPA > Flying dog' // - call is toggleRefine('beer > IPA') // - refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0 ); if (upOneOrMultipleLevel) { if (value.indexOf(separator) === -1) { // go back to root level mod[facet] = []; } else { mod[facet] = [value.slice(0, value.lastIndexOf(separator))]; } } else { mod[facet] = [value]; } return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Adds a refinement on a hierarchical facet. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is refined */ addHierarchicalFacetRefinement: function(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is not refined */ removeHierarchicalFacetRefinement: function(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Switch the tag refinement * @method * @param {string} tag the tag to remove or add * @return {SearchParameters} */ toggleTagRefinement: function toggleTagRefinement(tag) { if (this.isTagRefined(tag)) { return this.removeTagRefinement(tag); } return this.addTagRefinement(tag); }, /** * Test if the facet name is from one of the disjunctive facets * @method * @param {string} facet facet name to test * @return {boolean} */ isDisjunctiveFacet: function(facet) { return indexOf_1(this.disjunctiveFacets, facet) > -1; }, /** * Test if the facet name is from one of the hierarchical facets * @method * @param {string} facetName facet name to test * @return {boolean} */ isHierarchicalFacet: function(facetName) { return this.getHierarchicalFacetByName(facetName) !== undefined; }, /** * Test if the facet name is from one of the conjunctive/normal facets * @method * @param {string} facet facet name to test * @return {boolean} */ isConjunctiveFacet: function(facet) { return indexOf_1(this.facets, facet) > -1; }, /** * Returns true if the facet is refined, either for a specific value or in * general. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value, optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isFacetRefined: function isFacetRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsRefinements, facet, value); }, /** * Returns true if the facet contains exclusions or if a specific value is * excluded. * * @method * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isExcludeRefined: function isExcludeRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsExcludes, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return indexOf_1(refinements, value) !== -1; }, /** * Test if the triple (attribute, operator, value) is already refined. * If only the attribute and the operator are provided, it tests if the * contains any refinement value. * @method * @param {string} attribute attribute for which the refinement is applied * @param {string} [operator] operator of the refinement * @param {string} [value] value of the refinement * @return {boolean} true if it is refined */ isNumericRefined: function isNumericRefined(attribute, operator, value) { if (isUndefined_1(value) && isUndefined_1(operator)) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && !isUndefined_1(this.numericRefinements[attribute][operator]); if (isUndefined_1(value) || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber_1(value); var isAttributeValueDefined = !isUndefined_1( findArray(this.numericRefinements[attribute][operator], parsedValue) ); return isOperatorDefined && isAttributeValueDefined; }, /** * Returns true if the tag refined, false otherwise * @method * @param {string} tag the tag to check * @return {boolean} */ isTagRefined: function isTagRefined(tag) { return indexOf_1(this.tagRefinements, tag) !== -1; }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection_1( keys_1(this.numericRefinements), this.disjunctiveFacets ); return keys_1(this.disjunctiveFacetsRefinements) .concat(disjunctiveNumericRefinedFacets) .concat(this.getRefinedHierarchicalFacets()); }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() { return intersection_1( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index map_1(this.hierarchicalFacets, 'name'), keys_1(this.hierarchicalFacetsRefinements) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return filter_1(this.disjunctiveFacets, function(f) { return indexOf_1(refinedFacets, f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; forOwn_1(this, function(paramValue, paramName) { if (indexOf_1(managedParameters, paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * Let the user retrieve any parameter value from the SearchParameters * @param {string} paramName name of the parameter * @return {any} the value of the parameter */ getQueryParameter: function getQueryParameter(paramName) { if (!this.hasOwnProperty(paramName)) { throw new Error( "Parameter '" + paramName + "' is not an attribute of SearchParameters " + '(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)'); } return this[paramName]; }, /** * Let the user set a specific value for a given parameter. Will return the * same instance if the parameter is invalid or if the value is the same as the * previous one. * @method * @param {string} parameter the parameter name * @param {any} value the value to be set, must be compliant with the definition * of the attribute on the object * @return {SearchParameters} the updated state */ setQueryParameter: function setParameter(parameter, value) { if (this[parameter] === value) return this; var modification = {}; modification[parameter] = value; return this.setQueryParameters(modification); }, /** * Let the user set any of the parameters with a plain object. * @method * @param {object} params all the keys and the values to be updated * @return {SearchParameters} a new updated instance */ setQueryParameters: function setQueryParameters(params) { if (!params) return this; var error = SearchParameters.validate(this, params); if (error) { throw error; } var parsedParams = SearchParameters._parseNumbers(params); return this.mutateMe(function mergeWith(newInstance) { var ks = keys_1(params); forEach_1(ks, function(k) { newInstance[k] = parsedParams[k]; }); return newInstance; }); }, /** * Returns an object with only the selected attributes. * @param {string[]} filters filters to retrieve only a subset of the state. It * accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage) * or attributes of the index with the notation 'attribute:nameOfMyAttribute' * @return {object} */ filter: function(filters) { return filterState_1(this, filters); }, /** * Helper function to make it easier to build new instances from a mutating * function * @private * @param {function} fn newMutableState -> previousState -> () function that will * change the value of the newMutable to the desired state * @return {SearchParameters} a new instance with the specified modifications applied */ mutateMe: function mutateMe(fn) { var newState = new this.constructor(this); fn(newState, this); return newState; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSortBy: function(hierarchicalFacet) { return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc']; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSeparator: function(hierarchicalFacet) { return hierarchicalFacet.separator || ' > '; }, /** * Helper function to get the hierarchicalFacet prefix path or null * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.rootPath or null as default */ _getHierarchicalRootPath: function(hierarchicalFacet) { return hierarchicalFacet.rootPath || null; }, /** * Helper function to check if we show the parent level of the hierarchicalFacet * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.showParentLevel or true as default */ _getHierarchicalShowParentLevel: function(hierarchicalFacet) { if (typeof hierarchicalFacet.showParentLevel === 'boolean') { return hierarchicalFacet.showParentLevel; } return true; }, /** * Helper function to get the hierarchicalFacet by it's name * @param {string} hierarchicalFacetName * @return {object} a hierarchicalFacet */ getHierarchicalFacetByName: function(hierarchicalFacetName) { return find_1( this.hierarchicalFacets, {name: hierarchicalFacetName} ); }, /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ getHierarchicalFacetBreadcrumb: function(facetName) { if (!this.isHierarchicalFacet(facetName)) { throw new Error( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`'); } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return map_1(path, trim_1); }, toString: function() { return JSON.stringify(this, null, 2); } }; /** * Callback used for clearRefinement method * @callback SearchParameters.clearCallback * @param {OperatorList|FacetList} value the value of the filter * @param {string} key the current attribute name * @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude` * depending on the type of facet * @return {boolean} `true` if the element should be removed. `false` otherwise. */ var SearchParameters_1 = SearchParameters; /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } var compact_1 = compact; /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } var _baseSum = baseSum; /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? _baseSum(array, _baseIteratee(iteratee, 2)) : 0; } var sumBy_1 = sumBy; /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return _arrayMap(props, function(key) { return object[key]; }); } var _baseValues = baseValues; /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : _baseValues(object, keys_1(object)); } var values_1 = values; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$3 = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike_1(collection) ? collection : values_1(collection); fromIndex = (fromIndex && !guard) ? toInteger_1(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax$3(length + fromIndex, 0); } return isString_1(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && _baseIndexOf(collection, value, fromIndex) > -1); } var includes_1 = includes; /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } var _baseSortBy = baseSortBy; /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } var _compareAscending = compareAscending; /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = _compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } var _compareMultiple = compareMultiple; /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = _arrayMap(iteratees.length ? iteratees : [identity_1], _baseUnary(_baseIteratee)); var result = _baseMap(collection, function(value, key, collection) { var criteria = _arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return _baseSortBy(result, function(object, other) { return _compareMultiple(object, other, orders); }); } var _baseOrderBy = baseOrderBy; /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray_1(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray_1(orders)) { orders = orders == null ? [] : [orders]; } return _baseOrderBy(collection, iteratees, orders); } var orderBy_1 = orderBy; /** Used to store function metadata. */ var metaMap = _WeakMap && new _WeakMap; var _metaMap = metaMap; /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !_metaMap ? identity_1 : function(func, data) { _metaMap.set(func, data); return func; }; var _baseSetData = baseSetData; /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = _baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject_1(result) ? result : thisBinding; }; } var _createCtor = createCtor; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = _createCtor(func); function wrapper() { var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } var _createBind = createBind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$4 = Math.max; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax$4(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } var _composeArgs = composeArgs; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$5 = Math.max; /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax$5(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } var _composeArgsRight = composeArgsRight; /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } var _countHolders = countHolders; /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } var _baseLodash = baseLodash; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; var _LazyWrapper = LazyWrapper; /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop$1() { // No operation performed. } var noop_1 = noop$1; /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !_metaMap ? noop_1 : function(func) { return _metaMap.get(func); }; var _getData = getData; /** Used to lookup unminified function names. */ var realNames = {}; var _realNames = realNames; /** Used for built-in method references. */ var objectProto$i = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$g = objectProto$i.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = _realNames[result], length = hasOwnProperty$g.call(_realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } var _getFuncName = getFuncName; /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = _baseCreate(_baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; var _LodashWrapper = LodashWrapper; /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof _LazyWrapper) { return wrapper.clone(); } var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = _copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } var _wrapperClone = wrapperClone; /** Used for built-in method references. */ var objectProto$j = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$h = objectProto$j.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) { if (value instanceof _LodashWrapper) { return value; } if (hasOwnProperty$h.call(value, '__wrapped__')) { return _wrapperClone(value); } } return new _LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = _baseLodash.prototype; lodash.prototype.constructor = lodash; var wrapperLodash = lodash; /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = _getFuncName(func), other = wrapperLodash[funcName]; if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = _getData(other); return !!data && func === data[0]; } var _isLaziable = isLaziable; /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = _shortOut(_baseSetData); var _setData = setData; /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } var _getWrapDetails = getWrapDetails; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } var _insertWrapDetails = insertWrapDetails; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$1 = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG$1], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { _arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } var _updateWrapDetails = updateWrapDetails; /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask))); } var _setWrapToString = setWrapToString; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$2 = 1, WRAP_BIND_KEY_FLAG$1 = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG$1 = 8, WRAP_PARTIAL_FLAG$1 = 32, WRAP_PARTIAL_RIGHT_FLAG$1 = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG$1, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG$2 | WRAP_BIND_KEY_FLAG$1); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (_isLaziable(func)) { _setData(result, newData); } result.placeholder = placeholder; return _setWrapToString(result, func, bitmask); } var _createRecurry = createRecurry; /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = func; return object.placeholder; } var _getHolder = getHolder; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$1 = Math.min; /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin$1(indexes.length, arrLength), oldArray = _copyArray(array); while (length--) { var index = indexes[length]; array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } var _reorder = reorder; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } var _replaceHolders = replaceHolders; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$3 = 1, WRAP_BIND_KEY_FLAG$2 = 2, WRAP_CURRY_FLAG$2 = 8, WRAP_CURRY_RIGHT_FLAG$1 = 16, WRAP_ARY_FLAG$1 = 128, WRAP_FLIP_FLAG$1 = 512; /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG$1, isBind = bitmask & WRAP_BIND_FLAG$3, isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2, isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1), isFlip = bitmask & WRAP_FLIP_FLAG$1, Ctor = isBindKey ? undefined : _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = _getHolder(wrapper), holdersCount = _countHolders(args, placeholder); } if (partials) { args = _composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = _composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = _replaceHolders(args, placeholder); return _createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = _reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== _root && this instanceof wrapper) { fn = Ctor || _createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } var _createHybrid = createHybrid; /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = _getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : _replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return _createRecurry( func, bitmask, _createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return _apply(fn, this, args); } return wrapper; } var _createCurry = createCurry; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$4 = 1; /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG$4, Ctor = _createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return _apply(fn, isBind ? thisArg : this, args); } return wrapper; } var _createPartial = createPartial; /** Used as the internal argument placeholder. */ var PLACEHOLDER$1 = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$5 = 1, WRAP_BIND_KEY_FLAG$3 = 2, WRAP_CURRY_BOUND_FLAG$1 = 4, WRAP_CURRY_FLAG$3 = 8, WRAP_ARY_FLAG$2 = 128, WRAP_REARG_FLAG$1 = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$2 = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG$5 | WRAP_BIND_KEY_FLAG$3 | WRAP_ARY_FLAG$2); var isCombo = ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_CURRY_FLAG$3)) || ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$3)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG$5) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG$5 ? 0 : WRAP_CURRY_BOUND_FLAG$1; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? _composeArgs(partials, value, source[4]) : value; data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER$1) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER$1) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG$2) { data[8] = data[8] == null ? source[8] : nativeMin$2(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } var _mergeData = mergeData; /** Error message constants. */ var FUNC_ERROR_TEXT$1 = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$6 = 1, WRAP_BIND_KEY_FLAG$4 = 2, WRAP_CURRY_FLAG$4 = 8, WRAP_CURRY_RIGHT_FLAG$2 = 16, WRAP_PARTIAL_FLAG$2 = 32, WRAP_PARTIAL_RIGHT_FLAG$2 = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$6 = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG$4; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT$1); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG$2 | WRAP_PARTIAL_RIGHT_FLAG$2); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax$6(toInteger_1(ary), 0); arity = arity === undefined ? arity : toInteger_1(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG$2) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : _getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { _mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax$6(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2)) { bitmask &= ~(WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2); } if (!bitmask || bitmask == WRAP_BIND_FLAG$6) { var result = _createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG$4 || bitmask == WRAP_CURRY_RIGHT_FLAG$2) { result = _createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG$2 || bitmask == (WRAP_BIND_FLAG$6 | WRAP_PARTIAL_FLAG$2)) && !holders.length) { result = _createPartial(func, bitmask, thisArg, partials); } else { result = _createHybrid.apply(undefined, newData); } var setter = data ? _baseSetData : _setData; return _setWrapToString(setter(result, newData), func, bitmask); } var _createWrap = createWrap; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_FLAG$3 = 32; /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partial)); return _createWrap(func, WRAP_PARTIAL_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partial.placeholder = {}; var partial_1 = partial; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_RIGHT_FLAG$3 = 64; /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partialRight)); return _createWrap(func, WRAP_PARTIAL_RIGHT_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partialRight.placeholder = {}; var partialRight_1 = partialRight; /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } var _baseClamp = baseClamp; /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString_1(string); position = position == null ? 0 : _baseClamp(toInteger_1(position), 0, string.length); target = _baseToString(target); return string.slice(position, position + target.length) == target; } var startsWith_1 = startsWith; /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ var formatSort = function formatSort(sortBy, defaults) { return reduce_1(sortBy, function preparePredicate(out, sortInstruction) { var sortInstructions = sortInstruction.split(':'); if (defaults && sortInstructions.length === 1) { var similarDefault = find_1(defaults, function(predicate) { return startsWith_1(predicate, sortInstruction[0]); }); if (similarDefault) { sortInstructions = similarDefault.split(':'); } } out[0].push(sortInstructions[0]); out[1].push(sortInstructions[1]); return out; }, [[], []]); }; /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject_1(object)) { return object; } path = _castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = _toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject_1(objValue) ? objValue : (_isIndex(path[index + 1]) ? [] : {}); } } _assignValue(nested, key, newValue); nested = nested[key]; } return object; } var _baseSet = baseSet; /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = _baseGet(object, path); if (predicate(value, path)) { _baseSet(result, _castPath(path, object), value); } } return result; } var _basePickBy = basePickBy; /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = _arrayMap(_getAllKeysIn(object), function(prop) { return [prop]; }); predicate = _baseIteratee(predicate); return _basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } var pickBy_1 = pickBy; var generateHierarchicalTree_1 = generateTrees; function generateTrees(state) { return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) { var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex]; var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || ''; var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet); var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet); var sortBy = formatSort(state._getHierarchicalFacetSortBy(hierarchicalFacet)); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return reduce_1(results, generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path data: null }); }; } function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) { return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) { var parent = hierarchicalTree; if (currentHierarchicalLevel > 0) { var level = 0; parent = hierarchicalTree; while (level < currentHierarchicalLevel) { parent = parent && find_1(parent.data, {isRefined: true}); level++; } } // we found a refined parent, let's add current level data under it if (parent) { // filter values in case an object has multiple categories: // { // categories: { // level0: ['beers', 'bières'], // level1: ['beers > IPA', 'bières > Belges'] // } // } // // If parent refinement is `beers`, then we do not want to have `bières > Belges` // showing up var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); parent.data = orderBy_1( map_1( pickBy_1(hierarchicalFacetResult.data, onlyMatchingValuesFn), formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) ), sortBy[0], sortBy[1] ); } return hierarchicalTree; }; } function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { return function(facetCount, facetValue) { // we want the facetValue is a child of hierarchicalRootPath if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) { return false; } // we always want root levels (only when there is no prefix path) return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || // if there is a rootPath, being root level mean 1 level under rootPath hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || // if current refinement is a root level and current facetValue is a root level, // keep the facetValue facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || // currentRefinement is a child of the facet value currentRefinement.indexOf(facetValue) === 0 || // facetValue is a child of the current parent, add it facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0); }; } function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) { return function format(facetCount, facetValue) { return { name: trim_1(last_1(facetValue.split(hierarchicalSeparator))), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, data: null }; }; } /** * @typedef SearchResults.Facet * @type {object} * @property {string} name name of the attribute in the record * @property {object} data the faceting data: value, number of entries * @property {object} stats undefined unless facet_stats is retrieved from algolia */ /** * @typedef SearchResults.HierarchicalFacet * @type {object} * @property {string} name name of the current value given the hierarchical level, trimmed. * If root node, you get the facet name * @property {number} count number of objects matching this hierarchical value * @property {string} path the current hierarchical value full path * @property {boolean} isRefined `true` if the current value was refined, `false` otherwise * @property {HierarchicalFacet[]} data sub values for the current level */ /** * @typedef SearchResults.FacetValue * @type {object} * @property {string} name the facet value itself * @property {number} count times this facet appears in the results * @property {boolean} isRefined is the facet currently selected * @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets) */ /** * @typedef Refinement * @type {object} * @property {string} type the type of filter used: * `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical` * @property {string} attributeName name of the attribute used for filtering * @property {string} name the value of the filter * @property {number} numericValue the value as a number. Only for numeric filters. * @property {string} operator the operator used. Only for numeric filters. * @property {number} count the number of computed hits for this filter. Only on facets. * @property {boolean} exhaustive if the count is exhaustive */ function getIndices(obj) { var indices = {}; forEach_1(obj, function(val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find_1( hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { return includes_1(hierarchicalFacet.attributes, hierarchicalAttributeName); } ); } /*eslint-disable */ /** * Constructor for SearchResults * @class * @classdesc SearchResults contains the results of a query to Algolia using the * {@link AlgoliaSearchHelper}. * @param {SearchParameters} state state that led to the response * @param {array.<object>} results the results from algolia client * @example <caption>SearchResults of the first query in * <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption> { "hitsPerPage": 10, "processingTimeMS": 2, "facets": [ { "name": "type", "data": { "HardGood": 6627, "BlackTie": 550, "Music": 665, "Software": 131, "Game": 456, "Movie": 1571 }, "exhaustive": false }, { "exhaustive": false, "data": { "Free shipping": 5507 }, "name": "shipping" } ], "hits": [ { "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif", "_highlightResult": { "shortDescription": { "matchLevel": "none", "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "matchedWords": [] }, "category": { "matchLevel": "none", "value": "Computer Security Software", "matchedWords": [] }, "manufacturer": { "matchedWords": [], "value": "Webroot", "matchLevel": "none" }, "name": { "value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "matchedWords": [], "matchLevel": "none" } }, "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg", "shipping": "Free shipping", "bestSellingRank": 4, "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ", "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "category": "Computer Security Software", "salePrice_range": "1 - 50", "objectID": "1688832", "type": "Software", "customerReviewCount": 5980, "salePrice": 49.99, "manufacturer": "Webroot" }, .... ], "nbHits": 10000, "disjunctiveFacets": [ { "exhaustive": false, "data": { "5": 183, "12": 112, "7": 149, ... }, "name": "customerReviewCount", "stats": { "max": 7461, "avg": 157.939, "min": 1 } }, { "data": { "Printer Ink": 142, "Wireless Speakers": 60, "Point & Shoot Cameras": 48, ... }, "name": "category", "exhaustive": false }, { "exhaustive": false, "data": { "> 5000": 2, "1 - 50": 6524, "501 - 2000": 566, "201 - 500": 1501, "101 - 200": 1360, "2001 - 5000": 47 }, "name": "salePrice_range" }, { "data": { "Dynex™": 202, "Insignia™": 230, "PNY": 72, ... }, "name": "manufacturer", "exhaustive": false } ], "query": "", "nbPages": 100, "page": 0, "index": "bestbuy" } **/ /*eslint-enable */ function SearchResults(state, results) { var mainSubResponse = results[0]; this._rawResults = results; /** * query used to generate the results * @member {string} */ this.query = mainSubResponse.query; /** * The query as parsed by the engine given all the rules. * @member {string} */ this.parsedQuery = mainSubResponse.parsedQuery; /** * all the records that match the search parameters. Each record is * augmented with a new attribute `_highlightResult` * which is an object keyed by attribute and with the following properties: * - `value` : the value of the facet highlighted (html) * - `matchLevel`: full, partial or none depending on how the query terms match * @member {object[]} */ this.hits = mainSubResponse.hits; /** * index where the results come from * @member {string} */ this.index = mainSubResponse.index; /** * number of hits per page requested * @member {number} */ this.hitsPerPage = mainSubResponse.hitsPerPage; /** * total number of hits of this query on the index * @member {number} */ this.nbHits = mainSubResponse.nbHits; /** * total number of pages with respect to the number of hits per page and the total number of hits * @member {number} */ this.nbPages = mainSubResponse.nbPages; /** * current page * @member {number} */ this.page = mainSubResponse.page; /** * sum of the processing time of all the queries * @member {number} */ this.processingTimeMS = sumBy_1(results, 'processingTimeMS'); /** * The position if the position was guessed by IP. * @member {string} * @example "48.8637,2.3615", */ this.aroundLatLng = mainSubResponse.aroundLatLng; /** * The radius computed by Algolia. * @member {string} * @example "126792922", */ this.automaticRadius = mainSubResponse.automaticRadius; /** * String identifying the server used to serve this request. * @member {string} * @example "c7-use-2.algolia.net", */ this.serverUsed = mainSubResponse.serverUsed; /** * Boolean that indicates if the computation of the counts did time out. * @deprecated * @member {boolean} */ this.timeoutCounts = mainSubResponse.timeoutCounts; /** * Boolean that indicates if the computation of the hits did time out. * @deprecated * @member {boolean} */ this.timeoutHits = mainSubResponse.timeoutHits; /** * True if the counts of the facets is exhaustive * @member {boolean} */ this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount; /** * True if the number of hits is exhaustive * @member {boolean} */ this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits; /** * Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/). * @member {object[]} */ this.userData = mainSubResponse.userData; /** * queryID is the unique identifier of the query used to generate the current search results. * This value is only available if the `clickAnalytics` search parameter is set to `true`. * @member {string} */ this.queryID = mainSubResponse.queryID; /** * disjunctive facets results * @member {SearchResults.Facet[]} */ this.disjunctiveFacets = []; /** * disjunctive facets results * @member {SearchResults.HierarchicalFacet[]} */ this.hierarchicalFacets = map_1(state.hierarchicalFacets, function initFutureTree() { return []; }); /** * other facets results * @member {SearchResults.Facet[]} */ this.facets = []; var disjunctiveFacets = state.getRefinedDisjunctiveFacets(); var facetsIndices = getIndices(state.facets); var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets); var nextDisjunctiveResult = 1; var self = this; // Since we send request only for disjunctive facets that have been refined, // we get the facets informations from the first, general, response. forEach_1(mainSubResponse.facets, function(facetValueObject, facetKey) { var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName( state.hierarchicalFacets, facetKey ); if (hierarchicalFacet) { // Place the hierarchicalFacet data at the correct index depending on // the attributes order that was defined at the helper initialization var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey); var idxAttributeName = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = indexOf_1(state.disjunctiveFacets, facetKey) !== -1; var isFacetConjunctive = indexOf_1(state.facets, facetKey) !== -1; var position; if (isFacetDisjunctive) { position = disjunctiveFacetsIndices[facetKey]; self.disjunctiveFacets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey); } if (isFacetConjunctive) { position = facetsIndices[facetKey]; self.facets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey); } } }); // Make sure we do not keep holes within the hierarchical facets this.hierarchicalFacets = compact_1(this.hierarchicalFacets); // aggregate the refined disjunctive facets forEach_1(disjunctiveFacets, function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. forEach_1(result.facets, function(facetResults, dfacet) { var position; if (hierarchicalFacet) { position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } self.hierarchicalFacets[position][attributeIndex].data = merge_1( {}, self.hierarchicalFacets[position][attributeIndex].data, facetResults ); } else { position = disjunctiveFacetsIndices[dfacet]; var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}; self.disjunctiveFacets[position] = { name: dfacet, data: defaults_1({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { forEach_1(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && indexOf_1(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are already at a root refinement (or no refinement at all), there is no // root level values request if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) { return; } var result = results[nextDisjunctiveResult]; forEach_1(result.facets, function(facetResults, dfacet) { var position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5), // then the disjunctive values will be `beers` (count: 100), // but we do not want to display // | beers (100) // > IPA (5) // We want // | beers (5) // > IPA (5) var defaultData = {}; if (currentRefinement.length > 0) { var root = currentRefinement[0].split(separator)[0]; defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root]; } self.hierarchicalFacets[position][attributeIndex].data = defaults_1( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes forEach_1(state.facetsExcludes, function(excludes, facetName) { var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; forEach_1(excludes, function(facetValue) { self.facets[position] = self.facets[position] || {name: facetName}; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); this.hierarchicalFacets = map_1(this.hierarchicalFacets, generateHierarchicalTree_1(state)); this.facets = compact_1(this.facets); this.disjunctiveFacets = compact_1(this.disjunctiveFacets); this._state = state; } /** * Get a facet object with its name * @deprecated * @param {string} name name of the faceted attribute * @return {SearchResults.Facet} the facet object */ SearchResults.prototype.getFacetByName = function(name) { var predicate = {name: name}; return find_1(this.facets, predicate) || find_1(this.disjunctiveFacets, predicate) || find_1(this.hierarchicalFacets, predicate); }; /** * Get the facet values of a specified attribute from a SearchResults object. * @private * @param {SearchResults} results the search results to search in * @param {string} attribute name of the faceted attribute to search for * @return {array|object} facet values. For the hierarchical facets it is an object. */ function extractNormalizedFacetValues(results, attribute) { var predicate = {name: attribute}; if (results._state.isConjunctiveFacet(attribute)) { var facet = find_1(results.facets, predicate); if (!facet) return []; return map_1(facet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isFacetRefined(attribute, k), isExcluded: results._state.isExcludeRefined(attribute, k) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find_1(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return map_1(disjunctiveFacet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isDisjunctiveFacetRefined(attribute, k) }; }); } else if (results._state.isHierarchicalFacet(attribute)) { return find_1(results.hierarchicalFacets, predicate); } } /** * Sort nodes of a hierarchical facet results * @private * @param {HierarchicalFacet} node node to upon which we want to apply the sort */ function recSort(sortFn, node) { if (!node.data || node.data.length === 0) { return node; } var children = map_1(node.data, partial_1(recSort, sortFn)); var sortedChildren = sortFn(children); var newNode = merge_1({}, node, {data: sortedChildren}); return newNode; } SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc']; function vanillaSortFn(order, data) { return data.sort(order); } /** * Get a the list of values for a given facet attribute. Those values are sorted * refinement first, descending count (bigger value on top), and name ascending * (alphabetical order). The sort formula can overridden using either string based * predicates or a function. * * This method will return all the values returned by the Algolia engine plus all * the values already refined. This means that it can happen that the * `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet) * might not be respected if you have facet values that are already refined. * @param {string} attribute attribute name * @param {object} opts configuration options. * @param {Array.<string> | function} opts.sortBy * When using strings, it consists of * the name of the [FacetValue](#SearchResults.FacetValue) or the * [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the * order (`asc` or `desc`). For example to order the value by count, the * argument would be `['count:asc']`. * * If only the attribute name is specified, the ordering defaults to the one * specified in the default value for this attribute. * * When not specified, the order is * ascending. This parameter can also be a function which takes two facet * values and should return a number, 0 if equal, 1 if the first argument is * bigger or -1 otherwise. * * The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']` * @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('results', function(content){ * //get values ordered only by name ascending using the string predicate * content.getFacetValues('city', {sortBy: ['name:asc']}); * //get values ordered only by count ascending using a function * content.getFacetValues('city', { * // this is equivalent to ['count:asc'] * sortBy: function(a, b) { * if (a.count === b.count) return 0; * if (a.count > b.count) return 1; * if (b.count > a.count) return -1; * } * }); * }); */ SearchResults.prototype.getFacetValues = function(attribute, opts) { var facetValues = extractNormalizedFacetValues(this, attribute); if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.'); var options = defaults_1({}, opts, {sortBy: SearchResults.DEFAULT_SORT}); if (Array.isArray(options.sortBy)) { var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT); if (Array.isArray(facetValues)) { return orderBy_1(facetValues, order[0], order[1]); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partialRight_1(orderBy_1, order[0], order[1]), facetValues); } else if (isFunction_1(options.sortBy)) { if (Array.isArray(facetValues)) { return facetValues.sort(options.sortBy); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partial_1(vanillaSortFn, options.sortBy), facetValues); } throw new Error( 'options.sortBy is optional but if defined it must be ' + 'either an array of string (predicates) or a sorting function' ); }; /** * Returns the facet stats if attribute is defined and the facet contains some. * Otherwise returns undefined. * @param {string} attribute name of the faceted attribute * @return {object} The stats of the facet */ SearchResults.prototype.getFacetStats = function(attribute) { if (this._state.isConjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.facets, attribute); } else if (this._state.isDisjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute); } throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`'); }; function getFacetStatsIfAvailable(facetList, facetName) { var data = find_1(facetList, {name: facetName}); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhausistivity for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function() { var state = this._state; var results = this; var res = []; forEach_1(state.facetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); forEach_1(state.facetsExcludes, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); forEach_1(state.hierarchicalFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); forEach_1(state.numericRefinements, function(operators, attributeName) { forEach_1(operators, function(values, operator) { forEach_1(values, function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); forEach_1(state.tagRefinements, function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var count = get_1(facet, 'data[' + name + ']'); var exhaustive = get_1(facet, 'exhaustive'); return { type: type, attributeName: attributeName, name: name, count: count || 0, exhaustive: exhaustive || false }; } function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var splitted = name.split(facetDeclaration.separator); var configuredName = splitted[splitted.length - 1]; for (var i = 0; facet !== undefined && i < splitted.length; ++i) { facet = find_1(facet.data, {name: splitted[i]}); } var count = get_1(facet, 'count'); var exhaustive = get_1(facet, 'exhaustive'); return { type: 'hierarchical', attributeName: attributeName, name: configuredName, count: count || 0, exhaustive: exhaustive || false }; } var SearchResults_1 = SearchResults; var isBufferBrowser = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }; var inherits_browser = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var util = createCommonjsModule(function (module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(commonjsGlobal.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } var warned = false; function deprecated() { if (!warned) { { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var length = output.reduce(function(prev, cur) { if (cur.indexOf('\n') >= 0) ; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = isBufferBrowser; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = inherits_browser; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }); var util_1 = util.format; var util_2 = util.deprecate; var util_3 = util.debuglog; var util_4 = util.inspect; var util_5 = util.isArray; var util_6 = util.isBoolean; var util_7 = util.isNull; var util_8 = util.isNullOrUndefined; var util_9 = util.isNumber; var util_10 = util.isString; var util_11 = util.isSymbol; var util_12 = util.isUndefined; var util_13 = util.isRegExp; var util_14 = util.isObject; var util_15 = util.isDate; var util_16 = util.isError; var util_17 = util.isFunction; var util_18 = util.isPrimitive; var util_19 = util.isBuffer; var util_20 = util.log; var util_21 = util.inherits; var util_22 = util._extend; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } var events = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber$1(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject$1(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined$1(handler)) return false; if (isFunction$1(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject$1(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction$1(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction$1(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject$1(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject$1(this._events[type]) && !this._events[type].warned) { if (!isUndefined$1(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction$1(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction$1(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction$1(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject$1(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction$1(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction$1(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction$1(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction$1(arg) { return typeof arg === 'function'; } function isNumber$1(arg) { return typeof arg === 'number'; } function isObject$1(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined$1(arg) { return arg === void 0; } /** * A DerivedHelper is a way to create sub requests to * Algolia from a main helper. * @class * @classdesc The DerivedHelper provides an event based interface for search callbacks: * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. */ function DerivedHelper(mainHelper, fn) { this.main = mainHelper; this.fn = fn; this.lastResults = null; } util.inherits(DerivedHelper, events.EventEmitter); /** * Detach this helper from the main helper * @return {undefined} * @throws Error if the derived helper is already detached */ DerivedHelper.prototype.detach = function() { this.removeAllListeners(); this.main.detachDerivedHelper(this); }; DerivedHelper.prototype.getModifiedState = function(parameters) { return this.fn(parameters); }; var DerivedHelper_1 = DerivedHelper; var requestBuilder = { /** * Get all the queries to send to the client, those queries can used directly * with the Algolia client. * @private * @return {object[]} The queries */ _getQueries: function getQueries(index, state) { var queries = []; // One query for the hits queries.push({ indexName: index, params: requestBuilder._getHitsSearchParams(state) }); // One for each disjunctive facets forEach_1(state.getRefinedDisjunctiveFacets(), function(refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are deeper than level 0 (starting from `beer > IPA`) // we want to get the root values var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true) }); } }); return queries; }, /** * Build search parameters used to fetch hits * @private * @return {object.<string, any>} */ _getHitsSearchParams: function(state) { var facets = state.facets .concat(state.disjunctiveFacets) .concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state)); var facetFilters = requestBuilder._getFacetFilters(state); var numericFilters = requestBuilder._getNumericFilters(state); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { facets: facets, tagFilters: tagFilters }; if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Build search parameters used to fetch a disjunctive facet * @private * @param {string} facet the associated facet name * @param {boolean} hierarchicalRootLevel ?? FIXME * @return {object} */ _getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) { var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel); var numericFilters = requestBuilder._getNumericFilters(state, facet); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], tagFilters: tagFilters, analytics: false, clickAnalytics: false }; var hierarchicalFacet = state.getHierarchicalFacetByName(facet); if (hierarchicalFacet) { additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute( state, hierarchicalFacet, hierarchicalRootLevel ); } else { additionalParams.facets = facet; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Return the numeric filters in an algolia request fashion * @private * @param {string} [facetName] the name of the attribute for which the filters should be excluded * @return {string[]} the numeric filters in the algolia format */ _getNumericFilters: function(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; forEach_1(state.numericRefinements, function(operators, attribute) { forEach_1(operators, function(values, operator) { if (facetName !== attribute) { forEach_1(values, function(value) { if (Array.isArray(value)) { var vs = map_1(value, function(v) { return attribute + operator + v; }); numericFilters.push(vs); } else { numericFilters.push(attribute + operator + value); } }); } }); }); return numericFilters; }, /** * Return the tags filters depending * @private * @return {string} */ _getTagFilters: function(state) { if (state.tagFilters) { return state.tagFilters; } return state.tagRefinements.join(','); }, /** * Build facetFilters parameter based on current refinements. The array returned * contains strings representing the facet filters in the algolia format. * @private * @param {string} [facet] if set, the current disjunctive facet * @return {array.<string>} */ _getFacetFilters: function(state, facet, hierarchicalRootLevel) { var facetFilters = []; forEach_1(state.facetsRefinements, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); forEach_1(state.facetsExcludes, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(facetValues, facetName) { if (facetName === facet || !facetValues || facetValues.length === 0) return; var orFilters = []; forEach_1(facetValues, function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); forEach_1(state.hierarchicalFacetsRefinements, function(facetValues, facetName) { var facetValue = facetValues[0]; if (facetValue === undefined) { return; } var hierarchicalFacet = state.getHierarchicalFacetByName(facetName); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeToRefine; var attributesIndex; // we ask for parent facet values only when the `facet` is the current hierarchical facet if (facet === facetName) { // if we are at the root level already, no need to ask for facet values, we get them from // the hits query if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) || (rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) { return; } if (!rootPath) { attributesIndex = facetValue.split(separator).length - 2; facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator)); } else { attributesIndex = rootPath.split(separator).length - 1; facetValue = rootPath; } attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } else { attributesIndex = facetValue.split(separator).length - 1; attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } if (attributeToRefine) { facetFilters.push([attributeToRefine + ':' + facetValue]); } }); return facetFilters; }, _getHitsHierarchicalFacetsAttributes: function(state) { var out = []; return reduce_1( state.hierarchicalFacets, // ask for as much levels as there's hierarchical refinements function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) { var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0]; // if no refinement, ask for root level if (!hierarchicalRefinement) { allAttributes.push(hierarchicalFacet.attributes[0]); return allAttributes; } var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var level = hierarchicalRefinement.split(separator).length; var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1); return allAttributes.concat(newAttributes); }, out); }, _getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) { var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (rootLevel === true) { var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeIndex = 0; if (rootPath) { attributeIndex = rootPath.split(separator).length; } return [hierarchicalFacet.attributes[attributeIndex]]; } var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || ''; // if refinement is 'beers > IPA > Flying dog', // then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values) var parentLevel = hierarchicalRefinement.split(separator).length - 1; return hierarchicalFacet.attributes.slice(0, parentLevel + 1); }, getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) { var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state; var searchForFacetSearchParameters = { facetQuery: query, facetName: facetName }; if (typeof maxFacetHits === 'number') { searchForFacetSearchParameters.maxFacetHits = maxFacetHits; } var queries = merge_1(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters); return queries; } }; var requestBuilder_1 = requestBuilder; /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { _baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } var _baseInverter = baseInverter; /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return _baseInverter(object, setter, toIteratee(iteratee), {}); }; } var _createInverter = createInverter; /** Used for built-in method references. */ var objectProto$k = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$2 = objectProto$k.toString; /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = _createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString$2.call(value); } result[value] = key; }, constant_1(identity_1)); var invert_1 = invert; var keys2Short = { advancedSyntax: 'aS', allowTyposOnNumericTokens: 'aTONT', analyticsTags: 'aT', analytics: 'a', aroundLatLngViaIP: 'aLLVIP', aroundLatLng: 'aLL', aroundPrecision: 'aP', aroundRadius: 'aR', attributesToHighlight: 'aTH', attributesToRetrieve: 'aTR', attributesToSnippet: 'aTS', disjunctiveFacetsRefinements: 'dFR', disjunctiveFacets: 'dF', distinct: 'd', facetsExcludes: 'fE', facetsRefinements: 'fR', facets: 'f', getRankingInfo: 'gRI', hierarchicalFacetsRefinements: 'hFR', hierarchicalFacets: 'hF', highlightPostTag: 'hPoT', highlightPreTag: 'hPrT', hitsPerPage: 'hPP', ignorePlurals: 'iP', index: 'idx', insideBoundingBox: 'iBB', insidePolygon: 'iPg', length: 'l', maxValuesPerFacet: 'mVPF', minimumAroundRadius: 'mAR', minProximity: 'mP', minWordSizefor1Typo: 'mWS1T', minWordSizefor2Typos: 'mWS2T', numericFilters: 'nF', numericRefinements: 'nR', offset: 'o', optionalWords: 'oW', page: 'p', queryType: 'qT', query: 'q', removeWordsIfNoResults: 'rWINR', replaceSynonymsInHighlight: 'rSIH', restrictSearchableAttributes: 'rSA', synonyms: 's', tagFilters: 'tF', tagRefinements: 'tR', typoTolerance: 'tT', optionalTagFilters: 'oTF', optionalFacetFilters: 'oFF', snippetEllipsisText: 'sET', disableExactOnAttributes: 'dEOA', enableExactOnSingleWordQuery: 'eEOSWQ' }; var short2Keys = invert_1(keys2Short); var shortener = { /** * All the keys of the state, encoded. * @const */ ENCODED_PARAMETERS: keys_1(short2Keys), /** * Decode a shorten attribute * @param {string} shortKey the shorten attribute * @return {string} the decoded attribute, undefined otherwise */ decode: function(shortKey) { return short2Keys[shortKey]; }, /** * Encode an attribute into a short version * @param {string} key the attribute * @return {string} the shorten attribute */ encode: function(key) { return keys2Short[key]; } }; var utils = createCommonjsModule(function (module, exports) { var has = Object.prototype.hasOwnProperty; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { var obj; while (queue.length) { var item = queue.pop(); obj = item.obj[item.prop]; if (Array.isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } return obj; }; exports.arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.merge = function merge(target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = exports.arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = exports.merge(target[i], item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = exports.merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; exports.assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.encode = function encode(str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; exports.compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } return compactQueue(queue); }; exports.isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function isBuffer(obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; }); var utils_1 = utils.arrayToObject; var utils_2 = utils.merge; var utils_3 = utils.assign; var utils_4 = utils.decode; var utils_5 = utils.encode; var utils_6 = utils.compact; var utils_7 = utils.isRegExp; var utils_8 = utils.isBuffer; var replace = String.prototype.replace; var percentTwenties = /%20/g; var formats = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching return prefix + '[]'; }, indices: function indices(prefix, key) { // eslint-disable-line func-name-matching return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { // eslint-disable-line func-name-matching return prefix; } }; var toISO = Date.prototype.toISOString; var defaults$1 = { delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify( // eslint-disable-line func-name-matching object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults$1.encoder) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$1.encoder); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$1.encoder))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } } return values; }; var stringify_1 = function (object, opts) { var obj = object; var options = opts ? utils.assign({}, opts) : {}; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var delimiter = typeof options.delimiter === 'undefined' ? defaults$1.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$1.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults$1.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults$1.encode; var encoder = typeof options.encoder === 'function' ? options.encoder : defaults$1.encoder; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults$1.serializeDate; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults$1.encodeValuesOnly; if (typeof options.format === 'undefined') { options.format = formats['default']; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; return joined.length > 0 ? prefix + joined : ''; }; var has = Object.prototype.hasOwnProperty; var defaults$2 = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults$2.decoder); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults$2.decoder); val = options.decoder(part.slice(pos + 1), defaults$2.decoder); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]') { obj = []; obj = obj.concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; var parse = function (str, opts) { var options = opts ? utils.assign({}, opts) : {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults$2.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults$2.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults$2.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults$2.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults$2.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults$2.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults$2.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults$2.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$2.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; var lib$1 = { formats: formats, parse: parse, stringify: stringify_1 }; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$7 = 1, WRAP_PARTIAL_FLAG$4 = 32; /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = _baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG$7; if (partials.length) { var holders = _replaceHolders(partials, _getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG$4; } return _createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; var bind_1 = bind; /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return _basePickBy(object, paths, function(value, path) { return hasIn_1(object, path); }); } var _basePick = basePick; /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = _flatRest(function(object, paths) { return object == null ? {} : _basePick(object, paths); }); var pick_1 = pick; /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, iteratee(value, key, object), value); }); return result; } var mapKeys_1 = mapKeys; /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } var mapValues_1 = mapValues; /** * Module containing the functions to serialize and deserialize * {SearchParameters} in the query string format * @module algoliasearchHelper.url */ var encode = utils.encode; function recursiveEncode(input) { if (isPlainObject_1(input)) { return mapValues_1(input, recursiveEncode); } if (Array.isArray(input)) { return map_1(input, recursiveEncode); } if (isString_1(input)) { return encode(input); } return input; } var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR']; var stateKeys = shortener.ENCODED_PARAMETERS; function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) { if (prefixRegexp !== null) { a = a.replace(prefixRegexp, ''); b = b.replace(prefixRegexp, ''); } a = invertedMapping[a] || a; b = invertedMapping[b] || b; if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) { if (a === 'q') return -1; if (b === 'q') return 1; var isARefinements = refinementsParameters.indexOf(a) !== -1; var isBRefinements = refinementsParameters.indexOf(b) !== -1; if (isARefinements && !isBRefinements) { return 1; } else if (isBRefinements && !isARefinements) { return -1; } } return a.localeCompare(b); } /** * Read a query string and return an object containing the state * @param {string} queryString the query string that will be decoded * @param {object} [options] accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) */ var getStateFromQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var partialStateWithPrefix = lib$1.parse(queryString); var prefixRegexp = new RegExp('^' + prefixForParameters); var partialState = mapKeys_1( partialStateWithPrefix, function(v, k) { var hasPrefix = prefixForParameters && prefixRegexp.test(k); var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k; var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey); return decodedKey || unprefixedKey; } ); var partialStateWithParsedNumbers = SearchParameters_1._parseNumbers(partialState); return pick_1(partialStateWithParsedNumbers, SearchParameters_1.PARAMETERS); }; /** * Retrieve an object of all the properties that are not understandable as helper * parameters. * @param {string} queryString the query string to read * @param {object} [options] the options * - prefixForParameters : prefix used for the helper configuration keys * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} the object containing the parsed configuration that doesn't * to the helper */ var getUnrecognizedParametersInQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var foreignConfig = {}; var config = lib$1.parse(queryString); if (prefixForParameters) { var prefixRegexp = new RegExp('^' + prefixForParameters); forEach_1(config, function(v, key) { if (!prefixRegexp.test(key)) foreignConfig[key] = v; }); } else { forEach_1(config, function(v, key) { if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v; }); } return foreignConfig; }; /** * Generate a query string for the state passed according to the options * @param {SearchParameters} state state to serialize * @param {object} [options] May contain the following parameters : * - prefix : prefix in front of the keys * - mapping : map short attributes to another value e.g. {q: 'query'} * - moreAttributes : more values to be added in the query string. Those values * won't be prefixed. * - safe : get safe urls for use in emails, chat apps or any application auto linking urls. * All parameters and values will be encoded in a way that it's safe to share them. * Default to false for legacy reasons () * @return {string} the query string */ var getQueryStringFromState = function(state, options) { var moreAttributes = options && options.moreAttributes; var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var safe = options && options.safe || false; var invertedMapping = invert_1(mapping); var stateForUrl = safe ? state : recursiveEncode(state); var encodedState = mapKeys_1( stateForUrl, function(v, k) { var shortK = shortener.encode(k); return prefixForParameters + (mapping[shortK] || shortK); } ); var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters); var sort = bind_1(sortQueryStringValues, null, prefixRegexp, invertedMapping); if (!isEmpty_1(moreAttributes)) { var stateQs = lib$1.stringify(encodedState, {encode: safe, sort: sort}); var moreQs = lib$1.stringify(moreAttributes, {encode: safe}); if (!stateQs) return moreQs; return stateQs + '&' + moreQs; } return lib$1.stringify(encodedState, {encode: safe, sort: sort}); }; var url = { getStateFromQueryString: getStateFromQueryString, getUnrecognizedParametersInQueryString: getUnrecognizedParametersInQueryString, getQueryStringFromState: getQueryStringFromState }; var version$1 = '2.26.0'; /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {SearchParameters} state the current parameters with the latest changes applied * @property {SearchResults} lastResults the previous results received from Algolia. `null` before * the first request * @example * helper.on('change', function(state, lastResults) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when a main search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {SearchParameters} state the parameters used for this search * @property {SearchResults} lastResults the results from the previous search. `null` if * it is the first search. * @example * helper.on('search', function(state, lastResults) { * console.log('Search sent'); * }); */ /** * Event triggered when a search using `searchForFacetValues` is sent to Algolia * @event AlgoliaSearchHelper#event:searchForFacetValues * @property {SearchParameters} state the parameters used for this search * it is the first search. * @property {string} facet the facet searched into * @property {string} query the query used to search in the facets * @example * helper.on('searchForFacetValues', function(state, facet, query) { * console.log('searchForFacetValues sent'); * }); */ /** * Event triggered when a search using `searchOnce` is sent to Algolia * @event AlgoliaSearchHelper#event:searchOnce * @property {SearchParameters} state the parameters used for this search * it is the first search. * @example * helper.on('searchOnce', function(state) { * console.log('searchOnce sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {SearchResults} results the results received from Algolia * @property {SearchParameters} state the parameters used to query Algolia. Those might * be different from the one in the helper instance (for example if the network is unreliable). * @example * helper.on('result', function(results, state) { * console.log('Search results received'); * }); */ /** * Event triggered when Algolia sends back an error. For example, if an unknown parameter is * used, the error can be caught using this event. * @event AlgoliaSearchHelper#event:error * @property {Error} error the error returned by the Algolia. * @example * helper.on('error', function(error) { * console.log('Houston we got a problem.'); * }); */ /** * Event triggered when the queue of queries have been depleted (with any result or outdated queries) * @event AlgoliaSearchHelper#event:searchQueueEmpty * @example * helper.on('searchQueueEmpty', function() { * console.log('No more search pending'); * // This is received before the result event if we're not expecting new results * }); * * helper.search(); */ /** * Initialize a new AlgoliaSearchHelper * @class * @classdesc The AlgoliaSearchHelper is a class that ease the management of the * search. It provides an event based interface for search callbacks: * - change: when the internal search state is changed. * This event contains a {@link SearchParameters} object and the * {@link SearchResults} of the last result if any. * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. * - error: when the response is an error. This event contains the error returned by the server. * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {SearchParameters | object} options an object defining the initial * config of the search. It doesn't have to be a {SearchParameters}, * just an object containing the properties you need from it. */ function AlgoliaSearchHelper(client, index, options) { if (client.addAlgoliaAgent && !doesClientAgentContainsHelper(client)) { client.addAlgoliaAgent('JS Helper ' + version$1); } this.setClient(client); var opts = options || {}; opts.index = index; this.state = SearchParameters_1.make(opts); this.lastResults = null; this._queryId = 0; this._lastQueryIdReceived = -1; this.derivedHelpers = []; this._currentNbQueries = 0; } util.inherits(AlgoliaSearchHelper, events.EventEmitter); /** * Start the search with the parameters set in the state. When the * method is called, it triggers a `search` event. The results will * be available through the `result` event. If an error occurs, an * `error` will be fired instead. * @return {AlgoliaSearchHelper} * @fires search * @fires result * @fires error * @chainable */ AlgoliaSearchHelper.prototype.search = function() { this._search(); return this; }; /** * Gets the search query parameters that would be sent to the Algolia Client * for the hits * @return {object} Query Parameters */ AlgoliaSearchHelper.prototype.getQuery = function() { var state = this.state; return requestBuilder_1._getHitsSearchParams(state); }; /** * Start a search using a modified version of the current state. This method does * not trigger the helper lifecycle and does not modify the state kept internally * by the helper. This second aspect means that the next search call will be the * same as a search call before calling searchOnce. * @param {object} options can contain all the parameters that can be set to SearchParameters * plus the index * @param {function} [callback] optional callback executed when the response from the * server is back. * @return {promise|undefined} if a callback is passed the method returns undefined * otherwise it returns a promise containing an object with two keys : * - content with a SearchResults * - state with the state used for the query as a SearchParameters * @example * // Changing the number of records returned per page to 1 * // This example uses the callback API * var state = helper.searchOnce({hitsPerPage: 1}, * function(error, content, state) { * // if an error occurred it will be passed in error, otherwise its value is null * // content contains the results formatted as a SearchResults * // state is the instance of SearchParameters used for this search * }); * @example * // Changing the number of records returned per page to 1 * // This example uses the promise API * var state1 = helper.searchOnce({hitsPerPage: 1}) * .then(promiseHandler); * * function promiseHandler(res) { * // res contains * // { * // content : SearchResults * // state : SearchParameters (the one used for this specific search) * // } * } */ AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) { var tempState = !options ? this.state : this.state.setQueryParameters(options); var queries = requestBuilder_1._getQueries(tempState.index, tempState); var self = this; this._currentNbQueries++; this.emit('searchOnce', tempState); if (cb) { this.client .search(queries) .then(function(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) { self.emit('searchQueueEmpty'); } cb(null, new SearchResults_1(tempState, content.results), tempState); }) .catch(function(err) { self._currentNbQueries--; if (self._currentNbQueries === 0) { self.emit('searchQueueEmpty'); } cb(err, null, tempState); }); return undefined; } return this.client.search(queries).then(function(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); return { content: new SearchResults_1(tempState, content.results), state: tempState, _originalResponse: content }; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Structure of each result when using * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * @typedef FacetSearchHit * @type {object} * @property {string} value the facet value * @property {string} highlighted the facet value highlighted with the query string * @property {number} count number of occurrence of this facet value * @property {boolean} isRefined true if the value is already refined */ /** * Structure of the data resolved by the * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * promise. * @typedef FacetSearchResult * @type {object} * @property {FacetSearchHit} facetHits the results for this search for facet values * @property {number} processingTimeMS time taken by the query inside the engine */ /** * Search for facet values based on an query and the name of a faceted attribute. This * triggers a search and will return a promise. On top of using the query, it also sends * the parameters from the state so that the search is narrowed down to only the possible values. * * See the description of [FacetSearchResult](reference.html#FacetSearchResult) * @param {string} facet the name of the faceted attribute * @param {string} query the string query for the search * @param {number} [maxFacetHits] the maximum number values returned. Should be > 0 and <= 100 * @param {object} [userState] the set of custom parameters to use on top of the current state. Setting a property to `undefined` removes * it in the generated query. * @return {promise.<FacetSearchResult>} the results of the search */ AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits, userState) { var state = this.state.setQueryParameters(userState || {}); var isDisjunctive = state.isDisjunctiveFacet(facet); var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, state); this._currentNbQueries++; var self = this; this.emit('searchForFacetValues', state, facet, query); var searchForFacetValuesPromise = typeof this.client.searchForFacetValues === 'function' ? this.client.searchForFacetValues([{indexName: state.index, params: algoliaQuery}]) : this.client.initIndex(state.index).searchForFacetValues(algoliaQuery); return searchForFacetValuesPromise.then(function addIsRefined(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); content = Array.isArray(content) ? content[0] : content; content.facetHits = forEach_1(content.facetHits, function(f) { f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value); }); return content; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Sets the text query used for the search. * * This method resets the current page to 0. * @param {string} q the user query * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setQuery = function(q) { this._change(this.state.setPage(0).setQuery(q)); return this; }; /** * Remove all the types of refinements except tags. A string can be provided to remove * only the refinements of a specific attribute. For more advanced use case, you can * provide a function instead. This function should follow the * [clearCallback definition](#SearchParameters.clearCallback). * * This method resets the current page to 0. * @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * // Removing all the refinements * helper.clearRefinements().search(); * @example * // Removing all the filters on a the category attribute. * helper.clearRefinements('category').search(); * @example * // Removing only the exclude filters on the category facet. * helper.clearRefinements(function(value, attribute, type) { * return type === 'exclude' && attribute === 'category'; * }).search(); */ AlgoliaSearchHelper.prototype.clearRefinements = function(name) { this._change(this.state.setPage(0).clearRefinements(name)); return this; }; /** * Remove all the tag filters. * * This method resets the current page to 0. * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.clearTags = function() { this._change(this.state.setPage(0).clearTags()); return this; }; /** * Adds a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() { return this.addDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Adds a refinement on a hierarchical facet. It will throw * an exception if the facet is not defined or if the facet * is already refined. * * This method resets the current page to 0. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is refined * @chainable * @fires change */ AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addHierarchicalFacetRefinement(facet, value)); return this; }; /** * Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} operator the operator of the filter * @param {number} value the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) { this._change(this.state.setPage(0).addNumericRefinement(attribute, operator, value)); return this; }; /** * Adds a filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement} */ AlgoliaSearchHelper.prototype.addRefine = function() { return this.addFacetRefinement.apply(this, arguments); }; /** * Adds a an exclusion filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).addExcludeRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion} */ AlgoliaSearchHelper.prototype.addExclude = function() { return this.addFacetExclusion.apply(this, arguments); }; /** * Adds a tag filter with the `tag` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag the tag to add to the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addTag = function(tag) { this._change(this.state.setPage(0).addTagRefinement(tag)); return this; }; /** * Removes an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is not set, it doesn't change the filters. * * Some parameters are optional, triggering different behavior: * - if the value is not provided, then all the numeric value will be removed for the * specified attribute/operator couple. * - if the operator is not provided either, then all the numeric filter on this attribute * will be removed. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} [operator] the operator of the filter * @param {number} [value] the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) { this._change(this.state.setPage(0).removeNumericRefinement(attribute, operator, value)); return this; }; /** * Removes a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() { return this.removeDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is not refined * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) { this._change(this.state.setPage(0).removeHierarchicalFacetRefinement(facet)); return this; }; /** * Removes a filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).removeFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement} */ AlgoliaSearchHelper.prototype.removeRefine = function() { return this.removeFacetRefinement.apply(this, arguments); }; /** * Removes an exclusion filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).removeExcludeRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion} */ AlgoliaSearchHelper.prototype.removeExclude = function() { return this.removeFacetExclusion.apply(this, arguments); }; /** * Removes a tag filter with the `tag` provided. If the * filter is not set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag tag to remove from the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeTag = function(tag) { this._change(this.state.setPage(0).removeTagRefinement(tag)); return this; }; /** * Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).toggleExcludeFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion} */ AlgoliaSearchHelper.prototype.toggleExclude = function() { return this.toggleFacetExclusion.apply(this, arguments); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable * @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) { return this.toggleFacetRefinement(facet, value); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).toggleFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefine = function() { return this.toggleFacetRefinement.apply(this, arguments); }; /** * Adds or removes a tag filter with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} tag tag to remove or add * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleTag = function(tag) { this._change(this.state.setPage(0).toggleTagRefinement(tag)); return this; }; /** * Increments the page number by one. * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setPage(0).nextPage().getPage(); * // returns 1 */ AlgoliaSearchHelper.prototype.nextPage = function() { return this.setPage(this.state.page + 1); }; /** * Decrements the page number by one. * @fires change * @return {AlgoliaSearchHelper} * @chainable * @example * helper.setPage(1).previousPage().getPage(); * // returns 0 */ AlgoliaSearchHelper.prototype.previousPage = function() { return this.setPage(this.state.page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this._change(this.state.setPage(page)); return this; } /** * Change the current page * @deprecated * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage; /** * Updates the current page. * @function * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setPage = setCurrentPage; /** * Updates the name of the index that will be targeted by the query. * * This method resets the current page to 0. * @param {string} name the index name * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setIndex = function(name) { this._change(this.state.setPage(0).setIndex(name)); return this; }; /** * Update a parameter of the search. This method reset the page * * The complete list of parameters is available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters and facets have their own API) * * This method resets the current page to 0. * @param {string} parameter name of the parameter to update * @param {any} value new value of the parameter * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setQueryParameter('hitsPerPage', 20).search(); */ AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) { this._change(this.state.setPage(0).setQueryParameter(parameter, value)); return this; }; /** * Set the whole state (warning: will erase previous state) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setState = function(newState) { this._change(SearchParameters_1.make(newState)); return this; }; /** * Get the current search state stored in the helper. This object is immutable. * @param {string[]} [filters] optional filters to retrieve only a subset of the state * @return {SearchParameters|object} if filters is specified a plain object is * returned containing only the requested fields, otherwise return the unfiltered * state * @example * // Get the complete state as stored in the helper * helper.getState(); * @example * // Get a part of the state with all the refinements on attributes and the query * helper.getState(['query', 'attribute:category']); */ AlgoliaSearchHelper.prototype.getState = function(filters) { if (filters === undefined) return this.state; return this.state.filter(filters); }; /** * DEPRECATED Get part of the state as a query string. By default, the output keys will not * be prefixed and will only take the applied refinements and the query. * @deprecated * @param {object} [options] May contain the following parameters : * * **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for * the index, all the refinements with `attribute:*` or for some specific attributes with * `attribute:theAttribute` * * **prefix** : prefix in front of the keys * * **moreAttributes** : more values to be added in the query string. Those values * won't be prefixed. * @return {string} the query string */ AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) { var filters = options && options.filters || ['query', 'attribute:*']; var partialState = this.getState(filters); return url.getQueryStringFromState(partialState, options); }; /** * DEPRECATED Read a query string and return an object containing the state. Use * url module. * @deprecated * @static * @param {string} queryString the query string that will be decoded * @param {object} options accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) * @see {@link url#getStateFromQueryString} */ AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString; /** * DEPRECATED Retrieve an object of all the properties that are not understandable as helper * parameters. Use url module. * @deprecated * @static * @param {string} queryString the query string to read * @param {object} options the options * - prefixForParameters : prefix used for the helper configuration keys * @return {object} the object containing the parsed configuration that doesn't * to the helper */ AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString; /** * DEPRECATED Overrides part of the state with the properties stored in the provided query * string. * @deprecated * @param {string} queryString the query string containing the informations to url the state * @param {object} options optional parameters : * - prefix : prefix used for the algolia parameters * - triggerChange : if set to true the state update will trigger a change event */ AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) { var triggerChange = options && options.triggerChange || false; var configuration = url.getStateFromQueryString(queryString, options); var updatedState = this.state.setQueryParameters(configuration); if (triggerChange) this.setState(updatedState); else this.overrideStateWithoutTriggeringChangeEvent(updatedState); }; /** * Override the current state without triggering a change event. * Do not use this method unless you know what you are doing. (see the example * for a legit use case) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @example * helper.on('change', function(state){ * // In this function you might want to find a way to store the state in the url/history * updateYourURL(state) * }) * window.onpopstate = function(event){ * // This is naive though as you should check if the state is really defined etc. * helper.overrideStateWithoutTriggeringChangeEvent(event.state).search() * } * @chainable */ AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) { this.state = new SearchParameters_1(newState); return this; }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isRefined = function(facet, value) { if (this.state.isConjunctiveFacet(facet)) { return this.state.isFacetRefined(facet, value); } else if (this.state.isDisjunctiveFacet(facet)) { return this.state.isDisjunctiveFacetRefined(facet, value); } throw new Error(facet + ' is not properly defined in this helper configuration' + '(use the facets or disjunctiveFacets keys to configure it)'); }; /** * Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters. * @param {string} attribute the name of the attribute * @return {boolean} true if the attribute is filtered by at least one value * @example * // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters * helper.hasRefinements('price'); // false * helper.addNumericRefinement('price', '>', 100); * helper.hasRefinements('price'); // true * * helper.hasRefinements('color'); // false * helper.addFacetRefinement('color', 'blue'); * helper.hasRefinements('color'); // true * * helper.hasRefinements('material'); // false * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * helper.hasRefinements('material'); // true * * helper.hasRefinements('categories'); // false * helper.toggleFacetRefinement('categories', 'kitchen > knife'); * helper.hasRefinements('categories'); // true * */ AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) { if (!isEmpty_1(this.state.getNumericRefinements(attribute))) { return true; } else if (this.state.isConjunctiveFacet(attribute)) { return this.state.isFacetRefined(attribute); } else if (this.state.isDisjunctiveFacet(attribute)) { return this.state.isDisjunctiveFacetRefined(attribute); } else if (this.state.isHierarchicalFacet(attribute)) { return this.state.isHierarchicalFacetRefined(attribute); } // there's currently no way to know that the user did call `addNumericRefinement` at some point // thus we cannot distinguish if there once was a numeric refinement that was cleared // so we will return false in every other situations to be consistent // while what we should do here is throw because we did not find the attribute in any type // of refinement return false; }; /** * Check if a value is excluded for a specific faceted attribute. If the value * is omitted then the function checks if there is any excluding refinements. * * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} true if refined * @example * helper.isExcludeRefined('color'); // false * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // false * * helper.addFacetExclusion('color', 'red'); * * helper.isExcludeRefined('color'); // true * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // true */ AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) { return this.state.isExcludeRefined(facet, value); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) { return this.state.isDisjunctiveFacetRefined(facet, value); }; /** * Check if the string is a currently filtering tag. * @param {string} tag tag to check * @return {boolean} */ AlgoliaSearchHelper.prototype.hasTag = function(tag) { return this.state.isTagRefined(tag); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag} */ AlgoliaSearchHelper.prototype.isTagRefined = function() { return this.hasTagRefinements.apply(this, arguments); }; /** * Get the name of the currently used index. * @return {string} * @example * helper.setIndex('highestPrice_products').getIndex(); * // returns 'highestPrice_products' */ AlgoliaSearchHelper.prototype.getIndex = function() { return this.state.index; }; function getCurrentPage() { return this.state.page; } /** * Get the currently selected page * @deprecated * @return {number} the current page */ AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage; /** * Get the currently selected page * @function * @return {number} the current page */ AlgoliaSearchHelper.prototype.getPage = getCurrentPage; /** * Get all the tags currently set to filters the results. * * @return {string[]} The list of tags currently set. */ AlgoliaSearchHelper.prototype.getTags = function() { return this.state.tagRefinements; }; /** * Get a parameter of the search by its name. It is possible that a parameter is directly * defined in the index dashboard, but it will be undefined using this method. * * The complete list of parameters is * available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters have their own API) * @param {string} parameterName the parameter name * @return {any} the parameter value * @example * var hitsPerPage = helper.getQueryParameter('hitsPerPage'); */ AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) { return this.state.getQueryParameter(parameterName); }; /** * Get the list of refinements for a given attribute. This method works with * conjunctive, disjunctive, excluding and numerical filters. * * See also SearchResults#getRefinements * * @param {string} facetName attribute name used for faceting * @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and * a type. Numeric also contains an operator. * @example * helper.addNumericRefinement('price', '>', 100); * helper.getRefinements('price'); * // [ * // { * // "value": [ * // 100 * // ], * // "operator": ">", * // "type": "numeric" * // } * // ] * @example * helper.addFacetRefinement('color', 'blue'); * helper.addFacetExclusion('color', 'red'); * helper.getRefinements('color'); * // [ * // { * // "value": "blue", * // "type": "conjunctive" * // }, * // { * // "value": "red", * // "type": "exclude" * // } * // ] * @example * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * // [ * // { * // "value": "plastic", * // "type": "disjunctive" * // } * // ] */ AlgoliaSearchHelper.prototype.getRefinements = function(facetName) { var refinements = []; if (this.state.isConjunctiveFacet(facetName)) { var conjRefinements = this.state.getConjunctiveRefinements(facetName); forEach_1(conjRefinements, function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); forEach_1(excludeRefinements, function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); forEach_1(disjRefinements, function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); forEach_1(numericRefinements, function(value, operator) { refinements.push({ value: value, operator: operator, type: 'numeric' }); }); return refinements; }; /** * Return the current refinement for the (attribute, operator) * @param {string} attribute attribute in the record * @param {string} operator operator applied on the refined values * @return {Array.<number|number[]>} refined values */ AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) { return this.state.getNumericRefinement(attribute, operator); }; /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) { return this.state.getHierarchicalFacetBreadcrumb(facetName); }; // /////////// PRIVATE /** * Perform the underlying queries * @private * @return {undefined} * @fires search * @fires result * @fires error */ AlgoliaSearchHelper.prototype._search = function() { var state = this.state; var mainQueries = requestBuilder_1._getQueries(state.index, state); var states = [{ state: state, queriesCount: mainQueries.length, helper: this }]; this.emit('search', state, this.lastResults); var derivedQueries = map_1(this.derivedHelpers, function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var queries = requestBuilder_1._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: queries.length, helper: derivedHelper }); derivedHelper.emit('search', derivedState, derivedHelper.lastResults); return queries; }); var queries = mainQueries.concat(flatten_1(derivedQueries)); var queryId = this._queryId++; this._currentNbQueries++; try { this.client.search(queries) .then(this._dispatchAlgoliaResponse.bind(this, states, queryId)) .catch(this._dispatchAlgoliaError.bind(this, queryId)); } catch (err) { // If we reach this part, we're in an internal error state this.emit('error', err); } }; /** * Transform the responses as sent by the server and transform them into a user * usable object that merge the results of all the batch requests. It will dispatch * over the different helper + derived helpers (when there are some). * @private * @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>} * state state used for to generate the request * @param {number} queryId id of the current request * @param {object} content content of the response * @return {undefined} */ AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, content) { // FIXME remove the number of outdated queries discarded instead of just one if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= (queryId - this._lastQueryIdReceived); this._lastQueryIdReceived = queryId; if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); var results = content.results; forEach_1(states, function(s) { var state = s.state; var queriesCount = s.queriesCount; var helper = s.helper; var specificResults = results.splice(0, queriesCount); var formattedResponse = helper.lastResults = new SearchResults_1(state, specificResults); helper.emit('result', formattedResponse, state); }); }; AlgoliaSearchHelper.prototype._dispatchAlgoliaError = function(queryId, err) { if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= queryId - this._lastQueryIdReceived; this._lastQueryIdReceived = queryId; this.emit('error', err); if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); }; AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) { return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0; }; /** * Test if there are some disjunctive refinements on the facet * @private * @param {string} facet the attribute to test * @return {boolean} */ AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) { return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0; }; AlgoliaSearchHelper.prototype._change = function(newState) { if (newState !== this.state) { this.state = newState; this.emit('change', this.state, this.lastResults); } }; /** * Clears the cache of the underlying Algolia client. * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.clearCache = function() { this.client.clearCache && this.client.clearCache(); return this; }; /** * Updates the internal client instance. If the reference of the clients * are equal then no update is actually done. * @param {AlgoliaSearch} newClient an AlgoliaSearch client * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.setClient = function(newClient) { if (this.client === newClient) return this; if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version$1); this.client = newClient; return this; }; /** * Gets the instance of the currently used client. * @return {AlgoliaSearch} */ AlgoliaSearchHelper.prototype.getClient = function() { return this.client; }; /** * Creates an derived instance of the Helper. A derived helper * is a way to request other indices synchronised with the lifecycle * of the main Helper. This mechanism uses the multiqueries feature * of Algolia to aggregate all the requests in a single network call. * * This method takes a function that is used to create a new SearchParameter * that will be used to create requests to Algolia. Those new requests * are created just before the `search` event. The signature of the function * is `SearchParameters -> SearchParameters`. * * This method returns a new DerivedHelper which is an EventEmitter * that fires the same `search`, `result` and `error` events. Those * events, however, will receive data specific to this DerivedHelper * and the SearchParameters that is returned by the call of the * parameter function. * @param {function} fn SearchParameters -> SearchParameters * @return {DerivedHelper} */ AlgoliaSearchHelper.prototype.derive = function(fn) { var derivedHelper = new DerivedHelper_1(this, fn); this.derivedHelpers.push(derivedHelper); return derivedHelper; }; /** * This method detaches a derived Helper from the main one. Prefer using the one from the * derived helper itself, to remove the event listeners too. * @private * @return {undefined} * @throws Error */ AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) { var pos = this.derivedHelpers.indexOf(derivedHelper); if (pos === -1) throw new Error('Derived helper already detached'); this.derivedHelpers.splice(pos, 1); }; /** * This method returns true if there is currently at least one on-going search. * @return {boolean} true if there is a search pending */ AlgoliaSearchHelper.prototype.hasPendingRequests = function() { return this._currentNbQueries > 0; }; /** * @typedef AlgoliaSearchHelper.NumericRefinement * @type {object} * @property {number[]} value the numbers that are used for filtering this attribute with * the operator specified. * @property {string} operator the faceting data: value, number of entries * @property {string} type will be 'numeric' */ /** * @typedef AlgoliaSearchHelper.FacetRefinement * @type {object} * @property {string} value the string use to filter the attribute * @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude' */ /* * This function tests if the _ua parameter of the client * already contains the JS Helper UA */ function doesClientAgentContainsHelper(client) { // this relies on JS Client internal variable, this might break if implementation changes var currentAgent = client._ua; return !currentAgent ? false : currentAgent.indexOf('JS Helper') !== -1; } var algoliasearch_helper = AlgoliaSearchHelper; /** * The algoliasearchHelper module is the function that will let its * contains everything needed to use the Algoliasearch * Helper. It is a also a function that instanciate the helper. * To use the helper, you also need the Algolia JS client v3. * @example * //using the UMD build * var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76'); * var helper = algoliasearchHelper(client, 'bestbuy', { * facets: ['shipping'], * disjunctiveFacets: ['category'] * }); * helper.on('result', function(result) { * console.log(result); * }); * helper.toggleRefine('Movies & TV Shows') * .toggleRefine('Free shipping') * .search(); * @example * // The helper is an event emitter using the node API * helper.on('result', updateTheResults); * helper.once('result', updateTheResults); * helper.removeListener('result', updateTheResults); * helper.removeAllListeners('result'); * @module algoliasearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the name of the index to query * @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it. * @return {AlgoliaSearchHelper} */ function algoliasearchHelper(client, index, opts) { return new algoliasearch_helper(client, index, opts); } /** * The version currently used * @member module:algoliasearchHelper.version * @type {number} */ algoliasearchHelper.version = version$1; /** * Constructor for the Helper. * @member module:algoliasearchHelper.AlgoliaSearchHelper * @type {AlgoliaSearchHelper} */ algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper; /** * Constructor for the object containing all the parameters of the search. * @member module:algoliasearchHelper.SearchParameters * @type {SearchParameters} */ algoliasearchHelper.SearchParameters = SearchParameters_1; /** * Constructor for the object containing the results of the search. * @member module:algoliasearchHelper.SearchResults * @type {SearchResults} */ algoliasearchHelper.SearchResults = SearchResults_1; /** * URL tools to generate query string and parse them from/into * SearchParameters * @member module:algoliasearchHelper.url * @type {object} {@link url} * */ algoliasearchHelper.url = url; var algoliasearchHelper_1 = algoliasearchHelper; var algoliasearchHelper_4 = algoliasearchHelper_1.SearchParameters; // From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js var shallowEqual = function shallowEqual(objA, objB) { if (objA === objB) { return true; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; }; var getDisplayName = function getDisplayName(Component) { return Component.displayName || Component.name || 'UnknownComponent'; }; var resolved = Promise.resolve(); var defer = function defer(f) { resolved.then(f); }; var removeEmptyKey = function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (isEmpty_1(value) && isPlainObject_1(value)) { delete obj[key]; } else if (isPlainObject_1(value)) { removeEmptyKey(value); } }); return obj; }; function createWidgetsManager(onWidgetsUpdate) { var widgets = []; // Is an update scheduled? var scheduled = false; // The state manager's updates need to be batched since more than one // component can register or unregister widgets during the same tick. function scheduleUpdate() { if (scheduled) { return; } scheduled = true; defer(function () { scheduled = false; onWidgetsUpdate(); }); } return { registerWidget: function registerWidget(widget) { widgets.push(widget); scheduleUpdate(); return function unregisterWidget() { widgets.splice(widgets.indexOf(widget), 1); scheduleUpdate(); }; }, update: scheduleUpdate, getWidgets: function getWidgets() { return widgets; } }; } function createStore(initialState) { var state = initialState; var listeners = []; function dispatch() { listeners.forEach(function (listener) { return listener(); }); } return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; dispatch(); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubcribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } var HIGHLIGHT_TAGS = { highlightPreTag: '<ais-highlight-0000000000>', highlightPostTag: '</ais-highlight-0000000000>' }; /** * Parses an highlighted attribute into an array of objects with the string value, and * a boolean that indicated if this part is highlighted. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature * @return {object[]} - An array of {value: string, isDefined: boolean}. */ function parseHighlightedAttribute(_ref) { var preTag = _ref.preTag, postTag = _ref.postTag, _ref$highlightedValue = _ref.highlightedValue, highlightedValue = _ref$highlightedValue === undefined ? '' : _ref$highlightedValue; var splitByPreTag = highlightedValue.split(preTag); var firstValue = splitByPreTag.shift(); var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }]; if (postTag === preTag) { var isHighlighted = true; splitByPreTag.forEach(function (split) { elements.push({ value: split, isHighlighted: isHighlighted }); isHighlighted = !isHighlighted; }); } else { splitByPreTag.forEach(function (split) { var splitByPostTag = split.split(postTag); elements.push({ value: splitByPostTag[0], isHighlighted: true }); if (splitByPostTag[1] !== '') { elements.push({ value: splitByPostTag[1], isHighlighted: false }); } }); } return elements; } /** * Find an highlighted attribute given an `attribute` and an `highlightProperty`, parses it, * and provided an array of objects with the string value and a boolean if this * value is highlighted. * * In order to use this feature, highlight must be activated in the configuration of * the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and * highligtPostTag in Algolia configuration. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightProperty - the property that contains the highlight structure in the results * @param {string} attribute - the highlighted attribute to look for * @param {object} hit - the actual hit returned by Algolia. * @return {object[]} - An array of {value: string, isHighlighted: boolean}. */ function parseAlgoliaHit(_ref2) { var _ref2$preTag = _ref2.preTag, preTag = _ref2$preTag === undefined ? '<em>' : _ref2$preTag, _ref2$postTag = _ref2.postTag, postTag = _ref2$postTag === undefined ? '</em>' : _ref2$postTag, highlightProperty = _ref2.highlightProperty, attribute = _ref2.attribute, hit = _ref2.hit; if (!hit) throw new Error('`hit`, the matching record, must be provided'); var highlightObject = get_1(hit[highlightProperty], attribute, {}); if (Array.isArray(highlightObject)) { return highlightObject.map(function (item) { return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: item.value }); }); } return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightObject.value }); } var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } /** * Creates a new instance of the InstantSearchManager which controls the widgets and * trigger the search when the widgets are updated. * @param {string} indexName - the main index name * @param {object} initialState - initial widget state * @param {object} SearchParameters - optional additional parameters to send to the algolia API * @param {number} stalledSearchDelay - time (in ms) after the search is stalled * @return {InstantSearchManager} a new instance of InstantSearchManager */ function createInstantSearchManager(_ref) { var indexName = _ref.indexName, _ref$initialState = _ref.initialState, initialState = _ref$initialState === undefined ? {} : _ref$initialState, searchClient = _ref.searchClient, resultsState = _ref.resultsState, stalledSearchDelay = _ref.stalledSearchDelay; var baseSP = new algoliasearchHelper_4(_extends({ index: indexName }, HIGHLIGHT_TAGS)); var stalledSearchTimer = null; var helper = algoliasearchHelper_1(searchClient, indexName, baseSP); helper.on('result', handleSearchSuccess); helper.on('error', handleSearchError); helper.on('search', handleNewSearch); var derivedHelpers = {}; var indexMapping = {}; // keep track of the original index where the parameters applied when sortBy is used. var initialSearchParameters = helper.state; var widgetsManager = createWidgetsManager(onWidgetsUpdate); var store = createStore({ widgets: initialState, metadata: [], results: resultsState || null, error: null, searching: false, isSearchStalled: true, searchingForFacetValues: false }); var skip = false; function skipSearch() { skip = true; } function updateClient(client) { helper.setClient(client); search(); } function clearCache() { helper.clearCache(); search(); } function getMetadata(state) { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getMetadata); }).map(function (widget) { return widget.getMetadata(state); }); } function getSearchParameters() { indexMapping = {}; var sharedParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return !widget.context.multiIndexContext && (widget.props.indexName === indexName || !widget.props.indexName); }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, initialSearchParameters); indexMapping[sharedParameters.index] = indexName; var derivatedWidgets = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex !== indexName || widget.props.indexName && widget.props.indexName !== indexName; }).reduce(function (indices, widget) { var targetedIndex = widget.context.multiIndexContext ? widget.context.multiIndexContext.targetedIndex : widget.props.indexName; var index = find_1(indices, function (i) { return i.targetedIndex === targetedIndex; }); if (index) { index.widgets.push(widget); } else { indices.push({ targetedIndex: targetedIndex, widgets: [widget] }); } return indices; }, []); var mainIndexParameters = widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getSearchParameters); }).filter(function (widget) { return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex === indexName || widget.props.indexName && widget.props.indexName === indexName; }).reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); indexMapping[mainIndexParameters.index] = indexName; return { sharedParameters: sharedParameters, mainIndexParameters: mainIndexParameters, derivatedWidgets: derivatedWidgets }; } function search() { if (!skip) { var _getSearchParameters = getSearchParameters(helper.state), sharedParameters = _getSearchParameters.sharedParameters, mainIndexParameters = _getSearchParameters.mainIndexParameters, derivatedWidgets = _getSearchParameters.derivatedWidgets; Object.keys(derivedHelpers).forEach(function (key) { return derivedHelpers[key].detach(); }); derivedHelpers = {}; helper.setState(sharedParameters); derivatedWidgets.forEach(function (derivatedSearchParameters) { var index = derivatedSearchParameters.targetedIndex; var derivedHelper = helper.derive(function () { var parameters = derivatedSearchParameters.widgets.reduce(function (res, widget) { return widget.getSearchParameters(res); }, sharedParameters); indexMapping[parameters.index] = index; return parameters; }); derivedHelper.on('result', handleSearchSuccess); derivedHelper.on('error', handleSearchError); derivedHelpers[index] = derivedHelper; }); helper.setState(mainIndexParameters); helper.search(); } } function handleSearchSuccess(content) { var state = store.getState(); var results = state.results ? state.results : {}; /* if switching from mono index to multi index and vice versa, results needs to reset to {}*/ results = !isEmpty_1(derivedHelpers) && results.getFacetByName ? {} : results; if (!isEmpty_1(derivedHelpers)) { results[indexMapping[content.index]] = content; } else { results = content; } var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); stalledSearchTimer = null; nextIsSearchStalled = false; } var nextState = omit_1(_extends({}, currentState, { results: results, isSearchStalled: nextIsSearchStalled, searching: false, error: null }), 'resultsFacetValues'); store.setState(nextState); } function handleSearchError(error) { var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); nextIsSearchStalled = false; } var nextState = omit_1(_extends({}, currentState, { isSearchStalled: nextIsSearchStalled, error: error, searching: false }), 'resultsFacetValues'); store.setState(nextState); } function handleNewSearch() { if (!stalledSearchTimer) { stalledSearchTimer = setTimeout(function () { var nextState = omit_1(_extends({}, store.getState(), { isSearchStalled: true }), 'resultsFacetValues'); store.setState(nextState); }, stalledSearchDelay); } } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_extends({}, store.getState(), { metadata: metadata, searching: true })); // Since the `getSearchParameters` method of widgets also depends on props, // the result search parameters might have changed. search(); } function transitionState(nextSearchState) { var searchState = store.getState().widgets; return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.transitionState); }).reduce(function (res, widget) { return widget.transitionState(searchState, res); }, nextSearchState); } function onExternalStateUpdate(nextSearchState) { var metadata = getMetadata(nextSearchState); store.setState(_extends({}, store.getState(), { widgets: nextSearchState, metadata: metadata, searching: true })); search(); } function onSearchForFacetValues(_ref2) { var facetName = _ref2.facetName, query = _ref2.query, maxFacetHits = _ref2.maxFacetHits; store.setState(_extends({}, store.getState(), { searchingForFacetValues: true })); helper.searchForFacetValues(facetName, query, maxFacetHits).then(function (content) { var _extends2; store.setState(_extends({}, store.getState(), { resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_extends2 = {}, _defineProperty$1(_extends2, facetName, content.facetHits), _defineProperty$1(_extends2, 'query', query), _extends2)), searchingForFacetValues: false })); }, function (error) { store.setState(_extends({}, store.getState(), { error: error, searchingForFacetValues: false })); }).catch(function (error) { // Since setState is synchronous, any error that occurs in the render of a // component will be swallowed by this promise. // This is a trick to make the error show up correctly in the console. // See http://stackoverflow.com/a/30741722/969302 setTimeout(function () { throw error; }); }); } function updateIndex(newIndex) { initialSearchParameters = initialSearchParameters.setIndex(newIndex); search(); } function getWidgetsIds() { return store.getState().metadata.reduce(function (res, meta) { return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res; }, []); } return { store: store, widgetsManager: widgetsManager, getWidgetsIds: getWidgetsIds, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, onSearchForFacetValues: onSearchForFacetValues, updateClient: updateClient, updateIndex: updateIndex, clearCache: clearCache, skipSearch: skipSearch }; } var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _extends$2 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); } }return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); }return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass))); }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function validateNextProps(props, nextProps) { if (!props.searchState && nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled"); } else if (props.searchState && !nextProps.searchState) { throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled"); } } /* eslint valid-jsdoc: 0 */ /** * @description * `<InstantSearch>` is the root component of all React InstantSearch implementations. * It provides all the connected components (aka widgets) a means to interact * with the searchState. * @kind widget * @name <InstantSearch> * @requirements You will need to have an Algolia account to be able to use this widget. * [Create one now](https://www.algolia.com/users/sign_up). * @propType {string} appId - Your Algolia application id. * @propType {string} apiKey - Your Algolia search-only API key. * @propType {string} indexName - Main index in which to search. * @propType {boolean} [refresh=false] - Flag to activate when the cache needs to be cleared so that the front-end is updated when a change occurs in the index. * @propType {object} [algoliaClient] - Provide a custom Algolia client instead of the internal one (deprecated in favor of `searchClient`). * @propType {object} [searchClient] - Provide a custom search client. * @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html). * @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html). * @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html). * @propType {SearchResults|SearchResults[]} [resultsState] - Use this to inject the results that will be used at first rendering. Those results are found by using the `findResultsState` function. Useful for [Server Side Rendering](guide/Server-side_rendering.html). * @propType {number} [stalledSearchDelay=200] - The amount of time before considering that the search takes too much time. The time is expressed in milliseconds. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import React from 'react'; * import { InstantSearch, SearchBox, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); */ var InstantSearch = function (_Component) { _inherits(InstantSearch, _Component); function InstantSearch(props) { _classCallCheck(this, InstantSearch); var _this = _possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props)); _this.isControlled = Boolean(props.searchState); var initialState = _this.isControlled ? props.searchState : {}; _this.isUnmounting = false; _this.aisManager = createInstantSearchManager({ indexName: props.indexName, searchClient: props.searchClient, initialState: initialState, resultsState: props.resultsState, stalledSearchDelay: props.stalledSearchDelay }); return _this; } _createClass(InstantSearch, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { validateNextProps(this.props, nextProps); if (this.props.indexName !== nextProps.indexName) { this.aisManager.updateIndex(nextProps.indexName); } if (this.props.refresh !== nextProps.refresh) { if (nextProps.refresh) { this.aisManager.clearCache(); } } if (this.props.searchClient !== nextProps.searchClient) { this.aisManager.updateClient(nextProps.searchClient); } if (this.isControlled) { this.aisManager.onExternalStateUpdate(nextProps.searchState); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.isUnmounting = true; this.aisManager.skipSearch(); } }, { key: 'getChildContext', value: function getChildContext() { // If not already cached, cache the bound methods so that we can forward them as part // of the context. if (!this._aisContextCache) { this._aisContextCache = { ais: { onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this), createHrefForState: this.createHrefForState.bind(this), onSearchForFacetValues: this.onSearchForFacetValues.bind(this), onSearchStateChange: this.onSearchStateChange.bind(this), onSearchParameters: this.onSearchParameters.bind(this) } }; } return { ais: _extends$2({}, this._aisContextCache.ais, { store: this.aisManager.store, widgetsManager: this.aisManager.widgetsManager, mainTargetedIndex: this.props.indexName }) }; } }, { key: 'createHrefForState', value: function createHrefForState(searchState) { searchState = this.aisManager.transitionState(searchState); return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: 'onWidgetsInternalStateUpdate', value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.aisManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.isControlled) { this.aisManager.onExternalStateUpdate(searchState); } } }, { key: 'onSearchStateChange', value: function onSearchStateChange(searchState) { if (this.props.onSearchStateChange && !this.isUnmounting) { this.props.onSearchStateChange(searchState); } } }, { key: 'onSearchParameters', value: function onSearchParameters(getSearchParameters, context, props) { if (this.props.onSearchParameters) { var searchState = this.props.searchState ? this.props.searchState : {}; this.props.onSearchParameters(getSearchParameters, context, props, searchState); } } }, { key: 'onSearchForFacetValues', value: function onSearchForFacetValues(searchState) { this.aisManager.onSearchForFacetValues(searchState); } }, { key: 'getKnownKeys', value: function getKnownKeys() { return this.aisManager.getWidgetsIds(); } }, { key: 'render', value: function render() { var childrenCount = React.Children.count(this.props.children); var _props$root = this.props.root, Root = _props$root.Root, props = _props$root.props; if (childrenCount === 0) return null;else return React__default.createElement(Root, props, this.props.children); } }]); return InstantSearch; }(React.Component); InstantSearch.defaultProps = { stalledSearchDelay: 200 }; InstantSearch.propTypes = { // @TODO: These props are currently constant. indexName: propTypes.string.isRequired, searchClient: propTypes.object.isRequired, createURL: propTypes.func, refresh: propTypes.bool.isRequired, searchState: propTypes.object, onSearchStateChange: propTypes.func, onSearchParameters: propTypes.func, resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]), children: propTypes.node, root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]), props: propTypes.object }).isRequired, stalledSearchDelay: propTypes.number }; InstantSearch.childContextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; var _createClass$2 = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); } }return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; }; }(); function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn$2(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); }return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self; } function _inherits$2(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass))); }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* eslint valid-jsdoc: 0 */ /** * @description * `<Index>` is the component that allows you to apply widgets to a dedicated index. It's * useful if you want to build an interface that targets multiple indices. * @kind widget * @name <Index> * @propType {string} indexName - index in which to search. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import React from 'react'; * import { InstantSearch, Index, SearchBox, Hits, Configure } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Configure hitsPerPage={5} /> * <SearchBox /> * <Index indexName="ikea"> * <Hits /> * </Index> * <Index indexName="bestbuy"> * <Hits /> * </Index> * </InstantSearch> * ); */ var Index = function (_Component) { _inherits$2(Index, _Component); function Index(props, context) { _classCallCheck$2(this, Index); var _this = _possibleConstructorReturn$2(this, (Index.__proto__ || Object.getPrototypeOf(Index)).call(this, props)); var widgetsManager = context.ais.widgetsManager; /* we want <Index> to be seen as a regular widget. It means that with only <Index> present a new query will be sent to Algolia. That way you don't need a virtual hits widget to use the connectAutoComplete. */ _this.unregisterWidget = widgetsManager.registerWidget(_this); return _this; } _createClass$2(Index, [{ key: 'componentWillMount', value: function componentWillMount() { this.context.ais.onSearchParameters(this.getSearchParameters, this.getChildContext(), this.props); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.props.indexName !== nextProps.indexName) { this.context.ais.widgetsManager.update(); } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unregisterWidget(); } }, { key: 'getChildContext', value: function getChildContext() { return { multiIndexContext: { targetedIndex: this.props.indexName } }; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters, props) { return searchParameters.setIndex(this.props ? this.props.indexName : props.indexName); } }, { key: 'render', value: function render() { var childrenCount = React.Children.count(this.props.children); var _props$root = this.props.root, Root = _props$root.Root, props = _props$root.props; if (childrenCount === 0) return null;else return React__default.createElement(Root, props, this.props.children); } }]); return Index; }(React.Component); Index.propTypes = { // @TODO: These props are currently constant. indexName: propTypes.string.isRequired, children: propTypes.node, root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func]), props: propTypes.object }).isRequired }; Index.childContextTypes = { multiIndexContext: propTypes.object.isRequired }; Index.contextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; /** Used for built-in method references. */ var objectProto$l = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$i = objectProto$l.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty$i.call(object, key); } var _baseHas = baseHas; /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has$1(object, path) { return object != null && _hasPath(object, path, _baseHas); } var has_1 = has$1; var _extends$3 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; var _createClass$3 = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); } }return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; }; }(); function _classCallCheck$3(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn$3(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); }return call && ((typeof call === 'undefined' ? 'undefined' : _typeof(call)) === "object" || typeof call === "function") ? call : self; } function _inherits$3(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === 'undefined' ? 'undefined' : _typeof(superClass))); }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = has_1(connectorDesc, 'refine'); var hasSearchForFacetValues = has_1(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = has_1(connectorDesc, 'getSearchParameters'); var hasMetadata = has_1(connectorDesc, 'getMetadata'); var hasTransitionState = has_1(connectorDesc, 'transitionState'); var hasCleanUp = has_1(connectorDesc, 'cleanUp'); var hasShouldComponentUpdate = has_1(connectorDesc, 'shouldComponentUpdate'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp, _initialiseProps; return _temp = _class = function (_Component) { _inherits$3(Connector, _Component); function Connector(props, context) { _classCallCheck$3(this, Connector); var _this = _possibleConstructorReturn$3(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context)); _initialiseProps.call(_this); var _context$ais = context.ais, store = _context$ais.store, widgetsManager = _context$ais.widgetsManager; var canRender = false; _this.state = { props: _this.getProvidedProps(_extends$3({}, props, { canRender: canRender })), canRender: canRender // use to know if a component is rendered (browser), or not (server). }; _this.unsubscribe = store.subscribe(function () { if (_this.state.canRender) { _this.setState({ props: _this.getProvidedProps(_extends$3({}, _this.props, { canRender: _this.state.canRender })) }); } }); if (isWidget) { _this.unregisterWidget = widgetsManager.registerWidget(_this); } return _this; } _createClass$3(Connector, [{ key: 'getMetadata', value: function getMetadata(nextWidgetsState) { if (hasMetadata) { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters) { if (hasSearchParameters) { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.context.ais.store.getState().widgets); } return null; } }, { key: 'transitionState', value: function transitionState(prevWidgetsState, nextWidgetsState) { if (hasTransitionState) { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { key: 'componentDidMount', value: function componentDidMount() { this.setState({ canRender: true }); } }, { key: 'componentWillMount', value: function componentWillMount() { if (connectorDesc.getSearchParameters) { this.context.ais.onSearchParameters(connectorDesc.getSearchParameters, this.context, this.props); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (!isEqual_1(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(nextProps) }); if (isWidget) { // Since props might have changed, we need to re-run getSearchParameters // and getMetadata with the new props. this.context.ais.widgetsManager.update(); if (connectorDesc.transitionState) { this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets)); } } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unsubscribe(); if (isWidget) { this.unregisterWidget(); // will schedule an update if (hasCleanUp) { var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_extends$3({}, this.context.ais.store.getState(), { widgets: newState })); this.context.ais.onSearchStateChange(removeEmptyKey(newState)); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { if (hasShouldComponentUpdate) { return connectorDesc.shouldComponentUpdate.call(this, this.props, nextProps, this.state, nextState); } var propsEqual = shallowEqual(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !shallowEqual(this.state.props, nextState.props); } }, { key: 'render', value: function render() { if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues } : {}; return React__default.createElement(Composed, _extends$3({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component), _class.displayName = connectorDesc.displayName + '(' + getDisplayName(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = { // @TODO: more precise state manager propType ais: propTypes.object.isRequired, multiIndexContext: propTypes.object }, _initialiseProps = function _initialiseProps() { var _this2 = this; this.getProvidedProps = function (props) { var store = _this2.context.ais.store; var _store$getState = store.getState(), results = _store$getState.results, searching = _store$getState.searching, error = _store$getState.error, widgets = _store$getState.widgets, metadata = _store$getState.metadata, resultsFacetValues = _store$getState.resultsFacetValues, searchingForFacetValues = _store$getState.searchingForFacetValues, isSearchStalled = _store$getState.isSearchStalled; var searchResults = { results: results, searching: searching, error: error, searchingForFacetValues: searchingForFacetValues, isSearchStalled: isSearchStalled }; return connectorDesc.getProvidedProps.call(_this2, props, widgets, searchResults, metadata, resultsFacetValues); }; this.refine = function () { var _connectorDesc$refine; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this2.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this2, _this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.searchForFacetValues = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this2.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.createURL = function () { var _connectorDesc$refine2; for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this2.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this2, _this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.cleanUp = function () { var _connectorDesc$cleanU; for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this2].concat(args)); }; }, _temp; }; } /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE$1 = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = _arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = _arrayMap(values, _baseUnary(iteratee)); } if (comparator) { includes = _arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE$1) { includes = _cacheHas; isCommon = false; values = new _SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } var _baseDifference = baseDifference; /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = _baseRest(function(array, values) { return isArrayLikeObject_1(array) ? _baseDifference(array, _baseFlatten(values, 1, isArrayLikeObject_1, true)) : []; }); var difference_1 = difference; var _extends$5 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; function _defineProperty$2(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } function getIndex(context) { return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (searchResults.results && !searchResults.results.hits) { return searchResults.results[getIndex(context)] ? searchResults.results[getIndex(context)] : null; } else { return searchResults.results ? searchResults.results : null; } } function hasMultipleIndex(context) { return context && context.multiIndexContext; } // eslint-disable-next-line max-params function refineValue(searchState, nextRefinement, context, resetPage, namespace) { if (hasMultipleIndex(context)) { return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage); } else { // When we have a multi index page with shared widgets we should also // reset their page to 1 if the resetPage is provided. Otherwise the // indices will always be reset // see: https://github.com/algolia/react-instantsearch/issues/310 // see: https://github.com/algolia/react-instantsearch/issues/637 if (searchState.indices && resetPage) { Object.keys(searchState.indices).forEach(function (targetedIndex) { searchState = refineValue(searchState, { page: 1 }, { multiIndexContext: { targetedIndex: targetedIndex } }, true, namespace); }); } return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage); } } function refineMultiIndex(searchState, nextRefinement, context, resetPage) { var page = resetPage ? { page: 1 } : undefined; var index = getIndex(context); var state = has_1(searchState, 'indices.' + index) ? _extends$5({}, searchState.indices, _defineProperty$2({}, index, _extends$5({}, searchState.indices[index], nextRefinement, page))) : _extends$5({}, searchState.indices, _defineProperty$2({}, index, _extends$5({}, nextRefinement, page))); return _extends$5({}, searchState, { indices: state }); } function refineSingleIndex(searchState, nextRefinement, resetPage) { var page = resetPage ? { page: 1 } : undefined; return _extends$5({}, searchState, nextRefinement, page); } // eslint-disable-next-line max-params function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) { var _extends4; var index = getIndex(context); var page = resetPage ? { page: 1 } : undefined; var state = has_1(searchState, 'indices.' + index) ? _extends$5({}, searchState.indices, _defineProperty$2({}, index, _extends$5({}, searchState.indices[index], (_extends4 = {}, _defineProperty$2(_extends4, namespace, _extends$5({}, searchState.indices[index][namespace], nextRefinement)), _defineProperty$2(_extends4, 'page', 1), _extends4)))) : _extends$5({}, searchState.indices, _defineProperty$2({}, index, _extends$5(_defineProperty$2({}, namespace, nextRefinement), page))); return _extends$5({}, searchState, { indices: state }); } function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) { var page = resetPage ? { page: 1 } : undefined; return _extends$5({}, searchState, _defineProperty$2({}, namespace, _extends$5({}, searchState[namespace], nextRefinement)), page); } function getNamespaceAndAttributeName(id) { var parts = id.match(/^([^.]*)\.(.*)/); var namespace = parts && parts[1]; var attributeName = parts && parts[2]; return { namespace: namespace, attributeName: attributeName }; } // eslint-disable-next-line max-params function getCurrentRefinementValue(props, searchState, context, id, defaultValue) { var refinementsCallback = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : function (x) { return x; }; var index = getIndex(context); var _getNamespaceAndAttri = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri.namespace, attributeName = _getNamespaceAndAttri.attributeName; var refinements = hasMultipleIndex(context) && searchState.indices && namespace && searchState.indices['' + index] && has_1(searchState.indices['' + index][namespace], '' + attributeName) || hasMultipleIndex(context) && searchState.indices && has_1(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && namespace && has_1(searchState[namespace], attributeName) || !hasMultipleIndex(context) && has_1(searchState, id); if (refinements) { var currentRefinement = void 0; if (hasMultipleIndex(context)) { currentRefinement = namespace ? get_1(searchState.indices['' + index][namespace], attributeName) : get_1(searchState.indices[index], id); } else { currentRefinement = namespace ? get_1(searchState[namespace], attributeName) : get_1(searchState, id); } return refinementsCallback(currentRefinement); } if (props.defaultRefinement) { return props.defaultRefinement; } return defaultValue; } function cleanUpValue(searchState, context, id) { var indexName = getIndex(context); var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri2.namespace, attributeName = _getNamespaceAndAttri2.attributeName; if (hasMultipleIndex(context) && Boolean(searchState.indices)) { return cleanUpValueWithMutliIndex({ attribute: attributeName, searchState: searchState, indexName: indexName, id: id, namespace: namespace }); } return cleanUpValueWithSingleIndex({ attribute: attributeName, searchState: searchState, id: id, namespace: namespace }); } function cleanUpValueWithSingleIndex(_ref) { var searchState = _ref.searchState, id = _ref.id, namespace = _ref.namespace, attribute = _ref.attribute; if (namespace) { return _extends$5({}, searchState, _defineProperty$2({}, namespace, omit_1(searchState[namespace], attribute))); } return omit_1(searchState, id); } function cleanUpValueWithMutliIndex(_ref2) { var searchState = _ref2.searchState, indexName = _ref2.indexName, id = _ref2.id, namespace = _ref2.namespace, attribute = _ref2.attribute; var index = searchState.indices[indexName]; if (namespace && index) { return _extends$5({}, searchState, { indices: _extends$5({}, searchState.indices, _defineProperty$2({}, indexName, _extends$5({}, index, _defineProperty$2({}, namespace, omit_1(index[namespace], attribute))))) }); } return omit_1(searchState, 'indices.' + indexName + '.' + id); } var _extends$6 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; function _defineProperty$3(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } function getId() { return 'configure'; } var connectConfigure = createConnector({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var items = omit_1(props, 'children'); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var items = omit_1(props, 'children'); var nonPresentKeys = this._props ? difference_1(keys_1(this._props), keys_1(props)) : []; this._props = props; var nextValue = _defineProperty$3({}, id, _extends$6({}, omit_1(nextSearchState[id], nonPresentKeys), items)); return refineValue(nextSearchState, nextValue, this.context); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var index = getIndex(this.context); var subState = hasMultipleIndex(this.context) && searchState.indices ? searchState.indices[index] : searchState; var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : []; var configureState = configureKeys.reduce(function (acc, item) { if (!props[item]) { acc[item] = subState[id][item]; } return acc; }, {}); var nextValue = _defineProperty$3({}, id, configureState); return refineValue(searchState, nextValue, this.context); } }); /** * Configure is a widget that lets you provide raw search parameters * to the Algolia API. * * Any of the props added to this widget will be forwarded to Algolia. For more information * on the different parameters that can be set, have a look at the * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). * * This widget can be used either with react-dom and react-native. It will not render anything * on screen, only configure some parameters. * * Read more in the [Search parameters](guide/Search_parameters.html) guide. * @name Configure * @kind widget * @example * import React from 'react'; * import { InstantSearch, Configure, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <Configure hitsPerPage={5} /> * <Hits /> * </InstantSearch> * ); */ connectConfigure(function () { return null; }); function _defineProperty$4(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; }return arr2; } else { return Array.from(arr); } } var getId$1 = function getId() { return 'query'; }; function getCurrentRefinement(props, searchState, context) { var id = getId$1(); return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function getHits(searchResults) { if (searchResults.results) { if (searchResults.results.hits && Array.isArray(searchResults.results.hits)) { return searchResults.results.hits; } else { return Object.keys(searchResults.results).reduce(function (hits, index) { return [].concat(_toConsumableArray(hits), [{ index: index, hits: searchResults.results[index].hits }]); }, []); } } else { return []; } } function _refine(props, searchState, nextRefinement, context) { var id = getId$1(); var nextValue = _defineProperty$4({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage); } function _cleanUp(props, searchState, context) { return cleanUpValue(searchState, context, getId$1()); } /** * connectAutoComplete connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * @name connectAutoComplete * @kind connector * @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 = createConnector({ displayName: 'AlgoliaAutoComplete', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { hits: getHits(searchResults), currentRefinement: getCurrentRefinement(props, searchState, this.context) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, /* connectAutoComplete needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement(props, searchState, this.context)); } }); function _defineProperty$5(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var getId$2 = function getId(props) { return props.attributes[0]; }; var namespace = 'hierarchicalMenu'; function _refine$1(props, searchState, nextRefinement, context) { var id = getId$2(props); var nextValue = _defineProperty$5({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace); } function transformValue(values) { return values.reduce(function (acc, item) { if (item.isRefined) { acc.push({ label: item.name, // If dealing with a nested "items", "value" is equal to the previous value concatenated with the current label // If dealing with the first level, "value" is equal to the current label value: item.path }); // Create a variable in order to keep the same acc for the recursion, otherwise "reduce" returns a new one if (item.data) { acc = acc.concat(transformValue(item.data, acc)); } } return acc; }, []); } /** * The breadcrumb component is s a type of secondary navigation scheme that * reveals the user’s location in a website or web application. * * @name connectBreadcrumb * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a Breadcrumb of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display. */ var connectBreadcrumb = createConnector({ displayName: 'AlgoliaBreadcrumb', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var id = getId$2(props); var results = getResults(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], canRefine: false }; } var values = results.getFacetValues(id); var items = values.data ? transformValue(values.data) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { canRefine: transformedItems.length > 0, items: transformedItems }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$1(props, searchState, nextRefinement, this.context); } }); var _extends$7 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; /** * connectCurrentRefinements connector provides the logic to build a widget that will * give the user the ability to remove all or some of the filters that were * set. * @name connectCurrentRefinements * @kind connector * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {function} [clearsQuery=false] - Pass true to also clear the search query * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {array.<{label: string, attribute: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attribute` and `currentRefinement` are metadata containing row values. * @providedPropType {string} query - the search query */ var connectCurrentRefinements = createConnector({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) { var items = metadata.reduce(function (res, meta) { if (typeof meta.items !== 'undefined') { if (!props.clearsQuery && meta.id === 'query') { return res; } else { if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') { return res; } return res.concat(meta.items.map(function (item) { return _extends$7({}, item, { id: meta.id, index: meta.index }); })); } } return res; }, []); return { items: props.transformItems ? props.transformItems(items) : items, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, items) { // `value` corresponds to our internal clear function computed in each connector metadata. var refinementsToClear = items instanceof Array ? items.map(function (item) { return item.value; }) : [items]; return refinementsToClear.reduce(function (res, clear) { return clear(res); }, searchState); } }); function _defineProperty$6(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } 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; } /** * 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 (isEmpty_1(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$6({}, getBoundingBoxId(), nextValue); return refineValue(searchState, nextRefinement, context, resetPage); }; var connectGeoSearch = createConnector({ displayName: 'AlgoliaGeoSearch', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.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 immediatly 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, this.context); var currentRefinementFromSearchParameters = results && results._state.insideBoundingBox && stringToCurrentRefinement(results._state.insideBoundingBox) || undefined; var currentPositionFromSearchState = getCurrentPosition(props, searchState, this.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, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var currentRefinement = getCurrentRefinement$1(props, searchState, this.context); if (!currentRefinement) { return searchParameters; } return searchParameters.setQueryParameter('insideBoundingBox', currentRefinementToString(currentRefinement)); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getBoundingBoxId()); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var items = []; var id = getBoundingBoxId(); var index = getIndex(this.context); var nextRefinement = {}; var currentRefinement = getCurrentRefinement$1(props, searchState, this.context); if (currentRefinement) { items.push({ label: id + ': ' + currentRefinementToString(currentRefinement), value: function value(nextState) { return _refine$2(nextState, nextRefinement, _this.context); }, currentRefinement: currentRefinement }); } return { id: id, index: index, items: items }; }, shouldComponentUpdate: function shouldComponentUpdate() { return true; } }); var _extends$8 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; function _defineProperty$7(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var getId$3 = function getId(props) { return props.attributes[0]; }; var namespace$1 = 'hierarchicalMenu'; function getCurrentRefinement$2(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$1 + '.' + getId$3(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$1(path, props, searchState, context) { var id = props.id, attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel; var currentRefinement = getCurrentRefinement$2(props, searchState, context); var nextRefinement = void 0; if (currentRefinement === null) { nextRefinement = path; } else { var tmpSearchParameters = new algoliasearchHelper_4({ hierarchicalFacets: [{ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }] }); nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0]; } return nextRefinement; } function transformValue$1(value, props, searchState, context) { return value.map(function (v) { return { label: v.name, value: getValue$1(v.path, props, searchState, context), count: v.count, isRefined: v.isRefined, items: v.data && transformValue$1(v.data, props, searchState, context) }; }); } var truncate = function truncate() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; return items.slice(0, limit).map(function () { var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return Array.isArray(item.items) ? _extends$8({}, item, { items: truncate(item.items, limit) }) : item; }); }; function _refine$3(props, searchState, nextRefinement, context) { var id = getId$3(props); var nextValue = _defineProperty$7({}, id, nextRefinement || ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$1); } function _cleanUp$1(props, searchState, context) { return cleanUpValue(searchState, context, namespace$1 + '.' + getId$3(props)); } var sortBy = ['name:asc']; /** * connectHierarchicalMenu connector provides the logic to build a widget that will * give the user the ability to explore a tree-like structure. * This is commonly used for multi-level categorization of products on e-commerce * websites. From a UX point of view, we suggest not displaying more than two levels deep. * @name connectHierarchicalMenu * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a hiearchical menu of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {string} [defaultRefinement] - the item value selected by default * @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limit and showMoreLimit. * @propType {number} [limit=10] - The maximum number of items displayed. * @propType {number} [showMoreLimit=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false. * @propType {string} [separator='>'] - Specifies the level separator used in the data. * @propType {string[]} [rootPath=null] - The already selected and hidden path. * @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items. */ var connectHierarchicalMenu = createConnector({ displayName: 'AlgoliaHierarchicalMenu', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings'); } return undefined; }, separator: propTypes.string, rootPath: propTypes.string, showParentLevel: propTypes.bool, defaultRefinement: propTypes.string, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, transformItems: propTypes.func }, defaultProps: { showMore: false, limit: 10, showMoreLimit: 20, separator: ' > ', rootPath: null, showParentLevel: true }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var showMore = props.showMore, limit = props.limit, showMoreLimit = props.showMoreLimit; var id = getId$3(props); var results = getResults(searchResults, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement$2(props, searchState, this.context), canRefine: false }; } var itemsLimit = showMore ? showMoreLimit : limit; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue$1(value.data, props, searchState, this.context) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: truncate(transformedItems, itemsLimit), currentRefinement: getCurrentRefinement$2(props, searchState, this.context), canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$3(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$1(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel, showMore = props.showMore, limit = props.limit, showMoreLimit = props.showMoreLimit; var id = getId$3(props); var itemsLimit = showMore ? showMoreLimit : limit; searchParameters = searchParameters.addHierarchicalFacet({ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }).setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, itemsLimit) }); var currentRefinement = getCurrentRefinement$2(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var rootAttribute = props.attributes[0]; var id = getId$3(props); var currentRefinement = getCurrentRefinement$2(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: !currentRefinement ? [] : [{ label: rootAttribute + ': ' + currentRefinement, attribute: rootAttribute, value: function value(nextState) { return _refine$3(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); var highlight = function highlight(_ref) { var attribute = _ref.attribute, hit = _ref.hit, highlightProperty = _ref.highlightProperty, _ref$preTag = _ref.preTag, preTag = _ref$preTag === undefined ? HIGHLIGHT_TAGS.highlightPreTag : _ref$preTag, _ref$postTag = _ref.postTag, postTag = _ref$postTag === undefined ? HIGHLIGHT_TAGS.highlightPostTag : _ref$postTag; return parseAlgoliaHit({ attribute: attribute, highlightProperty: highlightProperty, hit: hit, preTag: preTag, postTag: postTag }); }; /** * connectHighlight connector provides the logic to create an highlighter * component that will retrieve, parse and render an highlighted attribute * from an Algolia hit. * @name connectHighlight * @kind connector * @category connector * @providedPropType {function} highlight - function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attributes: `highlightProperty` which is the property that contains the highlight structure from the records, `attribute` which is the name of the attribute (it can be either a string or an array of strings) to look for and `hit` which is the hit from Algolia. It returns an array of objects `{value: string, isHighlighted: boolean}`. If the element that corresponds to the attribute is an array of strings, it will return a nested array of objects. * @example * import React from 'react'; * import { InstantSearch, SearchBox, Hits, connectHighlight } from 'react-instantsearch-dom'; * * const CustomHighlight = connectHighlight( * ({ highlight, attribute, hit, highlightProperty }) => { * const highlights = highlight({ * highlightProperty: '_highlightResult', * attribute, * hit * }); * * return highlights.map(part => part.isHighlighted ? ( * <mark>{part.value}</mark> * ) : ( * <span>{part.value}</span> * )); * } * ); * * const Hit = ({ hit }) => ( * <p> * <CustomHighlight attribute="name" hit={hit} /> * </p> * ); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox defaultRefinement="legi" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var connectHighlight = createConnector({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); /** * connectHits connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * * **Warning:** you will need to use the **objectID** property available on every hit as a key * when iterating over them. This will ensure you have the best possible UI experience * especially on slow networks. * @name connectHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @example * import React from 'react'; * import { InstantSearch, Highlight, connectHits } from 'react-instantsearch-dom'; * * const CustomHits = connectHits(({ hits }) => ( * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attribute="name" hit={hit} /> * </p> * )} * </div> * ); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <CustomHits /> * </InstantSearch> * ); */ var connectHits = createConnector({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); var hits = results ? results.hits : []; return { hits: hits }; }, /* Hits needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters) { return searchParameters; } }); var _extends$9 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; function _defineProperty$8(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } function getId$4() { return 'hitsPerPage'; } function getCurrentRefinement$3(props, searchState, context) { var id = getId$4(); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * connectHitsPerPage connector provides the logic to create connected * components that will allow a user to choose to display more or less results from Algolia. * @name connectHitsPerPage * @kind connector * @propType {number} defaultRefinement - The number of items selected by default * @propType {{value: number, label: string}[]} items - List of hits per page options. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectHitsPerPage = createConnector({ displayName: 'AlgoliaHitsPerPage', propTypes: { defaultRefinement: propTypes.number.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.number.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$3(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends$9({}, item, { isRefined: true }) : _extends$9({}, item, { isRefined: false }); }); return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { var id = getId$4(); var nextValue = _defineProperty$8({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$4()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement$3(props, searchState, this.context)); }, getMetadata: function getMetadata() { return { id: getId$4() }; } }); function _defineProperty$9(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } function _toConsumableArray$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; }return arr2; } else { return Array.from(arr); } } function getId$5() { return 'page'; } function getCurrentRefinement$4(props, searchState, context) { var id = getId$5(); var page = 1; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { currentRefinement = parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * InfiniteHits connector provides the logic to create connected * components that will render an continuous list of results retrieved from * Algolia. This connector provides a function to load more results. * @name connectInfiniteHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @providedPropType {boolean} hasMore - indicates if there are more pages to load * @providedPropType {function} refine - call to load more results */ var connectInfiniteHits = createConnector({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); this._allResults = this._allResults || []; this._previousPage = this._previousPage || 0; if (!results) { return { hits: [], hasMore: false }; } var hits = results.hits, page = results.page, nbPages = results.nbPages; if (page === 0) { this._allResults = hits; } else if (page > this._previousPage) { this._allResults = [].concat(_toConsumableArray$1(this._allResults), _toConsumableArray$1(hits)); } else if (page < this._previousPage) { this._allResults = hits; } var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; this._previousPage = page; return { hits: this._allResults, hasMore: hasMore }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQueryParameters({ page: getCurrentRefinement$4(props, searchState, this.context) - 1 }); }, refine: function refine(props, searchState) { var id = getId$5(); var nextPage = getCurrentRefinement$4(props, searchState, this.context) + 1; var nextValue = _defineProperty$9({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, this.context, resetPage); } }); function _defineProperty$a(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var namespace$2 = 'menu'; function getId$6(props) { return props.attribute; } function getCurrentRefinement$5(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$2 + '.' + getId$6(props), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$2(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$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$a({}, id, nextRefinement ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$2); } function _cleanUp$2(props, searchState, context) { return cleanUpValue(searchState, context, namespace$2 + '.' + getId$6(props)); } var sortBy$1 = ['count:desc', 'name:asc']; /** * connectMenu connector provides the logic to build a widget that will * give the user the ability to choose a single value for a specific facet. * @name connectMenu * @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @kind connector * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limit=10] - the minimum number of diplayed items * @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {boolean} [searchable=false] - allow search inside values * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var connectMenu = createConnector({ displayName: 'AlgoliaMenu', propTypes: { attribute: propTypes.string.isRequired, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, defaultRefinement: propTypes.string, transformItems: propTypes.func, searchable: propTypes.bool }, defaultProps: { showMore: false, limit: 10, showMoreLimit: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var _this = this; var attribute = props.attribute, searchable = props.searchable; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search) if (searchable && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$5(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$2(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attribute, { sortBy: sortBy$1 }).map(function (v) { return { label: v.name, value: getValue$2(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var sortedItems = searchable && !isFromSearch ? orderBy_1(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items; var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems; return { items: transformedItems.slice(0, getLimit(props)), currentRefinement: getCurrentRefinement$5(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$4(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$2(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit(props)) }); searchParameters = searchParameters.addDisjunctiveFacet(attribute); var currentRefinement = getCurrentRefinement$5(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this2 = this; var id = getId$6(props); var currentRefinement = getCurrentRefinement$5(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: props.attribute + ': ' + currentRefinement, attribute: props.attribute, value: function value(nextState) { return _refine$4(props, nextState, '', _this2.context); }, currentRefinement: currentRefinement }] }; } }); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = [];var _n = true;var _d = false;var _e = undefined;try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value);if (i && _arr.length === i) break; } } catch (err) { _d = true;_e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } }return _arr; }return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); function _defineProperty$b(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } function stringifyItem(item) { if (typeof item.start === 'undefined' && typeof item.end === 'undefined') { return ''; } return (item.start ? item.start : '') + ':' + (item.end ? item.end : ''); } function parseItem(value) { if (value.length === 0) { return { start: null, end: null }; } var _value$split = value.split(':'), _value$split2 = _slicedToArray(_value$split, 2), startStr = _value$split2[0], endStr = _value$split2[1]; return { start: startStr.length > 0 ? parseInt(startStr, 10) : null, end: endStr.length > 0 ? parseInt(endStr, 10) : null }; } var namespace$3 = 'multiRange'; function getId$7(props) { return props.attribute; } function getCurrentRefinement$6(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$3 + '.' + getId$7(props), '', function (currentRefinement) { if (currentRefinement === '') { return ''; } return currentRefinement; }); } function isRefinementsRangeIncludesInsideItemRange(stats, start, end) { return stats.min > start && stats.min < end || stats.max > start && stats.max < end; } function isItemRangeIncludedInsideRefinementsRange(stats, start, end) { return start > stats.min && start < stats.max || end > stats.min && end < stats.max; } function itemHasRefinement(attribute, results, value) { var stats = results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null; var range = value.split(':'); var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]); var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]); return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end))); } function _refine$5(props, searchState, nextRefinement, context) { var nextValue = _defineProperty$b({}, getId$7(props, searchState), nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$3); } function _cleanUp$3(props, searchState, context) { return cleanUpValue(searchState, context, namespace$3 + '.' + getId$7(props)); } /** * connectNumericMenu connector provides the logic to build a widget that will * give the user the ability to select a range value for a numeric attribute. * Ranges are defined statically. * @name connectNumericMenu * @requirements The attribute passed to the `attribute` prop must be holding numerical values. * @kind connector * @propType {string} attribute - the name of the attribute in the records * @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds. * @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string. * @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the NumericMenu can display. */ var connectNumericMenu = createConnector({ displayName: 'AlgoliaNumericMenu', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node, start: propTypes.number, end: propTypes.number })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute; var currentRefinement = getCurrentRefinement$6(props, searchState, this.context); var results = getResults(searchResults, this.context); var items = props.items.map(function (item) { var value = stringifyItem(item); return { label: item.label, value: value, isRefined: value === currentRefinement, noRefinement: results ? itemHasRefinement(getId$7(props), results, value) : false }; }); var stats = results && results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null; var refinedItem = find_1(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: isEmpty_1(refinedItem), noRefinement: !stats, label: 'All' }); } return { items: props.transformItems ? props.transformItems(items) : items, currentRefinement: currentRefinement, canRefine: items.length > 0 && items.some(function (item) { return item.noRefinement === false; }) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$5(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$3(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; var _parseItem = parseItem(getCurrentRefinement$6(props, searchState, this.context)), start = _parseItem.start, end = _parseItem.end; searchParameters = searchParameters.addDisjunctiveFacet(attribute); if (start) { searchParameters = searchParameters.addNumericRefinement(attribute, '>=', start); } if (end) { searchParameters = searchParameters.addNumericRefinement(attribute, '<=', end); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$7(props); var value = getCurrentRefinement$6(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (value !== '') { var _find2 = find_1(props.items, function (item) { return stringifyItem(item) === value; }), label = _find2.label; items.push({ label: props.attribute + ': ' + label, attribute: props.attribute, currentRefinement: label, value: function value(nextState) { return _refine$5(props, nextState, '', _this.context); } }); } return { id: id, index: index, items: items }; } }); function _defineProperty$c(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } function getId$8() { return 'page'; } function getCurrentRefinement$7(props, searchState, context) { var id = getId$8(); var page = 1; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } function _refine$6(props, searchState, nextPage, context) { var id = getId$8(); var nextValue = _defineProperty$c({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, context, resetPage); } /** * connectPagination connector provides the logic to build a widget that will * let the user displays hits corresponding to a certain page. * @name connectPagination * @kind connector * @propType {boolean} [showFirst=true] - Display the first page link. * @propType {boolean} [showLast=false] - Display the last page link. * @propType {boolean} [showPrevious=true] - Display the previous page link. * @propType {boolean} [showNext=true] - Display the next page link. * @propType {number} [padding=3] - How many page links to display around the current page. * @propType {number} [totalPages=Infinity] - Maximum number of pages to display. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {number} nbPages - the total of existing pages * @providedPropType {number} currentRefinement - the page refinement currently applied */ var connectPagination = createConnector({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement$7(props, searchState, this.context), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine$6(props, searchState, nextPage, this.context); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$8()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement$7(props, searchState, this.context) - 1); }, getMetadata: function getMetadata() { return { id: getId$8() }; } }); /** * connectPoweredBy connector provides the logic to build a widget that * will display a link to algolia. * @name connectPoweredBy * @kind connector * @providedPropType {string} url - the url to redirect to algolia */ var connectPoweredBy = createConnector({ displayName: 'AlgoliaPoweredBy', propTypes: {}, getProvidedProps: function getProvidedProps(props) { var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + ('utm_content=' + (props.canRender ? location.hostname : '') + '&') + 'utm_campaign=poweredby'; return { url: url }; } }); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsFinite = _root.isFinite; /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } var _isFinite = isFinite; function _defineProperty$d(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } /** * connectRange connector provides the logic to create connected * components that will give the ability for a user to refine results using * a numeric range. * @name connectRange * @kind connector * @requirements The attribute passed to the `attribute` prop must be present in “attributes for faceting” * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * The values inside the attribute must be JavaScript numbers (not strings). * @propType {string} attribute - Name of the attribute for faceting * @propType {{min?: number, max?: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range. * @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index. * @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index. * @propType {number} [precision=0] - Number of digits after decimal point to use. * @providedPropType {function} refine - a function to select a range. * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {number} min - the minimum value available. * @providedPropType {number} max - the maximum value available. * @providedPropType {number} precision - Number of digits after decimal point to use. */ function getId$9(props) { return props.attribute; } var namespace$4 = 'range'; function getCurrentRange(boundaries, stats, precision) { var pow = Math.pow(10, precision); var min = void 0; if (_isFinite(boundaries.min)) { min = boundaries.min; } else if (_isFinite(stats.min)) { min = stats.min; } else { min = undefined; } var max = void 0; if (_isFinite(boundaries.max)) { max = boundaries.max; } else if (_isFinite(stats.max)) { max = stats.max; } else { max = undefined; } return { min: min !== undefined ? Math.floor(min * pow) / pow : min, max: max !== undefined ? Math.ceil(max * pow) / pow : max }; } function getCurrentRefinement$8(props, searchState, currentRange, context) { var refinement = getCurrentRefinementValue(props, searchState, context, namespace$4 + '.' + getId$9(props), {}, function (currentRefinement) { var min = currentRefinement.min, max = currentRefinement.max; var isFloatPrecision = Boolean(props.precision); var nextMin = min; if (typeof nextMin === 'string') { nextMin = isFloatPrecision ? parseFloat(nextMin) : parseInt(nextMin, 10); } var nextMax = max; if (typeof nextMax === 'string') { nextMax = isFloatPrecision ? parseFloat(nextMax) : parseInt(nextMax, 10); } return { min: nextMin, max: nextMax }; }); var hasMinBound = props.min !== undefined; var hasMaxBound = props.max !== undefined; var hasMinRefinment = refinement.min !== undefined; var hasMaxRefinment = refinement.max !== undefined; if (hasMinBound && hasMinRefinment && refinement.min < currentRange.min) { throw Error("You can't provide min value lower than range."); } if (hasMaxBound && hasMaxRefinment && refinement.max > currentRange.max) { throw Error("You can't provide max value greater than range."); } if (hasMinBound && !hasMinRefinment) { refinement.min = currentRange.min; } if (hasMaxBound && !hasMaxRefinment) { refinement.max = currentRange.max; } return refinement; } function getCurrentRefinementWithRange(refinement, range) { return { min: refinement.min !== undefined ? refinement.min : range.min, max: refinement.max !== undefined ? refinement.max : range.max }; } function nextValueForRefinement(hasBound, isReset, range, value) { var next = void 0; if (!hasBound && range === value) { next = undefined; } else if (hasBound && isReset) { next = range; } else { next = value; } return next; } function _refine$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$d({}, id, { min: nextValueForRefinement(props.min !== undefined, isMinReset, currentMinRange, nextMinAsNumber), max: nextValueForRefinement(props.max !== undefined, isMaxReset, currentMaxRange, nextMaxAsNumber) }); return refineValue(searchState, nextValue, context, resetPage, namespace$4); } function _cleanUp$4(props, searchState, context) { return cleanUpValue(searchState, context, namespace$4 + '.' + getId$9(props)); } var connectRange = createConnector({ displayName: 'AlgoliaRange', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, defaultRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }), min: propTypes.number, max: propTypes.number, precision: propTypes.number, header: propTypes.node, footer: propTypes.node }, defaultProps: { precision: 0 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute, precision = props.precision, minBound = props.min, maxBound = props.max; var results = getResults(searchResults, this.context); var hasFacet = results && results.getFacetByName(attribute); var stats = hasFacet ? results.getFacetStats(attribute) || {} : {}; var facetValues = hasFacet ? results.getFacetValues(attribute) : []; var count = facetValues.map(function (v) { return { value: v.name, count: v.count }; }); var _getCurrentRange = getCurrentRange({ min: minBound, max: maxBound }, stats, precision), rangeMin = _getCurrentRange.min, rangeMax = _getCurrentRange.max; // The searchState is not always in sync with the helper state. For example // when we set boundaries on the first render the searchState don't have // the correct refinement. If this behaviour change in the upcoming version // we could store the range inside the searchState instead of rely on `this`. this._currentRange = { min: rangeMin, max: rangeMax }; var currentRefinement = getCurrentRefinement$8(props, searchState, this._currentRange, this.context); return { min: rangeMin, max: rangeMax, canRefine: count.length > 0, currentRefinement: getCurrentRefinementWithRange(currentRefinement, this._currentRange), count: count, precision: precision }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$7(props, searchState, nextRefinement, this._currentRange, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$4(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attribute = props.attribute; var _getCurrentRefinement = getCurrentRefinement$8(props, searchState, this._currentRange, this.context), min = _getCurrentRefinement.min, max = _getCurrentRefinement.max; params = params.addDisjunctiveFacet(attribute); if (min !== undefined) { params = params.addNumericRefinement(attribute, '>=', min); } if (max !== undefined) { params = params.addNumericRefinement(attribute, '<=', max); } return params; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var _currentRange = this._currentRange, minRange = _currentRange.min, maxRange = _currentRange.max; var _getCurrentRefinement2 = getCurrentRefinement$8(props, searchState, this._currentRange, this.context), minValue = _getCurrentRefinement2.min, maxValue = _getCurrentRefinement2.max; var items = []; var hasMin = minValue !== undefined; var hasMax = maxValue !== undefined; var shouldDisplayMinLabel = hasMin && minValue !== minRange; var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange; if (shouldDisplayMinLabel || shouldDisplayMaxLabel) { var fragments = [hasMin ? minValue + ' <= ' : '', props.attribute, hasMax ? ' <= ' + maxValue : '']; items.push({ label: fragments.join(''), attribute: props.attribute, value: function value(nextState) { return _refine$7(props, nextState, {}, _this._currentRange, _this.context); }, currentRefinement: getCurrentRefinementWithRange({ min: minValue, max: maxValue }, { min: minRange, max: maxRange }) }); } return { id: getId$9(props), index: getIndex(this.context), items: items }; } }); function _defineProperty$e(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var namespace$5 = 'refinementList'; function getId$a(props) { return props.attribute; } function getCurrentRefinement$9(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$5 + '.' + getId$a(props), [], function (currentRefinement) { if (typeof currentRefinement === 'string') { // All items were unselected if (currentRefinement === '') { return []; } // Only one item was in the searchState but we know it should be an array return [currentRefinement]; } return currentRefinement; }); } function getValue$3(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$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$e({}, id, nextRefinement.length > 0 ? nextRefinement : ''); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$5); } function _cleanUp$5(props, searchState, context) { return cleanUpValue(searchState, context, namespace$5 + '.' + getId$a(props)); } /** * connectRefinementList connector provides the logic to build a widget that will * give the user the ability to choose multiple values for a specific facet. * @name connectRefinementList * @kind connector * @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [searchable=false] - allow search inside values * @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'. * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limit=10] - the minimum number of displayed items * @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var sortBy$2 = ['isRefined', 'count:desc', 'name:asc']; var connectRefinementList = createConnector({ displayName: 'AlgoliaRefinementList', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, operator: propTypes.oneOf(['and', 'or']), showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), searchable: propTypes.bool, transformItems: propTypes.func }, defaultProps: { operator: 'or', showMore: false, limit: 10, showMoreLimit: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) { var _this = this; var attribute = props.attribute, searchable = props.searchable; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search) if (searchable && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$9(props, searchState, this.context), canRefine: canRefine, isFromSearch: isFromSearch, searchable: searchable }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$3(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attribute, { sortBy: sortBy$2 }).map(function (v) { return { label: v.name, value: getValue$3(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit$1(props)), currentRefinement: getCurrentRefinement$9(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: items.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$8(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit$1(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$5(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, operator = props.operator; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = addKey + 'Refinement'; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props)) }); searchParameters = searchParameters[addKey](attribute); return getCurrentRefinement$9(props, searchState, this.context).reduce(function (res, val) { return res[addRefinementKey](attribute, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId$a(props); var context = this.context; return { id: id, index: getIndex(this.context), items: getCurrentRefinement$9(props, searchState, context).length > 0 ? [{ attribute: props.attribute, label: 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: '' + 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 = createConnector({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: propTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = getCurrentRefinementValue(props, searchState, this.context, id, null, function (currentRefinement) { return currentRefinement; }); if (!this._prevSearchState) { this._prevSearchState = {}; } /* Get the subpart of the state that interest us*/ if (hasMultipleIndex(this.context)) { var index = getIndex(this.context); searchState = searchState.indices ? searchState.indices[index] : {}; } /* if there is a change in the app that has been triggered by another element than "props.scrollOn (id) or the Configure widget, we need to keep track of the search state to know if there's a change in the app that was not triggered by the props.scrollOn (id) or the Configure widget. This is useful when using ScrollTo in combination of Pagination. As pagination can be change by every widget, we want to scroll only if it cames from the pagination widget itself. We also remove the configure key from the search state to do this comparaison because for now configure values are not present in the search state before a first refinement has been made and will false the results. See: https://github.com/algolia/react-instantsearch/issues/164 */ var cleanedSearchState = omit_1(omit_1(searchState, 'configure'), id); var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState); this._prevSearchState = cleanedSearchState; return { value: value, hasNotChanged: hasNotChanged }; } }); function _defineProperty$f(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } function getId$b() { return 'query'; } function getCurrentRefinement$a(props, searchState, context) { var id = getId$b(props); return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function _refine$9(props, searchState, nextRefinement, context) { var id = getId$b(); var nextValue = _defineProperty$f({}, 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 = createConnector({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: propTypes.string }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { currentRefinement: getCurrentRefinement$a(props, searchState, this.context), isSearchStalled: searchResults.isSearchStalled }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$9(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$6(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$a(props, searchState, this.context)); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$b(props); var currentRefinement = getCurrentRefinement$a(props, searchState, this.context); return { id: id, index: getIndex(this.context), items: currentRefinement === null ? [] : [{ label: id + ': ' + currentRefinement, value: function value(nextState) { return _refine$9(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); var _extends$a = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i];for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }return target; }; function _defineProperty$g(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } function getId$c() { return 'sortBy'; } function getCurrentRefinement$b(props, searchState, context) { var id = getId$c(props); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return null; }); } /** * The connectSortBy connector provides the logic to build a widget that will * display a list of indices. This allows a user to change how the hits are being sorted. * @name connectSortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind connector * @propType {string} defaultRefinement - The default selected index. * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectSortBy = createConnector({ displayName: 'AlgoliaSortBy', propTypes: { defaultRefinement: propTypes.string, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$b(props, searchState, this.context); var items = props.items.map(function (item) { return item.value === currentRefinement ? _extends$a({}, item, { isRefined: true }) : _extends$a({}, 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$g({}, id, nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$c()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement$b(props, searchState, this.context); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId$c() }; } }); /** * The `connectStateResults` connector provides a way to access the `searchState` and the `searchResults` * of InstantSearch. * For instance this connector allows you to create results/noResults or query/noQuery pages. * @name connectStateResults * @kind connector * @providedPropType {object} searchState - The search state of the instant search component. <br/><br/> See: [Search state structure](https://community.algolia.com/react-instantsearch/guide/Search_state.html) * @providedPropType {object} searchResults - The search results. <br/><br/> In case of multiple indices: if used under `<Index>`, results will be those of the corresponding index otherwise it'll be those of the root index See: [Search results structure](https://community.algolia.com/algoliasearch-helper-js/reference.html#searchresults) * @providedPropType {object} allSearchResults - In case of multiple indices you can retrieve all the results * @providedPropType {string} error - If the search failed, the error will be logged here. * @providedPropType {boolean} searching - If there is a search in progress. * @providedPropType {boolean} isSearchStalled - Flag that indicates if React InstantSearch has detected that searches are stalled. * @providedPropType {boolean} searchingForFacetValues - If there is a search in a list in progress. * @providedPropType {object} props - component props. * @example * import React from 'react'; * import { InstantSearch, SearchBox, Hits, connectStateResults } from 'react-instantsearch-dom'; * * const Content = connectStateResults(({ searchState, searchResults }) => { * const hasResults = searchResults && searchResults.nbHits !== 0; * * return ( * <div> * <div hidden={!hasResults}> * <Hits /> * </div> * <div hidden={hasResults}> * <div>No results has been found for {searchState.query}</div> * </div> * </div> * ); * }); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="ikea" * > * <SearchBox /> * <Content /> * </InstantSearch> * ); */ var connectStateResults = createConnector({ displayName: 'AlgoliaStateResults', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); return { searchState: searchState, searchResults: results, allSearchResults: searchResults.results, searching: searchResults.searching, isSearchStalled: searchResults.isSearchStalled, error: searchResults.error, searchingForFacetValues: searchResults.searchingForFacetValues, props: props }; } }); /** * connectStats connector provides the logic to build a widget that will * displays algolia search statistics (hits number and processing time). * @name connectStats * @kind connector * @providedPropType {number} nbHits - number of hits returned by Algolia. * @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results. */ var connectStats = createConnector({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); function _defineProperty$h(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } function getId$d(props) { return props.attribute; } var namespace$6 = 'toggle'; function getCurrentRefinement$c(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, namespace$6 + '.' + getId$d(props), false, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return false; }); } function _refine$a(props, searchState, nextRefinement, context) { var id = getId$d(props); var nextValue = _defineProperty$h({}, id, nextRefinement ? nextRefinement : false); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$6); } function _cleanUp$7(props, searchState, context) { return cleanUpValue(searchState, context, namespace$6 + '.' + getId$d(props)); } /** * connectToggleRefinement connector provides the logic to build a widget that will * provides an on/off filtering feature based on an attribute value. * @name connectToggleRefinement * @kind connector * @requirements To use this widget, you'll need an attribute to toggle on. * * You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an * extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details. * * @propType {string} attribute - Name of the attribute on which to apply the `value` refinement. Required when `value` is present. * @propType {string} label - Label for the toggle. * @propType {string} value - Value of the refinement to apply on `attribute`. * @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default? * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {boolean} currentRefinement - `true` when the refinement is applied, `false` otherwise */ var connectToggleRefinement = createConnector({ displayName: 'AlgoliaToggle', propTypes: { label: propTypes.string, filter: propTypes.func, attribute: propTypes.string, value: propTypes.any, defaultRefinement: propTypes.bool }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$c(props, searchState, this.context); return { currentRefinement: currentRefinement }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$a(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$7(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, value = props.value, filter = props.filter; var checked = getCurrentRefinement$c(props, searchState, this.context); if (checked) { if (attribute) { searchParameters = searchParameters.addFacet(attribute).addFacetRefinement(attribute, value); } if (filter) { searchParameters = filter(searchParameters); } } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$d(props); var checked = getCurrentRefinement$c(props, searchState, this.context); var items = []; var index = getIndex(this.context); if (checked) { items.push({ label: props.label, currentRefinement: checked, attribute: props.attribute, value: function value(nextState) { return _refine$a(props, nextState, false, _this.context); } }); } return { id: id, index: index, items: items }; } }); // Core exports.connectAutoComplete = connectAutoComplete; exports.connectBreadcrumb = connectBreadcrumb; exports.connectConfigure = connectConfigure; exports.connectCurrentRefinements = connectCurrentRefinements; exports.connectGeoSearch = connectGeoSearch; exports.connectHierarchicalMenu = connectHierarchicalMenu; exports.connectHighlight = connectHighlight; exports.connectHits = connectHits; exports.connectHitsPerPage = connectHitsPerPage; exports.connectInfiniteHits = connectInfiniteHits; exports.connectMenu = connectMenu; exports.connectNumericMenu = connectNumericMenu; exports.connectPagination = connectPagination; exports.connectPoweredBy = connectPoweredBy; exports.connectRange = connectRange; exports.connectRefinementList = connectRefinementList; exports.connectScrollTo = connectScrollTo; exports.connectSearchBox = connectSearchBox; exports.connectSortBy = connectSortBy; exports.connectStateResults = connectStateResults; exports.connectStats = connectStats; exports.connectToggleRefinement = connectToggleRefinement; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=Connectors.js.map
ajax/libs/boardgame-io/0.42.0/esm/react-native.js
cdnjs/cdnjs
import './Debug-ba7187a3.js'; import 'redux'; import './turn-order-7578f7f3.js'; import 'immer'; import './reducer-ef40323d.js'; import './initialize-ff341f37.js'; import 'flatted'; import './ai-4091d3f9.js'; import { C as Client$1 } from './client-b699de9a.js'; import React from 'react'; import PropTypes from 'prop-types'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } /** * Client * * boardgame.io React Native client. * * @param {...object} game - The return value of `Game`. * @param {...object} numPlayers - The number of players. * @param {...object} board - The React component for the game. * @param {...object} loading - (optional) The React component for the loading state. * @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO() * @param {...object} enhancer - Optional enhancer to send to the Redux store * * Returns: * A React Native component that wraps board and provides an * API through props for it to interact with the framework * and dispatch actions such as MAKE_MOVE. */ function Client(opts) { var _class, _temp; var game = opts.game, numPlayers = opts.numPlayers, board = opts.board, multiplayer = opts.multiplayer, enhancer = opts.enhancer; /* * WrappedBoard * * The main React component that wraps the passed in * board component and adds the API to its props. */ return _temp = _class = /*#__PURE__*/function (_React$Component) { _inherits(WrappedBoard, _React$Component); var _super = _createSuper(WrappedBoard); function WrappedBoard(props) { var _this; _classCallCheck(this, WrappedBoard); _this = _super.call(this, props); _this.client = Client$1({ game: game, numPlayers: numPlayers, multiplayer: multiplayer, matchID: props.matchID, playerID: props.playerID, credentials: props.credentials, debug: false, enhancer: enhancer }); return _this; } _createClass(WrappedBoard, [{ key: "componentDidMount", value: function componentDidMount() { var _this2 = this; this.unsubscribe = this.client.subscribe(function () { return _this2.forceUpdate(); }); this.client.start(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.client.stop(); this.unsubscribe(); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (prevProps.matchID != this.props.matchID) { this.client.updateMatchID(this.props.matchID); } if (prevProps.playerID != this.props.playerID) { this.client.updatePlayerID(this.props.playerID); } if (prevProps.credentials != this.props.credentials) { this.client.updateCredentials(this.props.credentials); } } }, { key: "render", value: function render() { var _board = null; var state = this.client.getState(); var _this$props = this.props, matchID = _this$props.matchID, playerID = _this$props.playerID, rest = _objectWithoutProperties(_this$props, ["matchID", "playerID"]); if (board) { _board = /*#__PURE__*/React.createElement(board, _objectSpread2(_objectSpread2(_objectSpread2({}, state), rest), {}, { matchID: matchID, playerID: playerID, isMultiplayer: !!multiplayer, moves: this.client.moves, events: this.client.events, step: this.client.step, reset: this.client.reset, undo: this.client.undo, redo: this.client.redo, matchData: this.client.matchData })); } return _board; } }]); return WrappedBoard; }(React.Component), _defineProperty(_class, "propTypes", { // The ID of a game to connect to. // Only relevant in multiplayer. matchID: PropTypes.string, // The ID of the player associated with this client. // Only relevant in multiplayer. playerID: PropTypes.string, // This client's authentication credentials. // Only relevant in multiplayer. credentials: PropTypes.string }), _defineProperty(_class, "defaultProps", { matchID: 'default', playerID: null, credentials: null }), _temp; } export { Client };
ajax/libs/material-ui/4.9.2/esm/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. */ var ClickAwayListener = React.forwardRef(function ClickAwayListener(props, ref) { var children = props.children, _props$mouseEvent = props.mouseEvent, mouseEvent = _props$mouseEvent === void 0 ? 'onClick' : _props$mouseEvent, _props$touchEvent = props.touchEvent, touchEvent = _props$touchEvent === void 0 ? 'onTouchEnd' : _props$touchEvent, onClickAway = props.onClickAway; var movedRef = React.useRef(false); var nodeRef = React.useRef(null); var mountedRef = React.useRef(false); React.useEffect(function () { mountedRef.current = true; return function () { mountedRef.current = false; }; }, []); var handleNodeRef = useForkRef(nodeRef, ref); // can be removed once we drop support for non ref forwarding class components var handleOwnRef = React.useCallback(function (instance) { // #StrictMode ready setRef(handleNodeRef, ReactDOM.findDOMNode(instance)); }, [handleNodeRef]); var handleRef = useForkRef(children.ref, handleOwnRef); var handleClickAway = useEventCallback(function (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 var doc = ownerDocument(nodeRef.current); if (doc.documentElement && doc.documentElement.contains(event.target) && !nodeRef.current.contains(event.target)) { onClickAway(event); } }); var handleTouchMove = React.useCallback(function () { movedRef.current = true; }, []); React.useEffect(function () { if (touchEvent !== false) { var mappedTouchEvent = mapEventPropToEvent(touchEvent); var doc = ownerDocument(nodeRef.current); doc.addEventListener(mappedTouchEvent, handleClickAway); doc.addEventListener('touchmove', handleTouchMove); return function () { doc.removeEventListener(mappedTouchEvent, handleClickAway); doc.removeEventListener('touchmove', handleTouchMove); }; } return undefined; }, [handleClickAway, handleTouchMove, touchEvent]); React.useEffect(function () { if (mouseEvent !== false) { var mappedMouseEvent = mapEventPropToEvent(mouseEvent); var doc = ownerDocument(nodeRef.current); doc.addEventListener(mappedMouseEvent, handleClickAway); return function () { 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/material-ui/4.9.2/es/TablePagination/TablePagination.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 { chainPropTypes } from '@material-ui/utils'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import InputBase from '../InputBase'; import MenuItem from '../MenuItem'; import Select from '../Select'; import TableCell from '../TableCell'; import Toolbar from '../Toolbar'; import Typography from '../Typography'; import TablePaginationActions from './TablePaginationActions'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { color: theme.palette.text.primary, fontSize: theme.typography.pxToRem(14), overflow: 'auto', // Increase the specificity to override TableCell. '&:last-child': { padding: 0 } }, /* Styles applied to the Toolbar component. */ toolbar: { minHeight: 52, paddingRight: 2 }, /* Styles applied to the spacer element. */ spacer: { flex: '1 1 100%' }, /* Styles applied to the caption Typography components if `variant="caption"`. */ caption: { flexShrink: 0 }, /* Styles applied to the Select component root element. */ selectRoot: { // `.selectRoot` should be merged with `.input` in v5. marginRight: 32, marginLeft: 8 }, /* Styles applied to the Select component `select` class. */ select: { paddingLeft: 8, paddingRight: 24, textAlign: 'right', textAlignLast: 'right' // Align <select> on Chrome. }, // TODO v5: remove /* Styles applied to the Select component `icon` class. */ selectIcon: {}, /* Styles applied to the `InputBase` component. */ input: { color: 'inherit', fontSize: 'inherit', flexShrink: 0 }, /* Styles applied to the MenuItem component. */ menuItem: {}, /* Styles applied to the internal `TablePaginationActions` component. */ actions: { flexShrink: 0, marginLeft: 20 } }); const defaultLabelDisplayedRows = ({ from, to, count }) => `${from}-${to === -1 ? count : to} of ${count !== -1 ? count : `more than ${to}`}`; const defaultRowsPerPageOptions = [10, 25, 50, 100]; /** * A `TableCell` based component for placing inside `TableFooter` for pagination. */ const TablePagination = React.forwardRef(function TablePagination(props, ref) { const { ActionsComponent = TablePaginationActions, backIconButtonProps, backIconButtonText = 'Previous page', classes, className, colSpan: colSpanProp, component: Component = TableCell, count, labelDisplayedRows = defaultLabelDisplayedRows, labelRowsPerPage = 'Rows per page:', nextIconButtonProps, nextIconButtonText = 'Next page', onChangePage, onChangeRowsPerPage, page, rowsPerPage, rowsPerPageOptions = defaultRowsPerPageOptions, SelectProps = {} } = props, other = _objectWithoutPropertiesLoose(props, ["ActionsComponent", "backIconButtonProps", "backIconButtonText", "classes", "className", "colSpan", "component", "count", "labelDisplayedRows", "labelRowsPerPage", "nextIconButtonProps", "nextIconButtonText", "onChangePage", "onChangeRowsPerPage", "page", "rowsPerPage", "rowsPerPageOptions", "SelectProps"]); let colSpan; if (Component === TableCell || Component === 'td') { colSpan = colSpanProp || 1000; // col-span over everything } const MenuItemComponent = SelectProps.native ? 'option' : MenuItem; return React.createElement(Component, _extends({ className: clsx(classes.root, className), colSpan: colSpan, ref: ref }, other), React.createElement(Toolbar, { className: classes.toolbar }, React.createElement("div", { className: classes.spacer }), rowsPerPageOptions.length > 1 && React.createElement(Typography, { color: "inherit", variant: "body2", className: classes.caption }, labelRowsPerPage), rowsPerPageOptions.length > 1 && React.createElement(Select, _extends({ classes: { select: classes.select, icon: classes.selectIcon }, input: React.createElement(InputBase, { className: clsx(classes.input, classes.selectRoot) }), value: rowsPerPage, onChange: onChangeRowsPerPage }, SelectProps), rowsPerPageOptions.map(rowsPerPageOption => React.createElement(MenuItemComponent, { className: classes.menuItem, key: rowsPerPageOption.value ? rowsPerPageOption.value : rowsPerPageOption, value: rowsPerPageOption.value ? rowsPerPageOption.value : rowsPerPageOption }, rowsPerPageOption.label ? rowsPerPageOption.label : rowsPerPageOption))), React.createElement(Typography, { color: "inherit", variant: "body2", className: classes.caption }, labelDisplayedRows({ from: count === 0 ? 0 : page * rowsPerPage + 1, to: count !== -1 ? Math.min(count, (page + 1) * rowsPerPage) : (page + 1) * rowsPerPage, count, page })), React.createElement(ActionsComponent, { className: classes.actions, backIconButtonProps: _extends({ title: backIconButtonText, 'aria-label': backIconButtonText }, backIconButtonProps), count: count, nextIconButtonProps: _extends({ title: nextIconButtonText, 'aria-label': nextIconButtonText }, nextIconButtonProps), onChangePage: onChangePage, page: page, rowsPerPage: rowsPerPage }))); }); process.env.NODE_ENV !== "production" ? TablePagination.propTypes = { /** * The component used for displaying the actions. * Either a string to use a DOM element or a component. */ ActionsComponent: PropTypes.elementType, /** * Props applied to the back arrow [`IconButton`](/api/icon-button/) component. */ backIconButtonProps: PropTypes.object, /** * Text label for the back arrow icon button. * * For localization purposes, you can use the provided [translations](/guides/localization/). */ backIconButtonText: PropTypes.string, /** * 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 */ colSpan: PropTypes.number, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component: PropTypes.elementType, /** * The total number of rows. * * To enable server side pagination for an unknown number of items, provide -1. */ count: PropTypes.number.isRequired, /** * Customize the displayed rows label. * * For localization purposes, you can use the provided [translations](/guides/localization/). */ labelDisplayedRows: PropTypes.func, /** * Customize the rows per page label. Invoked with a `{ from, to, count, page }` * object. * * For localization purposes, you can use the provided [translations](/guides/localization/). */ labelRowsPerPage: PropTypes.node, /** * Props applied to the next arrow [`IconButton`](/api/icon-button/) element. */ nextIconButtonProps: PropTypes.object, /** * Text label for the next arrow icon button. * * For localization purposes, you can use the provided [translations](/guides/localization/). */ nextIconButtonText: PropTypes.string, /** * Callback fired when the page is changed. * * @param {object} event The event source of the callback. * @param {number} page The page selected. */ onChangePage: PropTypes.func.isRequired, /** * Callback fired when the number of rows per page is changed. * * @param {object} event The event source of the callback. */ onChangeRowsPerPage: PropTypes.func, /** * The zero-based index of the current page. */ page: chainPropTypes(PropTypes.number.isRequired, props => { const { count, page, rowsPerPage } = props; const newLastPage = Math.max(0, Math.ceil(count / rowsPerPage) - 1); if (page < 0 || page > newLastPage) { return new Error('Material-UI: the page prop of a TablePagination is out of range ' + `(0 to ${newLastPage}, but page is ${page}).`); } return null; }), /** * The number of rows per page. */ rowsPerPage: PropTypes.number.isRequired, /** * Customizes the options of the rows per page select field. If less than two options are * available, no select field will be displayed. */ rowsPerPageOptions: PropTypes.array, /** * Props applied to the rows per page [`Select`](/api/select/) element. */ SelectProps: PropTypes.object } : void 0; export default withStyles(styles, { name: 'MuiTablePagination' })(TablePagination);
ajax/libs/react-native-web/0.0.0-466063b7e/exports/AppRegistry/renderApplication.js
cdnjs/cdnjs
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AppContainer from './AppContainer'; import invariant from 'fbjs/lib/invariant'; import render, { hydrate } from '../render'; import styleResolver from '../StyleSheet/styleResolver'; import React from 'react'; export default function renderApplication(RootComponent, WrapperComponent, callback, options) { var shouldHydrate = options.hydrate, initialProps = options.initialProps, rootTag = options.rootTag; var renderFn = shouldHydrate ? hydrate : render; invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag); renderFn(React.createElement(AppContainer, { rootTag: rootTag, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)), rootTag, callback); } export function getApplication(RootComponent, initialProps, WrapperComponent) { var element = React.createElement(AppContainer, { rootTag: {}, WrapperComponent: WrapperComponent }, React.createElement(RootComponent, initialProps)); // Don't escape CSS text var getStyleElement = function getStyleElement(props) { var sheet = styleResolver.getStyleSheet(); return React.createElement("style", _extends({}, props, { dangerouslySetInnerHTML: { __html: sheet.textContent }, id: sheet.id })); }; return { element: element, getStyleElement: getStyleElement }; }
ajax/libs/react-native-web/0.13.7/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/primereact/6.5.0/editor/editor.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 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 Editor = /*#__PURE__*/function (_Component) { _inherits(Editor, _Component); var _super = _createSuper(Editor); function Editor() { _classCallCheck(this, Editor); return _super.apply(this, arguments); } _createClass(Editor, [{ key: "getQuill", value: function getQuill() { return this.quill; } }, { key: "componentDidMount", value: function componentDidMount() { var _this = this; import('quill').then(function (module) { if (module && module.default) { _this.quill = new module.default(_this.editorElement, { modules: _objectSpread({ toolbar: _this.toolbarElement }, _this.props.modules), placeholder: _this.props.placeholder, readOnly: _this.props.readOnly, theme: _this.props.theme, formats: _this.props.formats }); if (_this.props.value) { _this.quill.setContents(_this.quill.clipboard.convert(_this.props.value)); } _this.quill.on('text-change', function (delta, source) { var html = _this.editorElement.children[0].innerHTML; var text = _this.quill.getText(); if (html === '<p><br></p>') { html = null; } if (_this.props.onTextChange) { _this.props.onTextChange({ htmlValue: html, textValue: text, delta: delta, source: source }); } }); _this.quill.on('selection-change', function (range, oldRange, source) { if (_this.props.onSelectionChange) { _this.props.onSelectionChange({ range: range, oldRange: oldRange, source: source }); } }); } }).then(function () { if (_this.quill && _this.quill.getModule('toolbar')) { _this.props.onLoad && _this.props.onLoad(_this.quill); } }); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props.value !== prevProps.value && this.quill && !this.quill.hasFocus()) { if (this.props.value) this.quill.setContents(this.quill.clipboard.convert(this.props.value));else this.quill.setText(''); } } }, { key: "render", value: function render() { var _this2 = this; var containerClass = classNames('p-component p-editor-container', this.props.className); var toolbarHeader = null; if (this.props.headerTemplate) { toolbarHeader = /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this2.toolbarElement = el; }, className: "p-editor-toolbar" }, this.props.headerTemplate); } else { toolbarHeader = /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this2.toolbarElement = el; }, className: "p-editor-toolbar" }, /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("select", { className: "ql-header", defaultValue: "0" }, /*#__PURE__*/React.createElement("option", { value: "1" }, "Heading"), /*#__PURE__*/React.createElement("option", { value: "2" }, "Subheading"), /*#__PURE__*/React.createElement("option", { value: "0" }, "Normal")), /*#__PURE__*/React.createElement("select", { className: "ql-font" }, /*#__PURE__*/React.createElement("option", null), /*#__PURE__*/React.createElement("option", { value: "serif" }), /*#__PURE__*/React.createElement("option", { value: "monospace" }))), /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-bold", "aria-label": "Bold" }), /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-italic", "aria-label": "Italic" }), /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-underline", "aria-label": "Underline" })), /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("select", { className: "ql-color" }), /*#__PURE__*/React.createElement("select", { className: "ql-background" })), /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-list", value: "ordered", "aria-label": "Ordered List" }), /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-list", value: "bullet", "aria-label": "Unordered List" }), /*#__PURE__*/React.createElement("select", { className: "ql-align" }, /*#__PURE__*/React.createElement("option", { defaultValue: true }), /*#__PURE__*/React.createElement("option", { value: "center" }), /*#__PURE__*/React.createElement("option", { value: "right" }), /*#__PURE__*/React.createElement("option", { value: "justify" }))), /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-link", "aria-label": "Insert Link" }), /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-image", "aria-label": "Insert Image" }), /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-code-block", "aria-label": "Insert Code Block" })), /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-clean", "aria-label": "Remove Styles" }))); } var content = /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this2.editorElement = el; }, className: "p-editor-content", style: this.props.style }); return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: containerClass }, toolbarHeader, content); } }]); return Editor; }(Component); _defineProperty(Editor, "defaultProps", { id: null, value: null, style: null, className: null, placeholder: null, readOnly: false, modules: null, formats: null, theme: 'snow', headerTemplate: null, onTextChange: null, onSelectionChange: null, onLoad: null }); export { Editor };
ajax/libs/react-big-calendar/0.22.0/react-big-calendar.esm.js
cdnjs/cdnjs
import _extends from '@babel/runtime/helpers/esm/extends'; import _objectWithoutPropertiesLoose from '@babel/runtime/helpers/esm/objectWithoutPropertiesLoose'; import _inheritsLoose from '@babel/runtime/helpers/esm/inheritsLoose'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { uncontrollable } from 'uncontrollable'; import cn from 'classnames'; import warning from 'warning'; import invariant from 'invariant'; import _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized'; import { findDOMNode } from 'react-dom'; import { eq, add, startOf, endOf, lte, hours, minutes, seconds, milliseconds, lt, gte, month, max, min, gt, inRange as inRange$1 } from 'date-arithmetic'; import chunk from 'lodash-es/chunk'; import getPosition from 'dom-helpers/query/position'; import raf from 'dom-helpers/util/requestAnimationFrame'; import getOffset from 'dom-helpers/query/offset'; import getScrollTop from 'dom-helpers/query/scrollTop'; import getScrollLeft from 'dom-helpers/query/scrollLeft'; import Overlay from 'react-overlays/Overlay'; import getHeight from 'dom-helpers/query/height'; import qsa from 'dom-helpers/query/querySelectorAll'; import contains from 'dom-helpers/query/contains'; import closest from 'dom-helpers/query/closest'; import events from 'dom-helpers/events'; import findIndex from 'lodash-es/findIndex'; import range$1 from 'lodash-es/range'; import memoize from 'memoize-one'; import _createClass from '@babel/runtime/helpers/esm/createClass'; import sortBy from 'lodash-es/sortBy'; import getWidth from 'dom-helpers/query/width'; import scrollbarSize from 'dom-helpers/util/scrollbarSize'; import classes from 'dom-helpers/class'; import omit from 'lodash-es/omit'; import defaults from 'lodash-es/defaults'; import transform from 'lodash-es/transform'; import mapValues from 'lodash-es/mapValues'; function NoopWrapper(props) { return props.children; } var navigate = { PREVIOUS: 'PREV', NEXT: 'NEXT', TODAY: 'TODAY', DATE: 'DATE' }; var views = { MONTH: 'month', WEEK: 'week', WORK_WEEK: 'work_week', DAY: 'day', AGENDA: 'agenda' }; var viewNames = Object.keys(views).map(function (k) { return views[k]; }); var accessor = PropTypes.oneOfType([PropTypes.string, PropTypes.func]); var dateFormat = PropTypes.any; var dateRangeFormat = PropTypes.func; /** * accepts either an array of builtin view names: * * ``` * views={['month', 'day', 'agenda']} * ``` * * or an object hash of the view name and the component (or boolean for builtin) * * ``` * views={{ * month: true, * week: false, * workweek: WorkWeekViewComponent, * }} * ``` */ var views$1 = PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOf(viewNames)), PropTypes.objectOf(function (prop, key) { var isBuiltinView = viewNames.indexOf(key) !== -1 && typeof prop[key] === 'boolean'; if (isBuiltinView) { return null; } else { for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } return PropTypes.elementType.apply(PropTypes, [prop, key].concat(args)); } })]); function notify(handler, args) { handler && handler.apply(null, [].concat(args)); } var localePropType = PropTypes.oneOfType([PropTypes.string, PropTypes.func]); function _format(localizer, formatter, value, format, culture) { var result = typeof format === 'function' ? format(value, culture, localizer) : formatter.call(localizer, value, format, culture); !(result == null || typeof result === 'string') ? process.env.NODE_ENV !== "production" ? invariant(false, '`localizer format(..)` must return a string, null, or undefined') : invariant(false) : void 0; return result; } var DateLocalizer = function DateLocalizer(spec) { var _this = this; !(typeof spec.format === 'function') ? process.env.NODE_ENV !== "production" ? invariant(false, 'date localizer `format(..)` must be a function') : invariant(false) : void 0; !(typeof spec.firstOfWeek === 'function') ? process.env.NODE_ENV !== "production" ? invariant(false, 'date localizer `firstOfWeek(..)` must be a function') : invariant(false) : void 0; this.propType = spec.propType || localePropType; this.startOfWeek = spec.firstOfWeek; this.formats = spec.formats; this.format = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _format.apply(void 0, [_this, spec.format].concat(args)); }; }; function mergeWithDefaults(localizer, culture, formatOverrides, messages) { var formats = _extends({}, localizer.formats, formatOverrides); return _extends({}, localizer, { messages: messages, startOfWeek: function startOfWeek() { return localizer.startOfWeek(culture); }, format: function format(value, _format2) { return localizer.format(value, formats[_format2] || _format2, culture); } }); } var defaultMessages = { date: 'Date', time: 'Time', event: 'Event', allDay: 'All Day', week: 'Week', work_week: 'Work Week', day: 'Day', month: 'Month', previous: 'Back', next: 'Next', yesterday: 'Yesterday', tomorrow: 'Tomorrow', today: 'Today', agenda: 'Agenda', noEventsInRange: 'There are no events in this range.', showMore: function showMore(total) { return "+" + total + " more"; } }; function messages(msgs) { return _extends({}, defaultMessages, msgs); } /* eslint no-fallthrough: off */ var MILLI = { seconds: 1000, minutes: 1000 * 60, hours: 1000 * 60 * 60, day: 1000 * 60 * 60 * 24 }; function firstVisibleDay(date, localizer) { var firstOfMonth = startOf(date, 'month'); return startOf(firstOfMonth, 'week', localizer.startOfWeek()); } function lastVisibleDay(date, localizer) { var endOfMonth = endOf(date, 'month'); return endOf(endOfMonth, 'week', localizer.startOfWeek()); } function visibleDays(date, localizer) { var current = firstVisibleDay(date, localizer), last = lastVisibleDay(date, localizer), days = []; while (lte(current, last, 'day')) { days.push(current); current = add(current, 1, 'day'); } return days; } function ceil(date, unit) { var floor = startOf(date, unit); return eq(floor, date) ? floor : add(floor, 1, unit); } function range(start, end, unit) { if (unit === void 0) { unit = 'day'; } var current = start, days = []; while (lte(current, end, unit)) { days.push(current); current = add(current, 1, unit); } return days; } function merge(date, time) { if (time == null && date == null) return null; if (time == null) time = new Date(); if (date == null) date = new Date(); date = startOf(date, 'day'); date = hours(date, hours(time)); date = minutes(date, minutes(time)); date = seconds(date, seconds(time)); return milliseconds(date, milliseconds(time)); } function isJustDate(date) { return hours(date) === 0 && minutes(date) === 0 && seconds(date) === 0 && milliseconds(date) === 0; } function diff(dateA, dateB, unit) { if (!unit || unit === 'milliseconds') return Math.abs(+dateA - +dateB); // the .round() handles an edge case // with DST where the total won't be exact // since one day in the range may be shorter/longer by an hour return Math.round(Math.abs(+startOf(dateA, unit) / MILLI[unit] - +startOf(dateB, unit) / MILLI[unit])); } var EventCell = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(EventCell, _React$Component); function EventCell() { return _React$Component.apply(this, arguments) || this; } var _proto = EventCell.prototype; _proto.render = function render() { var _this$props = this.props, style = _this$props.style, className = _this$props.className, event = _this$props.event, selected = _this$props.selected, isAllDay = _this$props.isAllDay, onSelect = _this$props.onSelect, _onDoubleClick = _this$props.onDoubleClick, localizer = _this$props.localizer, continuesPrior = _this$props.continuesPrior, continuesAfter = _this$props.continuesAfter, accessors = _this$props.accessors, getters = _this$props.getters, children = _this$props.children, _this$props$component = _this$props.components, Event = _this$props$component.event, EventWrapper = _this$props$component.eventWrapper, props = _objectWithoutPropertiesLoose(_this$props, ["style", "className", "event", "selected", "isAllDay", "onSelect", "onDoubleClick", "localizer", "continuesPrior", "continuesAfter", "accessors", "getters", "children", "components"]); var title = accessors.title(event); var tooltip = accessors.tooltip(event); var end = accessors.end(event); var start = accessors.start(event); var allDay = accessors.allDay(event); var showAsAllDay = isAllDay || allDay || diff(start, ceil(end, 'day'), 'day') > 1; var userProps = getters.eventProp(event, start, end, selected); var content = React.createElement("div", { className: "rbc-event-content", title: tooltip || undefined }, Event ? React.createElement(Event, { event: event, title: title, isAllDay: allDay, localizer: localizer }) : title); return React.createElement(EventWrapper, _extends({}, this.props, { type: "date" }), React.createElement("div", _extends({}, props, { tabIndex: 0, style: _extends({}, userProps.style, style), className: cn('rbc-event', className, userProps.className, { 'rbc-selected': selected, 'rbc-event-allday': showAsAllDay, 'rbc-event-continues-prior': continuesPrior, 'rbc-event-continues-after': continuesAfter }), onClick: function onClick(e) { return onSelect && onSelect(event, e); }, onDoubleClick: function onDoubleClick(e) { return _onDoubleClick && _onDoubleClick(event, e); } }), typeof children === 'function' ? children(content) : content)); }; return EventCell; }(React.Component); EventCell.propTypes = process.env.NODE_ENV !== "production" ? { event: PropTypes.object.isRequired, slotStart: PropTypes.instanceOf(Date), slotEnd: PropTypes.instanceOf(Date), selected: PropTypes.bool, isAllDay: PropTypes.bool, continuesPrior: PropTypes.bool, continuesAfter: PropTypes.bool, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object, onSelect: PropTypes.func, onDoubleClick: PropTypes.func } : {}; function isSelected(event, selected) { if (!event || selected == null) return false; return [].concat(selected).indexOf(event) !== -1; } function slotWidth(rowBox, slots) { var rowWidth = rowBox.right - rowBox.left; var cellWidth = rowWidth / slots; return cellWidth; } function getSlotAtX(rowBox, x, rtl, slots) { var cellWidth = slotWidth(rowBox, slots); return rtl ? slots - 1 - Math.floor((x - rowBox.left) / cellWidth) : Math.floor((x - rowBox.left) / cellWidth); } function pointInBox(box, _ref) { var x = _ref.x, y = _ref.y; return y >= box.top && y <= box.bottom && x >= box.left && x <= box.right; } function dateCellSelection(start, rowBox, box, slots, rtl) { var startIdx = -1; var endIdx = -1; var lastSlotIdx = slots - 1; var cellWidth = slotWidth(rowBox, slots); // cell under the mouse var currentSlot = getSlotAtX(rowBox, box.x, rtl, slots); // Identify row as either the initial row // or the row under the current mouse point var isCurrentRow = rowBox.top < box.y && rowBox.bottom > box.y; var isStartRow = rowBox.top < start.y && rowBox.bottom > start.y; // this row's position relative to the start point var isAboveStart = start.y > rowBox.bottom; var isBelowStart = rowBox.top > start.y; var isBetween = box.top < rowBox.top && box.bottom > rowBox.bottom; // this row is between the current and start rows, so entirely selected if (isBetween) { startIdx = 0; endIdx = lastSlotIdx; } if (isCurrentRow) { if (isBelowStart) { startIdx = 0; endIdx = currentSlot; } else if (isAboveStart) { startIdx = currentSlot; endIdx = lastSlotIdx; } } if (isStartRow) { // select the cell under the initial point startIdx = endIdx = rtl ? lastSlotIdx - Math.floor((start.x - rowBox.left) / cellWidth) : Math.floor((start.x - rowBox.left) / cellWidth); if (isCurrentRow) { if (currentSlot < startIdx) startIdx = currentSlot;else endIdx = currentSlot; //select current range } else if (start.y < box.y) { // the current row is below start row // select cells to the right of the start cell endIdx = lastSlotIdx; } else { // select cells to the left of the start cell startIdx = 0; } } return { startIdx: startIdx, endIdx: endIdx }; } var Popup = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Popup, _React$Component); function Popup() { return _React$Component.apply(this, arguments) || this; } var _proto = Popup.prototype; _proto.componentDidMount = function componentDidMount() { var _this$props = this.props, _this$props$popupOffs = _this$props.popupOffset, popupOffset = _this$props$popupOffs === void 0 ? 5 : _this$props$popupOffs, popperRef = _this$props.popperRef, _getOffset = getOffset(popperRef.current), top = _getOffset.top, left = _getOffset.left, width = _getOffset.width, height = _getOffset.height, viewBottom = window.innerHeight + getScrollTop(window), viewRight = window.innerWidth + getScrollLeft(window), bottom = top + height, right = left + width; if (bottom > viewBottom || right > viewRight) { var topOffset, leftOffset; if (bottom > viewBottom) topOffset = bottom - viewBottom + (popupOffset.y || +popupOffset || 0); if (right > viewRight) leftOffset = right - viewRight + (popupOffset.x || +popupOffset || 0); this.setState({ topOffset: topOffset, leftOffset: leftOffset }); //eslint-disable-line } }; _proto.render = function render() { var _this$props2 = this.props, events = _this$props2.events, selected = _this$props2.selected, getters = _this$props2.getters, accessors = _this$props2.accessors, components = _this$props2.components, onSelect = _this$props2.onSelect, onDoubleClick = _this$props2.onDoubleClick, slotStart = _this$props2.slotStart, slotEnd = _this$props2.slotEnd, localizer = _this$props2.localizer, popperRef = _this$props2.popperRef; var _this$props$position = this.props.position, left = _this$props$position.left, width = _this$props$position.width, top = _this$props$position.top, topOffset = (this.state || {}).topOffset || 0, leftOffset = (this.state || {}).leftOffset || 0; var style = { top: Math.max(0, top - topOffset), left: left - leftOffset, minWidth: width + width / 2 }; return React.createElement("div", { style: style, className: "rbc-overlay", ref: popperRef }, React.createElement("div", { className: "rbc-overlay-header" }, localizer.format(slotStart, 'dayHeaderFormat')), events.map(function (event, idx) { return React.createElement(EventCell, { key: idx, type: "popup", event: event, getters: getters, onSelect: onSelect, accessors: accessors, components: components, onDoubleClick: onDoubleClick, continuesPrior: lt(accessors.end(event), slotStart, 'day'), continuesAfter: gte(accessors.start(event), slotEnd, 'day'), selected: isSelected(event, selected) }); })); }; return Popup; }(React.Component); Popup.propTypes = process.env.NODE_ENV !== "production" ? { position: PropTypes.object, popupOffset: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ x: PropTypes.number, y: PropTypes.number })]), events: PropTypes.array, selected: PropTypes.object, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, onSelect: PropTypes.func, onDoubleClick: PropTypes.func, slotStart: PropTypes.instanceOf(Date), slotEnd: PropTypes.number, popperRef: PropTypes.oneOfType([PropTypes.func, PropTypes.shape({ current: PropTypes.Element })]) /** * The Overlay component, of react-overlays, creates a ref that is passed to the Popup, and * requires proper ref forwarding to be used without error */ } : {}; var Popup$1 = React.forwardRef(function (props, ref) { return React.createElement(Popup, _extends({ popperRef: ref }, props)); }); function addEventListener(type, handler, target) { if (target === void 0) { target = document; } events.on(target, type, handler, { passive: false }); return { remove: function remove() { events.off(target, type, handler); } }; } function isOverContainer(container, x, y) { return !container || contains(container, document.elementFromPoint(x, y)); } function getEventNodeFromPoint(node, _ref) { var clientX = _ref.clientX, clientY = _ref.clientY; var target = document.elementFromPoint(clientX, clientY); return closest(target, '.rbc-event', node); } function isEvent(node, bounds) { return !!getEventNodeFromPoint(node, bounds); } function getEventCoordinates(e) { var target = e; if (e.touches && e.touches.length) { target = e.touches[0]; } return { clientX: target.clientX, clientY: target.clientY, pageX: target.pageX, pageY: target.pageY }; } var clickTolerance = 5; var clickInterval = 250; var Selection = /*#__PURE__*/ function () { function Selection(node, _temp) { var _ref2 = _temp === void 0 ? {} : _temp, _ref2$global = _ref2.global, global = _ref2$global === void 0 ? false : _ref2$global, _ref2$longPressThresh = _ref2.longPressThreshold, longPressThreshold = _ref2$longPressThresh === void 0 ? 250 : _ref2$longPressThresh; this.isDetached = false; this.container = node; this.globalMouse = !node || global; this.longPressThreshold = longPressThreshold; this._listeners = Object.create(null); this._handleInitialEvent = this._handleInitialEvent.bind(this); this._handleMoveEvent = this._handleMoveEvent.bind(this); this._handleTerminatingEvent = this._handleTerminatingEvent.bind(this); this._keyListener = this._keyListener.bind(this); this._dropFromOutsideListener = this._dropFromOutsideListener.bind(this); // Fixes an iOS 10 bug where scrolling could not be prevented on the window. // https://github.com/metafizzy/flickity/issues/457#issuecomment-254501356 this._onTouchMoveWindowListener = addEventListener('touchmove', function () {}, window); this._onKeyDownListener = addEventListener('keydown', this._keyListener); this._onKeyUpListener = addEventListener('keyup', this._keyListener); this._onDropFromOutsideListener = addEventListener('drop', this._dropFromOutsideListener); this._addInitialEventListener(); } var _proto = Selection.prototype; _proto.on = function on(type, handler) { var handlers = this._listeners[type] || (this._listeners[type] = []); handlers.push(handler); return { remove: function remove() { var idx = handlers.indexOf(handler); if (idx !== -1) handlers.splice(idx, 1); } }; }; _proto.emit = function emit(type) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var result; var handlers = this._listeners[type] || []; handlers.forEach(function (fn) { if (result === undefined) result = fn.apply(void 0, args); }); return result; }; _proto.teardown = function teardown() { this.isDetached = true; this.listeners = Object.create(null); this._onTouchMoveWindowListener && this._onTouchMoveWindowListener.remove(); this._onInitialEventListener && this._onInitialEventListener.remove(); this._onEndListener && this._onEndListener.remove(); this._onEscListener && this._onEscListener.remove(); this._onMoveListener && this._onMoveListener.remove(); this._onKeyUpListener && this._onKeyUpListener.remove(); this._onKeyDownListener && this._onKeyDownListener.remove(); }; _proto.isSelected = function isSelected(node) { var box = this._selectRect; if (!box || !this.selecting) return false; return objectsCollide(box, getBoundsForNode(node)); }; _proto.filter = function filter(items) { var box = this._selectRect; //not selecting if (!box || !this.selecting) return []; return items.filter(this.isSelected, this); } // Adds a listener that will call the handler only after the user has pressed on the screen // without moving their finger for 250ms. ; _proto._addLongPressListener = function _addLongPressListener(handler, initialEvent) { var _this = this; var timer = null; var touchMoveListener = null; var touchEndListener = null; var handleTouchStart = function handleTouchStart(initialEvent) { timer = setTimeout(function () { cleanup(); handler(initialEvent); }, _this.longPressThreshold); touchMoveListener = addEventListener('touchmove', function () { return cleanup(); }); touchEndListener = addEventListener('touchend', function () { return cleanup(); }); }; var touchStartListener = addEventListener('touchstart', handleTouchStart); var cleanup = function cleanup() { if (timer) { clearTimeout(timer); } if (touchMoveListener) { touchMoveListener.remove(); } if (touchEndListener) { touchEndListener.remove(); } timer = null; touchMoveListener = null; touchEndListener = null; }; if (initialEvent) { handleTouchStart(initialEvent); } return { remove: function remove() { cleanup(); touchStartListener.remove(); } }; } // Listen for mousedown and touchstart events. When one is received, disable the other and setup // future event handling based on the type of event. ; _proto._addInitialEventListener = function _addInitialEventListener() { var _this2 = this; var mouseDownListener = addEventListener('mousedown', function (e) { _this2._onInitialEventListener.remove(); _this2._handleInitialEvent(e); _this2._onInitialEventListener = addEventListener('mousedown', _this2._handleInitialEvent); }); var touchStartListener = addEventListener('touchstart', function (e) { _this2._onInitialEventListener.remove(); _this2._onInitialEventListener = _this2._addLongPressListener(_this2._handleInitialEvent, e); }); this._onInitialEventListener = { remove: function remove() { mouseDownListener.remove(); touchStartListener.remove(); } }; }; _proto._dropFromOutsideListener = function _dropFromOutsideListener(e) { var _getEventCoordinates = getEventCoordinates(e), pageX = _getEventCoordinates.pageX, pageY = _getEventCoordinates.pageY, clientX = _getEventCoordinates.clientX, clientY = _getEventCoordinates.clientY; this.emit('dropFromOutside', { x: pageX, y: pageY, clientX: clientX, clientY: clientY }); e.preventDefault(); }; _proto._handleInitialEvent = function _handleInitialEvent(e) { if (this.isDetached) { return; } var _getEventCoordinates2 = getEventCoordinates(e), clientX = _getEventCoordinates2.clientX, clientY = _getEventCoordinates2.clientY, pageX = _getEventCoordinates2.pageX, pageY = _getEventCoordinates2.pageY; var node = this.container(), collides, offsetData; // Right clicks if (e.which === 3 || e.button === 2 || !isOverContainer(node, clientX, clientY)) return; if (!this.globalMouse && node && !contains(node, e.target)) { var _normalizeDistance = normalizeDistance(0), top = _normalizeDistance.top, left = _normalizeDistance.left, bottom = _normalizeDistance.bottom, right = _normalizeDistance.right; offsetData = getBoundsForNode(node); collides = objectsCollide({ top: offsetData.top - top, left: offsetData.left - left, bottom: offsetData.bottom + bottom, right: offsetData.right + right }, { top: pageY, left: pageX }); if (!collides) return; } var result = this.emit('beforeSelect', this._initialEventData = { isTouch: /^touch/.test(e.type), x: pageX, y: pageY, clientX: clientX, clientY: clientY }); if (result === false) return; switch (e.type) { case 'mousedown': this._onEndListener = addEventListener('mouseup', this._handleTerminatingEvent); this._onEscListener = addEventListener('keydown', this._handleTerminatingEvent); this._onMoveListener = addEventListener('mousemove', this._handleMoveEvent); break; case 'touchstart': this._handleMoveEvent(e); this._onEndListener = addEventListener('touchend', this._handleTerminatingEvent); this._onMoveListener = addEventListener('touchmove', this._handleMoveEvent); break; default: break; } }; _proto._handleTerminatingEvent = function _handleTerminatingEvent(e) { var _getEventCoordinates3 = getEventCoordinates(e), pageX = _getEventCoordinates3.pageX, pageY = _getEventCoordinates3.pageY; this.selecting = false; this._onEndListener && this._onEndListener.remove(); this._onMoveListener && this._onMoveListener.remove(); if (!this._initialEventData) return; var inRoot = !this.container || contains(this.container(), e.target); var bounds = this._selectRect; var click = this.isClick(pageX, pageY); this._initialEventData = null; if (e.key === 'Escape') { return this.emit('reset'); } if (!inRoot) { return this.emit('reset'); } if (click && inRoot) { return this._handleClickEvent(e); } // User drag-clicked in the Selectable area if (!click) return this.emit('select', bounds); }; _proto._handleClickEvent = function _handleClickEvent(e) { var _getEventCoordinates4 = getEventCoordinates(e), pageX = _getEventCoordinates4.pageX, pageY = _getEventCoordinates4.pageY, clientX = _getEventCoordinates4.clientX, clientY = _getEventCoordinates4.clientY; var now = new Date().getTime(); if (this._lastClickData && now - this._lastClickData.timestamp < clickInterval) { // Double click event this._lastClickData = null; return this.emit('doubleClick', { x: pageX, y: pageY, clientX: clientX, clientY: clientY }); } // Click event this._lastClickData = { timestamp: now }; return this.emit('click', { x: pageX, y: pageY, clientX: clientX, clientY: clientY }); }; _proto._handleMoveEvent = function _handleMoveEvent(e) { if (this._initialEventData === null || this.isDetached) { return; } var _this$_initialEventDa = this._initialEventData, x = _this$_initialEventDa.x, y = _this$_initialEventDa.y; var _getEventCoordinates5 = getEventCoordinates(e), pageX = _getEventCoordinates5.pageX, pageY = _getEventCoordinates5.pageY; var w = Math.abs(x - pageX); var h = Math.abs(y - pageY); var left = Math.min(pageX, x), top = Math.min(pageY, y), old = this.selecting; // Prevent emitting selectStart event until mouse is moved. // in Chrome on Windows, mouseMove event may be fired just after mouseDown event. if (this.isClick(pageX, pageY) && !old && !(w || h)) { return; } this.selecting = true; this._selectRect = { top: top, left: left, x: pageX, y: pageY, right: left + w, bottom: top + h }; if (!old) { this.emit('selectStart', this._initialEventData); } if (!this.isClick(pageX, pageY)) this.emit('selecting', this._selectRect); e.preventDefault(); }; _proto._keyListener = function _keyListener(e) { this.ctrl = e.metaKey || e.ctrlKey; }; _proto.isClick = function isClick(pageX, pageY) { var _this$_initialEventDa2 = this._initialEventData, x = _this$_initialEventDa2.x, y = _this$_initialEventDa2.y, isTouch = _this$_initialEventDa2.isTouch; return !isTouch && Math.abs(pageX - x) <= clickTolerance && Math.abs(pageY - y) <= clickTolerance; }; return Selection; }(); /** * Resolve the disance prop from either an Int or an Object * @return {Object} */ function normalizeDistance(distance) { if (distance === void 0) { distance = 0; } if (typeof distance !== 'object') distance = { top: distance, left: distance, right: distance, bottom: distance }; return distance; } /** * Given two objects containing "top", "left", "offsetWidth" and "offsetHeight" * properties, determine if they collide. * @param {Object|HTMLElement} a * @param {Object|HTMLElement} b * @return {bool} */ function objectsCollide(nodeA, nodeB, tolerance) { if (tolerance === void 0) { tolerance = 0; } var _getBoundsForNode = getBoundsForNode(nodeA), aTop = _getBoundsForNode.top, aLeft = _getBoundsForNode.left, _getBoundsForNode$rig = _getBoundsForNode.right, aRight = _getBoundsForNode$rig === void 0 ? aLeft : _getBoundsForNode$rig, _getBoundsForNode$bot = _getBoundsForNode.bottom, aBottom = _getBoundsForNode$bot === void 0 ? aTop : _getBoundsForNode$bot; var _getBoundsForNode2 = getBoundsForNode(nodeB), bTop = _getBoundsForNode2.top, bLeft = _getBoundsForNode2.left, _getBoundsForNode2$ri = _getBoundsForNode2.right, bRight = _getBoundsForNode2$ri === void 0 ? bLeft : _getBoundsForNode2$ri, _getBoundsForNode2$bo = _getBoundsForNode2.bottom, bBottom = _getBoundsForNode2$bo === void 0 ? bTop : _getBoundsForNode2$bo; return !( // 'a' bottom doesn't touch 'b' top aBottom - tolerance < bTop || // 'a' top doesn't touch 'b' bottom aTop + tolerance > bBottom || // 'a' right doesn't touch 'b' left aRight - tolerance < bLeft || // 'a' left doesn't touch 'b' right aLeft + tolerance > bRight); } /** * Given a node, get everything needed to calculate its boundaries * @param {HTMLElement} node * @return {Object} */ function getBoundsForNode(node) { if (!node.getBoundingClientRect) return node; var rect = node.getBoundingClientRect(), left = rect.left + pageOffset('left'), top = rect.top + pageOffset('top'); return { top: top, left: left, right: (node.offsetWidth || 0) + left, bottom: (node.offsetHeight || 0) + top }; } function pageOffset(dir) { if (dir === 'left') return window.pageXOffset || document.body.scrollLeft || 0; if (dir === 'top') return window.pageYOffset || document.body.scrollTop || 0; } var BackgroundCells = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(BackgroundCells, _React$Component); function BackgroundCells(props, context) { var _this; _this = _React$Component.call(this, props, context) || this; _this.state = { selecting: false }; return _this; } var _proto = BackgroundCells.prototype; _proto.componentDidMount = function componentDidMount() { this.props.selectable && this._selectable(); }; _proto.componentWillUnmount = function componentWillUnmount() { this._teardownSelectable(); }; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (nextProps.selectable && !this.props.selectable) this._selectable(); if (!nextProps.selectable && this.props.selectable) this._teardownSelectable(); }; _proto.render = function render() { var _this$props = this.props, range = _this$props.range, getNow = _this$props.getNow, getters = _this$props.getters, currentDate = _this$props.date, Wrapper = _this$props.components.dateCellWrapper; var _this$state = this.state, selecting = _this$state.selecting, startIdx = _this$state.startIdx, endIdx = _this$state.endIdx; var current = getNow(); return React.createElement("div", { className: "rbc-row-bg" }, range.map(function (date, index) { var selected = selecting && index >= startIdx && index <= endIdx; var _getters$dayProp = getters.dayProp(date), className = _getters$dayProp.className, style = _getters$dayProp.style; return React.createElement(Wrapper, { key: index, value: date, range: range }, React.createElement("div", { style: style, className: cn('rbc-day-bg', className, selected && 'rbc-selected-cell', eq(date, current, 'day') && 'rbc-today', currentDate && month(currentDate) !== month(date) && 'rbc-off-range-bg') })); })); }; _proto._selectable = function _selectable() { var _this2 = this; var node = findDOMNode(this); var selector = this._selector = new Selection(this.props.container, { longPressThreshold: this.props.longPressThreshold }); var selectorClicksHandler = function selectorClicksHandler(point, actionType) { if (!isEvent(findDOMNode(_this2), point)) { var rowBox = getBoundsForNode(node); var _this2$props = _this2.props, range = _this2$props.range, rtl = _this2$props.rtl; if (pointInBox(rowBox, point)) { var currentCell = getSlotAtX(rowBox, point.x, rtl, range.length); _this2._selectSlot({ startIdx: currentCell, endIdx: currentCell, action: actionType, box: point }); } } _this2._initial = {}; _this2.setState({ selecting: false }); }; selector.on('selecting', function (box) { var _this2$props2 = _this2.props, range = _this2$props2.range, rtl = _this2$props2.rtl; var startIdx = -1; var endIdx = -1; if (!_this2.state.selecting) { notify(_this2.props.onSelectStart, [box]); _this2._initial = { x: box.x, y: box.y }; } if (selector.isSelected(node)) { var nodeBox = getBoundsForNode(node); var _dateCellSelection = dateCellSelection(_this2._initial, nodeBox, box, range.length, rtl); startIdx = _dateCellSelection.startIdx; endIdx = _dateCellSelection.endIdx; } _this2.setState({ selecting: true, startIdx: startIdx, endIdx: endIdx }); }); selector.on('beforeSelect', function (box) { if (_this2.props.selectable !== 'ignoreEvents') return; return !isEvent(findDOMNode(_this2), box); }); selector.on('click', function (point) { return selectorClicksHandler(point, 'click'); }); selector.on('doubleClick', function (point) { return selectorClicksHandler(point, 'doubleClick'); }); selector.on('select', function (bounds) { _this2._selectSlot(_extends({}, _this2.state, { action: 'select', bounds: bounds })); _this2._initial = {}; _this2.setState({ selecting: false }); notify(_this2.props.onSelectEnd, [_this2.state]); }); }; _proto._teardownSelectable = function _teardownSelectable() { if (!this._selector) return; this._selector.teardown(); this._selector = null; }; _proto._selectSlot = function _selectSlot(_ref) { var endIdx = _ref.endIdx, startIdx = _ref.startIdx, action = _ref.action, bounds = _ref.bounds, box = _ref.box; if (endIdx !== -1 && startIdx !== -1) this.props.onSelectSlot && this.props.onSelectSlot({ start: startIdx, end: endIdx, action: action, bounds: bounds, box: box }); }; return BackgroundCells; }(React.Component); BackgroundCells.propTypes = process.env.NODE_ENV !== "production" ? { date: PropTypes.instanceOf(Date), getNow: PropTypes.func.isRequired, getters: PropTypes.object.isRequired, components: PropTypes.object.isRequired, container: PropTypes.func, dayPropGetter: PropTypes.func, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), longPressThreshold: PropTypes.number, onSelectSlot: PropTypes.func.isRequired, onSelectEnd: PropTypes.func, onSelectStart: PropTypes.func, range: PropTypes.arrayOf(PropTypes.instanceOf(Date)), rtl: PropTypes.bool, type: PropTypes.string } : {}; /* eslint-disable react/prop-types */ var EventRowMixin = { propTypes: { slotMetrics: PropTypes.object.isRequired, selected: PropTypes.object, isAllDay: PropTypes.bool, accessors: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, onSelect: PropTypes.func, onDoubleClick: PropTypes.func }, defaultProps: { segments: [], selected: {} }, renderEvent: function renderEvent(props, event) { var selected = props.selected, _ = props.isAllDay, accessors = props.accessors, getters = props.getters, onSelect = props.onSelect, onDoubleClick = props.onDoubleClick, localizer = props.localizer, slotMetrics = props.slotMetrics, components = props.components; var continuesPrior = slotMetrics.continuesPrior(event); var continuesAfter = slotMetrics.continuesAfter(event); return React.createElement(EventCell, { event: event, getters: getters, localizer: localizer, accessors: accessors, components: components, onSelect: onSelect, onDoubleClick: onDoubleClick, continuesPrior: continuesPrior, continuesAfter: continuesAfter, selected: isSelected(event, selected) }); }, renderSpan: function renderSpan(slots, len, key, content) { if (content === void 0) { content = ' '; } var per = Math.abs(len) / slots * 100 + '%'; return React.createElement("div", { key: key, className: "rbc-row-segment" // IE10/11 need max-width. flex-basis doesn't respect box-sizing , style: { WebkitFlexBasis: per, flexBasis: per, maxWidth: per } }, content); } }; var EventRow = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(EventRow, _React$Component); function EventRow() { return _React$Component.apply(this, arguments) || this; } var _proto = EventRow.prototype; _proto.render = function render() { var _this = this; var _this$props = this.props, segments = _this$props.segments, slots = _this$props.slotMetrics.slots, className = _this$props.className; var lastEnd = 1; return React.createElement("div", { className: cn(className, 'rbc-row') }, segments.reduce(function (row, _ref, li) { var event = _ref.event, left = _ref.left, right = _ref.right, span = _ref.span; var key = '_lvl_' + li; var gap = left - lastEnd; var content = EventRowMixin.renderEvent(_this.props, event); if (gap) row.push(EventRowMixin.renderSpan(slots, gap, key + "_gap")); row.push(EventRowMixin.renderSpan(slots, span, key, content)); lastEnd = right + 1; return row; }, [])); }; return EventRow; }(React.Component); EventRow.propTypes = process.env.NODE_ENV !== "production" ? _extends({ segments: PropTypes.array }, EventRowMixin.propTypes) : {}; EventRow.defaultProps = _extends({}, EventRowMixin.defaultProps); function endOfRange(dateRange, unit) { if (unit === void 0) { unit = 'day'; } return { first: dateRange[0], last: add(dateRange[dateRange.length - 1], 1, unit) }; } function eventSegments(event, range, accessors) { var _endOfRange = endOfRange(range), first = _endOfRange.first, last = _endOfRange.last; var slots = diff(first, last, 'day'); var start = max(startOf(accessors.start(event), 'day'), first); var end = min(ceil(accessors.end(event), 'day'), last); var padding = findIndex(range, function (x) { return eq(x, start, 'day'); }); var span = diff(start, end, 'day'); span = Math.min(span, slots); span = Math.max(span, 1); return { event: event, span: span, left: padding + 1, right: Math.max(padding + span, 1) }; } function eventLevels(rowSegments, limit) { if (limit === void 0) { limit = Infinity; } var i, j, seg, levels = [], extra = []; for (i = 0; i < rowSegments.length; i++) { seg = rowSegments[i]; for (j = 0; j < levels.length; j++) { if (!segsOverlap(seg, levels[j])) break; } if (j >= limit) { extra.push(seg); } else { (levels[j] || (levels[j] = [])).push(seg); } } for (i = 0; i < levels.length; i++) { levels[i].sort(function (a, b) { return a.left - b.left; }); //eslint-disable-line } return { levels: levels, extra: extra }; } function inRange(e, start, end, accessors) { var eStart = startOf(accessors.start(e), 'day'); var eEnd = accessors.end(e); var startsBeforeEnd = lte(eStart, end, 'day'); // when the event is zero duration we need to handle a bit differently var endsAfterStart = !eq(eStart, eEnd, 'minutes') ? gt(eEnd, start, 'minutes') : gte(eEnd, start, 'minutes'); return startsBeforeEnd && endsAfterStart; } function segsOverlap(seg, otherSegs) { return otherSegs.some(function (otherSeg) { return otherSeg.left <= seg.right && otherSeg.right >= seg.left; }); } function sortEvents(evtA, evtB, accessors) { var startSort = +startOf(accessors.start(evtA), 'day') - +startOf(accessors.start(evtB), 'day'); var durA = diff(accessors.start(evtA), ceil(accessors.end(evtA), 'day'), 'day'); var durB = diff(accessors.start(evtB), ceil(accessors.end(evtB), 'day'), 'day'); return startSort || // sort by start Day first Math.max(durB, 1) - Math.max(durA, 1) || // events spanning multiple days go first !!accessors.allDay(evtB) - !!accessors.allDay(evtA) || // then allDay single day events +accessors.start(evtA) - +accessors.start(evtB); // then sort by start time } var isSegmentInSlot = function isSegmentInSlot(seg, slot) { return seg.left <= slot && seg.right >= slot; }; var eventsInSlot = function eventsInSlot(segments, slot) { return segments.filter(function (seg) { return isSegmentInSlot(seg, slot); }).length; }; var EventEndingRow = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(EventEndingRow, _React$Component); function EventEndingRow() { return _React$Component.apply(this, arguments) || this; } var _proto = EventEndingRow.prototype; _proto.render = function render() { var _this$props = this.props, segments = _this$props.segments, slots = _this$props.slotMetrics.slots; var rowSegments = eventLevels(segments).levels[0]; var current = 1, lastEnd = 1, row = []; while (current <= slots) { var key = '_lvl_' + current; var _ref = rowSegments.filter(function (seg) { return isSegmentInSlot(seg, current); })[0] || {}, event = _ref.event, left = _ref.left, right = _ref.right, span = _ref.span; //eslint-disable-line if (!event) { current++; continue; } var gap = Math.max(0, left - lastEnd); if (this.canRenderSlotEvent(left, span)) { var content = EventRowMixin.renderEvent(this.props, event); if (gap) { row.push(EventRowMixin.renderSpan(slots, gap, key + '_gap')); } row.push(EventRowMixin.renderSpan(slots, span, key, content)); lastEnd = current = right + 1; } else { if (gap) { row.push(EventRowMixin.renderSpan(slots, gap, key + '_gap')); } row.push(EventRowMixin.renderSpan(slots, 1, key, this.renderShowMore(segments, current))); lastEnd = current = current + 1; } } return React.createElement("div", { className: "rbc-row" }, row); }; _proto.canRenderSlotEvent = function canRenderSlotEvent(slot, span) { var segments = this.props.segments; return range$1(slot, slot + span).every(function (s) { var count = eventsInSlot(segments, s); return count === 1; }); }; _proto.renderShowMore = function renderShowMore(segments, slot) { var _this = this; var localizer = this.props.localizer; var count = eventsInSlot(segments, slot); return count ? React.createElement("a", { key: 'sm_' + slot, href: "#", className: 'rbc-show-more', onClick: function onClick(e) { return _this.showMore(slot, e); } }, localizer.messages.showMore(count)) : false; }; _proto.showMore = function showMore(slot, e) { e.preventDefault(); this.props.onShowMore(slot, e.target); }; return EventEndingRow; }(React.Component); EventEndingRow.propTypes = process.env.NODE_ENV !== "production" ? _extends({ segments: PropTypes.array, slots: PropTypes.number, onShowMore: PropTypes.func }, EventRowMixin.propTypes) : {}; EventEndingRow.defaultProps = _extends({}, EventRowMixin.defaultProps); var isSegmentInSlot$1 = function isSegmentInSlot(seg, slot) { return seg.left <= slot && seg.right >= slot; }; var isEqual = function isEqual(a, b) { return a.range === b.range && a.events === b.events; }; function getSlotMetrics() { return memoize(function (options) { var range = options.range, events = options.events, maxRows = options.maxRows, minRows = options.minRows, accessors = options.accessors; var _endOfRange = endOfRange(range), first = _endOfRange.first, last = _endOfRange.last; var segments = events.map(function (evt) { return eventSegments(evt, range, accessors); }); var _eventLevels = eventLevels(segments, Math.max(maxRows - 1, 1)), levels = _eventLevels.levels, extra = _eventLevels.extra; while (levels.length < minRows) { levels.push([]); } return { first: first, last: last, levels: levels, extra: extra, range: range, slots: range.length, clone: function clone(args) { var metrics = getSlotMetrics(); return metrics(_extends({}, options, args)); }, getDateForSlot: function getDateForSlot(slotNumber) { return range[slotNumber]; }, getSlotForDate: function getSlotForDate(date) { return range.find(function (r) { return eq(r, date, 'day'); }); }, getEventsForSlot: function getEventsForSlot(slot) { return segments.filter(function (seg) { return isSegmentInSlot$1(seg, slot); }).map(function (seg) { return seg.event; }); }, continuesPrior: function continuesPrior(event) { return lt(accessors.start(event), first, 'day'); }, continuesAfter: function continuesAfter(event) { var eventEnd = accessors.end(event); var singleDayDuration = eq(accessors.start(event), eventEnd, 'minutes'); return singleDayDuration ? gte(eventEnd, last, 'minutes') : gt(eventEnd, last, 'minutes'); } }; }, isEqual); } var DateContentRow = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(DateContentRow, _React$Component); function DateContentRow() { 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.handleSelectSlot = function (slot) { var _this$props = _this.props, range = _this$props.range, onSelectSlot = _this$props.onSelectSlot; onSelectSlot(range.slice(slot.start, slot.end + 1), slot); }; _this.handleShowMore = function (slot, target) { var _this$props2 = _this.props, range = _this$props2.range, onShowMore = _this$props2.onShowMore; var metrics = _this.slotMetrics(_this.props); var row = qsa(findDOMNode(_assertThisInitialized(_this)), '.rbc-row-bg')[0]; var cell; if (row) cell = row.children[slot - 1]; var events = metrics.getEventsForSlot(slot); onShowMore(events, range[slot - 1], cell, slot, target); }; _this.createHeadingRef = function (r) { _this.headingRow = r; }; _this.createEventRef = function (r) { _this.eventRow = r; }; _this.getContainer = function () { var container = _this.props.container; return container ? container() : findDOMNode(_assertThisInitialized(_this)); }; _this.renderHeadingCell = function (date, index) { var _this$props3 = _this.props, renderHeader = _this$props3.renderHeader, getNow = _this$props3.getNow; return renderHeader({ date: date, key: "header_" + index, className: cn('rbc-date-cell', eq(date, getNow(), 'day') && 'rbc-now') }); }; _this.renderDummy = function () { var _this$props4 = _this.props, className = _this$props4.className, range = _this$props4.range, renderHeader = _this$props4.renderHeader; return React.createElement("div", { className: className }, React.createElement("div", { className: "rbc-row-content" }, renderHeader && React.createElement("div", { className: "rbc-row", ref: _this.createHeadingRef }, range.map(_this.renderHeadingCell)), React.createElement("div", { className: "rbc-row", ref: _this.createEventRef }, React.createElement("div", { className: "rbc-row-segment" }, React.createElement("div", { className: "rbc-event" }, React.createElement("div", { className: "rbc-event-content" }, "\xA0")))))); }; _this.slotMetrics = getSlotMetrics(); return _this; } var _proto = DateContentRow.prototype; _proto.getRowLimit = function getRowLimit() { var eventHeight = getHeight(this.eventRow); var headingHeight = this.headingRow ? getHeight(this.headingRow) : 0; var eventSpace = getHeight(findDOMNode(this)) - headingHeight; return Math.max(Math.floor(eventSpace / eventHeight), 1); }; _proto.render = function render() { var _this$props5 = this.props, date = _this$props5.date, rtl = _this$props5.rtl, range = _this$props5.range, className = _this$props5.className, selected = _this$props5.selected, selectable = _this$props5.selectable, renderForMeasure = _this$props5.renderForMeasure, accessors = _this$props5.accessors, getters = _this$props5.getters, components = _this$props5.components, getNow = _this$props5.getNow, renderHeader = _this$props5.renderHeader, onSelect = _this$props5.onSelect, localizer = _this$props5.localizer, onSelectStart = _this$props5.onSelectStart, onSelectEnd = _this$props5.onSelectEnd, onDoubleClick = _this$props5.onDoubleClick, resourceId = _this$props5.resourceId, longPressThreshold = _this$props5.longPressThreshold, isAllDay = _this$props5.isAllDay; if (renderForMeasure) return this.renderDummy(); var metrics = this.slotMetrics(this.props); var levels = metrics.levels, extra = metrics.extra; var WeekWrapper = components.weekWrapper; var eventRowProps = { selected: selected, accessors: accessors, getters: getters, localizer: localizer, components: components, onSelect: onSelect, onDoubleClick: onDoubleClick, resourceId: resourceId, slotMetrics: metrics }; return React.createElement("div", { className: className }, React.createElement(BackgroundCells, { date: date, getNow: getNow, rtl: rtl, range: range, selectable: selectable, container: this.getContainer, getters: getters, onSelectStart: onSelectStart, onSelectEnd: onSelectEnd, onSelectSlot: this.handleSelectSlot, components: components, longPressThreshold: longPressThreshold }), React.createElement("div", { className: "rbc-row-content" }, renderHeader && React.createElement("div", { className: "rbc-row ", ref: this.createHeadingRef }, range.map(this.renderHeadingCell)), React.createElement(WeekWrapper, _extends({ isAllDay: isAllDay }, eventRowProps), levels.map(function (segs, idx) { return React.createElement(EventRow, _extends({ key: idx, segments: segs }, eventRowProps)); }), !!extra.length && React.createElement(EventEndingRow, _extends({ segments: extra, onShowMore: this.handleShowMore }, eventRowProps))))); }; return DateContentRow; }(React.Component); DateContentRow.propTypes = process.env.NODE_ENV !== "production" ? { date: PropTypes.instanceOf(Date), events: PropTypes.array.isRequired, range: PropTypes.array.isRequired, rtl: PropTypes.bool, resourceId: PropTypes.any, renderForMeasure: PropTypes.bool, renderHeader: PropTypes.func, container: PropTypes.func, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), longPressThreshold: PropTypes.number, onShowMore: PropTypes.func, onSelectSlot: PropTypes.func, onSelect: PropTypes.func, onSelectEnd: PropTypes.func, onSelectStart: PropTypes.func, onDoubleClick: PropTypes.func, dayPropGetter: PropTypes.func, getNow: PropTypes.func.isRequired, isAllDay: PropTypes.bool, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, minRows: PropTypes.number.isRequired, maxRows: PropTypes.number.isRequired } : {}; DateContentRow.defaultProps = { minRows: 0, maxRows: Infinity }; var Header = function Header(_ref) { var label = _ref.label; return React.createElement("span", null, label); }; Header.propTypes = process.env.NODE_ENV !== "production" ? { label: PropTypes.node } : {}; var DateHeader = function DateHeader(_ref) { var label = _ref.label, drilldownView = _ref.drilldownView, onDrillDown = _ref.onDrillDown; if (!drilldownView) { return React.createElement("span", null, label); } return React.createElement("a", { href: "#", onClick: onDrillDown }, label); }; DateHeader.propTypes = process.env.NODE_ENV !== "production" ? { label: PropTypes.node, date: PropTypes.instanceOf(Date), drilldownView: PropTypes.string, onDrillDown: PropTypes.func, isOffRange: PropTypes.bool } : {}; var eventsForWeek = function eventsForWeek(evts, start, end, accessors) { return evts.filter(function (e) { return inRange(e, start, end, accessors); }); }; var MonthView = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(MonthView, _React$Component); function MonthView() { 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.getContainer = function () { return findDOMNode(_assertThisInitialized(_this)); }; _this.renderWeek = function (week, weekIdx) { var _this$props = _this.props, events = _this$props.events, components = _this$props.components, selectable = _this$props.selectable, getNow = _this$props.getNow, selected = _this$props.selected, date = _this$props.date, localizer = _this$props.localizer, longPressThreshold = _this$props.longPressThreshold, accessors = _this$props.accessors, getters = _this$props.getters; var _this$state = _this.state, needLimitMeasure = _this$state.needLimitMeasure, rowLimit = _this$state.rowLimit; events = eventsForWeek(events, week[0], week[week.length - 1], accessors); events.sort(function (a, b) { return sortEvents(a, b, accessors); }); return React.createElement(DateContentRow, { key: weekIdx, ref: weekIdx === 0 ? _this.slotRowRef : undefined, container: _this.getContainer, className: "rbc-month-row", getNow: getNow, date: date, range: week, events: events, maxRows: rowLimit, selected: selected, selectable: selectable, components: components, accessors: accessors, getters: getters, localizer: localizer, renderHeader: _this.readerDateHeading, renderForMeasure: needLimitMeasure, onShowMore: _this.handleShowMore, onSelect: _this.handleSelectEvent, onDoubleClick: _this.handleDoubleClickEvent, onSelectSlot: _this.handleSelectSlot, longPressThreshold: longPressThreshold, rtl: _this.props.rtl }); }; _this.readerDateHeading = function (_ref) { var date = _ref.date, className = _ref.className, props = _objectWithoutPropertiesLoose(_ref, ["date", "className"]); var _this$props2 = _this.props, currentDate = _this$props2.date, getDrilldownView = _this$props2.getDrilldownView, localizer = _this$props2.localizer; var isOffRange = month(date) !== month(currentDate); var isCurrent = eq(date, currentDate, 'day'); var drilldownView = getDrilldownView(date); var label = localizer.format(date, 'dateFormat'); var DateHeaderComponent = _this.props.components.dateHeader || DateHeader; return React.createElement("div", _extends({}, props, { className: cn(className, isOffRange && 'rbc-off-range', isCurrent && 'rbc-current') }), React.createElement(DateHeaderComponent, { label: label, date: date, drilldownView: drilldownView, isOffRange: isOffRange, onDrillDown: function onDrillDown(e) { return _this.handleHeadingClick(date, drilldownView, e); } })); }; _this.handleSelectSlot = function (range, slotInfo) { _this._pendingSelection = _this._pendingSelection.concat(range); clearTimeout(_this._selectTimer); _this._selectTimer = setTimeout(function () { return _this.selectDates(slotInfo); }); }; _this.handleHeadingClick = function (date, view, e) { e.preventDefault(); _this.clearSelection(); notify(_this.props.onDrillDown, [date, view]); }; _this.handleSelectEvent = function () { _this.clearSelection(); for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } notify(_this.props.onSelectEvent, args); }; _this.handleDoubleClickEvent = function () { _this.clearSelection(); for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } notify(_this.props.onDoubleClickEvent, args); }; _this.handleShowMore = function (events, date, cell, slot, target) { var _this$props3 = _this.props, popup = _this$props3.popup, onDrillDown = _this$props3.onDrillDown, onShowMore = _this$props3.onShowMore, getDrilldownView = _this$props3.getDrilldownView; //cancel any pending selections so only the event click goes through. _this.clearSelection(); if (popup) { var position = getPosition(cell, findDOMNode(_assertThisInitialized(_this))); _this.setState({ overlay: { date: date, events: events, position: position, target: target } }); } else { notify(onDrillDown, [date, getDrilldownView(date) || views.DAY]); } notify(onShowMore, [events, date, slot]); }; _this._bgRows = []; _this._pendingSelection = []; _this.slotRowRef = React.createRef(); _this.state = { rowLimit: 5, needLimitMeasure: true }; return _this; } var _proto = MonthView.prototype; _proto.componentWillReceiveProps = function componentWillReceiveProps(_ref2) { var date = _ref2.date; this.setState({ needLimitMeasure: !eq(date, this.props.date, 'month') }); }; _proto.componentDidMount = function componentDidMount() { var _this2 = this; var running; if (this.state.needLimitMeasure) this.measureRowLimit(this.props); window.addEventListener('resize', this._resizeListener = function () { if (!running) { raf(function () { running = false; _this2.setState({ needLimitMeasure: true }); //eslint-disable-line }); } }, false); }; _proto.componentDidUpdate = function componentDidUpdate() { if (this.state.needLimitMeasure) this.measureRowLimit(this.props); }; _proto.componentWillUnmount = function componentWillUnmount() { window.removeEventListener('resize', this._resizeListener, false); }; _proto.render = function render() { var _this$props4 = this.props, date = _this$props4.date, localizer = _this$props4.localizer, className = _this$props4.className, month = visibleDays(date, localizer), weeks = chunk(month, 7); this._weekCount = weeks.length; return React.createElement("div", { className: cn('rbc-month-view', className) }, React.createElement("div", { className: "rbc-row rbc-month-header" }, this.renderHeaders(weeks[0])), weeks.map(this.renderWeek), this.props.popup && this.renderOverlay()); }; _proto.renderHeaders = function renderHeaders(row) { var _this$props5 = this.props, localizer = _this$props5.localizer, components = _this$props5.components; var first = row[0]; var last = row[row.length - 1]; var HeaderComponent = components.header || Header; return range(first, last, 'day').map(function (day, idx) { return React.createElement("div", { key: 'header_' + idx, className: "rbc-header" }, React.createElement(HeaderComponent, { date: day, localizer: localizer, label: localizer.format(day, 'weekdayFormat') })); }); }; _proto.renderOverlay = function renderOverlay() { var _this3 = this; var overlay = this.state && this.state.overlay || {}; var _this$props6 = this.props, accessors = _this$props6.accessors, localizer = _this$props6.localizer, components = _this$props6.components, getters = _this$props6.getters, selected = _this$props6.selected; return React.createElement(Overlay, { rootClose: true, placement: "bottom", container: this, show: !!overlay.position, onHide: function onHide() { return _this3.setState({ overlay: null }); }, target: function target() { return overlay.target; } }, function (_ref3) { var props = _ref3.props; return React.createElement(Popup$1, _extends({}, props, { accessors: accessors, getters: getters, selected: selected, components: components, localizer: localizer, position: overlay.position, events: overlay.events, slotStart: overlay.date, slotEnd: overlay.end, onSelect: _this3.handleSelectEvent, onDoubleClick: _this3.handleDoubleClickEvent })); }); }; _proto.measureRowLimit = function measureRowLimit() { this.setState({ needLimitMeasure: false, rowLimit: this.slotRowRef.current.getRowLimit() }); }; _proto.selectDates = function selectDates(slotInfo) { var slots = this._pendingSelection.slice(); this._pendingSelection = []; slots.sort(function (a, b) { return +a - +b; }); notify(this.props.onSelectSlot, { slots: slots, start: slots[0], end: slots[slots.length - 1], action: slotInfo.action, bounds: slotInfo.bounds, box: slotInfo.box }); }; _proto.clearSelection = function clearSelection() { clearTimeout(this._selectTimer); this._pendingSelection = []; }; return MonthView; }(React.Component); MonthView.propTypes = process.env.NODE_ENV !== "production" ? { events: PropTypes.array.isRequired, date: PropTypes.instanceOf(Date), min: PropTypes.instanceOf(Date), max: PropTypes.instanceOf(Date), step: PropTypes.number, getNow: PropTypes.func.isRequired, scrollToTime: PropTypes.instanceOf(Date), rtl: PropTypes.bool, width: PropTypes.number, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), longPressThreshold: PropTypes.number, onNavigate: PropTypes.func, onSelectSlot: PropTypes.func, onSelectEvent: PropTypes.func, onDoubleClickEvent: PropTypes.func, onShowMore: PropTypes.func, onDrillDown: PropTypes.func, getDrilldownView: PropTypes.func.isRequired, popup: PropTypes.bool, popupOffset: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ x: PropTypes.number, y: PropTypes.number })]) } : {}; MonthView.range = function (date, _ref4) { var localizer = _ref4.localizer; var start = firstVisibleDay(date, localizer); var end = lastVisibleDay(date, localizer); return { start: start, end: end }; }; MonthView.navigate = function (date, action) { switch (action) { case navigate.PREVIOUS: return add(date, -1, 'month'); case navigate.NEXT: return add(date, 1, 'month'); default: return date; } }; MonthView.title = function (date, _ref5) { var localizer = _ref5.localizer; return localizer.format(date, 'monthHeaderFormat'); }; var getDstOffset = function getDstOffset(start, end) { return start.getTimezoneOffset() - end.getTimezoneOffset(); }; var getKey = function getKey(min, max, step, slots) { return "" + +startOf(min, 'minutes') + ("" + +startOf(max, 'minutes')) + (step + "-" + slots); }; function getSlotMetrics$1(_ref) { var start = _ref.min, end = _ref.max, step = _ref.step, timeslots = _ref.timeslots; var key = getKey(start, end, step, timeslots); // if the start is on a DST-changing day but *after* the moment of DST // transition we need to add those extra minutes to our minutesFromMidnight var daystart = startOf(start, 'day'); var daystartdstoffset = getDstOffset(daystart, start); var totalMin = 1 + diff(start, end, 'minutes') + getDstOffset(start, end); var minutesFromMidnight = diff(daystart, start, 'minutes') + daystartdstoffset; var numGroups = Math.ceil(totalMin / (step * timeslots)); var numSlots = numGroups * timeslots; var groups = new Array(numGroups); var slots = new Array(numSlots); // Each slot date is created from "zero", instead of adding `step` to // the previous one, in order to avoid DST oddities for (var grp = 0; grp < numGroups; grp++) { groups[grp] = new Array(timeslots); for (var slot = 0; slot < timeslots; slot++) { var slotIdx = grp * timeslots + slot; var minFromStart = slotIdx * step; // A date with total minutes calculated from the start of the day slots[slotIdx] = groups[grp][slot] = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, minutesFromMidnight + minFromStart, 0, 0); } } // Necessary to be able to select up until the last timeslot in a day var lastSlotMinFromStart = slots.length * step; slots.push(new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, minutesFromMidnight + lastSlotMinFromStart, 0, 0)); function positionFromDate(date) { var diff$1 = diff(start, date, 'minutes') + getDstOffset(start, date); return Math.min(diff$1, totalMin); } return { groups: groups, update: function update(args) { if (getKey(args) !== key) return getSlotMetrics$1(args); return this; }, dateIsInGroup: function dateIsInGroup(date, groupIndex) { var nextGroup = groups[groupIndex + 1]; return inRange$1(date, groups[groupIndex][0], nextGroup ? nextGroup[0] : end, 'minutes'); }, nextSlot: function nextSlot(slot) { var next = slots[Math.min(slots.indexOf(slot) + 1, slots.length - 1)]; // in the case of the last slot we won't a long enough range so manually get it if (next === slot) next = add(slot, step, 'minutes'); return next; }, closestSlotToPosition: function closestSlotToPosition(percent) { var slot = Math.min(slots.length - 1, Math.max(0, Math.floor(percent * numSlots))); return slots[slot]; }, closestSlotFromPoint: function closestSlotFromPoint(point, boundaryRect) { var range = Math.abs(boundaryRect.top - boundaryRect.bottom); return this.closestSlotToPosition((point.y - boundaryRect.top) / range); }, closestSlotFromDate: function closestSlotFromDate(date, offset) { if (offset === void 0) { offset = 0; } if (lt(date, start, 'minutes')) return slots[0]; var diffMins = diff(start, date, 'minutes'); return slots[(diffMins - diffMins % step) / step + offset]; }, startsBeforeDay: function startsBeforeDay(date) { return lt(date, start, 'day'); }, startsAfterDay: function startsAfterDay(date) { return gt(date, end, 'day'); }, startsBefore: function startsBefore(date) { return lt(merge(start, date), start, 'minutes'); }, startsAfter: function startsAfter(date) { return gt(merge(end, date), end, 'minutes'); }, getRange: function getRange(rangeStart, rangeEnd, ignoreMin, ignoreMax) { if (!ignoreMin) rangeStart = min(end, max(start, rangeStart)); if (!ignoreMax) rangeEnd = min(end, max(start, rangeEnd)); var rangeStartMin = positionFromDate(rangeStart); var rangeEndMin = positionFromDate(rangeEnd); var top = rangeEndMin - rangeStartMin < step ? (rangeStartMin - step) / (step * numSlots) * 100 : rangeStartMin / (step * numSlots) * 100; return { top: top, height: rangeEndMin / (step * numSlots) * 100 - top, start: positionFromDate(rangeStart), startDate: rangeStart, end: positionFromDate(rangeEnd), endDate: rangeEnd }; } }; } var Event = /*#__PURE__*/ function () { function Event(data, _ref) { var accessors = _ref.accessors, slotMetrics = _ref.slotMetrics; var _slotMetrics$getRange = slotMetrics.getRange(accessors.start(data), accessors.end(data)), start = _slotMetrics$getRange.start, startDate = _slotMetrics$getRange.startDate, end = _slotMetrics$getRange.end, endDate = _slotMetrics$getRange.endDate, top = _slotMetrics$getRange.top, height = _slotMetrics$getRange.height; this.start = start; this.end = end; this.startMs = +startDate; this.endMs = +endDate; this.top = top; this.height = height; this.data = data; } /** * The event's width without any overlap. */ _createClass(Event, [{ key: "_width", get: function get() { // The container event's width is determined by the maximum number of // events in any of its rows. if (this.rows) { var columns = this.rows.reduce(function (max, row) { return Math.max(max, row.leaves.length + 1); }, // add itself 0) + 1; // add the container return 100 / columns; } var availableWidth = 100 - this.container._width; // The row event's width is the space left by the container, divided // among itself and its leaves. if (this.leaves) { return availableWidth / (this.leaves.length + 1); } // The leaf event's width is determined by its row's width return this.row._width; } /** * The event's calculated width, possibly with extra width added for * overlapping effect. */ }, { key: "width", get: function get() { var noOverlap = this._width; var overlap = Math.min(100, this._width * 1.7); // Containers can always grow. if (this.rows) { return overlap; } // Rows can grow if they have leaves. if (this.leaves) { return this.leaves.length > 0 ? overlap : noOverlap; } // Leaves can grow unless they're the last item in a row. var leaves = this.row.leaves; var index = leaves.indexOf(this); return index === leaves.length - 1 ? noOverlap : overlap; } }, { key: "xOffset", get: function get() { // Containers have no offset. if (this.rows) return 0; // Rows always start where their container ends. if (this.leaves) return this.container._width; // Leaves are spread out evenly on the space left by its row. var _this$row = this.row, leaves = _this$row.leaves, xOffset = _this$row.xOffset, _width = _this$row._width; var index = leaves.indexOf(this) + 1; return xOffset + index * _width; } }]); return Event; }(); /** * Return true if event a and b is considered to be on the same row. */ function onSameRow(a, b, minimumStartDifference) { return (// Occupies the same start slot. Math.abs(b.start - a.start) < minimumStartDifference || // A's start slot overlaps with b's end slot. b.start > a.start && b.start < a.end ); } function sortByRender(events) { var sortedByTime = sortBy(events, ['startMs', function (e) { return -e.endMs; }]); var sorted = []; while (sortedByTime.length > 0) { var event = sortedByTime.shift(); sorted.push(event); for (var i = 0; i < sortedByTime.length; i++) { var test = sortedByTime[i]; // Still inside this event, look for next. if (event.endMs > test.startMs) continue; // We've found the first event of the next event group. // If that event is not right next to our current event, we have to // move it here. if (i > 0) { var _event = sortedByTime.splice(i, 1)[0]; sorted.push(_event); } // We've already found the next event group, so stop looking. break; } } return sorted; } function getStyledEvents(_ref2) { var events = _ref2.events, minimumStartDifference = _ref2.minimumStartDifference, slotMetrics = _ref2.slotMetrics, accessors = _ref2.accessors; // Create proxy events and order them so that we don't have // to fiddle with z-indexes. var proxies = events.map(function (event) { return new Event(event, { slotMetrics: slotMetrics, accessors: accessors }); }); var eventsInRenderOrder = sortByRender(proxies); // Group overlapping events, while keeping order. // Every event is always one of: container, row or leaf. // Containers can contain rows, and rows can contain leaves. var containerEvents = []; var _loop = function _loop(i) { var event = eventsInRenderOrder[i]; // Check if this event can go into a container event. var container = containerEvents.find(function (c) { return c.end > event.start || Math.abs(event.start - c.start) < minimumStartDifference; }); // Couldn't find a container — that means this event is a container. if (!container) { event.rows = []; containerEvents.push(event); return "continue"; } // Found a container for the event. event.container = container; // Check if the event can be placed in an existing row. // Start looking from behind. var row = null; for (var j = container.rows.length - 1; !row && j >= 0; j--) { if (onSameRow(container.rows[j], event, minimumStartDifference)) { row = container.rows[j]; } } if (row) { // Found a row, so add it. row.leaves.push(event); event.row = row; } else { // Couldn't find a row – that means this event is a row. event.leaves = []; container.rows.push(event); } }; for (var i = 0; i < eventsInRenderOrder.length; i++) { var _ret = _loop(i); if (_ret === "continue") continue; } // Return the original events, along with their styles. return eventsInRenderOrder.map(function (event) { return { event: event.data, style: { top: event.top, height: event.height, width: event.width, xOffset: event.xOffset } }; }); } var TimeSlotGroup = /*#__PURE__*/ function (_Component) { _inheritsLoose(TimeSlotGroup, _Component); function TimeSlotGroup() { return _Component.apply(this, arguments) || this; } var _proto = TimeSlotGroup.prototype; _proto.render = function render() { var _this$props = this.props, renderSlot = _this$props.renderSlot, resource = _this$props.resource, group = _this$props.group, getters = _this$props.getters, _this$props$component = _this$props.components; _this$props$component = _this$props$component === void 0 ? {} : _this$props$component; var _this$props$component2 = _this$props$component.timeSlotWrapper, Wrapper = _this$props$component2 === void 0 ? NoopWrapper : _this$props$component2; return React.createElement("div", { className: "rbc-timeslot-group" }, group.map(function (value, idx) { var slotProps = getters ? getters.slotProp(value, resource) : {}; return React.createElement(Wrapper, { key: idx, value: value, resource: resource }, React.createElement("div", _extends({}, slotProps, { className: cn('rbc-time-slot', slotProps.className) }), renderSlot && renderSlot(value, idx))); })); }; return TimeSlotGroup; }(Component); TimeSlotGroup.propTypes = process.env.NODE_ENV !== "production" ? { renderSlot: PropTypes.func, group: PropTypes.array.isRequired, resource: PropTypes.any, components: PropTypes.object, getters: PropTypes.object } : {}; /* eslint-disable react/prop-types */ function TimeGridEvent(props) { var _extends2; var style = props.style, className = props.className, event = props.event, accessors = props.accessors, rtl = props.rtl, selected = props.selected, label = props.label, continuesEarlier = props.continuesEarlier, continuesLater = props.continuesLater, getters = props.getters, onClick = props.onClick, onDoubleClick = props.onDoubleClick, _props$components = props.components, Event = _props$components.event, EventWrapper = _props$components.eventWrapper; var title = accessors.title(event); var tooltip = accessors.tooltip(event); var end = accessors.end(event); var start = accessors.start(event); var userProps = getters.eventProp(event, start, end, selected); var height = style.height, top = style.top, width = style.width, xOffset = style.xOffset; var inner = [React.createElement("div", { key: "1", className: "rbc-event-label" }, label), React.createElement("div", { key: "2", className: "rbc-event-content" }, Event ? React.createElement(Event, { event: event, title: title }) : title)]; return React.createElement(EventWrapper, _extends({ type: "time" }, props), React.createElement("div", { onClick: onClick, onDoubleClick: onDoubleClick, style: _extends({}, userProps.style, (_extends2 = { top: top + "%", height: height + "%" }, _extends2[rtl ? 'right' : 'left'] = Math.max(0, xOffset) + "%", _extends2.width = width + "%", _extends2)), title: tooltip ? (typeof label === 'string' ? label + ': ' : '') + tooltip : undefined, className: cn('rbc-event', className, userProps.className, { 'rbc-selected': selected, 'rbc-event-continues-earlier': continuesEarlier, 'rbc-event-continues-later': continuesLater }) }, inner)); } var DayColumn = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(DayColumn, _React$Component); function DayColumn() { 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.state = { selecting: false, timeIndicatorPosition: null }; _this.intervalTriggered = false; _this.renderEvents = function () { var _this$props = _this.props, events = _this$props.events, rtl = _this$props.rtl, selected = _this$props.selected, accessors = _this$props.accessors, localizer = _this$props.localizer, getters = _this$props.getters, components = _this$props.components, step = _this$props.step, timeslots = _this$props.timeslots; var _assertThisInitialize = _assertThisInitialized(_this), slotMetrics = _assertThisInitialize.slotMetrics; var messages = localizer.messages; var styledEvents = getStyledEvents({ events: events, accessors: accessors, slotMetrics: slotMetrics, minimumStartDifference: Math.ceil(step * timeslots / 2) }); return styledEvents.map(function (_ref, idx) { var event = _ref.event, style = _ref.style; var end = accessors.end(event); var start = accessors.start(event); var format = 'eventTimeRangeFormat'; var label; var startsBeforeDay = slotMetrics.startsBeforeDay(start); var startsAfterDay = slotMetrics.startsAfterDay(end); if (startsBeforeDay) format = 'eventTimeRangeEndFormat';else if (startsAfterDay) format = 'eventTimeRangeStartFormat'; if (startsBeforeDay && startsAfterDay) label = messages.allDay;else label = localizer.format({ start: start, end: end }, format); var continuesEarlier = startsBeforeDay || slotMetrics.startsBefore(start); var continuesLater = startsAfterDay || slotMetrics.startsAfter(end); return React.createElement(TimeGridEvent, { style: style, event: event, label: label, key: 'evt_' + idx, getters: getters, rtl: rtl, components: components, continuesEarlier: continuesEarlier, continuesLater: continuesLater, accessors: accessors, selected: isSelected(event, selected), onClick: function onClick(e) { return _this._select(event, e); }, onDoubleClick: function onDoubleClick(e) { return _this._doubleClick(event, e); } }); }); }; _this._selectable = function () { var node = findDOMNode(_assertThisInitialized(_this)); var selector = _this._selector = new Selection(function () { return findDOMNode(_assertThisInitialized(_this)); }, { longPressThreshold: _this.props.longPressThreshold }); var maybeSelect = function maybeSelect(box) { var onSelecting = _this.props.onSelecting; var current = _this.state || {}; var state = selectionState(box); var start = state.startDate, end = state.endDate; if (onSelecting) { if (eq(current.startDate, start, 'minutes') && eq(current.endDate, end, 'minutes') || onSelecting({ start: start, end: end }) === false) return; } if (_this.state.start !== state.start || _this.state.end !== state.end || _this.state.selecting !== state.selecting) { _this.setState(state); } }; var selectionState = function selectionState(point) { var currentSlot = _this.slotMetrics.closestSlotFromPoint(point, getBoundsForNode(node)); if (!_this.state.selecting) _this._initialSlot = currentSlot; var initialSlot = _this._initialSlot; if (initialSlot === currentSlot) currentSlot = _this.slotMetrics.nextSlot(initialSlot); var selectRange = _this.slotMetrics.getRange(min(initialSlot, currentSlot), max(initialSlot, currentSlot)); return _extends({}, selectRange, { selecting: true, top: selectRange.top + "%", height: selectRange.height + "%" }); }; var selectorClicksHandler = function selectorClicksHandler(box, actionType) { if (!isEvent(findDOMNode(_assertThisInitialized(_this)), box)) { var _selectionState = selectionState(box), startDate = _selectionState.startDate, endDate = _selectionState.endDate; _this._selectSlot({ startDate: startDate, endDate: endDate, action: actionType, box: box }); } _this.setState({ selecting: false }); }; selector.on('selecting', maybeSelect); selector.on('selectStart', maybeSelect); selector.on('beforeSelect', function (box) { if (_this.props.selectable !== 'ignoreEvents') return; return !isEvent(findDOMNode(_assertThisInitialized(_this)), box); }); selector.on('click', function (box) { return selectorClicksHandler(box, 'click'); }); selector.on('doubleClick', function (box) { return selectorClicksHandler(box, 'doubleClick'); }); selector.on('select', function (bounds) { if (_this.state.selecting) { _this._selectSlot(_extends({}, _this.state, { action: 'select', bounds: bounds })); _this.setState({ selecting: false }); } }); selector.on('reset', function () { if (_this.state.selecting) { _this.setState({ selecting: false }); } }); }; _this._teardownSelectable = function () { if (!_this._selector) return; _this._selector.teardown(); _this._selector = null; }; _this._selectSlot = function (_ref2) { var startDate = _ref2.startDate, endDate = _ref2.endDate, action = _ref2.action, bounds = _ref2.bounds, box = _ref2.box; var current = startDate, slots = []; while (lte(current, endDate)) { slots.push(current); current = add(current, _this.props.step, 'minutes'); } notify(_this.props.onSelectSlot, { slots: slots, start: startDate, end: endDate, resourceId: _this.props.resource, action: action, bounds: bounds, box: box }); }; _this._select = function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } notify(_this.props.onSelectEvent, args); }; _this._doubleClick = function () { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } notify(_this.props.onDoubleClickEvent, args); }; _this.slotMetrics = getSlotMetrics$1(_this.props); return _this; } var _proto = DayColumn.prototype; _proto.componentDidMount = function componentDidMount() { this.props.selectable && this._selectable(); if (this.props.isNow) { this.setTimeIndicatorPositionUpdateInterval(); } }; _proto.componentWillUnmount = function componentWillUnmount() { this._teardownSelectable(); this.clearTimeIndicatorInterval(); }; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (nextProps.selectable && !this.props.selectable) this._selectable(); if (!nextProps.selectable && this.props.selectable) this._teardownSelectable(); this.slotMetrics = this.slotMetrics.update(nextProps); }; _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) { var getNowChanged = !eq(prevProps.getNow(), this.props.getNow(), 'minutes'); if (prevProps.isNow !== this.props.isNow || getNowChanged) { this.clearTimeIndicatorInterval(); if (this.props.isNow) { var tail = !getNowChanged && eq(prevProps.date, this.props.date, 'minutes') && prevState.timeIndicatorPosition === this.state.timeIndicatorPosition; this.setTimeIndicatorPositionUpdateInterval(tail); } } else if (this.props.isNow && !eq(prevProps.min, this.props.min, 'minutes')) { this.positionTimeIndicator(); } }; /** * @param tail {Boolean} - whether `positionTimeIndicator` call should be * deferred or called upon setting interval (`true` - if deferred); */ _proto.setTimeIndicatorPositionUpdateInterval = function setTimeIndicatorPositionUpdateInterval(tail) { var _this2 = this; if (tail === void 0) { tail = false; } if (!this.intervalTriggered && !tail) { this.positionTimeIndicator(); } this._timeIndicatorTimeout = window.setTimeout(function () { _this2.intervalTriggered = true; _this2.positionTimeIndicator(); _this2.setTimeIndicatorPositionUpdateInterval(); }, 60000); }; _proto.clearTimeIndicatorInterval = function clearTimeIndicatorInterval() { this.intervalTriggered = false; window.clearTimeout(this._timeIndicatorTimeout); }; _proto.positionTimeIndicator = function positionTimeIndicator() { var _this$props2 = this.props, min = _this$props2.min, max = _this$props2.max, getNow = _this$props2.getNow; var current = getNow(); if (current >= min && current <= max) { var _this$slotMetrics$get = this.slotMetrics.getRange(current, current), top = _this$slotMetrics$get.top; this.setState({ timeIndicatorPosition: top }); } else { this.clearTimeIndicatorInterval(); } }; _proto.render = function render() { var _this$props3 = this.props, max = _this$props3.max, rtl = _this$props3.rtl, isNow = _this$props3.isNow, resource = _this$props3.resource, accessors = _this$props3.accessors, localizer = _this$props3.localizer, _this$props3$getters = _this$props3.getters, dayProp = _this$props3$getters.dayProp, getters = _objectWithoutPropertiesLoose(_this$props3$getters, ["dayProp"]), _this$props3$componen = _this$props3.components, EventContainer = _this$props3$componen.eventContainerWrapper, components = _objectWithoutPropertiesLoose(_this$props3$componen, ["eventContainerWrapper"]); var slotMetrics = this.slotMetrics; var _this$state = this.state, selecting = _this$state.selecting, top = _this$state.top, height = _this$state.height, startDate = _this$state.startDate, endDate = _this$state.endDate; var selectDates = { start: startDate, end: endDate }; var _dayProp = dayProp(max), className = _dayProp.className, style = _dayProp.style; return React.createElement("div", { style: style, className: cn(className, 'rbc-day-slot', 'rbc-time-column', isNow && 'rbc-now', isNow && 'rbc-today', // WHY selecting && 'rbc-slot-selecting') }, slotMetrics.groups.map(function (grp, idx) { return React.createElement(TimeSlotGroup, { key: idx, group: grp, resource: resource, getters: getters, components: components }); }), React.createElement(EventContainer, { localizer: localizer, resource: resource, accessors: accessors, getters: getters, components: components, slotMetrics: slotMetrics }, React.createElement("div", { className: cn('rbc-events-container', rtl && 'rtl') }, this.renderEvents())), selecting && React.createElement("div", { className: "rbc-slot-selection", style: { top: top, height: height } }, React.createElement("span", null, localizer.format(selectDates, 'selectRangeFormat'))), isNow && React.createElement("div", { className: "rbc-current-time-indicator", style: { top: this.state.timeIndicatorPosition + "%" } })); }; return DayColumn; }(React.Component); DayColumn.propTypes = process.env.NODE_ENV !== "production" ? { events: PropTypes.array.isRequired, step: PropTypes.number.isRequired, date: PropTypes.instanceOf(Date).isRequired, min: PropTypes.instanceOf(Date).isRequired, max: PropTypes.instanceOf(Date).isRequired, getNow: PropTypes.func.isRequired, isNow: PropTypes.bool, rtl: PropTypes.bool, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, showMultiDayTimes: PropTypes.bool, culture: PropTypes.string, timeslots: PropTypes.number, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), eventOffset: PropTypes.number, longPressThreshold: PropTypes.number, onSelecting: PropTypes.func, onSelectSlot: PropTypes.func.isRequired, onSelectEvent: PropTypes.func.isRequired, onDoubleClickEvent: PropTypes.func.isRequired, className: PropTypes.string, dragThroughEvents: PropTypes.bool, resource: PropTypes.any } : {}; DayColumn.defaultProps = { dragThroughEvents: true, timeslots: 2 }; var TimeGutter = /*#__PURE__*/ function (_Component) { _inheritsLoose(TimeGutter, _Component); function TimeGutter() { 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.renderSlot = function (value, idx) { if (idx !== 0) return null; var _this$props = _this.props, localizer = _this$props.localizer, getNow = _this$props.getNow; var isNow = _this.slotMetrics.dateIsInGroup(getNow(), idx); return React.createElement("span", { className: cn('rbc-label', isNow && 'rbc-now') }, localizer.format(value, 'timeGutterFormat')); }; var _this$props2 = _this.props, min = _this$props2.min, max = _this$props2.max, timeslots = _this$props2.timeslots, step = _this$props2.step; _this.slotMetrics = getSlotMetrics$1({ min: min, max: max, timeslots: timeslots, step: step }); return _this; } var _proto = TimeGutter.prototype; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var min = nextProps.min, max = nextProps.max, timeslots = nextProps.timeslots, step = nextProps.step; this.slotMetrics = this.slotMetrics.update({ min: min, max: max, timeslots: timeslots, step: step }); }; _proto.render = function render() { var _this2 = this; var _this$props3 = this.props, resource = _this$props3.resource, components = _this$props3.components; return React.createElement("div", { className: "rbc-time-gutter rbc-time-column" }, this.slotMetrics.groups.map(function (grp, idx) { return React.createElement(TimeSlotGroup, { key: idx, group: grp, resource: resource, components: components, renderSlot: _this2.renderSlot }); })); }; return TimeGutter; }(Component); TimeGutter.propTypes = process.env.NODE_ENV !== "production" ? { min: PropTypes.instanceOf(Date).isRequired, max: PropTypes.instanceOf(Date).isRequired, timeslots: PropTypes.number.isRequired, step: PropTypes.number.isRequired, getNow: PropTypes.func.isRequired, components: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, resource: PropTypes.string } : {}; var ResourceHeader = function ResourceHeader(_ref) { var label = _ref.label; return React.createElement(React.Fragment, null, label); }; ResourceHeader.propTypes = process.env.NODE_ENV !== "production" ? { label: PropTypes.node, index: PropTypes.number, resource: PropTypes.object } : {}; var TimeGridHeader = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(TimeGridHeader, _React$Component); function TimeGridHeader() { 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.handleHeaderClick = function (date, view, e) { e.preventDefault(); notify(_this.props.onDrillDown, [date, view]); }; _this.renderRow = function (resource) { var _this$props = _this.props, events = _this$props.events, rtl = _this$props.rtl, selectable = _this$props.selectable, getNow = _this$props.getNow, range = _this$props.range, getters = _this$props.getters, localizer = _this$props.localizer, accessors = _this$props.accessors, components = _this$props.components; var resourceId = accessors.resourceId(resource); var eventsToDisplay = resource ? events.filter(function (event) { return accessors.resource(event) === resourceId; }) : events; return React.createElement(DateContentRow, { isAllDay: true, rtl: rtl, getNow: getNow, minRows: 2, range: range, events: eventsToDisplay, resourceId: resourceId, className: "rbc-allday-cell", selectable: selectable, selected: _this.props.selected, components: components, accessors: accessors, getters: getters, localizer: localizer, onSelect: _this.props.onSelectEvent, onDoubleClick: _this.props.onDoubleClickEvent, onSelectSlot: _this.props.onSelectSlot, longPressThreshold: _this.props.longPressThreshold }); }; return _this; } var _proto = TimeGridHeader.prototype; _proto.renderHeaderCells = function renderHeaderCells(range) { var _this2 = this; var _this$props2 = this.props, localizer = _this$props2.localizer, getDrilldownView = _this$props2.getDrilldownView, getNow = _this$props2.getNow, dayProp = _this$props2.getters.dayProp, _this$props2$componen = _this$props2.components.header, HeaderComponent = _this$props2$componen === void 0 ? Header : _this$props2$componen; var today = getNow(); return range.map(function (date, i) { var drilldownView = getDrilldownView(date); var label = localizer.format(date, 'dayFormat'); var _dayProp = dayProp(date), className = _dayProp.className, style = _dayProp.style; var header = React.createElement(HeaderComponent, { date: date, label: label, localizer: localizer }); return React.createElement("div", { key: i, style: style, className: cn('rbc-header', className, eq(date, today, 'day') && 'rbc-today') }, drilldownView ? React.createElement("a", { href: "#", onClick: function onClick(e) { return _this2.handleHeaderClick(date, drilldownView, e); } }, header) : React.createElement("span", null, header)); }); }; _proto.render = function render() { var _this3 = this; var _this$props3 = this.props, width = _this$props3.width, rtl = _this$props3.rtl, resources = _this$props3.resources, range = _this$props3.range, events = _this$props3.events, getNow = _this$props3.getNow, accessors = _this$props3.accessors, selectable = _this$props3.selectable, components = _this$props3.components, getters = _this$props3.getters, scrollRef = _this$props3.scrollRef, localizer = _this$props3.localizer, isOverflowing = _this$props3.isOverflowing, _this$props3$componen = _this$props3.components, TimeGutterHeader = _this$props3$componen.timeGutterHeader, _this$props3$componen2 = _this$props3$componen.resourceHeader, ResourceHeaderComponent = _this$props3$componen2 === void 0 ? ResourceHeader : _this$props3$componen2; var style = {}; if (isOverflowing) { style[rtl ? 'marginLeft' : 'marginRight'] = scrollbarSize() + "px"; } var groupedEvents = resources.groupEvents(events); return React.createElement("div", { style: style, ref: scrollRef, className: cn('rbc-time-header', isOverflowing && 'rbc-overflowing') }, React.createElement("div", { className: "rbc-label rbc-time-header-gutter", style: { width: width, minWidth: width, maxWidth: width } }, TimeGutterHeader && React.createElement(TimeGutterHeader, null)), resources.map(function (_ref, idx) { var id = _ref[0], resource = _ref[1]; return React.createElement("div", { className: "rbc-time-header-content", key: id || idx }, resource && React.createElement("div", { className: "rbc-row rbc-row-resource", key: "resource_" + idx }, React.createElement("div", { className: "rbc-header" }, React.createElement(ResourceHeaderComponent, { index: idx, label: accessors.resourceTitle(resource), resource: resource }))), React.createElement("div", { className: "rbc-row rbc-time-header-cell" + (range.length <= 1 ? ' rbc-time-header-cell-single-day' : '') }, _this3.renderHeaderCells(range)), React.createElement(DateContentRow, { isAllDay: true, rtl: rtl, getNow: getNow, minRows: 2, range: range, events: groupedEvents.get(id) || [], resourceId: resource && id, className: "rbc-allday-cell", selectable: selectable, selected: _this3.props.selected, components: components, accessors: accessors, getters: getters, localizer: localizer, onSelect: _this3.props.onSelectEvent, onDoubleClick: _this3.props.onDoubleClickEvent, onSelectSlot: _this3.props.onSelectSlot, longPressThreshold: _this3.props.longPressThreshold })); })); }; return TimeGridHeader; }(React.Component); TimeGridHeader.propTypes = process.env.NODE_ENV !== "production" ? { range: PropTypes.array.isRequired, events: PropTypes.array.isRequired, resources: PropTypes.object, getNow: PropTypes.func.isRequired, isOverflowing: PropTypes.bool, rtl: PropTypes.bool, width: PropTypes.number, localizer: PropTypes.object.isRequired, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), longPressThreshold: PropTypes.number, onSelectSlot: PropTypes.func, onSelectEvent: PropTypes.func, onDoubleClickEvent: PropTypes.func, onDrillDown: PropTypes.func, getDrilldownView: PropTypes.func.isRequired, scrollRef: PropTypes.any } : {}; var NONE = {}; function Resources(resources, accessors) { return { map: function map(fn) { if (!resources) return [fn([NONE, null], 0)]; return resources.map(function (resource, idx) { return fn([accessors.resourceId(resource), resource], idx); }); }, groupEvents: function groupEvents(events) { var eventsByResource = new Map(); if (!resources) { // Return all events if resources are not provided eventsByResource.set(NONE, events); return eventsByResource; } events.forEach(function (event) { var id = accessors.resource(event) || NONE; var resourceEvents = eventsByResource.get(id) || []; resourceEvents.push(event); eventsByResource.set(id, resourceEvents); }); return eventsByResource; } }; } var TimeGrid = /*#__PURE__*/ function (_Component) { _inheritsLoose(TimeGrid, _Component); function TimeGrid(props) { var _this; _this = _Component.call(this, props) || this; _this.handleScroll = function (e) { if (_this.scrollRef.current) { _this.scrollRef.current.scrollLeft = e.target.scrollLeft; } }; _this.handleResize = function () { raf.cancel(_this.rafHandle); _this.rafHandle = raf(_this.checkOverflow); }; _this.gutterRef = function (ref) { _this.gutter = ref && findDOMNode(ref); }; _this.handleSelectAlldayEvent = function () { //cancel any pending selections so only the event click goes through. _this.clearSelection(); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } notify(_this.props.onSelectEvent, args); }; _this.handleSelectAllDaySlot = function (slots, slotInfo) { var onSelectSlot = _this.props.onSelectSlot; notify(onSelectSlot, { slots: slots, start: slots[0], end: slots[slots.length - 1], action: slotInfo.action }); }; _this.checkOverflow = function () { if (_this._updatingOverflow) return; var content = _this.contentRef.current; var isOverflowing = content.scrollHeight > content.clientHeight; if (_this.state.isOverflowing !== isOverflowing) { _this._updatingOverflow = true; _this.setState({ isOverflowing: isOverflowing }, function () { _this._updatingOverflow = false; }); } }; _this.memoizedResources = memoize(function (resources, accessors) { return Resources(resources, accessors); }); _this.state = { gutterWidth: undefined, isOverflowing: null }; _this.scrollRef = React.createRef(); _this.contentRef = React.createRef(); return _this; } var _proto = TimeGrid.prototype; _proto.componentWillMount = function componentWillMount() { this.calculateScroll(); }; _proto.componentDidMount = function componentDidMount() { this.checkOverflow(); if (this.props.width == null) { this.measureGutter(); } this.applyScroll(); window.addEventListener('resize', this.handleResize); }; _proto.componentWillUnmount = function componentWillUnmount() { window.removeEventListener('resize', this.handleResize); raf.cancel(this.rafHandle); if (this.measureGutterAnimationFrameRequest) { window.cancelAnimationFrame(this.measureGutterAnimationFrameRequest); } }; _proto.componentDidUpdate = function componentDidUpdate() { if (this.props.width == null) { this.measureGutter(); } this.applyScroll(); //this.checkOverflow() }; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { var _this$props = this.props, range = _this$props.range, scrollToTime = _this$props.scrollToTime; // When paginating, reset scroll if (!eq(nextProps.range[0], range[0], 'minute') || !eq(nextProps.scrollToTime, scrollToTime, 'minute')) { this.calculateScroll(nextProps); } }; _proto.renderEvents = function renderEvents(range, events, now) { var _this2 = this; var _this$props2 = this.props, min = _this$props2.min, max = _this$props2.max, components = _this$props2.components, accessors = _this$props2.accessors, localizer = _this$props2.localizer; var resources = this.memoizedResources(this.props.resources, accessors); var groupedEvents = resources.groupEvents(events); return resources.map(function (_ref, i) { var id = _ref[0], resource = _ref[1]; return range.map(function (date, jj) { var daysEvents = (groupedEvents.get(id) || []).filter(function (event) { return inRange$1(date, accessors.start(event), accessors.end(event), 'day'); }); return React.createElement(DayColumn, _extends({}, _this2.props, { localizer: localizer, min: merge(date, min), max: merge(date, max), resource: resource && id, components: components, isNow: eq(date, now, 'day'), key: i + '-' + jj, date: date, events: daysEvents })); }); }); }; _proto.render = function render() { var _this$props3 = this.props, events = _this$props3.events, range = _this$props3.range, width = _this$props3.width, rtl = _this$props3.rtl, selected = _this$props3.selected, getNow = _this$props3.getNow, resources = _this$props3.resources, components = _this$props3.components, accessors = _this$props3.accessors, getters = _this$props3.getters, localizer = _this$props3.localizer, min = _this$props3.min, max = _this$props3.max, showMultiDayTimes = _this$props3.showMultiDayTimes, longPressThreshold = _this$props3.longPressThreshold; width = width || this.state.gutterWidth; var start = range[0], end = range[range.length - 1]; this.slots = range.length; var allDayEvents = [], rangeEvents = []; events.forEach(function (event) { if (inRange(event, start, end, accessors)) { var eStart = accessors.start(event), eEnd = accessors.end(event); if (accessors.allDay(event) || isJustDate(eStart) && isJustDate(eEnd) || !showMultiDayTimes && !eq(eStart, eEnd, 'day')) { allDayEvents.push(event); } else { rangeEvents.push(event); } } }); allDayEvents.sort(function (a, b) { return sortEvents(a, b, accessors); }); return React.createElement("div", { className: cn('rbc-time-view', resources && 'rbc-time-view-resources') }, React.createElement(TimeGridHeader, { range: range, events: allDayEvents, width: width, rtl: rtl, getNow: getNow, localizer: localizer, selected: selected, resources: this.memoizedResources(resources, accessors), selectable: this.props.selectable, accessors: accessors, getters: getters, components: components, scrollRef: this.scrollRef, isOverflowing: this.state.isOverflowing, longPressThreshold: longPressThreshold, onSelectSlot: this.handleSelectAllDaySlot, onSelectEvent: this.handleSelectAlldayEvent, onDoubleClickEvent: this.props.onDoubleClickEvent, onDrillDown: this.props.onDrillDown, getDrilldownView: this.props.getDrilldownView }), React.createElement("div", { ref: this.contentRef, className: "rbc-time-content", onScroll: this.handleScroll }, React.createElement(TimeGutter, { date: start, ref: this.gutterRef, localizer: localizer, min: merge(start, min), max: merge(start, max), step: this.props.step, getNow: this.props.getNow, timeslots: this.props.timeslots, components: components, className: "rbc-time-gutter" }), this.renderEvents(range, rangeEvents, getNow()))); }; _proto.clearSelection = function clearSelection() { clearTimeout(this._selectTimer); this._pendingSelection = []; }; _proto.measureGutter = function measureGutter() { var _this3 = this; if (this.measureGutterAnimationFrameRequest) { window.cancelAnimationFrame(this.measureGutterAnimationFrameRequest); } this.measureGutterAnimationFrameRequest = window.requestAnimationFrame(function () { var width = getWidth(_this3.gutter); if (width && _this3.state.gutterWidth !== width) { _this3.setState({ gutterWidth: width }); } }); }; _proto.applyScroll = function applyScroll() { if (this._scrollRatio) { var content = this.contentRef.current; content.scrollTop = content.scrollHeight * this._scrollRatio; // Only do this once this._scrollRatio = null; } }; _proto.calculateScroll = function calculateScroll(props) { if (props === void 0) { props = this.props; } var _props = props, min = _props.min, max = _props.max, scrollToTime = _props.scrollToTime; var diffMillis = scrollToTime - startOf(scrollToTime, 'day'); var totalMillis = diff(max, min); this._scrollRatio = diffMillis / totalMillis; }; return TimeGrid; }(Component); TimeGrid.propTypes = process.env.NODE_ENV !== "production" ? { events: PropTypes.array.isRequired, resources: PropTypes.array, step: PropTypes.number, timeslots: PropTypes.number, range: PropTypes.arrayOf(PropTypes.instanceOf(Date)), min: PropTypes.instanceOf(Date), max: PropTypes.instanceOf(Date), getNow: PropTypes.func.isRequired, scrollToTime: PropTypes.instanceOf(Date), showMultiDayTimes: PropTypes.bool, rtl: PropTypes.bool, width: PropTypes.number, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired, selected: PropTypes.object, selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), longPressThreshold: PropTypes.number, onNavigate: PropTypes.func, onSelectSlot: PropTypes.func, onSelectEnd: PropTypes.func, onSelectStart: PropTypes.func, onSelectEvent: PropTypes.func, onDoubleClickEvent: PropTypes.func, onDrillDown: PropTypes.func, getDrilldownView: PropTypes.func.isRequired } : {}; TimeGrid.defaultProps = { step: 30, timeslots: 2, min: startOf(new Date(), 'day'), max: endOf(new Date(), 'day'), scrollToTime: startOf(new Date(), 'day') }; var Day = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Day, _React$Component); function Day() { return _React$Component.apply(this, arguments) || this; } var _proto = Day.prototype; _proto.render = function render() { var _this$props = this.props, date = _this$props.date, props = _objectWithoutPropertiesLoose(_this$props, ["date"]); var range = Day.range(date); return React.createElement(TimeGrid, _extends({}, props, { range: range, eventOffset: 10 })); }; return Day; }(React.Component); Day.propTypes = process.env.NODE_ENV !== "production" ? { date: PropTypes.instanceOf(Date).isRequired } : {}; Day.range = function (date) { return [startOf(date, 'day')]; }; Day.navigate = function (date, action) { switch (action) { case navigate.PREVIOUS: return add(date, -1, 'day'); case navigate.NEXT: return add(date, 1, 'day'); default: return date; } }; Day.title = function (date, _ref) { var localizer = _ref.localizer; return localizer.format(date, 'dayHeaderFormat'); }; var Week = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Week, _React$Component); function Week() { return _React$Component.apply(this, arguments) || this; } var _proto = Week.prototype; _proto.render = function render() { var _this$props = this.props, date = _this$props.date, props = _objectWithoutPropertiesLoose(_this$props, ["date"]); var range = Week.range(date, this.props); return React.createElement(TimeGrid, _extends({}, props, { range: range, eventOffset: 15 })); }; return Week; }(React.Component); Week.propTypes = process.env.NODE_ENV !== "production" ? { date: PropTypes.instanceOf(Date).isRequired } : {}; Week.defaultProps = TimeGrid.defaultProps; Week.navigate = function (date, action) { switch (action) { case navigate.PREVIOUS: return add(date, -1, 'week'); case navigate.NEXT: return add(date, 1, 'week'); default: return date; } }; Week.range = function (date, _ref) { var localizer = _ref.localizer; var firstOfWeek = localizer.startOfWeek(); var start = startOf(date, 'week', firstOfWeek); var end = endOf(date, 'week', firstOfWeek); return range(start, end); }; Week.title = function (date, _ref2) { var localizer = _ref2.localizer; var _Week$range = Week.range(date, { localizer: localizer }), start = _Week$range[0], rest = _Week$range.slice(1); return localizer.format({ start: start, end: rest.pop() }, 'dayRangeHeaderFormat'); }; function workWeekRange(date, options) { return Week.range(date, options).filter(function (d) { return [6, 0].indexOf(d.getDay()) === -1; }); } var WorkWeek = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(WorkWeek, _React$Component); function WorkWeek() { return _React$Component.apply(this, arguments) || this; } var _proto = WorkWeek.prototype; _proto.render = function render() { var _this$props = this.props, date = _this$props.date, props = _objectWithoutPropertiesLoose(_this$props, ["date"]); var range = workWeekRange(date, this.props); return React.createElement(TimeGrid, _extends({}, props, { range: range, eventOffset: 15 })); }; return WorkWeek; }(React.Component); WorkWeek.propTypes = process.env.NODE_ENV !== "production" ? { date: PropTypes.instanceOf(Date).isRequired } : {}; WorkWeek.defaultProps = TimeGrid.defaultProps; WorkWeek.range = workWeekRange; WorkWeek.navigate = Week.navigate; WorkWeek.title = function (date, _ref) { var localizer = _ref.localizer; var _workWeekRange = workWeekRange(date, { localizer: localizer }), start = _workWeekRange[0], rest = _workWeekRange.slice(1); return localizer.format({ start: start, end: rest.pop() }, 'dayRangeHeaderFormat'); }; var Agenda = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Agenda, _React$Component); function Agenda(props) { var _this; _this = _React$Component.call(this, props) || this; _this.renderDay = function (day, events, dayKey) { var _this$props = _this.props, selected = _this$props.selected, getters = _this$props.getters, accessors = _this$props.accessors, localizer = _this$props.localizer, _this$props$component = _this$props.components, Event = _this$props$component.event, AgendaDate = _this$props$component.date; events = events.filter(function (e) { return inRange(e, startOf(day, 'day'), endOf(day, 'day'), accessors); }); return events.map(function (event, idx) { var title = accessors.title(event); var end = accessors.end(event); var start = accessors.start(event); var userProps = getters.eventProp(event, start, end, isSelected(event, selected)); var dateLabel = idx === 0 && localizer.format(day, 'agendaDateFormat'); var first = idx === 0 ? React.createElement("td", { rowSpan: events.length, className: "rbc-agenda-date-cell" }, AgendaDate ? React.createElement(AgendaDate, { day: day, label: dateLabel }) : dateLabel) : false; return React.createElement("tr", { key: dayKey + '_' + idx, className: userProps.className, style: userProps.style }, first, React.createElement("td", { className: "rbc-agenda-time-cell" }, _this.timeRangeLabel(day, event)), React.createElement("td", { className: "rbc-agenda-event-cell" }, Event ? React.createElement(Event, { event: event, title: title }) : title)); }, []); }; _this.timeRangeLabel = function (day, event) { var _this$props2 = _this.props, accessors = _this$props2.accessors, localizer = _this$props2.localizer, components = _this$props2.components; var labelClass = '', TimeComponent = components.time, label = localizer.messages.allDay; var end = accessors.end(event); var start = accessors.start(event); if (!accessors.allDay(event)) { if (eq(start, end)) { label = localizer.format(start, 'agendaTimeFormat'); } else if (eq(start, end, 'day')) { label = localizer.format({ start: start, end: end }, 'agendaTimeRangeFormat'); } else if (eq(day, start, 'day')) { label = localizer.format(start, 'agendaTimeFormat'); } else if (eq(day, end, 'day')) { label = localizer.format(end, 'agendaTimeFormat'); } } if (gt(day, start, 'day')) labelClass = 'rbc-continues-prior'; if (lt(day, end, 'day')) labelClass += ' rbc-continues-after'; return React.createElement("span", { className: labelClass.trim() }, TimeComponent ? React.createElement(TimeComponent, { event: event, day: day, label: label }) : label); }; _this._adjustHeader = function () { if (!_this.tbodyRef.current) return; var header = _this.headerRef.current; var firstRow = _this.tbodyRef.current.firstChild; if (!firstRow) return; var isOverflowing = _this.contentRef.current.scrollHeight > _this.contentRef.current.clientHeight; var widths = _this._widths || []; _this._widths = [getWidth(firstRow.children[0]), getWidth(firstRow.children[1])]; if (widths[0] !== _this._widths[0] || widths[1] !== _this._widths[1]) { _this.dateColRef.current.style.width = _this._widths[0] + 'px'; _this.timeColRef.current.style.width = _this._widths[1] + 'px'; } if (isOverflowing) { classes.addClass(header, 'rbc-header-overflowing'); header.style.marginRight = scrollbarSize() + 'px'; } else { classes.removeClass(header, 'rbc-header-overflowing'); } }; _this.headerRef = React.createRef(); _this.dateColRef = React.createRef(); _this.timeColRef = React.createRef(); _this.contentRef = React.createRef(); _this.tbodyRef = React.createRef(); return _this; } var _proto = Agenda.prototype; _proto.componentDidMount = function componentDidMount() { this._adjustHeader(); }; _proto.componentDidUpdate = function componentDidUpdate() { this._adjustHeader(); }; _proto.render = function render() { var _this2 = this; var _this$props3 = this.props, length = _this$props3.length, date = _this$props3.date, events = _this$props3.events, accessors = _this$props3.accessors, localizer = _this$props3.localizer; var messages = localizer.messages; var end = add(date, length, 'day'); var range$1 = range(date, end, 'day'); events = events.filter(function (event) { return inRange(event, date, end, accessors); }); events.sort(function (a, b) { return +accessors.start(a) - +accessors.start(b); }); return React.createElement("div", { className: "rbc-agenda-view" }, events.length !== 0 ? React.createElement(React.Fragment, null, React.createElement("table", { ref: this.headerRef, className: "rbc-agenda-table" }, React.createElement("thead", null, React.createElement("tr", null, React.createElement("th", { className: "rbc-header", ref: this.dateColRef }, messages.date), React.createElement("th", { className: "rbc-header", ref: this.timeColRef }, messages.time), React.createElement("th", { className: "rbc-header" }, messages.event)))), React.createElement("div", { className: "rbc-agenda-content", ref: this.contentRef }, React.createElement("table", { className: "rbc-agenda-table" }, React.createElement("tbody", { ref: this.tbodyRef }, range$1.map(function (day, idx) { return _this2.renderDay(day, events, idx); }))))) : React.createElement("span", { className: "rbc-agenda-empty" }, messages.noEventsInRange)); }; return Agenda; }(React.Component); Agenda.propTypes = process.env.NODE_ENV !== "production" ? { events: PropTypes.array, date: PropTypes.instanceOf(Date), length: PropTypes.number.isRequired, selected: PropTypes.object, accessors: PropTypes.object.isRequired, components: PropTypes.object.isRequired, getters: PropTypes.object.isRequired, localizer: PropTypes.object.isRequired } : {}; Agenda.defaultProps = { length: 30 }; Agenda.range = function (start, _ref) { var _ref$length = _ref.length, length = _ref$length === void 0 ? Agenda.defaultProps.length : _ref$length; var end = add(start, length, 'day'); return { start: start, end: end }; }; Agenda.navigate = function (date, action, _ref2) { var _ref2$length = _ref2.length, length = _ref2$length === void 0 ? Agenda.defaultProps.length : _ref2$length; switch (action) { case navigate.PREVIOUS: return add(date, -length, 'day'); case navigate.NEXT: return add(date, length, 'day'); default: return date; } }; Agenda.title = function (start, _ref3) { var _ref3$length = _ref3.length, length = _ref3$length === void 0 ? Agenda.defaultProps.length : _ref3$length, localizer = _ref3.localizer; var end = add(start, length, 'day'); return localizer.format({ start: start, end: end }, 'agendaHeaderFormat'); }; var _VIEWS; var VIEWS = (_VIEWS = {}, _VIEWS[views.MONTH] = MonthView, _VIEWS[views.WEEK] = Week, _VIEWS[views.WORK_WEEK] = WorkWeek, _VIEWS[views.DAY] = Day, _VIEWS[views.AGENDA] = Agenda, _VIEWS); function moveDate(View, _ref) { var action = _ref.action, date = _ref.date, today = _ref.today, props = _objectWithoutPropertiesLoose(_ref, ["action", "date", "today"]); View = typeof View === 'string' ? VIEWS[View] : View; switch (action) { case navigate.TODAY: date = today || new Date(); break; case navigate.DATE: break; default: !(View && typeof View.navigate === 'function') ? process.env.NODE_ENV !== "production" ? invariant(false, 'Calendar View components must implement a static `.navigate(date, action)` method.s') : invariant(false) : void 0; date = View.navigate(date, action, props); } return date; } var Toolbar = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Toolbar, _React$Component); function Toolbar() { 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.navigate = function (action) { _this.props.onNavigate(action); }; _this.view = function (view) { _this.props.onView(view); }; return _this; } var _proto = Toolbar.prototype; _proto.render = function render() { var _this$props = this.props, messages = _this$props.localizer.messages, label = _this$props.label; return React.createElement("div", { className: "rbc-toolbar" }, React.createElement("span", { className: "rbc-btn-group" }, React.createElement("button", { type: "button", onClick: this.navigate.bind(null, navigate.TODAY) }, messages.today), React.createElement("button", { type: "button", onClick: this.navigate.bind(null, navigate.PREVIOUS) }, messages.previous), React.createElement("button", { type: "button", onClick: this.navigate.bind(null, navigate.NEXT) }, messages.next)), React.createElement("span", { className: "rbc-toolbar-label" }, label), React.createElement("span", { className: "rbc-btn-group" }, this.viewNamesGroup(messages))); }; _proto.viewNamesGroup = function viewNamesGroup(messages) { var _this2 = this; var viewNames = this.props.views; var view = this.props.view; if (viewNames.length > 1) { return viewNames.map(function (name) { return React.createElement("button", { type: "button", key: name, className: cn({ 'rbc-active': view === name }), onClick: _this2.view.bind(null, name) }, messages[name]); }); } }; return Toolbar; }(React.Component); Toolbar.propTypes = process.env.NODE_ENV !== "production" ? { view: PropTypes.string.isRequired, views: PropTypes.arrayOf(PropTypes.string).isRequired, label: PropTypes.node.isRequired, localizer: PropTypes.object, onNavigate: PropTypes.func.isRequired, onView: PropTypes.func.isRequired } : {}; /** * Retrieve via an accessor-like property * * accessor(obj, 'name') // => retrieves obj['name'] * accessor(data, func) // => retrieves func(data) * ... otherwise null */ function accessor$1(data, field) { var value = null; if (typeof field === 'function') value = field(data);else if (typeof field === 'string' && typeof data === 'object' && data != null && field in data) value = data[field]; return value; } var wrapAccessor = function wrapAccessor(acc) { return function (data) { return accessor$1(data, acc); }; }; function viewNames$1(_views) { return !Array.isArray(_views) ? Object.keys(_views) : _views; } function isValidView(view, _ref) { var _views = _ref.views; var names = viewNames$1(_views); return names.indexOf(view) !== -1; } /** * react-big-calendar is a full featured Calendar component for managing events and dates. It uses * modern `flexbox` for layout, making it super responsive and performant. Leaving most of the layout heavy lifting * to the browser. __note:__ The default styles use `height: 100%` which means your container must set an explicit * height (feel free to adjust the styles to suit your specific needs). * * Big Calendar is unopiniated about editing and moving events, preferring to let you implement it in a way that makes * the most sense to your app. It also tries not to be prescriptive about your event data structures, just tell it * how to find the start and end datetimes and you can pass it whatever you want. * * One thing to note is that, `react-big-calendar` treats event start/end dates as an _exclusive_ range. * which means that the event spans up to, but not including, the end date. In the case * of displaying events on whole days, end dates are rounded _up_ to the next day. So an * event ending on `Apr 8th 12:00:00 am` will not appear on the 8th, whereas one ending * on `Apr 8th 12:01:00 am` will. If you want _inclusive_ ranges consider providing a * function `endAccessor` that returns the end date + 1 day for those events that end at midnight. */ var Calendar = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Calendar, _React$Component); function Calendar() { 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.getViews = function () { var views = _this.props.views; if (Array.isArray(views)) { return transform(views, function (obj, name) { return obj[name] = VIEWS[name]; }, {}); } if (typeof views === 'object') { return mapValues(views, function (value, key) { if (value === true) { return VIEWS[key]; } return value; }); } return VIEWS; }; _this.getView = function () { var views = _this.getViews(); return views[_this.props.view]; }; _this.getDrilldownView = function (date) { var _this$props = _this.props, view = _this$props.view, drilldownView = _this$props.drilldownView, getDrilldownView = _this$props.getDrilldownView; if (!getDrilldownView) return drilldownView; return getDrilldownView(date, view, Object.keys(_this.getViews())); }; _this.handleRangeChange = function (date, viewComponent, view) { var _this$props2 = _this.props, onRangeChange = _this$props2.onRangeChange, localizer = _this$props2.localizer; if (onRangeChange) { if (viewComponent.range) { onRangeChange(viewComponent.range(date, { localizer: localizer }), view); } else { process.env.NODE_ENV !== "production" ? warning(true, 'onRangeChange prop not supported for this view') : void 0; } } }; _this.handleNavigate = function (action, newDate) { var _this$props3 = _this.props, view = _this$props3.view, date = _this$props3.date, getNow = _this$props3.getNow, onNavigate = _this$props3.onNavigate, props = _objectWithoutPropertiesLoose(_this$props3, ["view", "date", "getNow", "onNavigate"]); var ViewComponent = _this.getView(); var today = getNow(); date = moveDate(ViewComponent, _extends({}, props, { action: action, date: newDate || date || today, today: today })); onNavigate(date, view, action); _this.handleRangeChange(date, ViewComponent); }; _this.handleViewChange = function (view) { if (view !== _this.props.view && isValidView(view, _this.props)) { _this.props.onView(view); } var views = _this.getViews(); _this.handleRangeChange(_this.props.date || _this.props.getNow(), views[view], view); }; _this.handleSelectEvent = function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } notify(_this.props.onSelectEvent, args); }; _this.handleDoubleClickEvent = function () { for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } notify(_this.props.onDoubleClickEvent, args); }; _this.handleSelectSlot = function (slotInfo) { notify(_this.props.onSelectSlot, slotInfo); }; _this.handleDrillDown = function (date, view) { var onDrillDown = _this.props.onDrillDown; if (onDrillDown) { onDrillDown(date, view, _this.drilldownView); return; } if (view) _this.handleViewChange(view); _this.handleNavigate(navigate.DATE, date); }; _this.state = { context: _this.getContext(_this.props) }; return _this; } var _proto = Calendar.prototype; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { this.setState({ context: this.getContext(nextProps) }); }; _proto.getContext = function getContext(_ref2) { var startAccessor = _ref2.startAccessor, endAccessor = _ref2.endAccessor, allDayAccessor = _ref2.allDayAccessor, tooltipAccessor = _ref2.tooltipAccessor, titleAccessor = _ref2.titleAccessor, resourceAccessor = _ref2.resourceAccessor, resourceIdAccessor = _ref2.resourceIdAccessor, resourceTitleAccessor = _ref2.resourceTitleAccessor, eventPropGetter = _ref2.eventPropGetter, slotPropGetter = _ref2.slotPropGetter, dayPropGetter = _ref2.dayPropGetter, view = _ref2.view, views = _ref2.views, localizer = _ref2.localizer, culture = _ref2.culture, _ref2$messages = _ref2.messages, messages$1 = _ref2$messages === void 0 ? {} : _ref2$messages, _ref2$components = _ref2.components, components = _ref2$components === void 0 ? {} : _ref2$components, _ref2$formats = _ref2.formats, formats = _ref2$formats === void 0 ? {} : _ref2$formats; var names = viewNames$1(views); var msgs = messages(messages$1); return { viewNames: names, localizer: mergeWithDefaults(localizer, culture, formats, msgs), getters: { eventProp: function eventProp() { return eventPropGetter && eventPropGetter.apply(void 0, arguments) || {}; }, slotProp: function slotProp() { return slotPropGetter && slotPropGetter.apply(void 0, arguments) || {}; }, dayProp: function dayProp() { return dayPropGetter && dayPropGetter.apply(void 0, arguments) || {}; } }, components: defaults(components[view] || {}, omit(components, names), { eventWrapper: NoopWrapper, eventContainerWrapper: NoopWrapper, dateCellWrapper: NoopWrapper, weekWrapper: NoopWrapper, timeSlotWrapper: NoopWrapper }), accessors: { start: wrapAccessor(startAccessor), end: wrapAccessor(endAccessor), allDay: wrapAccessor(allDayAccessor), tooltip: wrapAccessor(tooltipAccessor), title: wrapAccessor(titleAccessor), resource: wrapAccessor(resourceAccessor), resourceId: wrapAccessor(resourceIdAccessor), resourceTitle: wrapAccessor(resourceTitleAccessor) } }; }; _proto.render = function render() { var _this$props4 = this.props, view = _this$props4.view, toolbar = _this$props4.toolbar, events = _this$props4.events, style = _this$props4.style, className = _this$props4.className, elementProps = _this$props4.elementProps, current = _this$props4.date, getNow = _this$props4.getNow, length = _this$props4.length, showMultiDayTimes = _this$props4.showMultiDayTimes, onShowMore = _this$props4.onShowMore, _0 = _this$props4.components, _1 = _this$props4.formats, _2 = _this$props4.messages, _3 = _this$props4.culture, props = _objectWithoutPropertiesLoose(_this$props4, ["view", "toolbar", "events", "style", "className", "elementProps", "date", "getNow", "length", "showMultiDayTimes", "onShowMore", "components", "formats", "messages", "culture"]); current = current || getNow(); var View = this.getView(); var _this$state$context = this.state.context, accessors = _this$state$context.accessors, components = _this$state$context.components, getters = _this$state$context.getters, localizer = _this$state$context.localizer, viewNames = _this$state$context.viewNames; var CalToolbar = components.toolbar || Toolbar; var label = View.title(current, { localizer: localizer, length: length }); return React.createElement("div", _extends({}, elementProps, { className: cn(className, 'rbc-calendar', props.rtl && 'rbc-rtl'), style: style }), toolbar && React.createElement(CalToolbar, { date: current, view: view, views: viewNames, label: label, onView: this.handleViewChange, onNavigate: this.handleNavigate, localizer: localizer }), React.createElement(View, _extends({}, props, { events: events, date: current, getNow: getNow, length: length, localizer: localizer, getters: getters, components: components, accessors: accessors, showMultiDayTimes: showMultiDayTimes, getDrilldownView: this.getDrilldownView, onNavigate: this.handleNavigate, onDrillDown: this.handleDrillDown, onSelectEvent: this.handleSelectEvent, onDoubleClickEvent: this.handleDoubleClickEvent, onSelectSlot: this.handleSelectSlot, onShowMore: onShowMore }))); } /** * * @param date * @param viewComponent * @param {'month'|'week'|'work_week'|'day'|'agenda'} [view] - optional * parameter. It appears when range change on view changing. It could be handy * when you need to have both: range and view type at once, i.e. for manage rbc * state via url */ ; return Calendar; }(React.Component); Calendar.defaultProps = { elementProps: {}, popup: false, toolbar: true, view: views.MONTH, views: [views.MONTH, views.WEEK, views.DAY, views.AGENDA], step: 30, length: 30, drilldownView: views.DAY, titleAccessor: 'title', tooltipAccessor: 'title', allDayAccessor: 'allDay', startAccessor: 'start', endAccessor: 'end', resourceAccessor: 'resourceId', resourceIdAccessor: 'id', resourceTitleAccessor: 'title', longPressThreshold: 250, getNow: function getNow() { return new Date(); } }; Calendar.propTypes = process.env.NODE_ENV !== "production" ? { localizer: PropTypes.object.isRequired, /** * Props passed to main calendar `<div>`. * */ elementProps: PropTypes.object, /** * The current date value of the calendar. Determines the visible view range. * If `date` is omitted then the result of `getNow` is used; otherwise the * current date is used. * * @controllable onNavigate */ date: PropTypes.instanceOf(Date), /** * The current view of the calendar. * * @default 'month' * @controllable onView */ view: PropTypes.string, /** * The initial view set for the Calendar. * @type Calendar.Views ('month'|'week'|'work_week'|'day'|'agenda') * @default 'month' */ defaultView: PropTypes.string, /** * An array of event objects to display on the calendar. Events objects * can be any shape, as long as the Calendar knows how to retrieve the * following details of the event: * * - start time * - end time * - title * - whether its an "all day" event or not * - any resource the event may be related to * * Each of these properties can be customized or generated dynamically by * setting the various "accessor" props. Without any configuration the default * event should look like: * * ```js * Event { * title: string, * start: Date, * end: Date, * allDay?: boolean * resource?: any, * } * ``` */ events: PropTypes.arrayOf(PropTypes.object), /** * Accessor for the event title, used to display event information. Should * resolve to a `renderable` value. * * ```js * string | (event: Object) => string * ``` * * @type {(func|string)} */ titleAccessor: accessor, /** * Accessor for the event tooltip. Should * resolve to a `renderable` value. Removes the tooltip if null. * * ```js * string | (event: Object) => string * ``` * * @type {(func|string)} */ tooltipAccessor: accessor, /** * Determines whether the event should be considered an "all day" event and ignore time. * Must resolve to a `boolean` value. * * ```js * string | (event: Object) => boolean * ``` * * @type {(func|string)} */ allDayAccessor: accessor, /** * The start date/time of the event. Must resolve to a JavaScript `Date` object. * * ```js * string | (event: Object) => Date * ``` * * @type {(func|string)} */ startAccessor: accessor, /** * The end date/time of the event. Must resolve to a JavaScript `Date` object. * * ```js * string | (event: Object) => Date * ``` * * @type {(func|string)} */ endAccessor: accessor, /** * Returns the id of the `resource` that the event is a member of. This * id should match at least one resource in the `resources` array. * * ```js * string | (event: Object) => Date * ``` * * @type {(func|string)} */ resourceAccessor: accessor, /** * An array of resource objects that map events to a specific resource. * Resource objects, like events, can be any shape or have any properties, * but should be uniquly identifiable via the `resourceIdAccessor`, as * well as a "title" or name as provided by the `resourceTitleAccessor` prop. */ resources: PropTypes.arrayOf(PropTypes.object), /** * Provides a unique identifier for each resource in the `resources` array * * ```js * string | (resource: Object) => any * ``` * * @type {(func|string)} */ resourceIdAccessor: accessor, /** * Provides a human readable name for the resource object, used in headers. * * ```js * string | (resource: Object) => any * ``` * * @type {(func|string)} */ resourceTitleAccessor: accessor, /** * Determines the current date/time which is highlighted in the views. * * The value affects which day is shaded and which time is shown as * the current time. It also affects the date used by the Today button in * the toolbar. * * Providing a value here can be useful when you are implementing time zones * using the `startAccessor` and `endAccessor` properties. * * @type {func} * @default () => new Date() */ getNow: PropTypes.func, /** * Callback fired when the `date` value changes. * * @controllable date */ onNavigate: PropTypes.func, /** * Callback fired when the `view` value changes. * * @controllable view */ onView: PropTypes.func, /** * Callback fired when date header, or the truncated events links are clicked * */ onDrillDown: PropTypes.func, /** * * ```js * (dates: Date[] | { start: Date; end: Date }, view?: 'month'|'week'|'work_week'|'day'|'agenda') => void * ``` * * Callback fired when the visible date range changes. Returns an Array of dates * or an object with start and end dates for BUILTIN views. Optionally new `view` * will be returned when callback called after view change. * * Custom views may return something different. */ onRangeChange: PropTypes.func, /** * A callback fired when a date selection is made. Only fires when `selectable` is `true`. * * ```js * ( * slotInfo: { * start: Date, * end: Date, * slots: Array<Date>, * action: "select" | "click" | "doubleClick", * bounds: ?{ // For "select" action * x: number, * y: number, * top: number, * right: number, * left: number, * bottom: number, * }, * box: ?{ // For "click" or "doubleClick" actions * clientX: number, * clientY: number, * x: number, * y: number, * }, * } * ) => any * ``` */ onSelectSlot: PropTypes.func, /** * Callback fired when a calendar event is selected. * * ```js * (event: Object, e: SyntheticEvent) => any * ``` * * @controllable selected */ onSelectEvent: PropTypes.func, /** * Callback fired when a calendar event is clicked twice. * * ```js * (event: Object, e: SyntheticEvent) => void * ``` */ onDoubleClickEvent: PropTypes.func, /** * Callback fired when dragging a selection in the Time views. * * Returning `false` from the handler will prevent a selection. * * ```js * (range: { start: Date, end: Date }) => ?boolean * ``` */ onSelecting: PropTypes.func, /** * Callback fired when a +{count} more is clicked * * ```js * (events: Object, date: Date) => any * ``` */ onShowMore: PropTypes.func, /** * The selected event, if any. */ selected: PropTypes.object, /** * An array of built-in view names to allow the calendar to display. * accepts either an array of builtin view names, * * ```jsx * views={['month', 'day', 'agenda']} * ``` * or an object hash of the view name and the component (or boolean for builtin). * * ```jsx * views={{ * month: true, * week: false, * myweek: WorkWeekViewComponent, * }} * ``` * * Custom views can be any React component, that implements the following * interface: * * ```js * interface View { * static title(date: Date, { formats: DateFormat[], culture: string?, ...props }): string * static navigate(date: Date, action: 'PREV' | 'NEXT' | 'DATE'): Date * } * ``` * * @type Views ('month'|'week'|'work_week'|'day'|'agenda') * @View ['month', 'week', 'day', 'agenda'] */ views: views$1, /** * The string name of the destination view for drill-down actions, such * as clicking a date header, or the truncated events links. If * `getDrilldownView` is also specified it will be used instead. * * Set to `null` to disable drill-down actions. * * ```js * <Calendar * drilldownView="agenda" * /> * ``` */ drilldownView: PropTypes.string, /** * Functionally equivalent to `drilldownView`, but accepts a function * that can return a view name. It's useful for customizing the drill-down * actions depending on the target date and triggering view. * * Return `null` to disable drill-down actions. * * ```js * <Calendar * getDrilldownView={(targetDate, currentViewName, configuredViewNames) => * if (currentViewName === 'month' && configuredViewNames.includes('week')) * return 'week' * * return null; * }} * /> * ``` */ getDrilldownView: PropTypes.func, /** * Determines the end date from date prop in the agenda view * date prop + length (in number of days) = end date */ length: PropTypes.number, /** * Determines whether the toolbar is displayed */ toolbar: PropTypes.bool, /** * Show truncated events in an overlay when you click the "+_x_ more" link. */ popup: PropTypes.bool, /** * Distance in pixels, from the edges of the viewport, the "show more" overlay should be positioned. * * ```jsx * <Calendar popupOffset={30}/> * <Calendar popupOffset={{x: 30, y: 20}}/> * ``` */ popupOffset: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ x: PropTypes.number, y: PropTypes.number })]), /** * Allows mouse selection of ranges of dates/times. * * The 'ignoreEvents' option prevents selection code from running when a * drag begins over an event. Useful when you want custom event click or drag * logic */ selectable: PropTypes.oneOf([true, false, 'ignoreEvents']), /** * Specifies the number of miliseconds the user must press and hold on the screen for a touch * to be considered a "long press." Long presses are used for time slot selection on touch * devices. * * @type {number} * @default 250 */ longPressThreshold: PropTypes.number, /** * Determines the selectable time increments in week and day views */ step: PropTypes.number, /** * The number of slots per "section" in the time grid views. Adjust with `step` * to change the default of 1 hour long groups, with 30 minute slots. */ timeslots: PropTypes.number, /** *Switch the calendar to a `right-to-left` read direction. */ rtl: PropTypes.bool, /** * Optionally provide a function that returns an object of className or style props * to be applied to the the event node. * * ```js * ( * event: Object, * start: Date, * end: Date, * isSelected: boolean * ) => { className?: string, style?: Object } * ``` */ eventPropGetter: PropTypes.func, /** * Optionally provide a function that returns an object of className or style props * to be applied to the the time-slot node. Caution! Styles that change layout or * position may break the calendar in unexpected ways. * * ```js * (date: Date, resourceId: (number|string)) => { className?: string, style?: Object } * ``` */ slotPropGetter: PropTypes.func, /** * Optionally provide a function that returns an object of className or style props * to be applied to the the day background. Caution! Styles that change layout or * position may break the calendar in unexpected ways. * * ```js * (date: Date) => { className?: string, style?: Object } * ``` */ dayPropGetter: PropTypes.func, /** * Support to show multi-day events with specific start and end times in the * main time grid (rather than in the all day header). * * **Note: This may cause calendars with several events to look very busy in * the week and day views.** */ showMultiDayTimes: PropTypes.bool, /** * Constrains the minimum _time_ of the Day and Week views. */ min: PropTypes.instanceOf(Date), /** * Constrains the maximum _time_ of the Day and Week views. */ max: PropTypes.instanceOf(Date), /** * Determines how far down the scroll pane is initially scrolled down. */ scrollToTime: PropTypes.instanceOf(Date), /** * Specify a specific culture code for the Calendar. * * **Note: it's generally better to handle this globally via your i18n library.** */ culture: PropTypes.string, /** * Localizer specific formats, tell the Calendar how to format and display dates. * * `format` types are dependent on the configured localizer; both Moment and Globalize * accept strings of tokens according to their own specification, such as: `'DD mm yyyy'`. * * ```jsx * let formats = { * dateFormat: 'dd', * * dayFormat: (date, , localizer) => * localizer.format(date, 'DDD', culture), * * dayRangeHeaderFormat: ({ start, end }, culture, localizer) => * localizer.format(start, { date: 'short' }, culture) + ' — ' + * localizer.format(end, { date: 'short' }, culture) * } * * <Calendar formats={formats} /> * ``` * * All localizers accept a function of * the form `(date: Date, culture: ?string, localizer: Localizer) -> string` */ formats: PropTypes.shape({ /** * Format for the day of the month heading in the Month view. * e.g. "01", "02", "03", etc */ dateFormat: dateFormat, /** * A day of the week format for Week and Day headings, * e.g. "Wed 01/04" * */ dayFormat: dateFormat, /** * Week day name format for the Month week day headings, * e.g: "Sun", "Mon", "Tue", etc * */ weekdayFormat: dateFormat, /** * The timestamp cell formats in Week and Time views, e.g. "4:00 AM" */ timeGutterFormat: dateFormat, /** * Toolbar header format for the Month view, e.g "2015 April" * */ monthHeaderFormat: dateFormat, /** * Toolbar header format for the Week views, e.g. "Mar 29 - Apr 04" */ dayRangeHeaderFormat: dateRangeFormat, /** * Toolbar header format for the Day view, e.g. "Wednesday Apr 01" */ dayHeaderFormat: dateFormat, /** * Toolbar header format for the Agenda view, e.g. "4/1/2015 — 5/1/2015" */ agendaHeaderFormat: dateRangeFormat, /** * A time range format for selecting time slots, e.g "8:00am — 2:00pm" */ selectRangeFormat: dateRangeFormat, agendaDateFormat: dateFormat, agendaTimeFormat: dateFormat, agendaTimeRangeFormat: dateRangeFormat, /** * Time range displayed on events. */ eventTimeRangeFormat: dateRangeFormat, /** * An optional event time range for events that continue onto another day */ eventTimeRangeStartFormat: dateFormat, /** * An optional event time range for events that continue from another day */ eventTimeRangeEndFormat: dateFormat }), /** * Customize how different sections of the calendar render by providing custom Components. * In particular the `Event` component can be specified for the entire calendar, or you can * provide an individual component for each view type. * * ```jsx * let components = { * event: MyEvent, // used by each view (Month, Day, Week) * eventWrapper: MyEventWrapper, * eventContainerWrapper: MyEventContainerWrapper, * dateCellWrapper: MyDateCellWrapper, * timeSlotWrapper: MyTimeSlotWrapper, * timeGutterHeader: MyTimeGutterWrapper, * toolbar: MyToolbar, * agenda: { * event: MyAgendaEvent // with the agenda view use a different component to render events * time: MyAgendaTime, * date: MyAgendaDate, * }, * day: { * header: MyDayHeader, * event: MyDayEvent, * }, * week: { * header: MyWeekHeader, * event: MyWeekEvent, * }, * month: { * header: MyMonthHeader, * dateHeader: MyMonthDateHeader, * event: MyMonthEvent, * } * } * <Calendar components={components} /> * ``` */ components: PropTypes.shape({ event: PropTypes.elementType, eventWrapper: PropTypes.elementType, eventContainerWrapper: PropTypes.elementType, dateCellWrapper: PropTypes.elementType, timeSlotWrapper: PropTypes.elementType, timeGutterHeader: PropTypes.elementType, resourceHeader: PropTypes.elementType, toolbar: PropTypes.elementType, agenda: PropTypes.shape({ date: PropTypes.elementType, time: PropTypes.elementType, event: PropTypes.elementType }), day: PropTypes.shape({ header: PropTypes.elementType, event: PropTypes.elementType }), week: PropTypes.shape({ header: PropTypes.elementType, event: PropTypes.elementType }), month: PropTypes.shape({ header: PropTypes.elementType, dateHeader: PropTypes.elementType, event: PropTypes.elementType }) }), /** * String messages used throughout the component, override to provide localizations */ messages: PropTypes.shape({ allDay: PropTypes.node, previous: PropTypes.node, next: PropTypes.node, today: PropTypes.node, month: PropTypes.node, week: PropTypes.node, day: PropTypes.node, agenda: PropTypes.node, date: PropTypes.node, time: PropTypes.node, event: PropTypes.node, noEventsInRange: PropTypes.node, showMore: PropTypes.func }) } : {}; var Calendar$1 = uncontrollable(Calendar, { view: 'onView', date: 'onNavigate', selected: 'onSelectEvent' }); var dateRangeFormat$1 = function dateRangeFormat(_ref, culture, local) { var start = _ref.start, end = _ref.end; return local.format(start, 'L', culture) + ' — ' + local.format(end, 'L', culture); }; var timeRangeFormat = function timeRangeFormat(_ref2, culture, local) { var start = _ref2.start, end = _ref2.end; return local.format(start, 'LT', culture) + ' — ' + local.format(end, 'LT', culture); }; var timeRangeStartFormat = function timeRangeStartFormat(_ref3, culture, local) { var start = _ref3.start; return local.format(start, 'LT', culture) + ' — '; }; var timeRangeEndFormat = function timeRangeEndFormat(_ref4, culture, local) { var end = _ref4.end; return ' — ' + local.format(end, 'LT', culture); }; var weekRangeFormat = function weekRangeFormat(_ref5, culture, local) { var start = _ref5.start, end = _ref5.end; return local.format(start, 'MMMM DD', culture) + ' - ' + local.format(end, eq(start, end, 'month') ? 'DD' : 'MMMM DD', culture); }; var formats = { dateFormat: 'DD', dayFormat: 'DD ddd', weekdayFormat: 'ddd', selectRangeFormat: timeRangeFormat, eventTimeRangeFormat: timeRangeFormat, eventTimeRangeStartFormat: timeRangeStartFormat, eventTimeRangeEndFormat: timeRangeEndFormat, timeGutterFormat: 'LT', monthHeaderFormat: 'MMMM YYYY', dayHeaderFormat: 'dddd MMM DD', dayRangeHeaderFormat: weekRangeFormat, agendaHeaderFormat: dateRangeFormat$1, agendaDateFormat: 'ddd MMM DD', agendaTimeFormat: 'LT', agendaTimeRangeFormat: timeRangeFormat }; function moment (moment) { var locale = function locale(m, c) { return c ? m.locale(c) : m; }; return new DateLocalizer({ formats: formats, firstOfWeek: function firstOfWeek(culture) { var data = culture ? moment.localeData(culture) : moment.localeData(); return data ? data.firstDayOfWeek() : 0; }, format: function format(value, _format, culture) { return locale(moment(value), culture).format(_format); } }); } var dateRangeFormat$2 = function dateRangeFormat(_ref, culture, local) { var start = _ref.start, end = _ref.end; return local.format(start, 'd', culture) + ' — ' + local.format(end, 'd', culture); }; var timeRangeFormat$1 = function timeRangeFormat(_ref2, culture, local) { var start = _ref2.start, end = _ref2.end; return local.format(start, 't', culture) + ' — ' + local.format(end, 't', culture); }; var timeRangeStartFormat$1 = function timeRangeStartFormat(_ref3, culture, local) { var start = _ref3.start; return local.format(start, 't', culture) + ' — '; }; var timeRangeEndFormat$1 = function timeRangeEndFormat(_ref4, culture, local) { var end = _ref4.end; return ' — ' + local.format(end, 't', culture); }; var weekRangeFormat$1 = function weekRangeFormat(_ref5, culture, local) { var start = _ref5.start, end = _ref5.end; return local.format(start, 'MMM dd', culture) + ' - ' + local.format(end, eq(start, end, 'month') ? 'dd' : 'MMM dd', culture); }; var formats$1 = { dateFormat: 'dd', dayFormat: 'ddd dd/MM', weekdayFormat: 'ddd', selectRangeFormat: timeRangeFormat$1, eventTimeRangeFormat: timeRangeFormat$1, eventTimeRangeStartFormat: timeRangeStartFormat$1, eventTimeRangeEndFormat: timeRangeEndFormat$1, timeGutterFormat: 't', monthHeaderFormat: 'Y', dayHeaderFormat: 'dddd MMM dd', dayRangeHeaderFormat: weekRangeFormat$1, agendaHeaderFormat: dateRangeFormat$2, agendaDateFormat: 'ddd MMM dd', agendaTimeFormat: 't', agendaTimeRangeFormat: timeRangeFormat$1 }; function oldGlobalize (globalize) { function getCulture(culture) { return culture ? globalize.findClosestCulture(culture) : globalize.culture(); } function firstOfWeek(culture) { culture = getCulture(culture); return culture && culture.calendar.firstDay || 0; } return new DateLocalizer({ firstOfWeek: firstOfWeek, formats: formats$1, format: function format(value, _format, culture) { return globalize.format(value, _format, culture); } }); } var dateRangeFormat$3 = function dateRangeFormat(_ref, culture, local) { var start = _ref.start, end = _ref.end; return local.format(start, { date: 'short' }, culture) + ' — ' + local.format(end, { date: 'short' }, culture); }; var timeRangeFormat$2 = function timeRangeFormat(_ref2, culture, local) { var start = _ref2.start, end = _ref2.end; return local.format(start, { time: 'short' }, culture) + ' — ' + local.format(end, { time: 'short' }, culture); }; var timeRangeStartFormat$2 = function timeRangeStartFormat(_ref3, culture, local) { var start = _ref3.start; return local.format(start, { time: 'short' }, culture) + ' — '; }; var timeRangeEndFormat$2 = function timeRangeEndFormat(_ref4, culture, local) { var end = _ref4.end; return ' — ' + local.format(end, { time: 'short' }, culture); }; var weekRangeFormat$2 = function weekRangeFormat(_ref5, culture, local) { var start = _ref5.start, end = _ref5.end; return local.format(start, 'MMM dd', culture) + ' — ' + local.format(end, eq(start, end, 'month') ? 'dd' : 'MMM dd', culture); }; var formats$2 = { dateFormat: 'dd', dayFormat: 'eee dd/MM', weekdayFormat: 'eee', selectRangeFormat: timeRangeFormat$2, eventTimeRangeFormat: timeRangeFormat$2, eventTimeRangeStartFormat: timeRangeStartFormat$2, eventTimeRangeEndFormat: timeRangeEndFormat$2, timeGutterFormat: { time: 'short' }, monthHeaderFormat: 'MMMM yyyy', dayHeaderFormat: 'eeee MMM dd', dayRangeHeaderFormat: weekRangeFormat$2, agendaHeaderFormat: dateRangeFormat$3, agendaDateFormat: 'eee MMM dd', agendaTimeFormat: { time: 'short' }, agendaTimeRangeFormat: timeRangeFormat$2 }; function globalize (globalize) { var locale = function locale(culture) { return culture ? globalize(culture) : globalize; }; // return the first day of the week from the locale data. Defaults to 'world' // territory if no territory is derivable from CLDR. // Failing to use CLDR supplemental (not loaded?), revert to the original // method of getting first day of week. function firstOfWeek(culture) { try { var days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; var cldr = locale(culture).cldr; var territory = cldr.attributes.territory; var weekData = cldr.get('supplemental').weekData; var firstDay = weekData.firstDay[territory || '001']; return days.indexOf(firstDay); } catch (e) { process.env.NODE_ENV !== "production" ? warning(true, "Failed to accurately determine first day of the week.\n Is supplemental data loaded into CLDR?") : void 0; // maybe cldr supplemental is not loaded? revert to original method var date = new Date(); //cldr-data doesn't seem to be zero based var localeDay = Math.max(parseInt(locale(culture).formatDate(date, { raw: 'e' }), 10) - 1, 0); return Math.abs(date.getDay() - localeDay); } } if (!globalize.load) return oldGlobalize(globalize); return new DateLocalizer({ firstOfWeek: firstOfWeek, formats: formats$2, format: function format(value, _format, culture) { _format = typeof _format === 'string' ? { raw: _format } : _format; return locale(culture).formatDate(value, _format); } }); } var components = { eventWrapper: NoopWrapper, timeSlotWrapper: NoopWrapper, dateCellWrapper: NoopWrapper }; export { Calendar$1 as Calendar, DateLocalizer, navigate as Navigate, views as Views, components, globalize as globalizeLocalizer, moment as momentLocalizer, moveDate as move };
ajax/libs/react-native-web/0.11.3/exports/Picker/PickerItemPropType.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 PickerItem from './PickerItem'; var PickerItemPropType = function PickerItemPropType(props, propName, componentName) { var prop = props[propName]; var error = null; React.Children.forEach(prop, function (child) { if (child.type !== PickerItem) { error = new Error('`Picker` children must be of type `Picker.Item`.'); } }); return error; }; export default PickerItemPropType;
ajax/libs/react-instantsearch/5.5.0/Dom.js
cdnjs/cdnjs
/*! React InstantSearch 5.5.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 _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); } 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 global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); // shim for using process in browser // based off https://github.com/defunctzombie/node-process/blob/master/browser.js function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } function nextTick(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; var title = 'browser'; var platform = 'browser'; var browser = true; var env = {}; var argv = []; var version = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; var config = {}; function noop() {} var on = noop; var addListener = noop; var once = noop; var off = noop; var removeListener = noop; var removeAllListeners = noop; var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); } function cwd () { return '/' } function chdir (dir) { throw new Error('process.chdir is not supported'); }function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function(){ return (new Date()).getTime() }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp){ var clocktime = performanceNow.call(performance)*1e-3; var seconds = Math.floor(clocktime); var nanoseconds = Math.floor((clocktime%1)*1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds<0) { seconds--; nanoseconds += 1e9; } } return [seconds,nanoseconds] } var startTime = new Date(); function uptime() { var currentTime = new Date(); var dif = currentTime - startTime; return dif / 1000; } var process = { nextTick: nextTick, title: title, browser: browser, env: env, argv: argv, version: version, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime }; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function commonjsRequire () { throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); } 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 _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; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } var _arrayMap = arrayMap; /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } var _listCacheClear = listCacheClear; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } var eq_1 = eq; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq_1(array[length][0], key)) { return length; } } return -1; } var _assocIndexOf = assocIndexOf; /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } var _listCacheDelete = listCacheDelete; /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = _assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } var _listCacheGet = listCacheGet; /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return _assocIndexOf(this.__data__, key) > -1; } var _listCacheHas = listCacheHas; /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } var _listCacheSet = listCacheSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = _listCacheClear; ListCache.prototype['delete'] = _listCacheDelete; ListCache.prototype.get = _listCacheGet; ListCache.prototype.has = _listCacheHas; ListCache.prototype.set = _listCacheSet; var _ListCache = ListCache; /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new _ListCache; this.size = 0; } var _stackClear = stackClear; /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } var _stackDelete = stackDelete; /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } var _stackGet = stackGet; /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } var _stackHas = stackHas; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var _freeGlobal = freeGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = _freeGlobal || freeSelf || Function('return this')(); var _root = root; /** Built-in value references. */ var Symbol$1 = _root.Symbol; var _Symbol = Symbol$1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty$1.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var _getRawTag = getRawTag; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$1.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } var _objectToString = objectToString; /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag$1 && symToStringTag$1 in Object(value)) ? _getRawTag(value) : _objectToString(value); } var _baseGetTag = baseGetTag; /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } var isObject_1 = isObject; /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject_1(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = _baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_1 = isFunction; /** Used to detect overreaching core-js shims. */ var coreJsData = _root['__core-js_shared__']; var _coreJsData = coreJsData; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } var _isMasked = isMasked; /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } var _toSource = toSource; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto$1 = Function.prototype, objectProto$2 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$1 = funcProto$1.toString; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$2.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject_1(value) || _isMasked(value)) { return false; } var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; return pattern.test(_toSource(value)); } var _baseIsNative = baseIsNative; /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } var _getValue = getValue; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = _getValue(object, key); return _baseIsNative(value) ? value : undefined; } var _getNative = getNative; /* Built-in method references that are verified to be native. */ var Map = _getNative(_root, 'Map'); var _Map = Map; /* Built-in method references that are verified to be native. */ var nativeCreate = _getNative(Object, 'create'); var _nativeCreate = nativeCreate; /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; this.size = 0; } var _hashClear = hashClear; /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } var _hashDelete = hashDelete; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$3.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (_nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty$3.call(data, key) ? data[key] : undefined; } var _hashGet = hashGet; /** Used for built-in method references. */ var objectProto$4 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$4 = objectProto$4.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$4.call(data, key); } var _hashHas = hashHas; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; return this; } var _hashSet = hashSet; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = _hashClear; Hash.prototype['delete'] = _hashDelete; Hash.prototype.get = _hashGet; Hash.prototype.has = _hashHas; Hash.prototype.set = _hashSet; var _Hash = Hash; /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new _Hash, 'map': new (_Map || _ListCache), 'string': new _Hash }; } var _mapCacheClear = mapCacheClear; /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } var _isKeyable = isKeyable; /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } var _getMapData = getMapData; /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = _getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } var _mapCacheDelete = mapCacheDelete; /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return _getMapData(this, key).get(key); } var _mapCacheGet = mapCacheGet; /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return _getMapData(this, key).has(key); } var _mapCacheHas = mapCacheHas; /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = _getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } var _mapCacheSet = mapCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = _mapCacheClear; MapCache.prototype['delete'] = _mapCacheDelete; MapCache.prototype.get = _mapCacheGet; MapCache.prototype.has = _mapCacheHas; MapCache.prototype.set = _mapCacheSet; var _MapCache = MapCache; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof _ListCache) { var pairs = data.__data__; if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new _MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } var _stackSet = stackSet; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new _ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = _stackClear; Stack.prototype['delete'] = _stackDelete; Stack.prototype.get = _stackGet; Stack.prototype.has = _stackHas; Stack.prototype.set = _stackSet; var _Stack = Stack; /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } var _arrayEach = arrayEach; var defineProperty = (function() { try { var func = _getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); var _defineProperty$1 = defineProperty; /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && _defineProperty$1) { _defineProperty$1(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } var _baseAssignValue = baseAssignValue; /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$5 = objectProto$5.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$5.call(object, key) && eq_1(objValue, value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignValue = assignValue; /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { _baseAssignValue(object, key, newValue); } else { _assignValue(object, key, newValue); } } return object; } var _copyObject = copyObject; /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } var _baseTimes = baseTimes; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } var isObjectLike_1 = isObjectLike; /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike_1(value) && _baseGetTag(value) == argsTag; } var _baseIsArguments = baseIsArguments; /** Used for built-in method references. */ var objectProto$6 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$6 = objectProto$6.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto$6.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { return isObjectLike_1(value) && hasOwnProperty$6.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; var isArguments_1 = isArguments; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; var isArray_1 = isArray; /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } var stubFalse_1 = stubFalse; var isBuffer_1 = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse_1; module.exports = isBuffer; }); /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } var _isIndex = isIndex; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; } var isLength_1 = isLength; /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag$1 = '[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$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; } var _baseIsTypedArray = baseIsTypedArray; /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } var _baseUnary = baseUnary; var _nodeUtil = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && _freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; }); /* Node.js helper references. */ var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; var isTypedArray_1 = isTypedArray; /** Used for built-in method references. */ var objectProto$7 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$7 = objectProto$7.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty$7.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. _isIndex(key, length) ))) { result.push(key); } } return result; } var _arrayLikeKeys = arrayLikeKeys; /** Used for built-in method references. */ var objectProto$8 = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$8; return value === proto; } var _isPrototype = isPrototype; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var _overArg = overArg; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = _overArg(Object.keys, Object); var _nativeKeys = nativeKeys; /** Used for built-in method references. */ var objectProto$9 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$8 = objectProto$9.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$8.call(object, key) && key != 'constructor') { result.push(key); } } return result; } var _baseKeys = baseKeys; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength_1(value.length) && !isFunction_1(value); } var isArrayLike_1 = isArrayLike; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); } var keys_1 = keys; /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && _copyObject(source, keys_1(source), object); } var _baseAssign = baseAssign; /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } var _nativeKeysIn = nativeKeysIn; /** Used for built-in method references. */ var objectProto$a = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$9 = objectProto$a.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject_1(object)) { return _nativeKeysIn(object); } var isProto = _isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty$9.call(object, key)))) { result.push(key); } } return result; } var _baseKeysIn = baseKeysIn; /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn$1(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object); } var keysIn_1 = keysIn$1; /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && _copyObject(source, keysIn_1(source), object); } var _baseAssignIn = baseAssignIn; var _cloneBuffer = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; }); /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } var _copyArray = copyArray; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } var _arrayFilter = arrayFilter; /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } var stubArray_1 = stubArray; /** Used for built-in method references. */ var objectProto$b = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable$1 = objectProto$b.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { if (object == null) { return []; } object = Object(object); return _arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable$1.call(object, symbol); }); }; var _getSymbols = getSymbols; /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return _copyObject(source, _getSymbols(source), object); } var _copySymbols = copySymbols; /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } var _arrayPush = arrayPush; /** Built-in value references. */ var getPrototype = _overArg(Object.getPrototypeOf, Object); var _getPrototype = getPrototype; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols$1 = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) { var result = []; while (object) { _arrayPush(result, _getSymbols(object)); object = _getPrototype(object); } return result; }; var _getSymbolsIn = getSymbolsIn; /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return _copyObject(source, _getSymbolsIn(source), object); } var _copySymbolsIn = copySymbolsIn; /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); } var _baseGetAllKeys = baseGetAllKeys; /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return _baseGetAllKeys(object, keys_1, _getSymbols); } var _getAllKeys = getAllKeys; /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn); } var _getAllKeysIn = getAllKeysIn; /* Built-in method references that are verified to be native. */ var DataView = _getNative(_root, 'DataView'); var _DataView = DataView; /* Built-in method references that are verified to be native. */ var Promise$1 = _getNative(_root, 'Promise'); var _Promise = Promise$1; /* Built-in method references that are verified to be native. */ var Set = _getNative(_root, 'Set'); var _Set = Set; /* Built-in method references that are verified to be native. */ var WeakMap = _getNative(_root, 'WeakMap'); var _WeakMap = WeakMap; /** `Object#toString` result references. */ var mapTag$1 = '[object Map]', objectTag$1 = '[object Object]', promiseTag = '[object Promise]', setTag$1 = '[object Set]', weakMapTag$1 = '[object WeakMap]'; var dataViewTag$1 = '[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$1) || (_Map && getTag(new _Map) != mapTag$1) || (_Promise && getTag(_Promise.resolve()) != promiseTag) || (_Set && getTag(new _Set) != setTag$1) || (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) { getTag = function(value) { var result = _baseGetTag(value), Ctor = result == objectTag$1 ? value.constructor : undefined, ctorString = Ctor ? _toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag$1; case mapCtorString: return mapTag$1; case promiseCtorString: return promiseTag; case setCtorString: return setTag$1; case weakMapCtorString: return weakMapTag$1; } } return result; }; } var _getTag = getTag; /** Used for built-in method references. */ var objectProto$c = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$a = objectProto$c.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty$a.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } var _initCloneArray = initCloneArray; /** Built-in value references. */ var Uint8Array = _root.Uint8Array; var _Uint8Array = Uint8Array; /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new _Uint8Array(result).set(new _Uint8Array(arrayBuffer)); return result; } var _cloneArrayBuffer = cloneArrayBuffer; /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } var _cloneDataView = cloneDataView; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } var _cloneRegExp = cloneRegExp; /** Used to convert symbols to primitives and strings. */ var symbolProto = _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)) : {}; } var _cloneSymbol = cloneSymbol; /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } var _cloneTypedArray = cloneTypedArray; /** `Object#toString` result references. */ var boolTag$1 = '[object Boolean]', dateTag$1 = '[object Date]', mapTag$2 = '[object Map]', numberTag$1 = '[object Number]', regexpTag$1 = '[object RegExp]', setTag$2 = '[object Set]', stringTag$1 = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag$1 = '[object ArrayBuffer]', dataViewTag$2 = '[object DataView]', float32Tag$1 = '[object Float32Array]', float64Tag$1 = '[object Float64Array]', int8Tag$1 = '[object Int8Array]', int16Tag$1 = '[object Int16Array]', int32Tag$1 = '[object Int32Array]', uint8Tag$1 = '[object Uint8Array]', uint8ClampedTag$1 = '[object Uint8ClampedArray]', uint16Tag$1 = '[object Uint16Array]', uint32Tag$1 = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag$1: return _cloneArrayBuffer(object); case boolTag$1: case dateTag$1: return new Ctor(+object); case dataViewTag$2: return _cloneDataView(object, isDeep); case float32Tag$1: case float64Tag$1: case int8Tag$1: case int16Tag$1: case int32Tag$1: case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: return _cloneTypedArray(object, isDeep); case mapTag$2: return new Ctor; case numberTag$1: case stringTag$1: return new Ctor(object); case regexpTag$1: return _cloneRegExp(object); case setTag$2: return new Ctor; case symbolTag: return _cloneSymbol(object); } } var _initCloneByTag = initCloneByTag; /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject_1(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); var _baseCreate = baseCreate; /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !_isPrototype(object)) ? _baseCreate(_getPrototype(object)) : {}; } var _initCloneObject = initCloneObject; /** `Object#toString` result references. */ var mapTag$3 = '[object Map]'; /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike_1(value) && _getTag(value) == mapTag$3; } var _baseIsMap = baseIsMap; /* Node.js helper references. */ var nodeIsMap = _nodeUtil && _nodeUtil.isMap; /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap; var isMap_1 = isMap; /** `Object#toString` result references. */ var setTag$3 = '[object Set]'; /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike_1(value) && _getTag(value) == setTag$3; } var _baseIsSet = baseIsSet; /* Node.js helper references. */ var nodeIsSet = _nodeUtil && _nodeUtil.isSet; /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet; var isSet_1 = isSet; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag$2 = '[object Arguments]', arrayTag$1 = '[object Array]', boolTag$2 = '[object Boolean]', dateTag$2 = '[object Date]', errorTag$1 = '[object Error]', funcTag$2 = '[object Function]', genTag$1 = '[object GeneratorFunction]', mapTag$4 = '[object Map]', numberTag$2 = '[object Number]', objectTag$2 = '[object Object]', regexpTag$2 = '[object RegExp]', setTag$4 = '[object Set]', stringTag$2 = '[object String]', symbolTag$1 = '[object Symbol]', weakMapTag$2 = '[object WeakMap]'; var arrayBufferTag$2 = '[object ArrayBuffer]', dataViewTag$3 = '[object DataView]', float32Tag$2 = '[object Float32Array]', float64Tag$2 = '[object Float64Array]', int8Tag$2 = '[object Int8Array]', int16Tag$2 = '[object Int16Array]', int32Tag$2 = '[object Int32Array]', uint8Tag$2 = '[object Uint8Array]', uint8ClampedTag$2 = '[object Uint8ClampedArray]', uint16Tag$2 = '[object Uint16Array]', uint32Tag$2 = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] = cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] = cloneableTags[boolTag$2] = cloneableTags[dateTag$2] = cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] = cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] = cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] = cloneableTags[numberTag$2] = cloneableTags[objectTag$2] = cloneableTags[regexpTag$2] = cloneableTags[setTag$4] = cloneableTags[stringTag$2] = cloneableTags[symbolTag$1] = cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] = cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true; cloneableTags[errorTag$1] = cloneableTags[funcTag$2] = cloneableTags[weakMapTag$2] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject_1(value)) { return value; } var isArr = isArray_1(value); if (isArr) { result = _initCloneArray(value); if (!isDeep) { return _copyArray(value, result); } } else { var tag = _getTag(value), isFunc = tag == funcTag$2 || tag == genTag$1; if (isBuffer_1(value)) { return _cloneBuffer(value, isDeep); } if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : _initCloneObject(value); if (!isDeep) { return isFlat ? _copySymbolsIn(value, _baseAssignIn(result, value)) : _copySymbols(value, _baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = _initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new _Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet_1(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); return result; } if (isMap_1(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var keysFunc = isFull ? (isFlat ? _getAllKeysIn : _getAllKeys) : (isFlat ? keysIn : keys_1); var props = isArr ? undefined : keysFunc(value); _arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var _baseClone = baseClone; /** `Object#toString` result references. */ var symbolTag$2 = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$2); } var isSymbol_1 = isSymbol; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray_1(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } var _isKey = isKey; /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || _MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = _MapCache; var memoize_1 = memoize; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize_1(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var _memoizeCapped = memoizeCapped; /** Used to match property names within property paths. */ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = _memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); var _stringToPath = stringToPath; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined, symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray_1(value)) { // Recursively convert values (susceptible to call stack limits). return _arrayMap(value, baseToString) + ''; } if (isSymbol_1(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } var _baseToString = baseToString; /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : _baseToString(value); } var toString_1 = toString; /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray_1(value)) { return value; } return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); } var _castPath = castPath; /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } var last_1 = last; /** Used as references for various `Number` constants. */ var INFINITY$1 = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol_1(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; } var _toKey = toKey; /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = _castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[_toKey(path[index++])]; } return (index && index == length) ? object : undefined; } var _baseGet = baseGet; /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } var _baseSlice = baseSlice; /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1)); } var _parent = parent; /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = _castPath(path, object); object = _parent(object, path); return object == null || delete object[_toKey(last_1(path))]; } var _baseUnset = baseUnset; /** `Object#toString` result references. */ var objectTag$3 = '[object Object]'; /** Used for built-in method references. */ var funcProto$2 = Function.prototype, objectProto$d = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$2 = funcProto$2.toString; /** Used to check objects for own properties. */ var hasOwnProperty$b = objectProto$d.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString$2.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) { return false; } var proto = _getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$b.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString; } var isPlainObject_1 = isPlainObject; /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject_1(value) ? undefined : value; } var _customOmitClone = customOmitClone; /** Built-in value references. */ var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } var _isFlattenable = isFlattenable; /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = _isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { _arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } var _baseFlatten = baseFlatten; /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? _baseFlatten(array, 1) : []; } var flatten_1 = flatten; /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } var _apply = apply; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return _apply(func, this, otherArgs); }; } var _overRest = overRest; /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } var constant_1 = constant; /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } var identity_1 = identity; /** * The base implementation of `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$1 ? identity_1 : function(func, string) { return _defineProperty$1(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant_1(string), 'writable': true }); }; var _baseSetToString = baseSetToString; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } var _shortOut = shortOut; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = _shortOut(_baseSetToString); var _setToString = setToString; /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return _setToString(_overRest(func, undefined, flatten_1), func + ''); } var _flatRest = flatRest; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG$1 = 1, CLONE_FLAT_FLAG$1 = 2, CLONE_SYMBOLS_FLAG$1 = 4; /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = _flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = _arrayMap(paths, function(path) { path = _castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); _copyObject(object, _getAllKeysIn(object), result); if (isDeep) { result = _baseClone(result, CLONE_DEEP_FLAG$1 | CLONE_FLAT_FLAG$1 | CLONE_SYMBOLS_FLAG$1, _customOmitClone); } var length = paths.length; while (length--) { _baseUnset(result, paths[length]); } return result; }); var omit_1 = omit; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED$2); return this; } var _setCacheAdd = setCacheAdd; /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } var _setCacheHas = setCacheHas; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new _MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; SetCache.prototype.has = _setCacheHas; var _SetCache = SetCache; /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } var _baseFindIndex = baseFindIndex; /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } var _baseIsNaN = baseIsNaN; /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } var _strictIndexOf = strictIndexOf; /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex); } var _baseIndexOf = baseIndexOf; /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && _baseIndexOf(array, value, 0) > -1; } var _arrayIncludes = arrayIncludes; /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } var _arrayIncludesWith = arrayIncludesWith; /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } var _cacheHas = cacheHas; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? _arrayIncludesWith : _arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = _arrayMap(array, _baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new _SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? _cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? _cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } var _baseIntersection = baseIntersection; /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return _setToString(_overRest(func, start, identity_1), func + ''); } var _baseRest = baseRest; /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike_1(value) && isArrayLike_1(value); } var isArrayLikeObject_1 = isArrayLikeObject; /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject_1(value) ? value : []; } var _castArrayLikeObject = castArrayLikeObject; /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = _baseRest(function(arrays) { var mapped = _arrayMap(arrays, _castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? _baseIntersection(mapped) : []; }); var intersection_1 = intersection; /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } var _createBaseFor = createBaseFor; /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = _createBaseFor(); var _baseFor = baseFor; /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && _baseFor(object, iteratee, keys_1); } var _baseForOwn = baseForOwn; /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity_1; } var _castFunction = castFunction; /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && _baseForOwn(object, _castFunction(iteratee)); } var forOwn_1 = forOwn; /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike_1(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } var _createBaseEach = createBaseEach; /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = _createBaseEach(_baseForOwn); var _baseEach = baseEach; /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray_1(collection) ? _arrayEach : _baseEach; return func(collection, _castFunction(iteratee)); } var forEach_1 = forEach; /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; _baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } var _baseFilter = baseFilter; /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } var _arraySome = arraySome; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!_arraySome(other, function(othValue, othIndex) { if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } var _equalArrays = equalArrays; /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } var _mapToArray = mapToArray; /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } var _setToArray = setToArray; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$1 = 1, COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ var boolTag$3 = '[object Boolean]', dateTag$3 = '[object Date]', errorTag$2 = '[object Error]', mapTag$5 = '[object Map]', numberTag$3 = '[object Number]', regexpTag$3 = '[object RegExp]', setTag$5 = '[object Set]', stringTag$3 = '[object String]', symbolTag$3 = '[object Symbol]'; var arrayBufferTag$3 = '[object ArrayBuffer]', dataViewTag$4 = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined, symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag$4: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag$3: if ((object.byteLength != other.byteLength) || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { return false; } return true; case boolTag$3: case dateTag$3: case numberTag$3: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq_1(+object, +other); case errorTag$2: return object.name == other.name && object.message == other.message; case regexpTag$3: case stringTag$3: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag$5: var convert = _mapToArray; case setTag$5: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; convert || (convert = _setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag$3: if (symbolValueOf$1) { return symbolValueOf$1.call(object) == symbolValueOf$1.call(other); } } return false; } var _equalByTag = equalByTag; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$2 = 1; /** Used for built-in method references. */ var objectProto$e = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$c = objectProto$e.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, objProps = _getAllKeys(object), objLength = objProps.length, othProps = _getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty$c.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } var _equalObjects = equalObjects; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$3 = 1; /** `Object#toString` result references. */ var argsTag$3 = '[object Arguments]', arrayTag$2 = '[object Array]', objectTag$4 = '[object Object]'; /** Used for built-in method references. */ var objectProto$f = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$d = objectProto$f.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray_1(object), othIsArr = isArray_1(other), objTag = objIsArr ? arrayTag$2 : _getTag(object), othTag = othIsArr ? arrayTag$2 : _getTag(other); objTag = objTag == argsTag$3 ? objectTag$4 : objTag; othTag = othTag == argsTag$3 ? objectTag$4 : othTag; var objIsObj = objTag == objectTag$4, othIsObj = othTag == objectTag$4, isSameTag = objTag == othTag; if (isSameTag && isBuffer_1(object)) { if (!isBuffer_1(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new _Stack); return (objIsArr || isTypedArray_1(object)) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { var objIsWrapped = objIsObj && hasOwnProperty$d.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty$d.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new _Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new _Stack); return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); } var _baseIsEqualDeep = baseIsEqualDeep; /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } var _baseIsEqual = baseIsEqual; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$4 = 1, COMPARE_UNORDERED_FLAG$2 = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new _Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result )) { return false; } } } return true; } var _baseIsMatch = baseIsMatch; /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject_1(value); } var _isStrictComparable = isStrictComparable; /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys_1(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, _isStrictComparable(value)]; } return result; } var _getMatchData = getMatchData; /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } var _matchesStrictComparable = matchesStrictComparable; /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = _getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return _matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || _baseIsMatch(object, source, matchData); }; } var _baseMatches = baseMatches; /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : _baseGet(object, path); return result === undefined ? defaultValue : result; } var get_1 = get; /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } var _baseHasIn = baseHasIn; /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = _castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = _toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); } var _hasPath = hasPath; /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && _hasPath(object, path, _baseHasIn); } var hasIn_1 = hasIn; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$5 = 1, COMPARE_UNORDERED_FLAG$3 = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (_isKey(path) && _isStrictComparable(srcValue)) { return _matchesStrictComparable(_toKey(path), srcValue); } return function(object) { var objValue = get_1(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); }; } var _baseMatchesProperty = baseMatchesProperty; /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } var _baseProperty = baseProperty; /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return _baseGet(object, path); }; } var _basePropertyDeep = basePropertyDeep; /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); } var property_1 = property; /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity_1; } if (typeof value == 'object') { return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value); } return property_1(value); } var _baseIteratee = baseIteratee; /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray_1(collection) ? _arrayFilter : _baseFilter; return func(collection, _baseIteratee(predicate, 3)); } var filter_1 = filter; /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike_1(collection) ? Array(collection.length) : []; _baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } var _baseMap = baseMap; /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray_1(collection) ? _arrayMap : _baseMap; return func(collection, _baseIteratee(iteratee, 3)); } var map_1 = map; /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } var _arrayReduce = arrayReduce; /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } var _baseReduce = baseReduce; /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray_1(collection) ? _arrayReduce : _baseReduce, initAccum = arguments.length < 3; return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEach); } var reduce_1 = reduce; /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol_1(value)) { return NAN; } if (isObject_1(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject_1(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } var toNumber_1 = toNumber; /** Used as references for various `Number` constants. */ var INFINITY$2 = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber_1(value); if (value === INFINITY$2 || value === -INFINITY$2) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } var toFinite_1 = toFinite; /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite_1(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } var toInteger_1 = toInteger; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$1 = Math.max; /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$1(length + index, 0); } return _baseIndexOf(array, value, index); } var indexOf_1 = indexOf; /** `Object#toString` result references. */ var numberTag$4 = '[object Number]'; /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike_1(value) && _baseGetTag(value) == numberTag$4); } var isNumber_1 = isNumber; /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN$1(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber_1(value) && value != +value; } var _isNaN = isNaN$1; /** `Object#toString` result references. */ var mapTag$6 = '[object Map]', setTag$6 = '[object Set]'; /** Used for built-in method references. */ var objectProto$g = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$e = objectProto$g.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike_1(value) && (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) { return !value.length; } var tag = _getTag(value); if (tag == mapTag$6 || tag == setTag$6) { return !value.size; } if (_isPrototype(value)) { return !_baseKeys(value).length; } for (var key in value) { if (hasOwnProperty$e.call(value, key)) { return false; } } return true; } var isEmpty_1 = isEmpty; /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return _baseIsEqual(value, other); } var isEqual_1 = isEqual; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } var isUndefined_1 = isUndefined; /** `Object#toString` result references. */ var stringTag$4 = '[object String]'; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$4); } var isString_1 = isString; /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike_1(collection)) { var iteratee = _baseIteratee(predicate, 3); collection = keys_1(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } var _createFind = createFind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$2 = Math.max; /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger_1(fromIndex); if (index < 0) { index = nativeMax$2(length + index, 0); } return _baseFindIndex(array, _baseIteratee(predicate, 3), index); } var findIndex_1 = findIndex; /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = _createFind(findIndex_1); var find_1 = find; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : _baseSlice(array, start, end); } var _castSlice = castSlice; /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsEndIndex = charsEndIndex; /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } var _charsStartIndex = charsStartIndex; /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } var _asciiToArray = asciiToArray; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsVarRange = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } var _hasUnicode = hasUnicode; /** Used to compose unicode character classes. */ var rsAstralRange$1 = '\\ud800-\\udfff', rsComboMarksRange$1 = '\\u0300-\\u036f', reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, rsVarRange$1 = '\\ufe0e\\ufe0f'; /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange$1 + ']', rsCombo = '[' + rsComboRange$1 + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange$1 + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsZWJ$1 = '\\u200d'; /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange$1 + ']?', rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } var _unicodeToArray = unicodeToArray; /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return _hasUnicode(string) ? _unicodeToArray(string) : _asciiToArray(string); } var _stringToArray = stringToArray; /** Used to match leading and trailing whitespace. */ var reTrim$1 = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString_1(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim$1, ''); } if (!string || !(chars = _baseToString(chars))) { return string; } var strSymbols = _stringToArray(string), chrSymbols = _stringToArray(chars), start = _charsStartIndex(strSymbols, chrSymbols), end = _charsEndIndex(strSymbols, chrSymbols) + 1; return _castSlice(strSymbols, start, end).join(''); } var trim_1 = trim; /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject_1(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike_1(object) && _isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq_1(object[index], value); } return false; } var _isIterateeCall = isIterateeCall; /** Used for built-in method references. */ var objectProto$h = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$f = objectProto$h.hasOwnProperty; /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = _baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && _isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn_1(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq_1(value, objectProto$h[key]) && !hasOwnProperty$f.call(object, key))) { object[key] = source[key]; } } } return object; }); var defaults_1 = defaults; /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq_1(object[key], value)) || (value === undefined && !(key in object))) { _baseAssignValue(object, key, value); } } var _assignMergeValue = assignMergeValue; /** * Gets the value at `key`, unless `key` is "__proto__". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key == '__proto__') { return; } return object[key]; } var _safeGet = safeGet; /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return _copyObject(value, keysIn_1(value)); } var toPlainObject_1 = toPlainObject; /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = _safeGet(object, key), srcValue = _safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { _assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray_1(srcValue), isBuff = !isArr && isBuffer_1(srcValue), isTyped = !isArr && !isBuff && isTypedArray_1(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray_1(objValue)) { newValue = objValue; } else if (isArrayLikeObject_1(objValue)) { newValue = _copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = _cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = _cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject_1(srcValue) || isArguments_1(srcValue)) { newValue = objValue; if (isArguments_1(objValue)) { newValue = toPlainObject_1(objValue); } else if (!isObject_1(objValue) || isFunction_1(objValue)) { newValue = _initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } _assignMergeValue(object, key, newValue); } var _baseMergeDeep = baseMergeDeep; /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } _baseFor(source, function(srcValue, key) { if (isObject_1(srcValue)) { stack || (stack = new _Stack); _baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(_safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } _assignMergeValue(object, key, newValue); } }, keysIn_1); } var _baseMerge = baseMerge; /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return _baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && _isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } var _createAssigner = createAssigner; /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = _createAssigner(function(object, source, srcIndex) { _baseMerge(object, source, srcIndex); }); var merge_1 = merge; function valToNumber(v) { if (isNumber_1(v)) { return v; } else if (isString_1(v)) { return parseFloat(v); } else if (Array.isArray(v)) { return map_1(v, valToNumber); } throw new Error('The value should be a number, a parseable string or an array of those.'); } var valToNumber_1 = valToNumber; function filterState(state, filters) { var partialState = {}; var attributeFilters = filter_1(filters, function(f) { return f.indexOf('attribute:') !== -1; }); var attributes = map_1(attributeFilters, function(aF) { return aF.split(':')[1]; }); if (indexOf_1(attributes, '*') === -1) { forEach_1(attributes, function(attr) { if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) { if (!partialState.facetsRefinements) partialState.facetsRefinements = {}; partialState.facetsRefinements[attr] = state.facetsRefinements[attr]; } if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) { if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {}; partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr]; } if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) { if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {}; partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr]; } var numericRefinements = state.getNumericRefinements(attr); if (!isEmpty_1(numericRefinements)) { if (!partialState.numericRefinements) partialState.numericRefinements = {}; partialState.numericRefinements[attr] = state.numericRefinements[attr]; } }); } else { if (!isEmpty_1(state.numericRefinements)) { partialState.numericRefinements = state.numericRefinements; } if (!isEmpty_1(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements; if (!isEmpty_1(state.disjunctiveFacetsRefinements)) { partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements; } if (!isEmpty_1(state.hierarchicalFacetsRefinements)) { partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements; } } var searchParameters = filter_1( filters, function(f) { return f.indexOf('attribute:') === -1; } ); forEach_1( searchParameters, function(parameterKey) { partialState[parameterKey] = state[parameterKey]; } ); return partialState; } var filterState_1 = filterState; /** * Functions to manipulate refinement lists * * The RefinementList is not formally defined through a prototype but is based * on a specific structure. * * @module SearchParameters.refinementList * * @typedef {string[]} SearchParameters.refinementList.Refinements * @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList */ var lib = { /** * Adds a refinement to a RefinementList * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement, if the value is not a string it will be converted * @return {RefinementList} a new and updated refinement list */ addRefinement: function addRefinement(refinementList, attribute, value) { if (lib.isRefined(refinementList, attribute, value)) { return refinementList; } var valueAsString = '' + value; var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString); var mod = {}; mod[attribute] = facetRefinement; return defaults_1({}, mod, refinementList); }, /** * Removes refinement(s) for an attribute: * - if the value is specified removes the refinement for the value on the attribute * - if no value is specified removes all the refinements for this attribute * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} [value] the value of the refinement * @return {RefinementList} a new and updated refinement lst */ removeRefinement: function removeRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) { return lib.clearRefinement(refinementList, attribute); } var valueAsString = '' + value; return lib.clearRefinement(refinementList, function(v, f) { return attribute === f && valueAsString === v; }); }, /** * Toggles the refinement value for an attribute. * @param {RefinementList} refinementList the initial list * @param {string} attribute the attribute to refine * @param {string} value the value of the refinement * @return {RefinementList} a new and updated list */ toggleRefinement: function toggleRefinement(refinementList, attribute, value) { if (isUndefined_1(value)) throw new Error('toggleRefinement should be used with a value'); if (lib.isRefined(refinementList, attribute, value)) { return lib.removeRefinement(refinementList, attribute, value); } return lib.addRefinement(refinementList, attribute, value); }, /** * Clear all or parts of a RefinementList. Depending on the arguments, three * kinds of behavior can happen: * - if no attribute is provided: clears the whole list * - if an attribute is provided as a string: clears the list for the specific attribute * - if an attribute is provided as a function: discards the elements for which the function returns true * @param {RefinementList} refinementList the initial list * @param {string} [attribute] the attribute or function to discard * @param {string} [refinementType] optional parameter to give more context to the attribute function * @return {RefinementList} a new and updated refinement list */ clearRefinement: function clearRefinement(refinementList, attribute, refinementType) { if (isUndefined_1(attribute)) { if (isEmpty_1(refinementList)) return refinementList; return {}; } else if (isString_1(attribute)) { if (isEmpty_1(refinementList[attribute])) return refinementList; return omit_1(refinementList, attribute); } else if (isFunction_1(attribute)) { var hasChanged = false; var newRefinementList = reduce_1(refinementList, function(memo, values, key) { var facetList = filter_1(values, function(value) { return !attribute(value, key, refinementType); }); if (!isEmpty_1(facetList)) { if (facetList.length !== values.length) hasChanged = true; memo[key] = facetList; } else hasChanged = true; return memo; }, {}); if (hasChanged) return newRefinementList; return refinementList; } }, /** * Test if the refinement value is used for the attribute. If no refinement value * is provided, test if the refinementList contains any refinement for the * given attribute. * @param {RefinementList} refinementList the list of refinement * @param {string} attribute name of the attribute * @param {string} [refinementValue] value of the filter/refinement * @return {boolean} */ isRefined: function isRefined(refinementList, attribute, refinementValue) { var indexOf = indexOf_1; var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0; if (isUndefined_1(refinementValue) || !containsRefinements) { return containsRefinements; } var refinementValueAsString = '' + refinementValue; return indexOf(refinementList[attribute], refinementValueAsString) !== -1; } }; var RefinementList = lib; /** * like _.find but using _.isEqual to be able to use it * to find arrays. * @private * @param {any[]} array array to search into * @param {any} searchedValue the value we're looking for * @return {any} the searched value or undefined */ function findArray(array, searchedValue) { return find_1(array, function(currentValue) { return isEqual_1(currentValue, searchedValue); }); } /** * The facet list is the structure used to store the list of values used to * filter a single attribute. * @typedef {string[]} SearchParameters.FacetList */ /** * Structure to store numeric filters with the operator as the key. The supported operators * are `=`, `>`, `<`, `>=`, `<=` and `!=`. * @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList */ /** * SearchParameters is the data structure that contains all the information * usable for making a search to Algolia API. It doesn't do the search itself, * nor does it contains logic about the parameters. * It is an immutable object, therefore it has been created in a way that each * changes does not change the object itself but returns a copy with the * modification. * This object should probably not be instantiated outside of the helper. It will * be provided when needed. This object is documented for reference as you'll * get it from events generated by the {@link AlgoliaSearchHelper}. * If need be, instantiate the Helper from the factory function {@link SearchParameters.make} * @constructor * @classdesc contains all the parameters of a search * @param {object|SearchParameters} newParameters existing parameters or partial object * for the properties of a new SearchParameters * @see SearchParameters.make * @example <caption>SearchParameters of the first query in * <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption> { "query": "", "disjunctiveFacets": [ "customerReviewCount", "category", "salePrice_range", "manufacturer" ], "maxValuesPerFacet": 30, "page": 0, "hitsPerPage": 10, "facets": [ "type", "shipping" ] } */ function SearchParameters(newParameters) { var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {}; /** * Targeted index. This parameter is mandatory. * @member {string} */ this.index = params.index || ''; // Query /** * Query string of the instant search. The empty string is a valid query. * @member {string} * @see https://www.algolia.com/doc/rest#param-query */ this.query = params.query || ''; // Facets /** * This attribute contains the list of all the conjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.facets = params.facets || []; /** * This attribute contains the list of all the disjunctive facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * @member {string[]} */ this.disjunctiveFacets = params.disjunctiveFacets || []; /** * This attribute contains the list of all the hierarchical facets * used. This list will be added to requested facets in the * [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia. * Hierarchical facets are a sub type of disjunctive facets that * let you filter faceted attributes hierarchically. * @member {string[]|object[]} */ this.hierarchicalFacets = params.hierarchicalFacets || []; // Refinements /** * This attribute contains all the filters that need to be * applied on the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsRefinements = params.facetsRefinements || {}; /** * This attribute contains all the filters that need to be * excluded from the conjunctive facets. Each facet must be properly * defined in the `facets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters excluded for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.facetsExcludes = params.facetsExcludes || {}; /** * This attribute contains all the filters that need to be * applied on the disjunctive facets. Each facet must be properly * defined in the `disjunctiveFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {}; /** * This attribute contains all the filters that need to be * applied on the numeric attributes. * * The key is the name of the attribute, and the value is the * filters to apply to this attribute. * * When querying algolia, the values stored in this attribute will * be translated into the `numericFilters` attribute. * @member {Object.<string, SearchParameters.OperatorList>} */ this.numericRefinements = params.numericRefinements || {}; /** * This attribute contains all the tags used to refine the query. * * When querying algolia, the values stored in this attribute will * be translated into the `tagFilters` attribute. * @member {string[]} */ this.tagRefinements = params.tagRefinements || []; /** * This attribute contains all the filters that need to be * applied on the hierarchical facets. Each facet must be properly * defined in the `hierarchicalFacets` attribute. * * The key is the name of the facet, and the `FacetList` contains all * filters selected for the associated facet name. The FacetList values * are structured as a string that contain the values for each level * separated by the configured separator. * * When querying algolia, the values stored in this attribute will * be translated into the `facetFilters` attribute. * @member {Object.<string, SearchParameters.FacetList>} */ this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {}; /** * Contains the numeric filters in the raw format of the Algolia API. Setting * this parameter is not compatible with the usage of numeric filters methods. * @see https://www.algolia.com/doc/javascript#numericFilters * @member {string} */ this.numericFilters = params.numericFilters; /** * Contains the tag filters in the raw format of the Algolia API. Setting this * parameter is not compatible with the of the add/remove/toggle methods of the * tag api. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.tagFilters = params.tagFilters; /** * Contains the optional tag filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalTagFilters = params.optionalTagFilters; /** * Contains the optional facet filters in the raw format of the Algolia API. * @see https://www.algolia.com/doc/rest#param-tagFilters * @member {string} */ this.optionalFacetFilters = params.optionalFacetFilters; // Misc. parameters /** * Number of hits to be returned by the search API * @member {number} * @see https://www.algolia.com/doc/rest#param-hitsPerPage */ this.hitsPerPage = params.hitsPerPage; /** * Number of values for each faceted attribute * @member {number} * @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet */ this.maxValuesPerFacet = params.maxValuesPerFacet; /** * The current page number * @member {number} * @see https://www.algolia.com/doc/rest#param-page */ this.page = params.page || 0; /** * How the query should be treated by the search engine. * Possible values: prefixAll, prefixLast, prefixNone * @see https://www.algolia.com/doc/rest#param-queryType * @member {string} */ this.queryType = params.queryType; /** * How the typo tolerance behave in the search engine. * Possible values: true, false, min, strict * @see https://www.algolia.com/doc/rest#param-typoTolerance * @member {string} */ this.typoTolerance = params.typoTolerance; /** * Number of characters to wait before doing one character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo * @member {number} */ this.minWordSizefor1Typo = params.minWordSizefor1Typo; /** * Number of characters to wait before doing a second character replacement. * @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos * @member {number} */ this.minWordSizefor2Typos = params.minWordSizefor2Typos; /** * Configure the precision of the proximity ranking criterion * @see https://www.algolia.com/doc/rest#param-minProximity */ this.minProximity = params.minProximity; /** * Should the engine allow typos on numerics. * @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens * @member {boolean} */ this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens; /** * Should the plurals be ignored * @see https://www.algolia.com/doc/rest#param-ignorePlurals * @member {boolean} */ this.ignorePlurals = params.ignorePlurals; /** * Restrict which attribute is searched. * @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes * @member {string} */ this.restrictSearchableAttributes = params.restrictSearchableAttributes; /** * Enable the advanced syntax. * @see https://www.algolia.com/doc/rest#param-advancedSyntax * @member {boolean} */ this.advancedSyntax = params.advancedSyntax; /** * Enable the analytics * @see https://www.algolia.com/doc/rest#param-analytics * @member {boolean} */ this.analytics = params.analytics; /** * Tag of the query in the analytics. * @see https://www.algolia.com/doc/rest#param-analyticsTags * @member {string} */ this.analyticsTags = params.analyticsTags; /** * Enable the synonyms * @see https://www.algolia.com/doc/rest#param-synonyms * @member {boolean} */ this.synonyms = params.synonyms; /** * Should the engine replace the synonyms in the highlighted results. * @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight * @member {boolean} */ this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight; /** * Add some optional words to those defined in the dashboard * @see https://www.algolia.com/doc/rest#param-optionalWords * @member {string} */ this.optionalWords = params.optionalWords; /** * Possible values are "lastWords" "firstWords" "allOptional" "none" (default) * @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults * @member {string} */ this.removeWordsIfNoResults = params.removeWordsIfNoResults; /** * List of attributes to retrieve * @see https://www.algolia.com/doc/rest#param-attributesToRetrieve * @member {string} */ this.attributesToRetrieve = params.attributesToRetrieve; /** * List of attributes to highlight * @see https://www.algolia.com/doc/rest#param-attributesToHighlight * @member {string} */ this.attributesToHighlight = params.attributesToHighlight; /** * Code to be embedded on the left part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPreTag * @member {string} */ this.highlightPreTag = params.highlightPreTag; /** * Code to be embedded on the right part of the highlighted results * @see https://www.algolia.com/doc/rest#param-highlightPostTag * @member {string} */ this.highlightPostTag = params.highlightPostTag; /** * List of attributes to snippet * @see https://www.algolia.com/doc/rest#param-attributesToSnippet * @member {string} */ this.attributesToSnippet = params.attributesToSnippet; /** * Enable the ranking informations in the response, set to 1 to activate * @see https://www.algolia.com/doc/rest#param-getRankingInfo * @member {number} */ this.getRankingInfo = params.getRankingInfo; /** * Remove duplicates based on the index setting attributeForDistinct * @see https://www.algolia.com/doc/rest#param-distinct * @member {boolean|number} */ this.distinct = params.distinct; /** * Center of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundLatLng * @member {string} */ this.aroundLatLng = params.aroundLatLng; /** * Center of the search, retrieve from the user IP. * @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP * @member {boolean} */ this.aroundLatLngViaIP = params.aroundLatLngViaIP; /** * Radius of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundRadius * @member {number} */ this.aroundRadius = params.aroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-aroundPrecision * @member {number} */ this.minimumAroundRadius = params.minimumAroundRadius; /** * Precision of the geo search. * @see https://www.algolia.com/doc/rest#param-minimumAroundRadius * @member {number} */ this.aroundPrecision = params.aroundPrecision; /** * Geo search inside a box. * @see https://www.algolia.com/doc/rest#param-insideBoundingBox * @member {string} */ this.insideBoundingBox = params.insideBoundingBox; /** * Geo search inside a polygon. * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.insidePolygon = params.insidePolygon; /** * Allows to specify an ellipsis character for the snippet when we truncate the text * (added before and after if truncated). * The default value is an empty string and we recommend to set it to "…" * @see https://www.algolia.com/doc/rest#param-insidePolygon * @member {string} */ this.snippetEllipsisText = params.snippetEllipsisText; /** * Allows to specify some attributes name on which exact won't be applied. * Attributes are separated with a comma (for example "name,address" ), you can also use a * JSON string array encoding (for example encodeURIComponent('["name","address"]') ). * By default the list is empty. * @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes * @member {string|string[]} */ this.disableExactOnAttributes = params.disableExactOnAttributes; /** * Applies 'exact' on single word queries if the word contains at least 3 characters * and is not a stop word. * Can take two values: true or false. * By default, its set to false. * @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery * @member {boolean} */ this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery; // Undocumented parameters, still needed otherwise we fail this.offset = params.offset; this.length = params.length; var self = this; forOwn_1(params, function checkForUnknownParameter(paramValue, paramName) { if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) { self[paramName] = paramValue; } }); } /** * List all the properties in SearchParameters and therefore all the known Algolia properties * This doesn't contain any beta/hidden features. * @private */ SearchParameters.PARAMETERS = keys_1(new SearchParameters()); /** * @private * @param {object} partialState full or part of a state * @return {object} a new object with the number keys as number */ SearchParameters._parseNumbers = function(partialState) { // Do not reparse numbers in SearchParameters, they ought to be parsed already if (partialState instanceof SearchParameters) return partialState; var numbers = {}; var numberKeys = [ 'aroundPrecision', 'aroundRadius', 'getRankingInfo', 'minWordSizefor2Typos', 'minWordSizefor1Typo', 'page', 'maxValuesPerFacet', 'distinct', 'minimumAroundRadius', 'hitsPerPage', 'minProximity' ]; forEach_1(numberKeys, function(k) { var value = partialState[k]; if (isString_1(value)) { var parsedValue = parseFloat(value); numbers[k] = _isNaN(parsedValue) ? value : parsedValue; } }); // there's two formats of insideBoundingBox, we need to parse // the one which is an array of float geo rectangles if (Array.isArray(partialState.insideBoundingBox)) { numbers.insideBoundingBox = partialState.insideBoundingBox.map(function(geoRect) { return geoRect.map(function(value) { return parseFloat(value); }); }); } if (partialState.numericRefinements) { var numericRefinements = {}; forEach_1(partialState.numericRefinements, function(operators, attribute) { numericRefinements[attribute] = {}; forEach_1(operators, function(values, operator) { var parsedValues = map_1(values, function(v) { if (Array.isArray(v)) { return map_1(v, function(vPrime) { if (isString_1(vPrime)) { return parseFloat(vPrime); } return vPrime; }); } else if (isString_1(v)) { return parseFloat(v); } return v; }); numericRefinements[attribute][operator] = parsedValues; }); }); numbers.numericRefinements = numericRefinements; } return merge_1({}, partialState, numbers); }; /** * Factory for SearchParameters * @param {object|SearchParameters} newParameters existing parameters or partial * object for the properties of a new SearchParameters * @return {SearchParameters} frozen instance of SearchParameters */ SearchParameters.make = function makeSearchParameters(newParameters) { var instance = new SearchParameters(newParameters); forEach_1(newParameters.hierarchicalFacets, function(facet) { if (facet.rootPath) { var currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) { instance = instance.clearRefinements(facet.name); } // get it again in case it has been cleared currentRefinement = instance.getHierarchicalRefinement(facet.name); if (currentRefinement.length === 0) { instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath); } } }); return instance; }; /** * Validates the new parameters based on the previous state * @param {SearchParameters} currentState the current state * @param {object|SearchParameters} parameters the new parameters to set * @return {Error|null} Error if the modification is invalid, null otherwise */ SearchParameters.validate = function(currentState, parameters) { var params = parameters || {}; if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) { return new Error( '[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' + 'an error, if it is really what you want, you should first clear the tags with clearTags method.'); } if (currentState.tagRefinements.length > 0 && params.tagFilters) { return new Error( '[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' + 'an error, if it is not, you should first clear the tags with clearTags method.'); } if (currentState.numericFilters && params.numericRefinements && !isEmpty_1(params.numericRefinements)) { return new Error( "[Numeric filters] Can't switch from the advanced to the managed API. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } if (!isEmpty_1(currentState.numericRefinements) && params.numericFilters) { return new Error( "[Numeric filters] Can't switch from the managed API to the advanced. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.'); } return null; }; SearchParameters.prototype = { constructor: SearchParameters, /** * Remove all refinements (disjunctive + conjunctive + excludes + numeric filters) * @method * @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {SearchParameters} */ clearRefinements: function clearRefinements(attribute) { var clear = RefinementList.clearRefinement; var patch = { numericRefinements: this._clearNumericRefinements(attribute), facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'), facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'), disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'), hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet') }; if (patch.numericRefinements === this.numericRefinements && patch.facetsRefinements === this.facetsRefinements && patch.facetsExcludes === this.facetsExcludes && patch.disjunctiveFacetsRefinements === this.disjunctiveFacetsRefinements && patch.hierarchicalFacetsRefinements === this.hierarchicalFacetsRefinements) { return this; } return this.setQueryParameters(patch); }, /** * Remove all the refined tags from the SearchParameters * @method * @return {SearchParameters} */ clearTags: function clearTags() { if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this; return this.setQueryParameters({ tagFilters: undefined, tagRefinements: [] }); }, /** * Set the index. * @method * @param {string} index the index name * @return {SearchParameters} */ setIndex: function setIndex(index) { if (index === this.index) return this; return this.setQueryParameters({ index: index }); }, /** * Query setter * @method * @param {string} newQuery value for the new query * @return {SearchParameters} */ setQuery: function setQuery(newQuery) { if (newQuery === this.query) return this; return this.setQueryParameters({ query: newQuery }); }, /** * Page setter * @method * @param {number} newPage new page number * @return {SearchParameters} */ setPage: function setPage(newPage) { if (newPage === this.page) return this; return this.setQueryParameters({ page: newPage }); }, /** * Facets setter * The facets are the simple facets, used for conjunctive (and) faceting. * @method * @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting * @return {SearchParameters} */ setFacets: function setFacets(facets) { return this.setQueryParameters({ facets: facets }); }, /** * Disjunctive facets setter * Change the list of disjunctive (or) facets the helper chan handle. * @method * @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting * @return {SearchParameters} */ setDisjunctiveFacets: function setDisjunctiveFacets(facets) { return this.setQueryParameters({ disjunctiveFacets: facets }); }, /** * HitsPerPage setter * Hits per page represents the number of hits retrieved for this query * @method * @param {number} n number of hits retrieved per page of results * @return {SearchParameters} */ setHitsPerPage: function setHitsPerPage(n) { if (this.hitsPerPage === n) return this; return this.setQueryParameters({ hitsPerPage: n }); }, /** * typoTolerance setter * Set the value of typoTolerance * @method * @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict") * @return {SearchParameters} */ setTypoTolerance: function setTypoTolerance(typoTolerance) { if (this.typoTolerance === typoTolerance) return this; return this.setQueryParameters({ typoTolerance: typoTolerance }); }, /** * Add a numeric filter for a given attribute * When value is an array, they are combined with OR * When value is a single value, it will combined with AND * @method * @param {string} attribute attribute to set the filter on * @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number | number[]} value value of the filter * @return {SearchParameters} * @example * // for price = 50 or 40 * searchparameter.addNumericRefinement('price', '=', [50, 40]); * @example * // for size = 38 and 40 * searchparameter.addNumericRefinement('size', '=', 38); * searchparameter.addNumericRefinement('size', '=', 40); */ addNumericRefinement: function(attribute, operator, v) { var value = valToNumber_1(v); if (this.isNumericRefined(attribute, operator, value)) return this; var mod = merge_1({}, this.numericRefinements); mod[attribute] = merge_1({}, mod[attribute]); if (mod[attribute][operator]) { // Array copy mod[attribute][operator] = mod[attribute][operator].slice(); // Add the element. Concat can't be used here because value can be an array. mod[attribute][operator].push(value); } else { mod[attribute][operator] = [value]; } return this.setQueryParameters({ numericRefinements: mod }); }, /** * Get the list of conjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getConjunctiveRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsRefinements[facetName] || []; }, /** * Get the list of disjunctive refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getDisjunctiveRefinements: function(facetName) { if (!this.isDisjunctiveFacet(facetName)) { throw new Error( facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration' ); } return this.disjunctiveFacetsRefinements[facetName] || []; }, /** * Get the list of hierarchical refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getHierarchicalRefinement: function(facetName) { // we send an array but we currently do not support multiple // hierarchicalRefinements for a hierarchicalFacet return this.hierarchicalFacetsRefinements[facetName] || []; }, /** * Get the list of exclude refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {string[]} list of refinements */ getExcludeRefinements: function(facetName) { if (!this.isConjunctiveFacet(facetName)) { throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration'); } return this.facetsExcludes[facetName] || []; }, /** * Remove all the numeric filter for a given (attribute, operator) * @method * @param {string} attribute attribute to set the filter on * @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=) * @param {number} [number] the value to be removed * @return {SearchParameters} */ removeNumericRefinement: function(attribute, operator, paramValue) { if (paramValue !== undefined) { var paramValueAsNumber = valToNumber_1(paramValue); if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator && isEqual_1(value.val, paramValueAsNumber); }) }); } else if (operator !== undefined) { if (!this.isNumericRefined(attribute, operator)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute && value.op === operator; }) }); } if (!this.isNumericRefined(attribute)) return this; return this.setQueryParameters({ numericRefinements: this._clearNumericRefinements(function(value, key) { return key === attribute; }) }); }, /** * Get the list of numeric refinements for a single facet * @param {string} facetName name of the attribute used for faceting * @return {SearchParameters.OperatorList[]} list of refinements */ getNumericRefinements: function(facetName) { return this.numericRefinements[facetName] || {}; }, /** * Return the current refinement for the (attribute, operator) * @param {string} attribute attribute in the record * @param {string} operator operator applied on the refined values * @return {Array.<number|number[]>} refined values */ getNumericRefinement: function(attribute, operator) { return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator]; }, /** * Clear numeric filters. * @method * @private * @param {string|SearchParameters.clearCallback} [attribute] optional string or function * - If not given, means to clear all the filters. * - If `string`, means to clear all refinements for the `attribute` named filter. * - If `function`, means to clear all the refinements that return truthy values. * @return {Object.<string, OperatorList>} */ _clearNumericRefinements: function _clearNumericRefinements(attribute) { if (isUndefined_1(attribute)) { if (isEmpty_1(this.numericRefinements)) return this.numericRefinements; return {}; } else if (isString_1(attribute)) { if (isEmpty_1(this.numericRefinements[attribute])) return this.numericRefinements; return omit_1(this.numericRefinements, attribute); } else if (isFunction_1(attribute)) { var hasChanged = false; var newNumericRefinements = reduce_1(this.numericRefinements, function(memo, operators, key) { var operatorList = {}; forEach_1(operators, function(values, operator) { var outValues = []; forEach_1(values, function(value) { var predicateResult = attribute({val: value, op: operator}, key, 'numeric'); if (!predicateResult) outValues.push(value); }); if (!isEmpty_1(outValues)) { if (outValues.length !== values.length) hasChanged = true; operatorList[operator] = outValues; } else hasChanged = true; }); if (!isEmpty_1(operatorList)) memo[key] = operatorList; return memo; }, {}); if (hasChanged) return newNumericRefinements; return this.numericRefinements; } }, /** * Add a facet to the facets attribute of the helper configuration, if it * isn't already present. * @method * @param {string} facet facet name to add * @return {SearchParameters} */ addFacet: function addFacet(facet) { if (this.isConjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ facets: this.facets.concat([facet]) }); }, /** * Add a disjunctive facet to the disjunctiveFacets attribute of the helper * configuration, if it isn't already present. * @method * @param {string} facet disjunctive facet name to add * @return {SearchParameters} */ addDisjunctiveFacet: function addDisjunctiveFacet(facet) { if (this.isDisjunctiveFacet(facet)) { return this; } return this.setQueryParameters({ disjunctiveFacets: this.disjunctiveFacets.concat([facet]) }); }, /** * Add a hierarchical facet to the hierarchicalFacets attribute of the helper * configuration. * @method * @param {object} hierarchicalFacet hierarchical facet to add * @return {SearchParameters} * @throws will throw an error if a hierarchical facet with the same name was already declared */ addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) { if (this.isHierarchicalFacet(hierarchicalFacet.name)) { throw new Error( 'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`'); } return this.setQueryParameters({ hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet]) }); }, /** * Add a refinement on a "normal" facet * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addFacetRefinement: function addFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value) }); }, /** * Exclude a value from a "normal" facet * @method * @param {string} facet attribute to apply the exclusion on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addExcludeRefinement: function addExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value) }); }, /** * Adds a refinement on a disjunctive facet. * @method * @param {string} facet attribute to apply the faceting on * @param {string} value value of the attribute (will be converted to string) * @return {SearchParameters} */ addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.addRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * addTagRefinement adds a tag to the list used to filter the results * @param {string} tag tag to be added * @return {SearchParameters} */ addTagRefinement: function addTagRefinement(tag) { if (this.isTagRefined(tag)) return this; var modification = { tagRefinements: this.tagRefinements.concat(tag) }; return this.setQueryParameters(modification); }, /** * Remove a facet from the facets attribute of the helper configuration, if it * is present. * @method * @param {string} facet facet name to remove * @return {SearchParameters} */ removeFacet: function removeFacet(facet) { if (!this.isConjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ facets: filter_1(this.facets, function(f) { return f !== facet; }) }); }, /** * Remove a disjunctive facet from the disjunctiveFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet disjunctive facet name to remove * @return {SearchParameters} */ removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) { if (!this.isDisjunctiveFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ disjunctiveFacets: filter_1(this.disjunctiveFacets, function(f) { return f !== facet; }) }); }, /** * Remove a hierarchical facet from the hierarchicalFacets attribute of the * helper configuration, if it is present. * @method * @param {string} facet hierarchical facet name to remove * @return {SearchParameters} */ removeHierarchicalFacet: function removeHierarchicalFacet(facet) { if (!this.isHierarchicalFacet(facet)) { return this; } return this.clearRefinements(facet).setQueryParameters({ hierarchicalFacets: filter_1(this.hierarchicalFacets, function(f) { return f.name !== facet; }) }); }, /** * Remove a refinement set on facet. If a value is provided, it will clear the * refinement for the given value, otherwise it will clear all the refinement * values for the faceted attribute. * @method * @param {string} facet name of the attribute used for faceting * @param {string} [value] value used to filter * @return {SearchParameters} */ removeFacetRefinement: function removeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this; return this.setQueryParameters({ facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value) }); }, /** * Remove a negative refinement on a facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeExcludeRefinement: function removeExcludeRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this; return this.setQueryParameters({ facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value) }); }, /** * Remove a refinement on a disjunctive facet * @method * @param {string} facet name of the attribute used for faceting * @param {string} value value used to filter * @return {SearchParameters} */ removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this; return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.removeRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Remove a tag from the list of tag refinements * @method * @param {string} tag the tag to remove * @return {SearchParameters} */ removeTagRefinement: function removeTagRefinement(tag) { if (!this.isTagRefined(tag)) return this; var modification = { tagRefinements: filter_1(this.tagRefinements, function(t) { return t !== tag; }) }; return this.setQueryParameters(modification); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper * @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement} */ toggleRefinement: function toggleRefinement(facet, value) { return this.toggleFacetRefinement(facet, value); }, /** * Generic toggle refinement method to use with facet, disjunctive facets * and hierarchical facets * @param {string} facet the facet to refine * @param {string} value the associated value * @return {SearchParameters} * @throws will throw an error if the facet is not declared in the settings of the helper */ toggleFacetRefinement: function toggleFacetRefinement(facet, value) { if (this.isHierarchicalFacet(facet)) { return this.toggleHierarchicalFacetRefinement(facet, value); } else if (this.isConjunctiveFacet(facet)) { return this.toggleConjunctiveFacetRefinement(facet, value); } else if (this.isDisjunctiveFacet(facet)) { return this.toggleDisjunctiveFacetRefinement(facet, value); } throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets'); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return this.setQueryParameters({ facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return this.setQueryParameters({ disjunctiveFacetsRefinements: RefinementList.toggleRefinement( this.disjunctiveFacetsRefinements, facet, value) }); }, /** * Switch the refinement applied over a facet/value * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {SearchParameters} */ toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet)); var mod = {}; var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined && this.hierarchicalFacetsRefinements[facet].length > 0 && ( // remove current refinement: // refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0] === value || // remove a parent refinement of the current refinement: // - refinement was 'beer > IPA > Flying dog' // - call is toggleRefine('beer > IPA') // - refinement should be `beer` this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0 ); if (upOneOrMultipleLevel) { if (value.indexOf(separator) === -1) { // go back to root level mod[facet] = []; } else { mod[facet] = [value.slice(0, value.lastIndexOf(separator))]; } } else { mod[facet] = [value]; } return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Adds a refinement on a hierarchical facet. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is refined */ addHierarchicalFacetRefinement: function(facet, path) { if (this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is already refined.'); } var mod = {}; mod[facet] = [path]; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {SearchParameter} the new state * @throws Error if the facet is not defined or if the facet is not refined */ removeHierarchicalFacetRefinement: function(facet) { if (!this.isHierarchicalFacetRefined(facet)) { throw new Error(facet + ' is not refined.'); } var mod = {}; mod[facet] = []; return this.setQueryParameters({ hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements) }); }, /** * Switch the tag refinement * @method * @param {string} tag the tag to remove or add * @return {SearchParameters} */ toggleTagRefinement: function toggleTagRefinement(tag) { if (this.isTagRefined(tag)) { return this.removeTagRefinement(tag); } return this.addTagRefinement(tag); }, /** * Test if the facet name is from one of the disjunctive facets * @method * @param {string} facet facet name to test * @return {boolean} */ isDisjunctiveFacet: function(facet) { return indexOf_1(this.disjunctiveFacets, facet) > -1; }, /** * Test if the facet name is from one of the hierarchical facets * @method * @param {string} facetName facet name to test * @return {boolean} */ isHierarchicalFacet: function(facetName) { return this.getHierarchicalFacetByName(facetName) !== undefined; }, /** * Test if the facet name is from one of the conjunctive/normal facets * @method * @param {string} facet facet name to test * @return {boolean} */ isConjunctiveFacet: function(facet) { return indexOf_1(this.facets, facet) > -1; }, /** * Returns true if the facet is refined, either for a specific value or in * general. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value, optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isFacetRefined: function isFacetRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsRefinements, facet, value); }, /** * Returns true if the facet contains exclusions or if a specific value is * excluded. * * @method * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} returns true if refined */ isExcludeRefined: function isExcludeRefined(facet, value) { if (!this.isConjunctiveFacet(facet)) { throw new Error(facet + ' is not defined in the facets attribute of the helper configuration'); } return RefinementList.isRefined(this.facetsExcludes, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) { if (!this.isDisjunctiveFacet(facet)) { throw new Error( facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration'); } return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value); }, /** * Returns true if the facet contains a refinement, or if a value passed is a * refinement for the facet. * @method * @param {string} facet name of the attribute for used for faceting * @param {string} value optional, will test if the value is used for refinement * if there is one, otherwise will test if the facet contains any refinement * @return {boolean} */ isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) { if (!this.isHierarchicalFacet(facet)) { throw new Error( facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration'); } var refinements = this.getHierarchicalRefinement(facet); if (!value) { return refinements.length > 0; } return indexOf_1(refinements, value) !== -1; }, /** * Test if the triple (attribute, operator, value) is already refined. * If only the attribute and the operator are provided, it tests if the * contains any refinement value. * @method * @param {string} attribute attribute for which the refinement is applied * @param {string} [operator] operator of the refinement * @param {string} [value] value of the refinement * @return {boolean} true if it is refined */ isNumericRefined: function isNumericRefined(attribute, operator, value) { if (isUndefined_1(value) && isUndefined_1(operator)) { return !!this.numericRefinements[attribute]; } var isOperatorDefined = this.numericRefinements[attribute] && !isUndefined_1(this.numericRefinements[attribute][operator]); if (isUndefined_1(value) || !isOperatorDefined) { return isOperatorDefined; } var parsedValue = valToNumber_1(value); var isAttributeValueDefined = !isUndefined_1( findArray(this.numericRefinements[attribute][operator], parsedValue) ); return isOperatorDefined && isAttributeValueDefined; }, /** * Returns true if the tag refined, false otherwise * @method * @param {string} tag the tag to check * @return {boolean} */ isTagRefined: function isTagRefined(tag) { return indexOf_1(this.tagRefinements, tag) !== -1; }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() { // attributes used for numeric filter can also be disjunctive var disjunctiveNumericRefinedFacets = intersection_1( keys_1(this.numericRefinements), this.disjunctiveFacets ); return keys_1(this.disjunctiveFacetsRefinements) .concat(disjunctiveNumericRefinedFacets) .concat(this.getRefinedHierarchicalFacets()); }, /** * Returns the list of all disjunctive facets refined * @method * @param {string} facet name of the attribute used for faceting * @param {value} value value used for filtering * @return {string[]} */ getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() { return intersection_1( // enforce the order between the two arrays, // so that refinement name index === hierarchical facet index map_1(this.hierarchicalFacets, 'name'), keys_1(this.hierarchicalFacetsRefinements) ); }, /** * Returned the list of all disjunctive facets not refined * @method * @return {string[]} */ getUnrefinedDisjunctiveFacets: function() { var refinedFacets = this.getRefinedDisjunctiveFacets(); return filter_1(this.disjunctiveFacets, function(f) { return indexOf_1(refinedFacets, f) === -1; }); }, managedParameters: [ 'index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements' ], getQueryParams: function getQueryParams() { var managedParameters = this.managedParameters; var queryParams = {}; forOwn_1(this, function(paramValue, paramName) { if (indexOf_1(managedParameters, paramName) === -1 && paramValue !== undefined) { queryParams[paramName] = paramValue; } }); return queryParams; }, /** * Let the user retrieve any parameter value from the SearchParameters * @param {string} paramName name of the parameter * @return {any} the value of the parameter */ getQueryParameter: function getQueryParameter(paramName) { if (!this.hasOwnProperty(paramName)) { throw new Error( "Parameter '" + paramName + "' is not an attribute of SearchParameters " + '(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)'); } return this[paramName]; }, /** * Let the user set a specific value for a given parameter. Will return the * same instance if the parameter is invalid or if the value is the same as the * previous one. * @method * @param {string} parameter the parameter name * @param {any} value the value to be set, must be compliant with the definition * of the attribute on the object * @return {SearchParameters} the updated state */ setQueryParameter: function setParameter(parameter, value) { if (this[parameter] === value) return this; var modification = {}; modification[parameter] = value; return this.setQueryParameters(modification); }, /** * Let the user set any of the parameters with a plain object. * @method * @param {object} params all the keys and the values to be updated * @return {SearchParameters} a new updated instance */ setQueryParameters: function setQueryParameters(params) { if (!params) return this; var error = SearchParameters.validate(this, params); if (error) { throw error; } var parsedParams = SearchParameters._parseNumbers(params); return this.mutateMe(function mergeWith(newInstance) { var ks = keys_1(params); forEach_1(ks, function(k) { newInstance[k] = parsedParams[k]; }); return newInstance; }); }, /** * Returns an object with only the selected attributes. * @param {string[]} filters filters to retrieve only a subset of the state. It * accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage) * or attributes of the index with the notation 'attribute:nameOfMyAttribute' * @return {object} */ filter: function(filters) { return filterState_1(this, filters); }, /** * Helper function to make it easier to build new instances from a mutating * function * @private * @param {function} fn newMutableState -> previousState -> () function that will * change the value of the newMutable to the desired state * @return {SearchParameters} a new instance with the specified modifications applied */ mutateMe: function mutateMe(fn) { var newState = new this.constructor(this); fn(newState, this); return newState; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSortBy: function(hierarchicalFacet) { return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc']; }, /** * Helper function to get the hierarchicalFacet separator or the default one (`>`) * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.separator or `>` as default */ _getHierarchicalFacetSeparator: function(hierarchicalFacet) { return hierarchicalFacet.separator || ' > '; }, /** * Helper function to get the hierarchicalFacet prefix path or null * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.rootPath or null as default */ _getHierarchicalRootPath: function(hierarchicalFacet) { return hierarchicalFacet.rootPath || null; }, /** * Helper function to check if we show the parent level of the hierarchicalFacet * @private * @param {object} hierarchicalFacet * @return {string} returns the hierarchicalFacet.showParentLevel or true as default */ _getHierarchicalShowParentLevel: function(hierarchicalFacet) { if (typeof hierarchicalFacet.showParentLevel === 'boolean') { return hierarchicalFacet.showParentLevel; } return true; }, /** * Helper function to get the hierarchicalFacet by it's name * @param {string} hierarchicalFacetName * @return {object} a hierarchicalFacet */ getHierarchicalFacetByName: function(hierarchicalFacetName) { return find_1( this.hierarchicalFacets, {name: hierarchicalFacetName} ); }, /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ getHierarchicalFacetBreadcrumb: function(facetName) { if (!this.isHierarchicalFacet(facetName)) { throw new Error( 'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`'); } var refinement = this.getHierarchicalRefinement(facetName)[0]; if (!refinement) return []; var separator = this._getHierarchicalFacetSeparator( this.getHierarchicalFacetByName(facetName) ); var path = refinement.split(separator); return map_1(path, trim_1); }, toString: function() { return JSON.stringify(this, null, 2); } }; /** * Callback used for clearRefinement method * @callback SearchParameters.clearCallback * @param {OperatorList|FacetList} value the value of the filter * @param {string} key the current attribute name * @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude` * depending on the type of facet * @return {boolean} `true` if the element should be removed. `false` otherwise. */ var SearchParameters_1 = SearchParameters; /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } var compact_1 = compact; /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } var _baseSum = baseSum; /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? _baseSum(array, _baseIteratee(iteratee, 2)) : 0; } var sumBy_1 = sumBy; /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return _arrayMap(props, function(key) { return object[key]; }); } var _baseValues = baseValues; /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : _baseValues(object, keys_1(object)); } var values_1 = values; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$3 = Math.max; /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike_1(collection) ? collection : values_1(collection); fromIndex = (fromIndex && !guard) ? toInteger_1(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax$3(length + fromIndex, 0); } return isString_1(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && _baseIndexOf(collection, value, fromIndex) > -1); } var includes_1 = includes; /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } var _baseSortBy = baseSortBy; /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol_1(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol_1(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } var _compareAscending = compareAscending; /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = _compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } var _compareMultiple = compareMultiple; /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = _arrayMap(iteratees.length ? iteratees : [identity_1], _baseUnary(_baseIteratee)); var result = _baseMap(collection, function(value, key, collection) { var criteria = _arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return _baseSortBy(result, function(object, other) { return _compareMultiple(object, other, orders); }); } var _baseOrderBy = baseOrderBy; /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray_1(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray_1(orders)) { orders = orders == null ? [] : [orders]; } return _baseOrderBy(collection, iteratees, orders); } var orderBy_1 = orderBy; /** Used to store function metadata. */ var metaMap = _WeakMap && new _WeakMap; var _metaMap = metaMap; /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !_metaMap ? identity_1 : function(func, data) { _metaMap.set(func, data); return func; }; var _baseSetData = baseSetData; /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = _baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject_1(result) ? result : thisBinding; }; } var _createCtor = createCtor; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = _createCtor(func); function wrapper() { var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } var _createBind = createBind; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$4 = Math.max; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax$4(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } var _composeArgs = composeArgs; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$5 = Math.max; /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax$5(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } var _composeArgsRight = composeArgsRight; /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } var _countHolders = countHolders; /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } var _baseLodash = baseLodash; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = _baseCreate(_baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; var _LazyWrapper = LazyWrapper; /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop$1() { // No operation performed. } var noop_1 = noop$1; /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !_metaMap ? noop_1 : function(func) { return _metaMap.get(func); }; var _getData = getData; /** Used to lookup unminified function names. */ var realNames = {}; var _realNames = realNames; /** Used for built-in method references. */ var objectProto$i = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$g = objectProto$i.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = _realNames[result], length = hasOwnProperty$g.call(_realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } var _getFuncName = getFuncName; /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = _baseCreate(_baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; var _LodashWrapper = LodashWrapper; /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof _LazyWrapper) { return wrapper.clone(); } var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = _copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } var _wrapperClone = wrapperClone; /** Used for built-in method references. */ var objectProto$j = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$h = objectProto$j.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) { if (value instanceof _LodashWrapper) { return value; } if (hasOwnProperty$h.call(value, '__wrapped__')) { return _wrapperClone(value); } } return new _LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = _baseLodash.prototype; lodash.prototype.constructor = lodash; var wrapperLodash = lodash; /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = _getFuncName(func), other = wrapperLodash[funcName]; if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = _getData(other); return !!data && func === data[0]; } var _isLaziable = isLaziable; /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = _shortOut(_baseSetData); var _setData = setData; /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } var _getWrapDetails = getWrapDetails; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } var _insertWrapDetails = insertWrapDetails; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$1 = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG$1], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { _arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } var _updateWrapDetails = updateWrapDetails; /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask))); } var _setWrapToString = setWrapToString; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$2 = 1, WRAP_BIND_KEY_FLAG$1 = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG$1 = 8, WRAP_PARTIAL_FLAG$1 = 32, WRAP_PARTIAL_RIGHT_FLAG$1 = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG$1, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG$2 | WRAP_BIND_KEY_FLAG$1); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (_isLaziable(func)) { _setData(result, newData); } result.placeholder = placeholder; return _setWrapToString(result, func, bitmask); } var _createRecurry = createRecurry; /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = func; return object.placeholder; } var _getHolder = getHolder; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$1 = Math.min; /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin$1(indexes.length, arrLength), oldArray = _copyArray(array); while (length--) { var index = indexes[length]; array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } var _reorder = reorder; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } var _replaceHolders = replaceHolders; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$3 = 1, WRAP_BIND_KEY_FLAG$2 = 2, WRAP_CURRY_FLAG$2 = 8, WRAP_CURRY_RIGHT_FLAG$1 = 16, WRAP_ARY_FLAG$1 = 128, WRAP_FLIP_FLAG$1 = 512; /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG$1, isBind = bitmask & WRAP_BIND_FLAG$3, isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2, isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1), isFlip = bitmask & WRAP_FLIP_FLAG$1, Ctor = isBindKey ? undefined : _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = _getHolder(wrapper), holdersCount = _countHolders(args, placeholder); } if (partials) { args = _composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = _composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = _replaceHolders(args, placeholder); return _createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = _reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== _root && this instanceof wrapper) { fn = Ctor || _createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } var _createHybrid = createHybrid; /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = _createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = _getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : _replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return _createRecurry( func, bitmask, _createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; return _apply(fn, this, args); } return wrapper; } var _createCurry = createCurry; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$4 = 1; /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG$4, Ctor = _createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return _apply(fn, isBind ? thisArg : this, args); } return wrapper; } var _createPartial = createPartial; /** Used as the internal argument placeholder. */ var PLACEHOLDER$1 = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$5 = 1, WRAP_BIND_KEY_FLAG$3 = 2, WRAP_CURRY_BOUND_FLAG$1 = 4, WRAP_CURRY_FLAG$3 = 8, WRAP_ARY_FLAG$2 = 128, WRAP_REARG_FLAG$1 = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin$2 = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG$5 | WRAP_BIND_KEY_FLAG$3 | WRAP_ARY_FLAG$2); var isCombo = ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_CURRY_FLAG$3)) || ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$3)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG$5) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG$5 ? 0 : WRAP_CURRY_BOUND_FLAG$1; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? _composeArgs(partials, value, source[4]) : value; data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER$1) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER$1) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG$2) { data[8] = data[8] == null ? source[8] : nativeMin$2(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } var _mergeData = mergeData; /** Error message constants. */ var FUNC_ERROR_TEXT$1 = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$6 = 1, WRAP_BIND_KEY_FLAG$4 = 2, WRAP_CURRY_FLAG$4 = 8, WRAP_CURRY_RIGHT_FLAG$2 = 16, WRAP_PARTIAL_FLAG$2 = 32, WRAP_PARTIAL_RIGHT_FLAG$2 = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax$6 = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG$4; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT$1); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG$2 | WRAP_PARTIAL_RIGHT_FLAG$2); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax$6(toInteger_1(ary), 0); arity = arity === undefined ? arity : toInteger_1(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG$2) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : _getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { _mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax$6(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2)) { bitmask &= ~(WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2); } if (!bitmask || bitmask == WRAP_BIND_FLAG$6) { var result = _createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG$4 || bitmask == WRAP_CURRY_RIGHT_FLAG$2) { result = _createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG$2 || bitmask == (WRAP_BIND_FLAG$6 | WRAP_PARTIAL_FLAG$2)) && !holders.length) { result = _createPartial(func, bitmask, thisArg, partials); } else { result = _createHybrid.apply(undefined, newData); } var setter = data ? _baseSetData : _setData; return _setWrapToString(setter(result, newData), func, bitmask); } var _createWrap = createWrap; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_FLAG$3 = 32; /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partial)); return _createWrap(func, WRAP_PARTIAL_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partial.placeholder = {}; var partial_1 = partial; /** Used to compose bitmasks for function metadata. */ var WRAP_PARTIAL_RIGHT_FLAG$3 = 64; /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = _baseRest(function(func, partials) { var holders = _replaceHolders(partials, _getHolder(partialRight)); return _createWrap(func, WRAP_PARTIAL_RIGHT_FLAG$3, undefined, partials, holders); }); // Assign default placeholders. partialRight.placeholder = {}; var partialRight_1 = partialRight; /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } var _baseClamp = baseClamp; /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString_1(string); position = position == null ? 0 : _baseClamp(toInteger_1(position), 0, string.length); target = _baseToString(target); return string.slice(position, position + target.length) == target; } var startsWith_1 = startsWith; /** * Transform sort format from user friendly notation to lodash format * @param {string[]} sortBy array of predicate of the form "attribute:order" * @return {array.<string[]>} array containing 2 elements : attributes, orders */ var formatSort = function formatSort(sortBy, defaults) { return reduce_1(sortBy, function preparePredicate(out, sortInstruction) { var sortInstructions = sortInstruction.split(':'); if (defaults && sortInstructions.length === 1) { var similarDefault = find_1(defaults, function(predicate) { return startsWith_1(predicate, sortInstruction[0]); }); if (similarDefault) { sortInstructions = similarDefault.split(':'); } } out[0].push(sortInstructions[0]); out[1].push(sortInstructions[1]); return out; }, [[], []]); }; /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject_1(object)) { return object; } path = _castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = _toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject_1(objValue) ? objValue : (_isIndex(path[index + 1]) ? [] : {}); } } _assignValue(nested, key, newValue); nested = nested[key]; } return object; } var _baseSet = baseSet; /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = _baseGet(object, path); if (predicate(value, path)) { _baseSet(result, _castPath(path, object), value); } } return result; } var _basePickBy = basePickBy; /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = _arrayMap(_getAllKeysIn(object), function(prop) { return [prop]; }); predicate = _baseIteratee(predicate); return _basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } var pickBy_1 = pickBy; var generateHierarchicalTree_1 = generateTrees; function generateTrees(state) { return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) { var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex]; var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || ''; var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet); var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet); var sortBy = formatSort(state._getHierarchicalFacetSortBy(hierarchicalFacet)); var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement); var results = hierarchicalFacetResult; if (hierarchicalRootPath) { results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length); } return reduce_1(results, generateTreeFn, { name: state.hierarchicalFacets[hierarchicalFacetIndex].name, count: null, // root level, no count isRefined: true, // root level, always refined path: null, // root level, no path data: null }); }; } function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) { return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) { var parent = hierarchicalTree; if (currentHierarchicalLevel > 0) { var level = 0; parent = hierarchicalTree; while (level < currentHierarchicalLevel) { parent = parent && find_1(parent.data, {isRefined: true}); level++; } } // we found a refined parent, let's add current level data under it if (parent) { // filter values in case an object has multiple categories: // { // categories: { // level0: ['beers', 'bières'], // level1: ['beers > IPA', 'bières > Belges'] // } // } // // If parent refinement is `beers`, then we do not want to have `bières > Belges` // showing up var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel); parent.data = orderBy_1( map_1( pickBy_1(hierarchicalFacetResult.data, onlyMatchingValuesFn), formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) ), sortBy[0], sortBy[1] ); } return hierarchicalTree; }; } function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) { return function(facetCount, facetValue) { // we want the facetValue is a child of hierarchicalRootPath if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) { return false; } // we always want root levels (only when there is no prefix path) return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || // if there is a rootPath, being root level mean 1 level under rootPath hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || // if current refinement is a root level and current facetValue is a root level, // keep the facetValue facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || // currentRefinement is a child of the facet value currentRefinement.indexOf(facetValue) === 0 || // facetValue is a child of the current parent, add it facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0); }; } function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) { return function format(facetCount, facetValue) { return { name: trim_1(last_1(facetValue.split(hierarchicalSeparator))), path: facetValue, count: facetCount, isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0, data: null }; }; } /** * @typedef SearchResults.Facet * @type {object} * @property {string} name name of the attribute in the record * @property {object} data the faceting data: value, number of entries * @property {object} stats undefined unless facet_stats is retrieved from algolia */ /** * @typedef SearchResults.HierarchicalFacet * @type {object} * @property {string} name name of the current value given the hierarchical level, trimmed. * If root node, you get the facet name * @property {number} count number of objects matching this hierarchical value * @property {string} path the current hierarchical value full path * @property {boolean} isRefined `true` if the current value was refined, `false` otherwise * @property {HierarchicalFacet[]} data sub values for the current level */ /** * @typedef SearchResults.FacetValue * @type {object} * @property {string} name the facet value itself * @property {number} count times this facet appears in the results * @property {boolean} isRefined is the facet currently selected * @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets) */ /** * @typedef Refinement * @type {object} * @property {string} type the type of filter used: * `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical` * @property {string} attributeName name of the attribute used for filtering * @property {string} name the value of the filter * @property {number} numericValue the value as a number. Only for numeric filters. * @property {string} operator the operator used. Only for numeric filters. * @property {number} count the number of computed hits for this filter. Only on facets. * @property {boolean} exhaustive if the count is exhaustive */ function getIndices(obj) { var indices = {}; forEach_1(obj, function(val, idx) { indices[val] = idx; }); return indices; } function assignFacetStats(dest, facetStats, key) { if (facetStats && facetStats[key]) { dest.stats = facetStats[key]; } } function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) { return find_1( hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) { return includes_1(hierarchicalFacet.attributes, hierarchicalAttributeName); } ); } /*eslint-disable */ /** * Constructor for SearchResults * @class * @classdesc SearchResults contains the results of a query to Algolia using the * {@link AlgoliaSearchHelper}. * @param {SearchParameters} state state that led to the response * @param {array.<object>} results the results from algolia client * @example <caption>SearchResults of the first query in * <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption> { "hitsPerPage": 10, "processingTimeMS": 2, "facets": [ { "name": "type", "data": { "HardGood": 6627, "BlackTie": 550, "Music": 665, "Software": 131, "Game": 456, "Movie": 1571 }, "exhaustive": false }, { "exhaustive": false, "data": { "Free shipping": 5507 }, "name": "shipping" } ], "hits": [ { "thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif", "_highlightResult": { "shortDescription": { "matchLevel": "none", "value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "matchedWords": [] }, "category": { "matchLevel": "none", "value": "Computer Security Software", "matchedWords": [] }, "manufacturer": { "matchedWords": [], "value": "Webroot", "matchLevel": "none" }, "name": { "value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "matchedWords": [], "matchLevel": "none" } }, "image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg", "shipping": "Free shipping", "bestSellingRank": 4, "shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection", "url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ", "name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows", "category": "Computer Security Software", "salePrice_range": "1 - 50", "objectID": "1688832", "type": "Software", "customerReviewCount": 5980, "salePrice": 49.99, "manufacturer": "Webroot" }, .... ], "nbHits": 10000, "disjunctiveFacets": [ { "exhaustive": false, "data": { "5": 183, "12": 112, "7": 149, ... }, "name": "customerReviewCount", "stats": { "max": 7461, "avg": 157.939, "min": 1 } }, { "data": { "Printer Ink": 142, "Wireless Speakers": 60, "Point & Shoot Cameras": 48, ... }, "name": "category", "exhaustive": false }, { "exhaustive": false, "data": { "> 5000": 2, "1 - 50": 6524, "501 - 2000": 566, "201 - 500": 1501, "101 - 200": 1360, "2001 - 5000": 47 }, "name": "salePrice_range" }, { "data": { "Dynex™": 202, "Insignia™": 230, "PNY": 72, ... }, "name": "manufacturer", "exhaustive": false } ], "query": "", "nbPages": 100, "page": 0, "index": "bestbuy" } **/ /*eslint-enable */ function SearchResults(state, results) { var mainSubResponse = results[0]; this._rawResults = results; /** * query used to generate the results * @member {string} */ this.query = mainSubResponse.query; /** * The query as parsed by the engine given all the rules. * @member {string} */ this.parsedQuery = mainSubResponse.parsedQuery; /** * all the records that match the search parameters. Each record is * augmented with a new attribute `_highlightResult` * which is an object keyed by attribute and with the following properties: * - `value` : the value of the facet highlighted (html) * - `matchLevel`: full, partial or none depending on how the query terms match * @member {object[]} */ this.hits = mainSubResponse.hits; /** * index where the results come from * @member {string} */ this.index = mainSubResponse.index; /** * number of hits per page requested * @member {number} */ this.hitsPerPage = mainSubResponse.hitsPerPage; /** * total number of hits of this query on the index * @member {number} */ this.nbHits = mainSubResponse.nbHits; /** * total number of pages with respect to the number of hits per page and the total number of hits * @member {number} */ this.nbPages = mainSubResponse.nbPages; /** * current page * @member {number} */ this.page = mainSubResponse.page; /** * sum of the processing time of all the queries * @member {number} */ this.processingTimeMS = sumBy_1(results, 'processingTimeMS'); /** * The position if the position was guessed by IP. * @member {string} * @example "48.8637,2.3615", */ this.aroundLatLng = mainSubResponse.aroundLatLng; /** * The radius computed by Algolia. * @member {string} * @example "126792922", */ this.automaticRadius = mainSubResponse.automaticRadius; /** * String identifying the server used to serve this request. * @member {string} * @example "c7-use-2.algolia.net", */ this.serverUsed = mainSubResponse.serverUsed; /** * Boolean that indicates if the computation of the counts did time out. * @deprecated * @member {boolean} */ this.timeoutCounts = mainSubResponse.timeoutCounts; /** * Boolean that indicates if the computation of the hits did time out. * @deprecated * @member {boolean} */ this.timeoutHits = mainSubResponse.timeoutHits; /** * True if the counts of the facets is exhaustive * @member {boolean} */ this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount; /** * True if the number of hits is exhaustive * @member {boolean} */ this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits; /** * Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/). * @member {object[]} */ this.userData = mainSubResponse.userData; /** * queryID is the unique identifier of the query used to generate the current search results. * This value is only available if the `clickAnalytics` search parameter is set to `true`. * @member {string} */ this.queryID = mainSubResponse.queryID; /** * disjunctive facets results * @member {SearchResults.Facet[]} */ this.disjunctiveFacets = []; /** * disjunctive facets results * @member {SearchResults.HierarchicalFacet[]} */ this.hierarchicalFacets = map_1(state.hierarchicalFacets, function initFutureTree() { return []; }); /** * other facets results * @member {SearchResults.Facet[]} */ this.facets = []; var disjunctiveFacets = state.getRefinedDisjunctiveFacets(); var facetsIndices = getIndices(state.facets); var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets); var nextDisjunctiveResult = 1; var self = this; // Since we send request only for disjunctive facets that have been refined, // we get the facets informations from the first, general, response. forEach_1(mainSubResponse.facets, function(facetValueObject, facetKey) { var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName( state.hierarchicalFacets, facetKey ); if (hierarchicalFacet) { // Place the hierarchicalFacet data at the correct index depending on // the attributes order that was defined at the helper initialization var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey); var idxAttributeName = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); self.hierarchicalFacets[idxAttributeName][facetIndex] = { attribute: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; } else { var isFacetDisjunctive = indexOf_1(state.disjunctiveFacets, facetKey) !== -1; var isFacetConjunctive = indexOf_1(state.facets, facetKey) !== -1; var position; if (isFacetDisjunctive) { position = disjunctiveFacetsIndices[facetKey]; self.disjunctiveFacets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey); } if (isFacetConjunctive) { position = facetsIndices[facetKey]; self.facets[position] = { name: facetKey, data: facetValueObject, exhaustive: mainSubResponse.exhaustiveFacetsCount }; assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey); } } }); // Make sure we do not keep holes within the hierarchical facets this.hierarchicalFacets = compact_1(this.hierarchicalFacets); // aggregate the refined disjunctive facets forEach_1(disjunctiveFacets, function(disjunctiveFacet) { var result = results[nextDisjunctiveResult]; var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets. forEach_1(result.facets, function(facetResults, dfacet) { var position; if (hierarchicalFacet) { position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } self.hierarchicalFacets[position][attributeIndex].data = merge_1( {}, self.hierarchicalFacets[position][attributeIndex].data, facetResults ); } else { position = disjunctiveFacetsIndices[dfacet]; var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {}; self.disjunctiveFacets[position] = { name: dfacet, data: defaults_1({}, facetResults, dataFromMainRequest), exhaustive: result.exhaustiveFacetsCount }; assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet); if (state.disjunctiveFacetsRefinements[dfacet]) { forEach_1(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) { // add the disjunctive refinements if it is no more retrieved if (!self.disjunctiveFacets[position].data[refinementValue] && indexOf_1(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) { self.disjunctiveFacets[position].data[refinementValue] = 0; } }); } } }); nextDisjunctiveResult++; }); // if we have some root level values for hierarchical facets, merge them forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are already at a root refinement (or no refinement at all), there is no // root level values request if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) { return; } var result = results[nextDisjunctiveResult]; forEach_1(result.facets, function(facetResults, dfacet) { var position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name}); var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet}); // previous refinements and no results so not able to find it if (attributeIndex === -1) { return; } // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5), // then the disjunctive values will be `beers` (count: 100), // but we do not want to display // | beers (100) // > IPA (5) // We want // | beers (5) // > IPA (5) var defaultData = {}; if (currentRefinement.length > 0) { var root = currentRefinement[0].split(separator)[0]; defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root]; } self.hierarchicalFacets[position][attributeIndex].data = defaults_1( defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data ); }); nextDisjunctiveResult++; }); // add the excludes forEach_1(state.facetsExcludes, function(excludes, facetName) { var position = facetsIndices[facetName]; self.facets[position] = { name: facetName, data: mainSubResponse.facets[facetName], exhaustive: mainSubResponse.exhaustiveFacetsCount }; forEach_1(excludes, function(facetValue) { self.facets[position] = self.facets[position] || {name: facetName}; self.facets[position].data = self.facets[position].data || {}; self.facets[position].data[facetValue] = 0; }); }); this.hierarchicalFacets = map_1(this.hierarchicalFacets, generateHierarchicalTree_1(state)); this.facets = compact_1(this.facets); this.disjunctiveFacets = compact_1(this.disjunctiveFacets); this._state = state; } /** * Get a facet object with its name * @deprecated * @param {string} name name of the faceted attribute * @return {SearchResults.Facet} the facet object */ SearchResults.prototype.getFacetByName = function(name) { var predicate = {name: name}; return find_1(this.facets, predicate) || find_1(this.disjunctiveFacets, predicate) || find_1(this.hierarchicalFacets, predicate); }; /** * Get the facet values of a specified attribute from a SearchResults object. * @private * @param {SearchResults} results the search results to search in * @param {string} attribute name of the faceted attribute to search for * @return {array|object} facet values. For the hierarchical facets it is an object. */ function extractNormalizedFacetValues(results, attribute) { var predicate = {name: attribute}; if (results._state.isConjunctiveFacet(attribute)) { var facet = find_1(results.facets, predicate); if (!facet) return []; return map_1(facet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isFacetRefined(attribute, k), isExcluded: results._state.isExcludeRefined(attribute, k) }; }); } else if (results._state.isDisjunctiveFacet(attribute)) { var disjunctiveFacet = find_1(results.disjunctiveFacets, predicate); if (!disjunctiveFacet) return []; return map_1(disjunctiveFacet.data, function(v, k) { return { name: k, count: v, isRefined: results._state.isDisjunctiveFacetRefined(attribute, k) }; }); } else if (results._state.isHierarchicalFacet(attribute)) { return find_1(results.hierarchicalFacets, predicate); } } /** * Sort nodes of a hierarchical facet results * @private * @param {HierarchicalFacet} node node to upon which we want to apply the sort */ function recSort(sortFn, node) { if (!node.data || node.data.length === 0) { return node; } var children = map_1(node.data, partial_1(recSort, sortFn)); var sortedChildren = sortFn(children); var newNode = merge_1({}, node, {data: sortedChildren}); return newNode; } SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc']; function vanillaSortFn(order, data) { return data.sort(order); } /** * Get a the list of values for a given facet attribute. Those values are sorted * refinement first, descending count (bigger value on top), and name ascending * (alphabetical order). The sort formula can overridden using either string based * predicates or a function. * * This method will return all the values returned by the Algolia engine plus all * the values already refined. This means that it can happen that the * `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet) * might not be respected if you have facet values that are already refined. * @param {string} attribute attribute name * @param {object} opts configuration options. * @param {Array.<string> | function} opts.sortBy * When using strings, it consists of * the name of the [FacetValue](#SearchResults.FacetValue) or the * [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the * order (`asc` or `desc`). For example to order the value by count, the * argument would be `['count:asc']`. * * If only the attribute name is specified, the ordering defaults to the one * specified in the default value for this attribute. * * When not specified, the order is * ascending. This parameter can also be a function which takes two facet * values and should return a number, 0 if equal, 1 if the first argument is * bigger or -1 otherwise. * * The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']` * @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of * the attribute requested (hierarchical, disjunctive or conjunctive) * @example * helper.on('results', function(content){ * //get values ordered only by name ascending using the string predicate * content.getFacetValues('city', {sortBy: ['name:asc']}); * //get values ordered only by count ascending using a function * content.getFacetValues('city', { * // this is equivalent to ['count:asc'] * sortBy: function(a, b) { * if (a.count === b.count) return 0; * if (a.count > b.count) return 1; * if (b.count > a.count) return -1; * } * }); * }); */ SearchResults.prototype.getFacetValues = function(attribute, opts) { var facetValues = extractNormalizedFacetValues(this, attribute); if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.'); var options = defaults_1({}, opts, {sortBy: SearchResults.DEFAULT_SORT}); if (Array.isArray(options.sortBy)) { var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT); if (Array.isArray(facetValues)) { return orderBy_1(facetValues, order[0], order[1]); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partialRight_1(orderBy_1, order[0], order[1]), facetValues); } else if (isFunction_1(options.sortBy)) { if (Array.isArray(facetValues)) { return facetValues.sort(options.sortBy); } // If facetValues is not an array, it's an object thus a hierarchical facet object return recSort(partial_1(vanillaSortFn, options.sortBy), facetValues); } throw new Error( 'options.sortBy is optional but if defined it must be ' + 'either an array of string (predicates) or a sorting function' ); }; /** * Returns the facet stats if attribute is defined and the facet contains some. * Otherwise returns undefined. * @param {string} attribute name of the faceted attribute * @return {object} The stats of the facet */ SearchResults.prototype.getFacetStats = function(attribute) { if (this._state.isConjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.facets, attribute); } else if (this._state.isDisjunctiveFacet(attribute)) { return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute); } throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`'); }; function getFacetStatsIfAvailable(facetList, facetName) { var data = find_1(facetList, {name: facetName}); return data && data.stats; } /** * Returns all refinements for all filters + tags. It also provides * additional information: count and exhausistivity for each filter. * * See the [refinement type](#Refinement) for an exhaustive view of the available * data. * * @return {Array.<Refinement>} all the refinements */ SearchResults.prototype.getRefinements = function() { var state = this._state; var results = this; var res = []; forEach_1(state.facetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'facet', attributeName, name, results.facets)); }); }); forEach_1(state.facetsExcludes, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'exclude', attributeName, name, results.facets)); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets)); }); }); forEach_1(state.hierarchicalFacetsRefinements, function(refinements, attributeName) { forEach_1(refinements, function(name) { res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets)); }); }); forEach_1(state.numericRefinements, function(operators, attributeName) { forEach_1(operators, function(values, operator) { forEach_1(values, function(value) { res.push({ type: 'numeric', attributeName: attributeName, name: value, numericValue: value, operator: operator }); }); }); }); forEach_1(state.tagRefinements, function(name) { res.push({type: 'tag', attributeName: '_tags', name: name}); }); return res; }; function getRefinement(state, type, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var count = get_1(facet, 'data[' + name + ']'); var exhaustive = get_1(facet, 'exhaustive'); return { type: type, attributeName: attributeName, name: name, count: count || 0, exhaustive: exhaustive || false }; } function getHierarchicalRefinement(state, attributeName, name, resultsFacets) { var facet = find_1(resultsFacets, {name: attributeName}); var facetDeclaration = state.getHierarchicalFacetByName(attributeName); var splitted = name.split(facetDeclaration.separator); var configuredName = splitted[splitted.length - 1]; for (var i = 0; facet !== undefined && i < splitted.length; ++i) { facet = find_1(facet.data, {name: splitted[i]}); } var count = get_1(facet, 'count'); var exhaustive = get_1(facet, 'exhaustive'); return { type: 'hierarchical', attributeName: attributeName, name: configuredName, count: count || 0, exhaustive: exhaustive || false }; } var SearchResults_1 = SearchResults; var isBufferBrowser = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; }; var inherits_browser = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var util = createCommonjsModule(function (module, exports) { // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(commonjsGlobal.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var length = output.reduce(function(prev, cur) { if (cur.indexOf('\n') >= 0) ; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = isBufferBrowser; function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = inherits_browser; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }); var util_1 = util.format; var util_2 = util.deprecate; var util_3 = util.debuglog; var util_4 = util.inspect; var util_5 = util.isArray; var util_6 = util.isBoolean; var util_7 = util.isNull; var util_8 = util.isNullOrUndefined; var util_9 = util.isNumber; var util_10 = util.isString; var util_11 = util.isSymbol; var util_12 = util.isUndefined; var util_13 = util.isRegExp; var util_14 = util.isObject; var util_15 = util.isDate; var util_16 = util.isError; var util_17 = util.isFunction; var util_18 = util.isPrimitive; var util_19 = util.isBuffer; var util_20 = util.log; var util_21 = util.inherits; var util_22 = util._extend; // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } var events = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber$1(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject$1(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined$1(handler)) return false; if (isFunction$1(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject$1(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction$1(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction$1(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject$1(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject$1(this._events[type]) && !this._events[type].warned) { if (!isUndefined$1(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction$1(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction$1(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction$1(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject$1(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction$1(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction$1(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction$1(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction$1(arg) { return typeof arg === 'function'; } function isNumber$1(arg) { return typeof arg === 'number'; } function isObject$1(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined$1(arg) { return arg === void 0; } /** * A DerivedHelper is a way to create sub requests to * Algolia from a main helper. * @class * @classdesc The DerivedHelper provides an event based interface for search callbacks: * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. */ function DerivedHelper(mainHelper, fn) { this.main = mainHelper; this.fn = fn; this.lastResults = null; } util.inherits(DerivedHelper, events.EventEmitter); /** * Detach this helper from the main helper * @return {undefined} * @throws Error if the derived helper is already detached */ DerivedHelper.prototype.detach = function() { this.removeAllListeners(); this.main.detachDerivedHelper(this); }; DerivedHelper.prototype.getModifiedState = function(parameters) { return this.fn(parameters); }; var DerivedHelper_1 = DerivedHelper; var requestBuilder = { /** * Get all the queries to send to the client, those queries can used directly * with the Algolia client. * @private * @return {object[]} The queries */ _getQueries: function getQueries(index, state) { var queries = []; // One query for the hits queries.push({ indexName: index, params: requestBuilder._getHitsSearchParams(state) }); // One for each disjunctive facets forEach_1(state.getRefinedDisjunctiveFacets(), function(refinedFacet) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet) }); }); // maybe more to get the root level of hierarchical facets when activated forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) { var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet); var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are deeper than level 0 (starting from `beer > IPA`) // we want to get the root values var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) { queries.push({ indexName: index, params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true) }); } }); return queries; }, /** * Build search parameters used to fetch hits * @private * @return {object.<string, any>} */ _getHitsSearchParams: function(state) { var facets = state.facets .concat(state.disjunctiveFacets) .concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state)); var facetFilters = requestBuilder._getFacetFilters(state); var numericFilters = requestBuilder._getNumericFilters(state); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { facets: facets, tagFilters: tagFilters }; if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Build search parameters used to fetch a disjunctive facet * @private * @param {string} facet the associated facet name * @param {boolean} hierarchicalRootLevel ?? FIXME * @return {object} */ _getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) { var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel); var numericFilters = requestBuilder._getNumericFilters(state, facet); var tagFilters = requestBuilder._getTagFilters(state); var additionalParams = { hitsPerPage: 1, page: 0, attributesToRetrieve: [], attributesToHighlight: [], attributesToSnippet: [], tagFilters: tagFilters, analytics: false, clickAnalytics: false }; var hierarchicalFacet = state.getHierarchicalFacetByName(facet); if (hierarchicalFacet) { additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute( state, hierarchicalFacet, hierarchicalRootLevel ); } else { additionalParams.facets = facet; } if (numericFilters.length > 0) { additionalParams.numericFilters = numericFilters; } if (facetFilters.length > 0) { additionalParams.facetFilters = facetFilters; } return merge_1(state.getQueryParams(), additionalParams); }, /** * Return the numeric filters in an algolia request fashion * @private * @param {string} [facetName] the name of the attribute for which the filters should be excluded * @return {string[]} the numeric filters in the algolia format */ _getNumericFilters: function(state, facetName) { if (state.numericFilters) { return state.numericFilters; } var numericFilters = []; forEach_1(state.numericRefinements, function(operators, attribute) { forEach_1(operators, function(values, operator) { if (facetName !== attribute) { forEach_1(values, function(value) { if (Array.isArray(value)) { var vs = map_1(value, function(v) { return attribute + operator + v; }); numericFilters.push(vs); } else { numericFilters.push(attribute + operator + value); } }); } }); }); return numericFilters; }, /** * Return the tags filters depending * @private * @return {string} */ _getTagFilters: function(state) { if (state.tagFilters) { return state.tagFilters; } return state.tagRefinements.join(','); }, /** * Build facetFilters parameter based on current refinements. The array returned * contains strings representing the facet filters in the algolia format. * @private * @param {string} [facet] if set, the current disjunctive facet * @return {array.<string>} */ _getFacetFilters: function(state, facet, hierarchicalRootLevel) { var facetFilters = []; forEach_1(state.facetsRefinements, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':' + facetValue); }); }); forEach_1(state.facetsExcludes, function(facetValues, facetName) { forEach_1(facetValues, function(facetValue) { facetFilters.push(facetName + ':-' + facetValue); }); }); forEach_1(state.disjunctiveFacetsRefinements, function(facetValues, facetName) { if (facetName === facet || !facetValues || facetValues.length === 0) return; var orFilters = []; forEach_1(facetValues, function(facetValue) { orFilters.push(facetName + ':' + facetValue); }); facetFilters.push(orFilters); }); forEach_1(state.hierarchicalFacetsRefinements, function(facetValues, facetName) { var facetValue = facetValues[0]; if (facetValue === undefined) { return; } var hierarchicalFacet = state.getHierarchicalFacetByName(facetName); var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeToRefine; var attributesIndex; // we ask for parent facet values only when the `facet` is the current hierarchical facet if (facet === facetName) { // if we are at the root level already, no need to ask for facet values, we get them from // the hits query if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) || (rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) { return; } if (!rootPath) { attributesIndex = facetValue.split(separator).length - 2; facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator)); } else { attributesIndex = rootPath.split(separator).length - 1; facetValue = rootPath; } attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } else { attributesIndex = facetValue.split(separator).length - 1; attributeToRefine = hierarchicalFacet.attributes[attributesIndex]; } if (attributeToRefine) { facetFilters.push([attributeToRefine + ':' + facetValue]); } }); return facetFilters; }, _getHitsHierarchicalFacetsAttributes: function(state) { var out = []; return reduce_1( state.hierarchicalFacets, // ask for as much levels as there's hierarchical refinements function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) { var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0]; // if no refinement, ask for root level if (!hierarchicalRefinement) { allAttributes.push(hierarchicalFacet.attributes[0]); return allAttributes; } var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); var level = hierarchicalRefinement.split(separator).length; var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1); return allAttributes.concat(newAttributes); }, out); }, _getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) { var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet); if (rootLevel === true) { var rootPath = state._getHierarchicalRootPath(hierarchicalFacet); var attributeIndex = 0; if (rootPath) { attributeIndex = rootPath.split(separator).length; } return [hierarchicalFacet.attributes[attributeIndex]]; } var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || ''; // if refinement is 'beers > IPA > Flying dog', // then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values) var parentLevel = hierarchicalRefinement.split(separator).length - 1; return hierarchicalFacet.attributes.slice(0, parentLevel + 1); }, getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) { var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state; var searchForFacetSearchParameters = { facetQuery: query, facetName: facetName }; if (typeof maxFacetHits === 'number') { searchForFacetSearchParameters.maxFacetHits = maxFacetHits; } var queries = merge_1(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters); return queries; } }; var requestBuilder_1 = requestBuilder; /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { _baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } var _baseInverter = baseInverter; /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return _baseInverter(object, setter, toIteratee(iteratee), {}); }; } var _createInverter = createInverter; /** Used for built-in method references. */ var objectProto$k = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$2 = objectProto$k.toString; /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = _createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString$2.call(value); } result[value] = key; }, constant_1(identity_1)); var invert_1 = invert; var keys2Short = { advancedSyntax: 'aS', allowTyposOnNumericTokens: 'aTONT', analyticsTags: 'aT', analytics: 'a', aroundLatLngViaIP: 'aLLVIP', aroundLatLng: 'aLL', aroundPrecision: 'aP', aroundRadius: 'aR', attributesToHighlight: 'aTH', attributesToRetrieve: 'aTR', attributesToSnippet: 'aTS', disjunctiveFacetsRefinements: 'dFR', disjunctiveFacets: 'dF', distinct: 'd', facetsExcludes: 'fE', facetsRefinements: 'fR', facets: 'f', getRankingInfo: 'gRI', hierarchicalFacetsRefinements: 'hFR', hierarchicalFacets: 'hF', highlightPostTag: 'hPoT', highlightPreTag: 'hPrT', hitsPerPage: 'hPP', ignorePlurals: 'iP', index: 'idx', insideBoundingBox: 'iBB', insidePolygon: 'iPg', length: 'l', maxValuesPerFacet: 'mVPF', minimumAroundRadius: 'mAR', minProximity: 'mP', minWordSizefor1Typo: 'mWS1T', minWordSizefor2Typos: 'mWS2T', numericFilters: 'nF', numericRefinements: 'nR', offset: 'o', optionalWords: 'oW', page: 'p', queryType: 'qT', query: 'q', removeWordsIfNoResults: 'rWINR', replaceSynonymsInHighlight: 'rSIH', restrictSearchableAttributes: 'rSA', synonyms: 's', tagFilters: 'tF', tagRefinements: 'tR', typoTolerance: 'tT', optionalTagFilters: 'oTF', optionalFacetFilters: 'oFF', snippetEllipsisText: 'sET', disableExactOnAttributes: 'dEOA', enableExactOnSingleWordQuery: 'eEOSWQ' }; var short2Keys = invert_1(keys2Short); var shortener = { /** * All the keys of the state, encoded. * @const */ ENCODED_PARAMETERS: keys_1(short2Keys), /** * Decode a shorten attribute * @param {string} shortKey the shorten attribute * @return {string} the decoded attribute, undefined otherwise */ decode: function(shortKey) { return short2Keys[shortKey]; }, /** * Encode an attribute into a short version * @param {string} key the attribute * @return {string} the shorten attribute */ encode: function(key) { return keys2Short[key]; } }; var utils = createCommonjsModule(function (module, exports) { var has = Object.prototype.hasOwnProperty; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { var obj; while (queue.length) { var item = queue.pop(); obj = item.obj[item.prop]; if (Array.isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } return obj; }; exports.arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.merge = function merge(target, source, options) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = exports.arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = exports.merge(target[i], item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = exports.merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; exports.assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.encode = function encode(str) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = typeof str === 'string' ? str : String(str); var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; exports.compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } return compactQueue(queue); }; exports.isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function isBuffer(obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; }); var utils_1 = utils.arrayToObject; var utils_2 = utils.merge; var utils_3 = utils.assign; var utils_4 = utils.decode; var utils_5 = utils.encode; var utils_6 = utils.compact; var utils_7 = utils.isRegExp; var utils_8 = utils.isBuffer; var replace = String.prototype.replace; var percentTwenties = /%20/g; var formats = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching return prefix + '[]'; }, indices: function indices(prefix, key) { // eslint-disable-line func-name-matching return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { // eslint-disable-line func-name-matching return prefix; } }; var toISO = Date.prototype.toISOString; var defaults$1 = { delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify( // eslint-disable-line func-name-matching object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults$1.encoder) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$1.encoder); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$1.encoder))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } } return values; }; var stringify_1 = function (object, opts) { var obj = object; var options = opts ? utils.assign({}, opts) : {}; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var delimiter = typeof options.delimiter === 'undefined' ? defaults$1.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$1.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults$1.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults$1.encode; var encoder = typeof options.encoder === 'function' ? options.encoder : defaults$1.encoder; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults$1.serializeDate; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults$1.encodeValuesOnly; if (typeof options.format === 'undefined') { options.format = formats['default']; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; return joined.length > 0 ? prefix + joined : ''; }; var has = Object.prototype.hasOwnProperty; var defaults$2 = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults$2.decoder); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults$2.decoder); val = options.decoder(part.slice(pos + 1), defaults$2.decoder); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]') { obj = []; obj = obj.concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys // that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options); }; var parse = function (str, opts) { var options = opts ? utils.assign({}, opts) : {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults$2.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults$2.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults$2.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults$2.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults$2.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults$2.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults$2.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults$2.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$2.strictNullHandling; if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; var lib$1 = { formats: formats, parse: parse, stringify: stringify_1 }; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG$7 = 1, WRAP_PARTIAL_FLAG$4 = 32; /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = _baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG$7; if (partials.length) { var holders = _replaceHolders(partials, _getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG$4; } return _createWrap(func, bitmask, thisArg, partials, holders); }); // Assign default placeholders. bind.placeholder = {}; var bind_1 = bind; /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return _basePickBy(object, paths, function(value, path) { return hasIn_1(object, path); }); } var _basePick = basePick; /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = _flatRest(function(object, paths) { return object == null ? {} : _basePick(object, paths); }); var pick_1 = pick; /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, iteratee(value, key, object), value); }); return result; } var mapKeys_1 = mapKeys; /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = _baseIteratee(iteratee, 3); _baseForOwn(object, function(value, key, object) { _baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } var mapValues_1 = mapValues; /** * Module containing the functions to serialize and deserialize * {SearchParameters} in the query string format * @module algoliasearchHelper.url */ var encode = utils.encode; function recursiveEncode(input) { if (isPlainObject_1(input)) { return mapValues_1(input, recursiveEncode); } if (Array.isArray(input)) { return map_1(input, recursiveEncode); } if (isString_1(input)) { return encode(input); } return input; } var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR']; var stateKeys = shortener.ENCODED_PARAMETERS; function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) { if (prefixRegexp !== null) { a = a.replace(prefixRegexp, ''); b = b.replace(prefixRegexp, ''); } a = invertedMapping[a] || a; b = invertedMapping[b] || b; if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) { if (a === 'q') return -1; if (b === 'q') return 1; var isARefinements = refinementsParameters.indexOf(a) !== -1; var isBRefinements = refinementsParameters.indexOf(b) !== -1; if (isARefinements && !isBRefinements) { return 1; } else if (isBRefinements && !isARefinements) { return -1; } } return a.localeCompare(b); } /** * Read a query string and return an object containing the state * @param {string} queryString the query string that will be decoded * @param {object} [options] accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) */ var getStateFromQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var partialStateWithPrefix = lib$1.parse(queryString); var prefixRegexp = new RegExp('^' + prefixForParameters); var partialState = mapKeys_1( partialStateWithPrefix, function(v, k) { var hasPrefix = prefixForParameters && prefixRegexp.test(k); var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k; var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey); return decodedKey || unprefixedKey; } ); var partialStateWithParsedNumbers = SearchParameters_1._parseNumbers(partialState); return pick_1(partialStateWithParsedNumbers, SearchParameters_1.PARAMETERS); }; /** * Retrieve an object of all the properties that are not understandable as helper * parameters. * @param {string} queryString the query string to read * @param {object} [options] the options * - prefixForParameters : prefix used for the helper configuration keys * - mapping : map short attributes to another value e.g. {q: 'query'} * @return {object} the object containing the parsed configuration that doesn't * to the helper */ var getUnrecognizedParametersInQueryString = function(queryString, options) { var prefixForParameters = options && options.prefix; var mapping = options && options.mapping || {}; var invertedMapping = invert_1(mapping); var foreignConfig = {}; var config = lib$1.parse(queryString); if (prefixForParameters) { var prefixRegexp = new RegExp('^' + prefixForParameters); forEach_1(config, function(v, key) { if (!prefixRegexp.test(key)) foreignConfig[key] = v; }); } else { forEach_1(config, function(v, key) { if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v; }); } return foreignConfig; }; /** * Generate a query string for the state passed according to the options * @param {SearchParameters} state state to serialize * @param {object} [options] May contain the following parameters : * - prefix : prefix in front of the keys * - mapping : map short attributes to another value e.g. {q: 'query'} * - moreAttributes : more values to be added in the query string. Those values * won't be prefixed. * - safe : get safe urls for use in emails, chat apps or any application auto linking urls. * All parameters and values will be encoded in a way that it's safe to share them. * Default to false for legacy reasons () * @return {string} the query string */ var getQueryStringFromState = function(state, options) { var moreAttributes = options && options.moreAttributes; var prefixForParameters = options && options.prefix || ''; var mapping = options && options.mapping || {}; var safe = options && options.safe || false; var invertedMapping = invert_1(mapping); var stateForUrl = safe ? state : recursiveEncode(state); var encodedState = mapKeys_1( stateForUrl, function(v, k) { var shortK = shortener.encode(k); return prefixForParameters + (mapping[shortK] || shortK); } ); var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters); var sort = bind_1(sortQueryStringValues, null, prefixRegexp, invertedMapping); if (!isEmpty_1(moreAttributes)) { var stateQs = lib$1.stringify(encodedState, {encode: safe, sort: sort}); var moreQs = lib$1.stringify(moreAttributes, {encode: safe}); if (!stateQs) return moreQs; return stateQs + '&' + moreQs; } return lib$1.stringify(encodedState, {encode: safe, sort: sort}); }; var url = { getStateFromQueryString: getStateFromQueryString, getUnrecognizedParametersInQueryString: getUnrecognizedParametersInQueryString, getQueryStringFromState: getQueryStringFromState }; var version$1 = '2.26.0'; /** * Event triggered when a parameter is set or updated * @event AlgoliaSearchHelper#event:change * @property {SearchParameters} state the current parameters with the latest changes applied * @property {SearchResults} lastResults the previous results received from Algolia. `null` before * the first request * @example * helper.on('change', function(state, lastResults) { * console.log('The parameters have changed'); * }); */ /** * Event triggered when a main search is sent to Algolia * @event AlgoliaSearchHelper#event:search * @property {SearchParameters} state the parameters used for this search * @property {SearchResults} lastResults the results from the previous search. `null` if * it is the first search. * @example * helper.on('search', function(state, lastResults) { * console.log('Search sent'); * }); */ /** * Event triggered when a search using `searchForFacetValues` is sent to Algolia * @event AlgoliaSearchHelper#event:searchForFacetValues * @property {SearchParameters} state the parameters used for this search * it is the first search. * @property {string} facet the facet searched into * @property {string} query the query used to search in the facets * @example * helper.on('searchForFacetValues', function(state, facet, query) { * console.log('searchForFacetValues sent'); * }); */ /** * Event triggered when a search using `searchOnce` is sent to Algolia * @event AlgoliaSearchHelper#event:searchOnce * @property {SearchParameters} state the parameters used for this search * it is the first search. * @example * helper.on('searchOnce', function(state) { * console.log('searchOnce sent'); * }); */ /** * Event triggered when the results are retrieved from Algolia * @event AlgoliaSearchHelper#event:result * @property {SearchResults} results the results received from Algolia * @property {SearchParameters} state the parameters used to query Algolia. Those might * be different from the one in the helper instance (for example if the network is unreliable). * @example * helper.on('result', function(results, state) { * console.log('Search results received'); * }); */ /** * Event triggered when Algolia sends back an error. For example, if an unknown parameter is * used, the error can be caught using this event. * @event AlgoliaSearchHelper#event:error * @property {Error} error the error returned by the Algolia. * @example * helper.on('error', function(error) { * console.log('Houston we got a problem.'); * }); */ /** * Event triggered when the queue of queries have been depleted (with any result or outdated queries) * @event AlgoliaSearchHelper#event:searchQueueEmpty * @example * helper.on('searchQueueEmpty', function() { * console.log('No more search pending'); * // This is received before the result event if we're not expecting new results * }); * * helper.search(); */ /** * Initialize a new AlgoliaSearchHelper * @class * @classdesc The AlgoliaSearchHelper is a class that ease the management of the * search. It provides an event based interface for search callbacks: * - change: when the internal search state is changed. * This event contains a {@link SearchParameters} object and the * {@link SearchResults} of the last result if any. * - search: when a search is triggered using the `search()` method. * - result: when the response is retrieved from Algolia and is processed. * This event contains a {@link SearchResults} object and the * {@link SearchParameters} corresponding to this answer. * - error: when the response is an error. This event contains the error returned by the server. * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the index name to query * @param {SearchParameters | object} options an object defining the initial * config of the search. It doesn't have to be a {SearchParameters}, * just an object containing the properties you need from it. */ function AlgoliaSearchHelper(client, index, options) { if (client.addAlgoliaAgent && !doesClientAgentContainsHelper(client)) { client.addAlgoliaAgent('JS Helper ' + version$1); } this.setClient(client); var opts = options || {}; opts.index = index; this.state = SearchParameters_1.make(opts); this.lastResults = null; this._queryId = 0; this._lastQueryIdReceived = -1; this.derivedHelpers = []; this._currentNbQueries = 0; } util.inherits(AlgoliaSearchHelper, events.EventEmitter); /** * Start the search with the parameters set in the state. When the * method is called, it triggers a `search` event. The results will * be available through the `result` event. If an error occurs, an * `error` will be fired instead. * @return {AlgoliaSearchHelper} * @fires search * @fires result * @fires error * @chainable */ AlgoliaSearchHelper.prototype.search = function() { this._search(); return this; }; /** * Gets the search query parameters that would be sent to the Algolia Client * for the hits * @return {object} Query Parameters */ AlgoliaSearchHelper.prototype.getQuery = function() { var state = this.state; return requestBuilder_1._getHitsSearchParams(state); }; /** * Start a search using a modified version of the current state. This method does * not trigger the helper lifecycle and does not modify the state kept internally * by the helper. This second aspect means that the next search call will be the * same as a search call before calling searchOnce. * @param {object} options can contain all the parameters that can be set to SearchParameters * plus the index * @param {function} [callback] optional callback executed when the response from the * server is back. * @return {promise|undefined} if a callback is passed the method returns undefined * otherwise it returns a promise containing an object with two keys : * - content with a SearchResults * - state with the state used for the query as a SearchParameters * @example * // Changing the number of records returned per page to 1 * // This example uses the callback API * var state = helper.searchOnce({hitsPerPage: 1}, * function(error, content, state) { * // if an error occurred it will be passed in error, otherwise its value is null * // content contains the results formatted as a SearchResults * // state is the instance of SearchParameters used for this search * }); * @example * // Changing the number of records returned per page to 1 * // This example uses the promise API * var state1 = helper.searchOnce({hitsPerPage: 1}) * .then(promiseHandler); * * function promiseHandler(res) { * // res contains * // { * // content : SearchResults * // state : SearchParameters (the one used for this specific search) * // } * } */ AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) { var tempState = !options ? this.state : this.state.setQueryParameters(options); var queries = requestBuilder_1._getQueries(tempState.index, tempState); var self = this; this._currentNbQueries++; this.emit('searchOnce', tempState); if (cb) { this.client .search(queries) .then(function(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) { self.emit('searchQueueEmpty'); } cb(null, new SearchResults_1(tempState, content.results), tempState); }) .catch(function(err) { self._currentNbQueries--; if (self._currentNbQueries === 0) { self.emit('searchQueueEmpty'); } cb(err, null, tempState); }); return undefined; } return this.client.search(queries).then(function(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); return { content: new SearchResults_1(tempState, content.results), state: tempState, _originalResponse: content }; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Structure of each result when using * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * @typedef FacetSearchHit * @type {object} * @property {string} value the facet value * @property {string} highlighted the facet value highlighted with the query string * @property {number} count number of occurrence of this facet value * @property {boolean} isRefined true if the value is already refined */ /** * Structure of the data resolved by the * [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues) * promise. * @typedef FacetSearchResult * @type {object} * @property {FacetSearchHit} facetHits the results for this search for facet values * @property {number} processingTimeMS time taken by the query inside the engine */ /** * Search for facet values based on an query and the name of a faceted attribute. This * triggers a search and will return a promise. On top of using the query, it also sends * the parameters from the state so that the search is narrowed down to only the possible values. * * See the description of [FacetSearchResult](reference.html#FacetSearchResult) * @param {string} facet the name of the faceted attribute * @param {string} query the string query for the search * @param {number} [maxFacetHits] the maximum number values returned. Should be > 0 and <= 100 * @param {object} [userState] the set of custom parameters to use on top of the current state. Setting a property to `undefined` removes * it in the generated query. * @return {promise.<FacetSearchResult>} the results of the search */ AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits, userState) { var state = this.state.setQueryParameters(userState || {}); var isDisjunctive = state.isDisjunctiveFacet(facet); var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, state); this._currentNbQueries++; var self = this; this.emit('searchForFacetValues', state, facet, query); var searchForFacetValuesPromise = typeof this.client.searchForFacetValues === 'function' ? this.client.searchForFacetValues([{indexName: state.index, params: algoliaQuery}]) : this.client.initIndex(state.index).searchForFacetValues(algoliaQuery); return searchForFacetValuesPromise.then(function addIsRefined(content) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); content = Array.isArray(content) ? content[0] : content; content.facetHits = forEach_1(content.facetHits, function(f) { f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value); }); return content; }, function(e) { self._currentNbQueries--; if (self._currentNbQueries === 0) self.emit('searchQueueEmpty'); throw e; }); }; /** * Sets the text query used for the search. * * This method resets the current page to 0. * @param {string} q the user query * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setQuery = function(q) { this._change(this.state.setPage(0).setQuery(q)); return this; }; /** * Remove all the types of refinements except tags. A string can be provided to remove * only the refinements of a specific attribute. For more advanced use case, you can * provide a function instead. This function should follow the * [clearCallback definition](#SearchParameters.clearCallback). * * This method resets the current page to 0. * @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * // Removing all the refinements * helper.clearRefinements().search(); * @example * // Removing all the filters on a the category attribute. * helper.clearRefinements('category').search(); * @example * // Removing only the exclude filters on the category facet. * helper.clearRefinements(function(value, attribute, type) { * return type === 'exclude' && attribute === 'category'; * }).search(); */ AlgoliaSearchHelper.prototype.clearRefinements = function(name) { this._change(this.state.setPage(0).clearRefinements(name)); return this; }; /** * Remove all the tag filters. * * This method resets the current page to 0. * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.clearTags = function() { this._change(this.state.setPage(0).clearTags()); return this; }; /** * Adds a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() { return this.addDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Adds a refinement on a hierarchical facet. It will throw * an exception if the facet is not defined or if the facet * is already refined. * * This method resets the current page to 0. * @param {string} facet the facet name * @param {string} path the hierarchical facet path * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is refined * @chainable * @fires change */ AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addHierarchicalFacetRefinement(facet, value)); return this; }; /** * Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} operator the operator of the filter * @param {number} value the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) { this._change(this.state.setPage(0).addNumericRefinement(attribute, operator, value)); return this; }; /** * Adds a filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).addFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement} */ AlgoliaSearchHelper.prototype.addRefine = function() { return this.addFacetRefinement.apply(this, arguments); }; /** * Adds a an exclusion filter to a faceted attribute with the `value` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value (will be converted to string) * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).addExcludeRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion} */ AlgoliaSearchHelper.prototype.addExclude = function() { return this.addFacetExclusion.apply(this, arguments); }; /** * Adds a tag filter with the `tag` provided. If the * filter is already set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag the tag to add to the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.addTag = function(tag) { this._change(this.state.setPage(0).addTagRefinement(tag)); return this; }; /** * Removes an numeric filter to an attribute with the `operator` and `value` provided. If the * filter is not set, it doesn't change the filters. * * Some parameters are optional, triggering different behavior: * - if the value is not provided, then all the numeric value will be removed for the * specified attribute/operator couple. * - if the operator is not provided either, then all the numeric filter on this attribute * will be removed. * * This method resets the current page to 0. * @param {string} attribute the attribute on which the numeric filter applies * @param {string} [operator] the operator of the filter * @param {number} [value] the value of the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) { this._change(this.state.setPage(0).removeNumericRefinement(attribute, operator, value)); return this; }; /** * Removes a disjunctive filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement} */ AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() { return this.removeDisjunctiveFacetRefinement.apply(this, arguments); }; /** * Removes the refinement set on a hierarchical facet. * @param {string} facet the facet name * @return {AlgoliaSearchHelper} * @throws Error if the facet is not defined or if the facet is not refined * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) { this._change(this.state.setPage(0).removeHierarchicalFacetRefinement(facet)); return this; }; /** * Removes a filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).removeFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement} */ AlgoliaSearchHelper.prototype.removeRefine = function() { return this.removeFacetRefinement.apply(this, arguments); }; /** * Removes an exclusion filter to a faceted attribute with the `value` provided. If the * filter is not set, it doesn't change the filters. * * If the value is omitted, then this method will remove all the filters for the * attribute. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} [value] the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).removeExcludeRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion} */ AlgoliaSearchHelper.prototype.removeExclude = function() { return this.removeFacetExclusion.apply(this, arguments); }; /** * Removes a tag filter with the `tag` provided. If the * filter is not set, it doesn't change the filters. * * This method resets the current page to 0. * @param {string} tag tag to remove from the filter * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.removeTag = function(tag) { this._change(this.state.setPage(0).removeTagRefinement(tag)); return this; }; /** * Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) { this._change(this.state.setPage(0).toggleExcludeFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion} */ AlgoliaSearchHelper.prototype.toggleExclude = function() { return this.toggleFacetExclusion.apply(this, arguments); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable * @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) { return this.toggleFacetRefinement(facet, value); }; /** * Adds or removes a filter to a faceted attribute with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method can be used for conjunctive, disjunctive and hierarchical filters. * * This method resets the current page to 0. * @param {string} facet the facet to refine * @param {string} value the associated value * @return {AlgoliaSearchHelper} * @throws Error will throw an error if the facet is not declared in the settings of the helper * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) { this._change(this.state.setPage(0).toggleFacetRefinement(facet, value)); return this; }; /** * @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement} */ AlgoliaSearchHelper.prototype.toggleRefine = function() { return this.toggleFacetRefinement.apply(this, arguments); }; /** * Adds or removes a tag filter with the `value` provided. If * the value is set then it removes it, otherwise it adds the filter. * * This method resets the current page to 0. * @param {string} tag tag to remove or add * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.toggleTag = function(tag) { this._change(this.state.setPage(0).toggleTagRefinement(tag)); return this; }; /** * Increments the page number by one. * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setPage(0).nextPage().getPage(); * // returns 1 */ AlgoliaSearchHelper.prototype.nextPage = function() { return this.setPage(this.state.page + 1); }; /** * Decrements the page number by one. * @fires change * @return {AlgoliaSearchHelper} * @chainable * @example * helper.setPage(1).previousPage().getPage(); * // returns 0 */ AlgoliaSearchHelper.prototype.previousPage = function() { return this.setPage(this.state.page - 1); }; /** * @private */ function setCurrentPage(page) { if (page < 0) throw new Error('Page requested below 0.'); this._change(this.state.setPage(page)); return this; } /** * Change the current page * @deprecated * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage; /** * Updates the current page. * @function * @param {number} page The page number * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setPage = setCurrentPage; /** * Updates the name of the index that will be targeted by the query. * * This method resets the current page to 0. * @param {string} name the index name * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setIndex = function(name) { this._change(this.state.setPage(0).setIndex(name)); return this; }; /** * Update a parameter of the search. This method reset the page * * The complete list of parameters is available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters and facets have their own API) * * This method resets the current page to 0. * @param {string} parameter name of the parameter to update * @param {any} value new value of the parameter * @return {AlgoliaSearchHelper} * @fires change * @chainable * @example * helper.setQueryParameter('hitsPerPage', 20).search(); */ AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) { this._change(this.state.setPage(0).setQueryParameter(parameter, value)); return this; }; /** * Set the whole state (warning: will erase previous state) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @fires change * @chainable */ AlgoliaSearchHelper.prototype.setState = function(newState) { this._change(SearchParameters_1.make(newState)); return this; }; /** * Get the current search state stored in the helper. This object is immutable. * @param {string[]} [filters] optional filters to retrieve only a subset of the state * @return {SearchParameters|object} if filters is specified a plain object is * returned containing only the requested fields, otherwise return the unfiltered * state * @example * // Get the complete state as stored in the helper * helper.getState(); * @example * // Get a part of the state with all the refinements on attributes and the query * helper.getState(['query', 'attribute:category']); */ AlgoliaSearchHelper.prototype.getState = function(filters) { if (filters === undefined) return this.state; return this.state.filter(filters); }; /** * DEPRECATED Get part of the state as a query string. By default, the output keys will not * be prefixed and will only take the applied refinements and the query. * @deprecated * @param {object} [options] May contain the following parameters : * * **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for * the index, all the refinements with `attribute:*` or for some specific attributes with * `attribute:theAttribute` * * **prefix** : prefix in front of the keys * * **moreAttributes** : more values to be added in the query string. Those values * won't be prefixed. * @return {string} the query string */ AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) { var filters = options && options.filters || ['query', 'attribute:*']; var partialState = this.getState(filters); return url.getQueryStringFromState(partialState, options); }; /** * DEPRECATED Read a query string and return an object containing the state. Use * url module. * @deprecated * @static * @param {string} queryString the query string that will be decoded * @param {object} options accepted options : * - prefix : the prefix used for the saved attributes, you have to provide the * same that was used for serialization * @return {object} partial search parameters object (same properties than in the * SearchParameters but not exhaustive) * @see {@link url#getStateFromQueryString} */ AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString; /** * DEPRECATED Retrieve an object of all the properties that are not understandable as helper * parameters. Use url module. * @deprecated * @static * @param {string} queryString the query string to read * @param {object} options the options * - prefixForParameters : prefix used for the helper configuration keys * @return {object} the object containing the parsed configuration that doesn't * to the helper */ AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString; /** * DEPRECATED Overrides part of the state with the properties stored in the provided query * string. * @deprecated * @param {string} queryString the query string containing the informations to url the state * @param {object} options optional parameters : * - prefix : prefix used for the algolia parameters * - triggerChange : if set to true the state update will trigger a change event */ AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) { var triggerChange = options && options.triggerChange || false; var configuration = url.getStateFromQueryString(queryString, options); var updatedState = this.state.setQueryParameters(configuration); if (triggerChange) this.setState(updatedState); else this.overrideStateWithoutTriggeringChangeEvent(updatedState); }; /** * Override the current state without triggering a change event. * Do not use this method unless you know what you are doing. (see the example * for a legit use case) * @param {SearchParameters} newState the whole new state * @return {AlgoliaSearchHelper} * @example * helper.on('change', function(state){ * // In this function you might want to find a way to store the state in the url/history * updateYourURL(state) * }) * window.onpopstate = function(event){ * // This is naive though as you should check if the state is really defined etc. * helper.overrideStateWithoutTriggeringChangeEvent(event.state).search() * } * @chainable */ AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) { this.state = new SearchParameters_1(newState); return this; }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isRefined = function(facet, value) { if (this.state.isConjunctiveFacet(facet)) { return this.state.isFacetRefined(facet, value); } else if (this.state.isDisjunctiveFacet(facet)) { return this.state.isDisjunctiveFacetRefined(facet, value); } throw new Error(facet + ' is not properly defined in this helper configuration' + '(use the facets or disjunctiveFacets keys to configure it)'); }; /** * Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters. * @param {string} attribute the name of the attribute * @return {boolean} true if the attribute is filtered by at least one value * @example * // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters * helper.hasRefinements('price'); // false * helper.addNumericRefinement('price', '>', 100); * helper.hasRefinements('price'); // true * * helper.hasRefinements('color'); // false * helper.addFacetRefinement('color', 'blue'); * helper.hasRefinements('color'); // true * * helper.hasRefinements('material'); // false * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * helper.hasRefinements('material'); // true * * helper.hasRefinements('categories'); // false * helper.toggleFacetRefinement('categories', 'kitchen > knife'); * helper.hasRefinements('categories'); // true * */ AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) { if (!isEmpty_1(this.state.getNumericRefinements(attribute))) { return true; } else if (this.state.isConjunctiveFacet(attribute)) { return this.state.isFacetRefined(attribute); } else if (this.state.isDisjunctiveFacet(attribute)) { return this.state.isDisjunctiveFacetRefined(attribute); } else if (this.state.isHierarchicalFacet(attribute)) { return this.state.isHierarchicalFacetRefined(attribute); } // there's currently no way to know that the user did call `addNumericRefinement` at some point // thus we cannot distinguish if there once was a numeric refinement that was cleared // so we will return false in every other situations to be consistent // while what we should do here is throw because we did not find the attribute in any type // of refinement return false; }; /** * Check if a value is excluded for a specific faceted attribute. If the value * is omitted then the function checks if there is any excluding refinements. * * @param {string} facet name of the attribute for used for faceting * @param {string} [value] optional value. If passed will test that this value * is filtering the given facet. * @return {boolean} true if refined * @example * helper.isExcludeRefined('color'); // false * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // false * * helper.addFacetExclusion('color', 'red'); * * helper.isExcludeRefined('color'); // true * helper.isExcludeRefined('color', 'blue') // false * helper.isExcludeRefined('color', 'red') // true */ AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) { return this.state.isExcludeRefined(facet, value); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements} */ AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) { return this.state.isDisjunctiveFacetRefined(facet, value); }; /** * Check if the string is a currently filtering tag. * @param {string} tag tag to check * @return {boolean} */ AlgoliaSearchHelper.prototype.hasTag = function(tag) { return this.state.isTagRefined(tag); }; /** * @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag} */ AlgoliaSearchHelper.prototype.isTagRefined = function() { return this.hasTagRefinements.apply(this, arguments); }; /** * Get the name of the currently used index. * @return {string} * @example * helper.setIndex('highestPrice_products').getIndex(); * // returns 'highestPrice_products' */ AlgoliaSearchHelper.prototype.getIndex = function() { return this.state.index; }; function getCurrentPage() { return this.state.page; } /** * Get the currently selected page * @deprecated * @return {number} the current page */ AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage; /** * Get the currently selected page * @function * @return {number} the current page */ AlgoliaSearchHelper.prototype.getPage = getCurrentPage; /** * Get all the tags currently set to filters the results. * * @return {string[]} The list of tags currently set. */ AlgoliaSearchHelper.prototype.getTags = function() { return this.state.tagRefinements; }; /** * Get a parameter of the search by its name. It is possible that a parameter is directly * defined in the index dashboard, but it will be undefined using this method. * * The complete list of parameters is * available on the * [Algolia website](https://www.algolia.com/doc/rest#query-an-index). * The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts) * or benefit from higher-level APIs (all the kind of filters have their own API) * @param {string} parameterName the parameter name * @return {any} the parameter value * @example * var hitsPerPage = helper.getQueryParameter('hitsPerPage'); */ AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) { return this.state.getQueryParameter(parameterName); }; /** * Get the list of refinements for a given attribute. This method works with * conjunctive, disjunctive, excluding and numerical filters. * * See also SearchResults#getRefinements * * @param {string} facetName attribute name used for faceting * @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and * a type. Numeric also contains an operator. * @example * helper.addNumericRefinement('price', '>', 100); * helper.getRefinements('price'); * // [ * // { * // "value": [ * // 100 * // ], * // "operator": ">", * // "type": "numeric" * // } * // ] * @example * helper.addFacetRefinement('color', 'blue'); * helper.addFacetExclusion('color', 'red'); * helper.getRefinements('color'); * // [ * // { * // "value": "blue", * // "type": "conjunctive" * // }, * // { * // "value": "red", * // "type": "exclude" * // } * // ] * @example * helper.addDisjunctiveFacetRefinement('material', 'plastic'); * // [ * // { * // "value": "plastic", * // "type": "disjunctive" * // } * // ] */ AlgoliaSearchHelper.prototype.getRefinements = function(facetName) { var refinements = []; if (this.state.isConjunctiveFacet(facetName)) { var conjRefinements = this.state.getConjunctiveRefinements(facetName); forEach_1(conjRefinements, function(r) { refinements.push({ value: r, type: 'conjunctive' }); }); var excludeRefinements = this.state.getExcludeRefinements(facetName); forEach_1(excludeRefinements, function(r) { refinements.push({ value: r, type: 'exclude' }); }); } else if (this.state.isDisjunctiveFacet(facetName)) { var disjRefinements = this.state.getDisjunctiveRefinements(facetName); forEach_1(disjRefinements, function(r) { refinements.push({ value: r, type: 'disjunctive' }); }); } var numericRefinements = this.state.getNumericRefinements(facetName); forEach_1(numericRefinements, function(value, operator) { refinements.push({ value: value, operator: operator, type: 'numeric' }); }); return refinements; }; /** * Return the current refinement for the (attribute, operator) * @param {string} attribute attribute in the record * @param {string} operator operator applied on the refined values * @return {Array.<number|number[]>} refined values */ AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) { return this.state.getNumericRefinement(attribute, operator); }; /** * Get the current breadcrumb for a hierarchical facet, as an array * @param {string} facetName Hierarchical facet name * @return {array.<string>} the path as an array of string */ AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) { return this.state.getHierarchicalFacetBreadcrumb(facetName); }; // /////////// PRIVATE /** * Perform the underlying queries * @private * @return {undefined} * @fires search * @fires result * @fires error */ AlgoliaSearchHelper.prototype._search = function() { var state = this.state; var mainQueries = requestBuilder_1._getQueries(state.index, state); var states = [{ state: state, queriesCount: mainQueries.length, helper: this }]; this.emit('search', state, this.lastResults); var derivedQueries = map_1(this.derivedHelpers, function(derivedHelper) { var derivedState = derivedHelper.getModifiedState(state); var queries = requestBuilder_1._getQueries(derivedState.index, derivedState); states.push({ state: derivedState, queriesCount: queries.length, helper: derivedHelper }); derivedHelper.emit('search', derivedState, derivedHelper.lastResults); return queries; }); var queries = mainQueries.concat(flatten_1(derivedQueries)); var queryId = this._queryId++; this._currentNbQueries++; try { this.client.search(queries) .then(this._dispatchAlgoliaResponse.bind(this, states, queryId)) .catch(this._dispatchAlgoliaError.bind(this, queryId)); } catch (err) { // If we reach this part, we're in an internal error state this.emit('error', err); } }; /** * Transform the responses as sent by the server and transform them into a user * usable object that merge the results of all the batch requests. It will dispatch * over the different helper + derived helpers (when there are some). * @private * @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>} * state state used for to generate the request * @param {number} queryId id of the current request * @param {object} content content of the response * @return {undefined} */ AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, content) { // FIXME remove the number of outdated queries discarded instead of just one if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= (queryId - this._lastQueryIdReceived); this._lastQueryIdReceived = queryId; if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); var results = content.results; forEach_1(states, function(s) { var state = s.state; var queriesCount = s.queriesCount; var helper = s.helper; var specificResults = results.splice(0, queriesCount); var formattedResponse = helper.lastResults = new SearchResults_1(state, specificResults); helper.emit('result', formattedResponse, state); }); }; AlgoliaSearchHelper.prototype._dispatchAlgoliaError = function(queryId, err) { if (queryId < this._lastQueryIdReceived) { // Outdated answer return; } this._currentNbQueries -= queryId - this._lastQueryIdReceived; this._lastQueryIdReceived = queryId; this.emit('error', err); if (this._currentNbQueries === 0) this.emit('searchQueueEmpty'); }; AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) { return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0; }; /** * Test if there are some disjunctive refinements on the facet * @private * @param {string} facet the attribute to test * @return {boolean} */ AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) { return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0; }; AlgoliaSearchHelper.prototype._change = function(newState) { if (newState !== this.state) { this.state = newState; this.emit('change', this.state, this.lastResults); } }; /** * Clears the cache of the underlying Algolia client. * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.clearCache = function() { this.client.clearCache && this.client.clearCache(); return this; }; /** * Updates the internal client instance. If the reference of the clients * are equal then no update is actually done. * @param {AlgoliaSearch} newClient an AlgoliaSearch client * @return {AlgoliaSearchHelper} */ AlgoliaSearchHelper.prototype.setClient = function(newClient) { if (this.client === newClient) return this; if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version$1); this.client = newClient; return this; }; /** * Gets the instance of the currently used client. * @return {AlgoliaSearch} */ AlgoliaSearchHelper.prototype.getClient = function() { return this.client; }; /** * Creates an derived instance of the Helper. A derived helper * is a way to request other indices synchronised with the lifecycle * of the main Helper. This mechanism uses the multiqueries feature * of Algolia to aggregate all the requests in a single network call. * * This method takes a function that is used to create a new SearchParameter * that will be used to create requests to Algolia. Those new requests * are created just before the `search` event. The signature of the function * is `SearchParameters -> SearchParameters`. * * This method returns a new DerivedHelper which is an EventEmitter * that fires the same `search`, `result` and `error` events. Those * events, however, will receive data specific to this DerivedHelper * and the SearchParameters that is returned by the call of the * parameter function. * @param {function} fn SearchParameters -> SearchParameters * @return {DerivedHelper} */ AlgoliaSearchHelper.prototype.derive = function(fn) { var derivedHelper = new DerivedHelper_1(this, fn); this.derivedHelpers.push(derivedHelper); return derivedHelper; }; /** * This method detaches a derived Helper from the main one. Prefer using the one from the * derived helper itself, to remove the event listeners too. * @private * @return {undefined} * @throws Error */ AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) { var pos = this.derivedHelpers.indexOf(derivedHelper); if (pos === -1) throw new Error('Derived helper already detached'); this.derivedHelpers.splice(pos, 1); }; /** * This method returns true if there is currently at least one on-going search. * @return {boolean} true if there is a search pending */ AlgoliaSearchHelper.prototype.hasPendingRequests = function() { return this._currentNbQueries > 0; }; /** * @typedef AlgoliaSearchHelper.NumericRefinement * @type {object} * @property {number[]} value the numbers that are used for filtering this attribute with * the operator specified. * @property {string} operator the faceting data: value, number of entries * @property {string} type will be 'numeric' */ /** * @typedef AlgoliaSearchHelper.FacetRefinement * @type {object} * @property {string} value the string use to filter the attribute * @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude' */ /* * This function tests if the _ua parameter of the client * already contains the JS Helper UA */ function doesClientAgentContainsHelper(client) { // this relies on JS Client internal variable, this might break if implementation changes var currentAgent = client._ua; return !currentAgent ? false : currentAgent.indexOf('JS Helper') !== -1; } var algoliasearch_helper = AlgoliaSearchHelper; /** * The algoliasearchHelper module is the function that will let its * contains everything needed to use the Algoliasearch * Helper. It is a also a function that instanciate the helper. * To use the helper, you also need the Algolia JS client v3. * @example * //using the UMD build * var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76'); * var helper = algoliasearchHelper(client, 'bestbuy', { * facets: ['shipping'], * disjunctiveFacets: ['category'] * }); * helper.on('result', function(result) { * console.log(result); * }); * helper.toggleRefine('Movies & TV Shows') * .toggleRefine('Free shipping') * .search(); * @example * // The helper is an event emitter using the node API * helper.on('result', updateTheResults); * helper.once('result', updateTheResults); * helper.removeListener('result', updateTheResults); * helper.removeAllListeners('result'); * @module algoliasearchHelper * @param {AlgoliaSearch} client an AlgoliaSearch client * @param {string} index the name of the index to query * @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it. * @return {AlgoliaSearchHelper} */ function algoliasearchHelper(client, index, opts) { return new algoliasearch_helper(client, index, opts); } /** * The version currently used * @member module:algoliasearchHelper.version * @type {number} */ algoliasearchHelper.version = version$1; /** * Constructor for the Helper. * @member module:algoliasearchHelper.AlgoliaSearchHelper * @type {AlgoliaSearchHelper} */ algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper; /** * Constructor for the object containing all the parameters of the search. * @member module:algoliasearchHelper.SearchParameters * @type {SearchParameters} */ algoliasearchHelper.SearchParameters = SearchParameters_1; /** * Constructor for the object containing the results of the search. * @member module:algoliasearchHelper.SearchResults * @type {SearchResults} */ algoliasearchHelper.SearchResults = SearchResults_1; /** * URL tools to generate query string and parse them from/into * SearchParameters * @member module:algoliasearchHelper.url * @type {object} {@link url} * */ algoliasearchHelper.url = url; var algoliasearchHelper_1 = algoliasearchHelper; var shallowEqual = function shallowEqual(objA, objB) { if (objA === objB) { return true; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; }; var getDisplayName = function getDisplayName(Component) { return Component.displayName || Component.name || 'UnknownComponent'; }; var resolved = Promise.resolve(); var defer = function defer(f) { resolved.then(f); }; var removeEmptyKey = function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (isEmpty_1(value) && isPlainObject_1(value)) { delete obj[key]; } else if (isPlainObject_1(value)) { removeEmptyKey(value); } }); return obj; }; function 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 createWidgetsManager(onWidgetsUpdate) { var widgets = []; // Is an update scheduled? var scheduled = false; // The state manager's updates need to be batched since more than one // component can register or unregister widgets during the same tick. function scheduleUpdate() { if (scheduled) { return; } scheduled = true; defer(function () { scheduled = false; onWidgetsUpdate(); }); } return { registerWidget: function registerWidget(widget) { widgets.push(widget); scheduleUpdate(); return function unregisterWidget() { widgets.splice(widgets.indexOf(widget), 1); scheduleUpdate(); }; }, update: scheduleUpdate, getWidgets: function getWidgets() { return widgets; } }; } function createStore(initialState) { var state = initialState; var listeners = []; function dispatch() { listeners.forEach(function (listener) { return listener(); }); } return { getState: function getState() { return state; }, setState: function setState(nextState) { state = nextState; dispatch(); }, subscribe: function subscribe(listener) { listeners.push(listener); return function unsubcribe() { listeners.splice(listeners.indexOf(listener), 1); }; } }; } var HIGHLIGHT_TAGS = { highlightPreTag: "<ais-highlight-0000000000>", highlightPostTag: "</ais-highlight-0000000000>" }; /** * Parses an highlighted attribute into an array of objects with the string value, and * a boolean that indicated if this part is highlighted. * * @param {string} preTag - string used to identify the start of an highlighted value * @param {string} postTag - string used to identify the end of an highlighted value * @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature * @return {object[]} - An array of {value: string, 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 = get_1(hit[highlightProperty], attribute, {}); if (Array.isArray(highlightObject)) { return highlightObject.map(function (item) { return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: item.value }); }); } return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightObject.value }); } /** Used for built-in method references. */ var objectProto$l = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$i = objectProto$l.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty$i.call(object, key); } var _baseHas = baseHas; /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has$1(object, path) { return object != null && _hasPath(object, path, _baseHas); } var has_1 = has$1; function getIndexId(context) { return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex; } function getResults(searchResults, context) { if (searchResults.results && !searchResults.results.hits) { return searchResults.results[getIndexId(context)] ? searchResults.results[getIndexId(context)] : null; } else { return searchResults.results ? searchResults.results : null; } } function hasMultipleIndices(context) { return context && context.multiIndexContext; } // eslint-disable-next-line max-params function refineValue(searchState, nextRefinement, context, resetPage, namespace) { if (hasMultipleIndices(context)) { return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage); } else { // When we have a multi index page with shared widgets we should also // reset their page to 1 if the resetPage is provided. Otherwise the // indices will always be reset // see: https://github.com/algolia/react-instantsearch/issues/310 // see: https://github.com/algolia/react-instantsearch/issues/637 if (searchState.indices && resetPage) { Object.keys(searchState.indices).forEach(function (targetedIndex) { searchState = refineValue(searchState, { page: 1 }, { multiIndexContext: { targetedIndex: targetedIndex } }, true, namespace); }); } return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage); } } function refineMultiIndex(searchState, nextRefinement, context, resetPage) { var page = resetPage ? { page: 1 } : undefined; var indexId = getIndexId(context); var state = has_1(searchState, "indices.".concat(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, context, resetPage, namespace) { var _objectSpread4; var indexId = getIndexId(context); var page = resetPage ? { page: 1 } : undefined; var state = has_1(searchState, "indices.".concat(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 }; } // eslint-disable-next-line max-params function getCurrentRefinementValue(props, searchState, context, id, defaultValue) { var refinementsCallback = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : function (x) { return x; }; var indexId = getIndexId(context); var _getNamespaceAndAttri = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri.namespace, attributeName = _getNamespaceAndAttri.attributeName; var refinements = hasMultipleIndices(context) && searchState.indices && namespace && searchState.indices["".concat(indexId)] && has_1(searchState.indices["".concat(indexId)][namespace], "".concat(attributeName)) || hasMultipleIndices(context) && searchState.indices && has_1(searchState, "indices.".concat(indexId, ".").concat(id)) || !hasMultipleIndices(context) && namespace && has_1(searchState[namespace], attributeName) || !hasMultipleIndices(context) && has_1(searchState, id); if (refinements) { var currentRefinement; if (hasMultipleIndices(context)) { currentRefinement = namespace ? get_1(searchState.indices["".concat(indexId)][namespace], attributeName) : get_1(searchState.indices[indexId], id); } else { currentRefinement = namespace ? get_1(searchState[namespace], attributeName) : get_1(searchState, id); } return refinementsCallback(currentRefinement); } if (props.defaultRefinement) { return props.defaultRefinement; } return defaultValue; } function cleanUpValue(searchState, context, id) { var indexId = getIndexId(context); var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id), namespace = _getNamespaceAndAttri2.namespace, attributeName = _getNamespaceAndAttri2.attributeName; if (hasMultipleIndices(context) && Boolean(searchState.indices)) { return cleanUpValueWithMutliIndex({ attribute: attributeName, searchState: searchState, indexId: indexId, id: id, namespace: namespace }); } return cleanUpValueWithSingleIndex({ attribute: attributeName, searchState: searchState, id: id, namespace: namespace }); } function cleanUpValueWithSingleIndex(_ref) { var searchState = _ref.searchState, id = _ref.id, namespace = _ref.namespace, attribute = _ref.attribute; if (namespace) { return _objectSpread({}, searchState, _defineProperty({}, namespace, omit_1(searchState[namespace], attribute))); } return omit_1(searchState, id); } function cleanUpValueWithMutliIndex(_ref2) { var searchState = _ref2.searchState, indexId = _ref2.indexId, id = _ref2.id, namespace = _ref2.namespace, attribute = _ref2.attribute; var indexSearchState = searchState.indices[indexId]; if (namespace && indexSearchState) { return _objectSpread({}, searchState, { indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, indexSearchState, _defineProperty({}, namespace, omit_1(indexSearchState[namespace], attribute))))) }); } return omit_1(searchState, "indices.".concat(indexId, ".").concat(id)); } var isMultiIndexContext = function isMultiIndexContext(widget) { return hasMultipleIndices(widget.context); }; var isTargetedIndexEqualIndex = function isTargetedIndexEqualIndex(widget, indexId) { return widget.context.multiIndexContext.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; }; /** * 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)); 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); var store = createStore({ widgets: initialState, metadata: [], results: resultsState || null, error: null, searching: false, isSearchStalled: true, searchingForFacetValues: false }); function skipSearch() { skip = true; } function updateClient(client) { helper.setClient(client); search(); } function clearCache() { helper.clearCache(); search(); } function getMetadata(state) { return widgetsManager.getWidgets().filter(function (widget) { return Boolean(widget.getMetadata); }).map(function (widget) { return widget.getMetadata(state); }); } function getSearchParameters() { 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; }).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; }).reduce(function (indices, widget) { var indexId = isMultiIndexContext(widget) ? widget.context.multiIndexContext.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(helper.state), 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 (content) { 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] = content; } else { results = content; } var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); stalledSearchTimer = null; nextIsSearchStalled = false; } var nextState = omit_1(_objectSpread({}, currentState, { results: results, isSearchStalled: nextIsSearchStalled, searching: false, error: null }), 'resultsFacetValues'); store.setState(nextState); }; } function handleSearchError(error) { var currentState = store.getState(); var nextIsSearchStalled = currentState.isSearchStalled; if (!helper.hasPendingRequests()) { clearTimeout(stalledSearchTimer); nextIsSearchStalled = false; } var nextState = omit_1(_objectSpread({}, currentState, { isSearchStalled: nextIsSearchStalled, error: error, searching: false }), 'resultsFacetValues'); store.setState(nextState); } function handleNewSearch() { if (!stalledSearchTimer) { stalledSearchTimer = setTimeout(function () { var nextState = omit_1(_objectSpread({}, store.getState(), { isSearchStalled: true }), 'resultsFacetValues'); store.setState(nextState); }, stalledSearchDelay); } } // Called whenever a widget has been rendered with new props. function onWidgetsUpdate() { var metadata = getMetadata(store.getState().widgets); store.setState(_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(_ref4) { var facetName = _ref4.facetName, query = _ref4.query, _ref4$maxFacetHits = _ref4.maxFacetHits, maxFacetHits = _ref4$maxFacetHits === void 0 ? 10 : _ref4$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 _objectSpread3; store.setState(_objectSpread({}, store.getState(), { error: null, searchingForFacetValues: false, resultsFacetValues: _objectSpread({}, store.getState().resultsFacetValues, (_objectSpread3 = {}, _defineProperty(_objectSpread3, facetName, content.facetHits), _defineProperty(_objectSpread3, "query", query), _objectSpread3)) })); }, 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); 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, getSearchParameters: getSearchParameters, onSearchForFacetValues: onSearchForFacetValues, onExternalStateUpdate: onExternalStateUpdate, transitionState: transitionState, updateClient: updateClient, updateIndex: updateIndex, clearCache: clearCache, skipSearch: skipSearch }; } 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"); } } /** * @description * `<InstantSearch>` is the root component of all React InstantSearch implementations. * It provides all the connected components (aka widgets) a means to interact * with the searchState. * @kind widget * @name <InstantSearch> * @requirements You will need to have an Algolia account to be able to use this widget. * [Create one now](https://www.algolia.com/users/sign_up). * @propType {string} appId - Your Algolia application id. * @propType {string} apiKey - Your Algolia search-only API key. * @propType {string} indexName - Main index in which to search. * @propType {boolean} [refresh=false] - Flag to activate when the cache needs to be cleared so that the front-end is updated when a change occurs in the index. * @propType {object} [algoliaClient] - Provide a custom Algolia client instead of the internal one (deprecated in favor of `searchClient`). * @propType {object} [searchClient] - Provide a custom search client. * @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html). * @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html). * @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html). * @propType {SearchResults|SearchResults[]} [resultsState] - Use this to inject the results that will be used at first rendering. Those results are found by using the `findResultsState` function. Useful for [Server Side Rendering](guide/Server-side_rendering.html). * @propType {number} [stalledSearchDelay=200] - The amount of time before considering that the search takes too much time. The time is expressed in milliseconds. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import React from 'react'; * import { InstantSearch, SearchBox, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <SearchBox /> * <Hits /> * </InstantSearch> * ); */ var InstantSearch = /*#__PURE__*/ function (_Component) { _inherits(InstantSearch, _Component); function InstantSearch(props) { var _this; _classCallCheck(this, InstantSearch); _this = _possibleConstructorReturn(this, _getPrototypeOf(InstantSearch).call(this, props)); _this.isControlled = Boolean(props.searchState); var initialState = _this.isControlled ? props.searchState : {}; _this.isUnmounting = false; _this.aisManager = createInstantSearchManager({ indexName: props.indexName, searchClient: props.searchClient, initialState: initialState, resultsState: props.resultsState, stalledSearchDelay: props.stalledSearchDelay }); return _this; } _createClass(InstantSearch, [{ key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { validateNextProps(this.props, nextProps); if (this.props.indexName !== nextProps.indexName) { this.aisManager.updateIndex(nextProps.indexName); } if (this.props.refresh !== nextProps.refresh) { if (nextProps.refresh) { this.aisManager.clearCache(); } } if (this.props.searchClient !== nextProps.searchClient) { this.aisManager.updateClient(nextProps.searchClient); } if (this.isControlled) { this.aisManager.onExternalStateUpdate(nextProps.searchState); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.isUnmounting = true; this.aisManager.skipSearch(); } }, { key: "getChildContext", value: function getChildContext() { // If not already cached, cache the bound methods so that we can forward them as part // of the context. if (!this._aisContextCache) { this._aisContextCache = { ais: { onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this), createHrefForState: this.createHrefForState.bind(this), onSearchForFacetValues: this.onSearchForFacetValues.bind(this), onSearchStateChange: this.onSearchStateChange.bind(this), onSearchParameters: this.onSearchParameters.bind(this) } }; } return { ais: _objectSpread({}, this._aisContextCache.ais, { store: this.aisManager.store, widgetsManager: this.aisManager.widgetsManager, mainTargetedIndex: this.props.indexName }) }; } }, { key: "createHrefForState", value: function createHrefForState(searchState) { searchState = this.aisManager.transitionState(searchState); return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#'; } }, { key: "onWidgetsInternalStateUpdate", value: function onWidgetsInternalStateUpdate(searchState) { searchState = this.aisManager.transitionState(searchState); this.onSearchStateChange(searchState); if (!this.isControlled) { this.aisManager.onExternalStateUpdate(searchState); } } }, { key: "onSearchStateChange", value: function onSearchStateChange(searchState) { if (this.props.onSearchStateChange && !this.isUnmounting) { this.props.onSearchStateChange(searchState); } } }, { key: "onSearchParameters", value: function onSearchParameters(getSearchParameters, context, props) { if (this.props.onSearchParameters) { var searchState = this.props.searchState ? this.props.searchState : {}; this.props.onSearchParameters(getSearchParameters, context, props, searchState); } } }, { key: "onSearchForFacetValues", value: function onSearchForFacetValues(searchState) { this.aisManager.onSearchForFacetValues(searchState); } }, { key: "getKnownKeys", value: function getKnownKeys() { return this.aisManager.getWidgetsIds(); } }, { key: "render", value: function render() { var childrenCount = React.Children.count(this.props.children); var _this$props$root = this.props.root, Root = _this$props$root.Root, props = _this$props$root.props; if (childrenCount === 0) return null;else return React__default.createElement(Root, props, this.props.children); } }]); return InstantSearch; }(React.Component); InstantSearch.defaultProps = { stalledSearchDelay: 200 }; InstantSearch.childContextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; var version$2 = '5.5.0'; /** * 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 = /*#__PURE__*/ function (_Component) { _inherits(CreateInstantSearch, _Component); function CreateInstantSearch() { var _getPrototypeOf2; var _this; _classCallCheck(this, CreateInstantSearch); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(CreateInstantSearch)).call.apply(_getPrototypeOf2, [this].concat(args))); if (_this.props.searchClient) { if (_this.props.appId || _this.props.apiKey || _this.props.algoliaClient) { throw new Error('react-instantsearch:: `searchClient` cannot be used with `appId`, `apiKey` or `algoliaClient`.'); } } if (_this.props.algoliaClient) { // eslint-disable-next-line no-console console.warn('`algoliaClient` option was renamed `searchClient`. Please use this new option before the next major version.'); } _this.client = _this.props.searchClient || _this.props.algoliaClient || defaultAlgoliaClient(_this.props.appId, _this.props.apiKey, { _useRequestCache: true }); if (typeof _this.client.addAlgoliaAgent === 'function') { _this.client.addAlgoliaAgent("react (".concat(React__default.version, ")")); _this.client.addAlgoliaAgent("react-instantsearch (".concat(version$2, ")")); } return _this; } _createClass(CreateInstantSearch, [{ key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { var props = this.props; if (nextProps.searchClient) { this.client = nextProps.searchClient; } else if (nextProps.algoliaClient) { this.client = nextProps.algoliaClient; } else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) { this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey); } if (typeof this.client.addAlgoliaAgent === 'function') { this.client.addAlgoliaAgent("react (".concat(React__default.version, ")")); this.client.addAlgoliaAgent("react-instantsearch (".concat(version$2, ")")); } } }, { key: "render", value: function render() { return React__default.createElement(InstantSearch, { createURL: this.props.createURL, indexName: this.props.indexName, searchState: this.props.searchState, onSearchStateChange: this.props.onSearchStateChange, onSearchParameters: this.props.onSearchParameters, root: this.props.root, searchClient: this.client, algoliaClient: this.client, refresh: this.props.refresh, resultsState: this.props.resultsState }, this.props.children); } }]); return CreateInstantSearch; }(React.Component), _defineProperty(_class, "propTypes", { algoliaClient: propTypes.object, searchClient: propTypes.object, appId: propTypes.string, apiKey: propTypes.string, children: propTypes.oneOfType([propTypes.arrayOf(propTypes.node), propTypes.node]), indexName: propTypes.string.isRequired, createURL: propTypes.func, searchState: propTypes.object, refresh: propTypes.bool.isRequired, onSearchStateChange: propTypes.func, onSearchParameters: propTypes.func, resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]), root: propTypes.shape({ Root: propTypes.oneOfType([propTypes.string, propTypes.func, propTypes.object]).isRequired, props: propTypes.object }) }), _defineProperty(_class, "defaultProps", { refresh: false, root: root }), _temp; } /** * @description * `<Index>` is the component that allows you to apply widgets to a dedicated index. It's * useful if you want to build an interface that targets multiple indices. * @kind widget * @name <Index> * @propType {string} indexName - index in which to search. * @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }` * @example * import React from 'react'; * import { InstantSearch, Index, SearchBox, Hits, Configure } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="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); function Index() { var _getPrototypeOf2; var _this; _classCallCheck(this, Index); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Index)).call.apply(_getPrototypeOf2, [this].concat(args))); /* we want <Index> to be seen as a regular widget. It means that with only <Index> present a new query will be sent to Algolia. That way you don't need a virtual hits widget to use the connectAutoComplete. */ _this.unregisterWidget = _this.context.ais.widgetsManager.registerWidget(_assertThisInitialized(_this)); return _this; } _createClass(Index, [{ key: "componentWillMount", value: function componentWillMount() { this.context.ais.onSearchParameters(this.getSearchParameters.bind(this), this.getChildContext(), this.props); } }, { key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { if (this.props.indexName !== nextProps.indexName) { this.context.ais.widgetsManager.update(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unregisterWidget(); } }, { key: "getChildContext", value: function getChildContext() { return { multiIndexContext: { targetedIndex: this.props.indexId } }; } }, { key: "getSearchParameters", value: function getSearchParameters(searchParameters, props) { return searchParameters.setIndex(this.props ? this.props.indexName : props.indexName); } }, { key: "render", value: function render() { var childrenCount = React.Children.count(this.props.children); var _this$props$root = this.props.root, Root = _this$props$root.Root, props = _this$props$root.props; if (childrenCount === 0) return null;else return React__default.createElement(Root, props, this.props.children); } }]); return Index; }(React.Component); Index.childContextTypes = { multiIndexContext: propTypes.object.isRequired }; Index.contextTypes = { // @TODO: more precise widgets manager propType ais: propTypes.object.isRequired }; /** * Creates a specialized root Index component. It accepts * a specification of the root Element. * @param {object} defaultRoot - the defininition of the root of an Index sub tree. * @return {object} a Index root */ var createIndex = function createIndex(defaultRoot) { var CreateIndex = function CreateIndex(_ref) { var indexName = _ref.indexName, indexId = _ref.indexId, root = _ref.root, children = _ref.children; return React__default.createElement(Index, { indexName: indexName, indexId: indexId || indexName, root: root }, children); }; CreateIndex.defaultProps = { root: defaultRoot }; return CreateIndex; }; 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); } /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = has_1(connectorDesc, 'refine'); var hasSearchForFacetValues = has_1(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = has_1(connectorDesc, 'getSearchParameters'); var hasMetadata = has_1(connectorDesc, 'getMetadata'); var hasTransitionState = has_1(connectorDesc, 'transitionState'); var hasCleanUp = has_1(connectorDesc, 'cleanUp'); var hasShouldComponentUpdate = has_1(connectorDesc, 'shouldComponentUpdate'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp; return _temp = _class = /*#__PURE__*/ function (_Component) { _inherits(Connector, _Component); function Connector() { var _getPrototypeOf2; var _this; _classCallCheck(this, Connector); for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) { _args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Connector)).call.apply(_getPrototypeOf2, [this].concat(_args))); _defineProperty(_assertThisInitialized(_this), "mounted", false); _defineProperty(_assertThisInitialized(_this), "unmounting", false); _defineProperty(_assertThisInitialized(_this), "refine", function () { var _connectorDesc$refine; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_assertThisInitialized(_this), _this.props, _this.context.ais.store.getState().widgets].concat(args))); }); _defineProperty(_assertThisInitialized(_this), "createURL", function () { var _connectorDesc$refine2; for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_assertThisInitialized(_this), _this.props, _this.context.ais.store.getState().widgets].concat(args))); }); _defineProperty(_assertThisInitialized(_this), "searchForFacetValues", function () { for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } _this.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this.props, _this.context.ais.store.getState().widgets].concat(args))); }); _this.state = { props: _this.getProvidedProps(_objectSpread({}, _this.props, { // @MAJOR: We cannot drop this beacuse it's a breaking change. The // prop is provided to `createConnector.getProvidedProps`. All the // custom connectors are impacted by this change. It should be fine // to drop it in the next major though. canRender: false })) }; return _this; } _createClass(Connector, [{ key: "componentWillMount", value: function componentWillMount() { if (connectorDesc.getSearchParameters) { this.context.ais.onSearchParameters(connectorDesc.getSearchParameters.bind(this), this.context, this.props); } } }, { key: "componentDidMount", value: function componentDidMount() { var _this2 = this; this.mounted = true; this.unsubscribe = this.context.ais.store.subscribe(function () { if (!_this2.unmounting) { _this2.setState({ props: _this2.getProvidedProps(_objectSpread({}, _this2.props, { // @MAJOR: see constructor canRender: true })) }); } }); if (isWidget) { this.unregisterWidget = this.context.ais.widgetsManager.registerWidget(this); } } }, { key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { if (!isEqual_1(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(_objectSpread({}, nextProps, { // @MAJOR: see constructor canRender: this.mounted })) }); if (isWidget) { 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: "shouldComponentUpdate", value: function shouldComponentUpdate(nextProps, nextState) { if (hasShouldComponentUpdate) { return connectorDesc.shouldComponentUpdate.call(this, this.props, nextProps, this.state, nextState); } var propsEqual = shallowEqual(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !shallowEqual(this.state.props, nextState.props); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this.unmounting = true; if (this.unsubscribe) { this.unsubscribe(); } if (this.unregisterWidget) { this.unregisterWidget(); if (hasCleanUp) { var nextState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_objectSpread({}, this.context.ais.store.getState(), { widgets: nextState })); this.context.ais.onSearchStateChange(removeEmptyKey(nextState)); } } } }, { key: "getProvidedProps", value: function getProvidedProps(props) { var _this$context$ais$sto = this.context.ais.store.getState(), widgets = _this$context$ais$sto.widgets, results = _this$context$ais$sto.results, resultsFacetValues = _this$context$ais$sto.resultsFacetValues, searching = _this$context$ais$sto.searching, searchingForFacetValues = _this$context$ais$sto.searchingForFacetValues, isSearchStalled = _this$context$ais$sto.isSearchStalled, metadata = _this$context$ais$sto.metadata, error = _this$context$ais$sto.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 resutls? resultsFacetValues); } }, { key: "getSearchParameters", value: function getSearchParameters(searchParameters) { if (hasSearchParameters) { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.context.ais.store.getState().widgets); } return null; } }, { key: "getMetadata", value: function getMetadata(nextWidgetsState) { if (hasMetadata) { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: "transitionState", value: function transitionState(prevWidgetsState, nextWidgetsState) { if (hasTransitionState) { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { key: "render", value: function render() { if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues } : {}; return React__default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component), _defineProperty(_class, "displayName", "".concat(connectorDesc.displayName, "(").concat(getDisplayName(Composed), ")")), _defineProperty(_class, "defaultClassNames", Composed.defaultClassNames), _defineProperty(_class, "propTypes", connectorDesc.propTypes), _defineProperty(_class, "defaultProps", connectorDesc.defaultProps), _defineProperty(_class, "contextTypes", { // @TODO: more precise state manager propType ais: propTypes.object.isRequired, multiIndexContext: propTypes.object }), _temp; }; } 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 && has_1(translations, 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; }; } /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE$1 = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = _arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = _arrayMap(values, _baseUnary(iteratee)); } if (comparator) { includes = _arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE$1) { includes = _cacheHas; isCommon = false; values = new _SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } var _baseDifference = baseDifference; /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = _baseRest(function(array, values) { return isArrayLikeObject_1(array) ? _baseDifference(array, _baseFlatten(values, 1, isArrayLikeObject_1, true)) : []; }); var difference_1 = difference; function getId() { return 'configure'; } var connectConfigure = createConnector({ displayName: 'AlgoliaConfigure', getProvidedProps: function getProvidedProps() { return {}; }, getSearchParameters: function getSearchParameters(searchParameters, props) { var items = omit_1(props, 'children'); return searchParameters.setQueryParameters(items); }, transitionState: function transitionState(props, prevSearchState, nextSearchState) { var id = getId(); var items = omit_1(props, 'children'); var nonPresentKeys = this._props ? difference_1(keys_1(this._props), keys_1(props)) : []; this._props = props; var nextValue = _defineProperty({}, id, _objectSpread({}, omit_1(nextSearchState[id], nonPresentKeys), items)); return refineValue(nextSearchState, nextValue, this.context); }, cleanUp: function cleanUp(props, searchState) { var id = getId(); var indexId = getIndexId(this.context); var subState = hasMultipleIndices(this.context) && 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, this.context); } }); /** * Configure is a widget that lets you provide raw search parameters * to the Algolia API. * * Any of the props added to this widget will be forwarded to Algolia. For more information * on the different parameters that can be set, have a look at the * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). * * This widget can be used either with react-dom and react-native. It will not render anything * on screen, only configure some parameters. * * Read more in the [Search parameters](guide/Search_parameters.html) guide. * @name Configure * @kind widget * @example * import React from 'react'; * import { InstantSearch, Configure, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <Configure hitsPerPage={5} /> * <Hits /> * </InstantSearch> * ); */ var Configure = connectConfigure(function () { return null; }); 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(); } // See https://www.algolia.com/doc/guides/managing-results/refine-results/merchandising-and-promoting/in-depth/implementing-query-rules/#context function escapeRuleContext(ruleName) { return ruleName.replace(/[^a-z0-9-_]+/gi, '_'); } function getWidgetRefinements(attribute, widgetKey, searchState) { var widgetState = searchState[widgetKey]; switch (widgetKey) { case 'range': return Object.keys(widgetState[attribute]).map(function (rangeKey) { return widgetState[attribute][rangeKey]; }); case 'refinementList': return widgetState[attribute]; case 'hierarchicalMenu': return [widgetState[attribute]]; case 'menu': return [widgetState[attribute]]; case 'multiRange': return widgetState[attribute].split(':'); case 'toggle': return [widgetState[attribute]]; default: return []; } } function getRefinements(attribute) { var searchState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var refinements = Object.keys(searchState).filter(function (widgetKey) { return typeof searchState[widgetKey][attribute] !== 'undefined'; }).map(function (widgetKey) { return getWidgetRefinements(attribute, widgetKey, searchState); }).reduce(function (acc, current) { return acc.concat(current); }, []); // flatten the refinements return refinements; } function getRuleContextsFromTrackedFilters(_ref) { var searchState = _ref.searchState, trackedFilters = _ref.trackedFilters; var ruleContexts = Object.keys(trackedFilters).reduce(function (facets, facetName) { var facetRefinements = getRefinements(facetName, searchState); var getTrackedFacetValues = trackedFilters[facetName]; var trackedFacetValues = getTrackedFacetValues(facetRefinements); return [].concat(_toConsumableArray(facets), _toConsumableArray(facetRefinements.filter(function (facetRefinement) { return trackedFacetValues.includes(facetRefinement); }).map(function (facetValue) { return escapeRuleContext("ais-".concat(facetName, "-").concat(facetValue)); }))); }, []); return ruleContexts; } var connectQueryRules = createConnector({ displayName: 'AlgoliaQueryRules', defaultProps: { transformItems: function transformItems(items) { return items; }, transformRuleContexts: function transformRuleContexts(ruleContexts) { return ruleContexts; }, trackedFilters: {} }, getProvidedProps: function getProvidedProps(props, _1, searchResults) { var results = getResults(searchResults, this.context); if (results === null) { return { items: [], canRefine: false }; } var _results$userData = results.userData, userData = _results$userData === void 0 ? [] : _results$userData; var transformItems = props.transformItems; var transformedItems = transformItems(userData); return { items: transformedItems, canRefine: transformedItems.length > 0 }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { if (Object.keys(props.trackedFilters).length === 0) { return searchParameters; } var indexSearchState = hasMultipleIndices(this.context) ? searchState.indices[getIndexId(this.context)] : searchState; var newRuleContexts = getRuleContextsFromTrackedFilters({ searchState: indexSearchState, trackedFilters: props.trackedFilters }); var initialRuleContexts = searchParameters.ruleContexts || []; var nextRuleContexts = [].concat(_toConsumableArray(initialRuleContexts), _toConsumableArray(newRuleContexts)); var ruleContexts = props.transformRuleContexts(nextRuleContexts).slice(0, 10); return searchParameters.setQueryParameter('ruleContexts', ruleContexts); } }); connectQueryRules(function QueryRuleContext() { return null; }); var getId$1 = function getId() { return 'query'; }; function getCurrentRefinement(props, searchState, context) { var id = getId$1(); return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return ''; }); } function getHits(searchResults) { if (searchResults.results) { if (searchResults.results.hits && Array.isArray(searchResults.results.hits)) { return searchResults.results.hits; } else { return Object.keys(searchResults.results).reduce(function (hits, index) { return [].concat(_toConsumableArray(hits), [{ index: index, hits: searchResults.results[index].hits }]); }, []); } } else { return []; } } function _refine(props, searchState, nextRefinement, context) { var id = getId$1(); var nextValue = _defineProperty({}, 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 */ createConnector({ displayName: 'AlgoliaAutoComplete', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { hits: getHits(searchResults), currentRefinement: getCurrentRefinement(props, searchState, this.context) }; }, refine: function refine(props, searchState, nextRefinement) { return _refine(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp(props, searchState, this.context); }, /* connectAutoComplete needs to be considered as a widget to trigger a search if no others widgets are used. * To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState * See createConnector.js * */ getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement(props, searchState, this.context)); } }); 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, acc)); } } return acc; }, []); } /** * The breadcrumb component is s a type of secondary navigation scheme that * reveals the user’s location in a website or web application. * * @name connectBreadcrumb * @requirements To use this widget, your attributes must be formatted in a specific way. * If you want for example to have a Breadcrumb of categories, objects in your index * should be formatted this way: * * ```json * { * "categories.lvl0": "products", * "categories.lvl1": "products > fruits", * "categories.lvl2": "products > fruits > citrus" * } * ``` * * It's also possible to provide more than one path for each level: * * ```json * { * "categories.lvl0": ["products", "goods"], * "categories.lvl1": ["products > fruits", "goods > to eat"] * } * ``` * * All attributes passed to the `attributes` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * * @kind connector * @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display. */ var connectBreadcrumb = createConnector({ displayName: 'AlgoliaBreadcrumb', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error("Invalid prop ".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, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], canRefine: false }; } var values = results.getFacetValues(id); var items = values.data ? transformValue(values.data) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { canRefine: transformedItems.length > 0, items: transformedItems }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$1(props, searchState, nextRefinement, this.context); } }); /** * connectCurrentRefinements connector provides the logic to build a widget that will * give the user the ability to remove all or some of the filters that were * set. * @name connectCurrentRefinements * @kind connector * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @propType {function} [clearsQuery=false] - Pass true to also clear the search query * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {array.<{label: string, attribute: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attribute` and `currentRefinement` are metadata containing row values. * @providedPropType {string} query - the search query */ var connectCurrentRefinements = createConnector({ displayName: 'AlgoliaCurrentRefinements', propTypes: { transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) { var items = metadata.reduce(function (res, meta) { if (typeof meta.items !== 'undefined') { if (!props.clearsQuery && meta.id === 'query') { return res; } else { if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') { return res; } return res.concat(meta.items.map(function (item) { return _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); } }); 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; } /** * 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 (isEmpty_1(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); }; createConnector({ displayName: 'AlgoliaGeoSearch', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.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 immediatly 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, this.context); var currentRefinementFromSearchParameters = results && results._state.insideBoundingBox && stringToCurrentRefinement(results._state.insideBoundingBox) || undefined; var currentPositionFromSearchState = getCurrentPosition(props, searchState, this.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, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var currentRefinement = getCurrentRefinement$1(props, searchState, this.context); if (!currentRefinement) { return searchParameters; } return searchParameters.setQueryParameter('insideBoundingBox', currentRefinementToString(currentRefinement)); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getBoundingBoxId()); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var items = []; var id = getBoundingBoxId(); var index = getIndexId(this.context); var nextRefinement = {}; var currentRefinement = getCurrentRefinement$1(props, searchState, this.context); if (currentRefinement) { items.push({ label: "".concat(id, ": ").concat(currentRefinementToString(currentRefinement)), value: function value(nextState) { return _refine$2(nextState, nextRefinement, _this.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) { return getCurrentRefinementValue(props, searchState, context, "".concat(namespace$1, ".").concat(getId$3(props)), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$1(path, props, searchState, context) { var id = props.id, attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel; var currentRefinement = getCurrentRefinement$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$1(v.path, props, searchState, context), count: v.count, isRefined: v.isRefined, items: v.data && transformValue$1(v.data, props, searchState, context) }; }); } var truncate = function truncate() { var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; return items.slice(0, limit).map(function () { var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return Array.isArray(item.items) ? _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 = createConnector({ displayName: 'AlgoliaHierarchicalMenu', propTypes: { attributes: function attributes(props, propName, componentName) { var isNotString = function isNotString(val) { return typeof val !== 'string'; }; if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) { return new Error("Invalid prop ".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, this.context); var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id)); if (!isFacetPresent) { return { items: [], currentRefinement: getCurrentRefinement$2(props, searchState, this.context), canRefine: false }; } var itemsLimit = showMore ? showMoreLimit : limit; var value = results.getFacetValues(id, { sortBy: sortBy }); var items = value.data ? transformValue$1(value.data, props, searchState, this.context) : []; var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: truncate(transformedItems, itemsLimit), currentRefinement: getCurrentRefinement$2(props, searchState, this.context), canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$3(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$1(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attributes = props.attributes, separator = props.separator, rootPath = props.rootPath, showParentLevel = props.showParentLevel, showMore = props.showMore, limit = props.limit, showMoreLimit = props.showMoreLimit; var id = getId$3(props); var itemsLimit = showMore ? showMoreLimit : limit; searchParameters = searchParameters.addHierarchicalFacet({ name: id, attributes: attributes, separator: separator, rootPath: rootPath, showParentLevel: showParentLevel }).setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, itemsLimit) }); var currentRefinement = getCurrentRefinement$2(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var rootAttribute = props.attributes[0]; var id = getId$3(props); var currentRefinement = getCurrentRefinement$2(props, searchState, this.context); return { id: id, index: getIndexId(this.context), items: !currentRefinement ? [] : [{ label: "".concat(rootAttribute, ": ").concat(currentRefinement), attribute: rootAttribute, value: function value(nextState) { return _refine$3(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); var highlight = function highlight(_ref) { var attribute = _ref.attribute, hit = _ref.hit, highlightProperty = _ref.highlightProperty, _ref$preTag = _ref.preTag, preTag = _ref$preTag === 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 { InstantSearch, SearchBox, Hits, connectHighlight } from 'react-instantsearch-dom'; * * const CustomHighlight = connectHighlight( * ({ highlight, attribute, hit, highlightProperty }) => { * const highlights = highlight({ * highlightProperty: '_highlightResult', * attribute, * hit * }); * * return highlights.map(part => part.isHighlighted ? ( * <mark>{part.value}</mark> * ) : ( * <span>{part.value}</span> * )); * } * ); * * const Hit = ({ hit }) => ( * <p> * <CustomHighlight attribute="name" hit={hit} /> * </p> * ); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <SearchBox defaultRefinement="pho" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var connectHighlight = createConnector({ displayName: 'AlgoliaHighlighter', propTypes: {}, getProvidedProps: function getProvidedProps() { return { highlight: highlight }; } }); /** * connectHits connector provides the logic to create connected * components that will render the results retrieved from * Algolia. * * To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html), * [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage * prop to a [Configure](guide/Search_parameters.html) widget. * * **Warning:** you will need to use the **objectID** property available on every hit as a key * when iterating over them. This will ensure you have the best possible UI experience * especially on slow networks. * @name connectHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @example * import React from 'react'; * import { InstantSearch, Highlight, connectHits } from 'react-instantsearch-dom'; * * const CustomHits = connectHits(({ hits }) => ( * <div> * {hits.map(hit => * <p key={hit.objectID}> * <Highlight attribute="name" hit={hit} /> * </p> * )} * </div> * )); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <CustomHits /> * </InstantSearch> * ); */ var connectHits = createConnector({ displayName: 'AlgoliaHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); 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 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; } }); function getId$4() { return 'hitsPerPage'; } function getCurrentRefinement$3(props, searchState, context) { var id = getId$4(); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (typeof currentRefinement === 'string') { return parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * connectHitsPerPage connector provides the logic to create connected * components that will allow a user to choose to display more or less results from Algolia. * @name connectHitsPerPage * @kind connector * @propType {number} defaultRefinement - The number of items selected by default * @propType {{value: number, label: string}[]} items - List of hits per page options. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectHitsPerPage = createConnector({ displayName: 'AlgoliaHitsPerPage', propTypes: { defaultRefinement: propTypes.number.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.number.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$3(props, searchState, this.context); 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, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$4()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setHitsPerPage(getCurrentRefinement$3(props, searchState, this.context)); }, 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; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { if (typeof currentRefinement === 'string') { currentRefinement = parseInt(currentRefinement, 10); } return currentRefinement; }); } /** * InfiniteHits connector provides the logic to create connected * components that will render an continuous list of results retrieved from * Algolia. This connector provides a function to load more results. * @name connectInfiniteHits * @kind connector * @providedPropType {array.<object>} hits - the records that matched the search state * @providedPropType {boolean} hasMore - indicates if there are more pages to load * @providedPropType {function} refine - call to load more results */ var connectInfiniteHits = createConnector({ displayName: 'AlgoliaInfiniteHits', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); this._allResults = this._allResults || []; this._previousPage = this._previousPage || 0; if (!results) { return { hits: [], hasMore: false }; } var hits = results.hits, hitsPerPage = results.hitsPerPage, page = results.page, nbPages = results.nbPages; var hitsWithPositions = addAbsolutePositions(hits, hitsPerPage, page); var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID); if (page === 0) { this._allResults = hitsWithPositionsAndQueryID; } else if (page > this._previousPage) { this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hitsWithPositionsAndQueryID)); } else if (page < this._previousPage) { this._allResults = hitsWithPositionsAndQueryID; } var lastPageIndex = nbPages - 1; var hasMore = page < lastPageIndex; this._previousPage = page; return { hits: this._allResults, hasMore: hasMore }; }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQueryParameters({ page: getCurrentRefinement$4(props, searchState, this.context) - 1 }); }, refine: function refine(props, searchState) { var id = getId$5(); var nextPage = getCurrentRefinement$4(props, searchState, this.context) + 1; var nextValue = _defineProperty({}, id, nextPage); var resetPage = false; return refineValue(searchState, nextValue, this.context, resetPage); } }); var namespace$2 = 'menu'; function getId$6(props) { return props.attribute; } function getCurrentRefinement$5(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, "".concat(namespace$2, ".").concat(getId$6(props)), null, function (currentRefinement) { if (currentRefinement === '') { return null; } return currentRefinement; }); } function getValue$2(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 sortBy$1 = ['count:desc', 'name:asc']; /** * connectMenu connector provides the logic to build a widget that will * give the user the ability to choose a single value for a specific facet. * @name connectMenu * @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting" * on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API. * @kind connector * @propType {string} attribute - the name of the attribute in the record * @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items * @propType {number} [limit=10] - the minimum number of diplayed items * @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true` * @propType {string} [defaultRefinement] - the value of the item selected by default * @propType {boolean} [searchable=false] - allow search inside values * @providedPropType {function} refine - a function to toggle a refinement * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string} currentRefinement - the refinement currently applied * @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display. * @providedPropType {function} searchForItems - a function to toggle a search inside items values * @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items. */ var connectMenu = createConnector({ displayName: 'AlgoliaMenu', propTypes: { attribute: propTypes.string.isRequired, showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, defaultRefinement: propTypes.string, transformItems: propTypes.func, searchable: propTypes.bool }, defaultProps: { showMore: false, limit: 10, showMoreLimit: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) { var _this = this; var attribute = props.attribute, searchable = props.searchable; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search) if (searchable && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$5(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: canRefine }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$2(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attribute, { sortBy: sortBy$1 }).map(function (v) { return { label: v.name, value: getValue$2(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var sortedItems = searchable && !isFromSearch ? orderBy_1(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items; var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems; return { items: transformedItems.slice(0, getLimit(props)), currentRefinement: getCurrentRefinement$5(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$4(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$2(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit(props)) }); searchParameters = searchParameters.addDisjunctiveFacet(attribute); var currentRefinement = getCurrentRefinement$5(props, searchState, this.context); if (currentRefinement !== null) { searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this2 = this; var id = getId$6(props); var currentRefinement = getCurrentRefinement$5(props, searchState, this.context); return { id: id, index: getIndexId(this.context), items: currentRefinement === null ? [] : [{ label: "".concat(props.attribute, ": ").concat(currentRefinement), attribute: props.attribute, value: function value(nextState) { return _refine$4(props, nextState, '', _this2.context); }, 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$7(props) { return props.attribute; } function getCurrentRefinement$6(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, "".concat(namespace$3, ".").concat(getId$7(props)), '', function (currentRefinement) { if (currentRefinement === '') { return ''; } return currentRefinement; }); } function isRefinementsRangeIncludesInsideItemRange(stats, start, end) { return stats.min > start && stats.min < end || stats.max > start && stats.max < end; } function isItemRangeIncludedInsideRefinementsRange(stats, start, end) { return start > stats.min && start < stats.max || end > stats.min && end < stats.max; } function itemHasRefinement(attribute, results, value) { var stats = results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null; var range = value.split(':'); var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]); var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]); return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end))); } function _refine$5(props, searchState, nextRefinement, context) { var nextValue = _defineProperty({}, getId$7(props, searchState), nextRefinement); var resetPage = true; return refineValue(searchState, nextValue, context, resetPage, namespace$3); } function _cleanUp$3(props, searchState, context) { return cleanUpValue(searchState, context, "".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 = createConnector({ displayName: 'AlgoliaNumericMenu', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.node, start: propTypes.number, end: propTypes.number })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute; var currentRefinement = getCurrentRefinement$6(props, searchState, this.context); var results = getResults(searchResults, this.context); var items = props.items.map(function (item) { var value = stringifyItem(item); return { label: item.label, value: value, isRefined: value === currentRefinement, noRefinement: results ? itemHasRefinement(getId$7(props), results, value) : false }; }); var stats = results && results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null; var refinedItem = find_1(items, function (item) { return item.isRefined === true; }); if (!items.some(function (item) { return item.value === ''; })) { items.push({ value: '', isRefined: isEmpty_1(refinedItem), noRefinement: !stats, label: 'All' }); } 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, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$3(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute; var _parseItem = parseItem(getCurrentRefinement$6(props, searchState, this.context)), start = _parseItem.start, end = _parseItem.end; searchParameters = searchParameters.addDisjunctiveFacet(attribute); if (start) { searchParameters = searchParameters.addNumericRefinement(attribute, '>=', start); } if (end) { searchParameters = searchParameters.addNumericRefinement(attribute, '<=', end); } return searchParameters; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$7(props); var value = getCurrentRefinement$6(props, searchState, this.context); var items = []; var index = getIndexId(this.context); if (value !== '') { var _find2 = find_1(props.items, function (item) { return stringifyItem(item) === value; }), label = _find2.label; items.push({ label: "".concat(props.attribute, ": ").concat(label), attribute: props.attribute, currentRefinement: label, value: function value(nextState) { return _refine$5(props, nextState, '', _this.context); } }); } 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; return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) { 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 = createConnector({ displayName: 'AlgoliaPagination', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } var nbPages = results.nbPages; return { nbPages: nbPages, currentRefinement: getCurrentRefinement$7(props, searchState, this.context), canRefine: nbPages > 1 }; }, refine: function refine(props, searchState, nextPage) { return _refine$6(props, searchState, nextPage, this.context); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$8()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setPage(getCurrentRefinement$7(props, searchState, this.context) - 1); }, getMetadata: function getMetadata() { return { id: getId$8() }; } }); /** * connectPoweredBy connector provides the logic to build a widget that * will display a link to algolia. * @name connectPoweredBy * @kind connector * @providedPropType {string} url - the url to redirect to algolia */ var connectPoweredBy = createConnector({ displayName: 'AlgoliaPoweredBy', getProvidedProps: function getProvidedProps() { var isServer = typeof window === 'undefined'; var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + "utm_content=".concat(!isServer ? window.location.hostname : '', "&") + 'utm_campaign=poweredby'; return { url: url }; } }); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsFinite = _root.isFinite; /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite$1(value) { return typeof value == 'number' && nativeIsFinite(value); } var _isFinite = isFinite$1; /** * 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 (_isFinite(boundaries.min)) { min = boundaries.min; } else if (_isFinite(stats.min)) { min = stats.min; } else { min = undefined; } var max; if (_isFinite(boundaries.max)) { max = boundaries.max; } else if (_isFinite(stats.max)) { max = stats.max; } else { max = undefined; } return { min: min !== undefined ? Math.floor(min * pow) / pow : min, max: max !== undefined ? Math.ceil(max * pow) / pow : max }; } function getCurrentRefinement$8(props, searchState, currentRange, context) { var refinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$4, ".").concat(getId$9(props)), {}, function (currentRefinement) { var min = currentRefinement.min, max = currentRefinement.max; var isFloatPrecision = Boolean(props.precision); var nextMin = min; if (typeof nextMin === 'string') { nextMin = isFloatPrecision ? parseFloat(nextMin) : parseInt(nextMin, 10); } var nextMax = max; if (typeof nextMax === 'string') { nextMax = isFloatPrecision ? parseFloat(nextMax) : parseInt(nextMax, 10); } return { min: nextMin, max: nextMax }; }); var hasMinBound = props.min !== undefined; var hasMaxBound = props.max !== undefined; var hasMinRefinment = refinement.min !== undefined; var hasMaxRefinment = refinement.max !== undefined; if (hasMinBound && hasMinRefinment && refinement.min < currentRange.min) { throw Error("You can't provide min value lower than range."); } if (hasMaxBound && hasMaxRefinment && refinement.max > currentRange.max) { throw Error("You can't provide max value greater than range."); } if (hasMinBound && !hasMinRefinment) { refinement.min = currentRange.min; } if (hasMaxBound && !hasMaxRefinment) { refinement.max = currentRange.max; } return refinement; } function getCurrentRefinementWithRange(refinement, range) { return { min: refinement.min !== undefined ? refinement.min : range.min, max: refinement.max !== undefined ? refinement.max : range.max }; } function nextValueForRefinement(hasBound, isReset, range, value) { var next; 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 = createConnector({ displayName: 'AlgoliaRange', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, defaultRefinement: propTypes.shape({ min: propTypes.number, max: propTypes.number }), min: propTypes.number, max: propTypes.number, precision: propTypes.number, header: propTypes.node, footer: propTypes.node }, defaultProps: { precision: 0 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var attribute = props.attribute, precision = props.precision, minBound = props.min, maxBound = props.max; var results = getResults(searchResults, this.context); var hasFacet = results && results.getFacetByName(attribute); var stats = hasFacet ? results.getFacetStats(attribute) || {} : {}; var facetValues = hasFacet ? results.getFacetValues(attribute) : []; var count = facetValues.map(function (v) { return { value: v.name, count: v.count }; }); var _getCurrentRange = getCurrentRange({ min: minBound, max: maxBound }, stats, precision), rangeMin = _getCurrentRange.min, rangeMax = _getCurrentRange.max; // The searchState is not always in sync with the helper state. For example // when we set boundaries on the first render the searchState don't have // the correct refinement. If this behaviour change in the upcoming version // we could store the range inside the searchState instead of rely on `this`. this._currentRange = { min: rangeMin, max: rangeMax }; var currentRefinement = getCurrentRefinement$8(props, searchState, this._currentRange, this.context); return { min: rangeMin, max: rangeMax, canRefine: count.length > 0, currentRefinement: getCurrentRefinementWithRange(currentRefinement, this._currentRange), count: count, precision: precision }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$7(props, searchState, nextRefinement, this._currentRange, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$4(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(params, props, searchState) { var attribute = props.attribute; var _getCurrentRefinement = getCurrentRefinement$8(props, searchState, this._currentRange, this.context), min = _getCurrentRefinement.min, max = _getCurrentRefinement.max; params = params.addDisjunctiveFacet(attribute); if (min !== undefined) { params = params.addNumericRefinement(attribute, '>=', min); } if (max !== undefined) { params = params.addNumericRefinement(attribute, '<=', max); } return params; }, getMetadata: function getMetadata(props, searchState) { var _this = this; var _this$_currentRange = this._currentRange, minRange = _this$_currentRange.min, maxRange = _this$_currentRange.max; var _getCurrentRefinement2 = getCurrentRefinement$8(props, searchState, this._currentRange, this.context), minValue = _getCurrentRefinement2.min, maxValue = _getCurrentRefinement2.max; var items = []; var hasMin = minValue !== undefined; var hasMax = maxValue !== undefined; var shouldDisplayMinLabel = hasMin && minValue !== minRange; var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange; if (shouldDisplayMinLabel || shouldDisplayMaxLabel) { var fragments = [hasMin ? "".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, _this.context); }, currentRefinement: getCurrentRefinementWithRange({ min: minValue, max: maxValue }, { min: minRange, max: maxRange }) }); } return { id: getId$9(props), index: getIndexId(this.context), items: items }; } }); var namespace$5 = 'refinementList'; function getId$a(props) { return props.attribute; } function getCurrentRefinement$9(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, "".concat(namespace$5, ".").concat(getId$a(props)), [], function (currentRefinement) { if (typeof currentRefinement === 'string') { // All items were unselected if (currentRefinement === '') { return []; } // Only one item was in the searchState but we know it should be an array return [currentRefinement]; } return currentRefinement; }); } function getValue$3(name, props, searchState, context) { var currentRefinement = getCurrentRefinement$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$2 = ['isRefined', 'count:desc', 'name:asc']; var connectRefinementList = createConnector({ displayName: 'AlgoliaRefinementList', propTypes: { id: propTypes.string, attribute: propTypes.string.isRequired, operator: propTypes.oneOf(['and', 'or']), showMore: propTypes.bool, limit: propTypes.number, showMoreLimit: propTypes.number, defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])), searchable: propTypes.bool, transformItems: propTypes.func }, defaultProps: { operator: 'or', showMore: false, limit: 10, showMoreLimit: 20 }, getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) { var _this = this; var attribute = props.attribute, searchable = props.searchable; var results = getResults(searchResults, this.context); var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute)); var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search) if (searchable && this.context.multiIndexContext) { throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context'); } if (!canRefine) { return { items: [], currentRefinement: getCurrentRefinement$9(props, searchState, this.context), canRefine: canRefine, isFromSearch: isFromSearch, searchable: searchable }; } var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) { return { label: v.value, value: getValue$3(v.value, props, searchState, _this.context), _highlightResult: { label: { value: v.highlighted } }, count: v.count, isRefined: v.isRefined }; }) : results.getFacetValues(attribute, { sortBy: sortBy$2 }).map(function (v) { return { label: v.name, value: getValue$3(v.name, props, searchState, _this.context), count: v.count, isRefined: v.isRefined }; }); var transformedItems = props.transformItems ? props.transformItems(items) : items; return { items: transformedItems.slice(0, getLimit$1(props)), currentRefinement: getCurrentRefinement$9(props, searchState, this.context), isFromSearch: isFromSearch, searchable: searchable, canRefine: transformedItems.length > 0 }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$8(props, searchState, nextRefinement, this.context); }, searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) { return { facetName: props.attribute, query: nextRefinement, maxFacetHits: getLimit$1(props) }; }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$5(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, operator = props.operator; var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet'; var addRefinementKey = "".concat(addKey, "Refinement"); searchParameters = searchParameters.setQueryParameters({ maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props)) }); searchParameters = searchParameters[addKey](attribute); return getCurrentRefinement$9(props, searchState, this.context).reduce(function (res, val) { return res[addRefinementKey](attribute, val); }, searchParameters); }, getMetadata: function getMetadata(props, searchState) { var id = getId$a(props); var context = this.context; return { id: id, index: getIndexId(this.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 = createConnector({ displayName: 'AlgoliaScrollTo', propTypes: { scrollOn: propTypes.string }, defaultProps: { scrollOn: 'page' }, getProvidedProps: function getProvidedProps(props, searchState) { var id = props.scrollOn; var value = getCurrentRefinementValue(props, searchState, this.context, id, null, function (currentRefinement) { return currentRefinement; }); if (!this._prevSearchState) { this._prevSearchState = {}; } /* Get the subpart of the state that interest us*/ if (hasMultipleIndices(this.context)) { searchState = searchState.indices ? searchState.indices[getIndexId(this.context)] : {}; } /* if there is a change in the app that has been triggered by another element than "props.scrollOn (id) or the Configure widget, we need to keep track of the search state to know if there's a change in the app that was not triggered by the props.scrollOn (id) or the Configure widget. This is useful when using ScrollTo in combination of Pagination. As pagination can be change by every widget, we want to scroll only if it cames from the pagination widget itself. We also remove the configure key from the search state to do this comparaison because for now configure values are not present in the search state before a first refinement has been made and will false the results. See: https://github.com/algolia/react-instantsearch/issues/164 */ var cleanedSearchState = omit_1(omit_1(searchState, 'configure'), id); var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState); this._prevSearchState = cleanedSearchState; return { value: value, hasNotChanged: hasNotChanged }; } }); function getId$b() { return 'query'; } function getCurrentRefinement$a(props, searchState, context) { var id = getId$b(props); return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) { 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 = createConnector({ displayName: 'AlgoliaSearchBox', propTypes: { defaultRefinement: propTypes.string }, getProvidedProps: function getProvidedProps(props, searchState, searchResults) { return { currentRefinement: getCurrentRefinement$a(props, searchState, this.context), isSearchStalled: searchResults.isSearchStalled }; }, refine: function refine(props, searchState, nextRefinement) { return _refine$9(props, searchState, nextRefinement, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$6(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { return searchParameters.setQuery(getCurrentRefinement$a(props, searchState, this.context)); }, getMetadata: function getMetadata(props, searchState) { var _this = this; var id = getId$b(props); var currentRefinement = getCurrentRefinement$a(props, searchState, this.context); return { id: id, index: getIndexId(this.context), items: currentRefinement === null ? [] : [{ label: "".concat(id, ": ").concat(currentRefinement), value: function value(nextState) { return _refine$9(props, nextState, '', _this.context); }, currentRefinement: currentRefinement }] }; } }); function getId$c() { return 'sortBy'; } function getCurrentRefinement$b(props, searchState, context) { var id = getId$c(props); return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return null; }); } /** * The connectSortBy connector provides the logic to build a widget that will * display a list of indices. This allows a user to change how the hits are being sorted. * @name connectSortBy * @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on * the Algolia website. * @kind connector * @propType {string} defaultRefinement - The default selected index. * @propType {{value: string, label: string}[]} items - The list of indexes to search in. * @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return. * @providedPropType {function} refine - a function to remove a single filter * @providedPropType {function} createURL - a function to generate a URL for the corresponding search state * @providedPropType {string[]} currentRefinement - the refinement currently applied * @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed. */ var connectSortBy = createConnector({ displayName: 'AlgoliaSortBy', propTypes: { defaultRefinement: propTypes.string, items: propTypes.arrayOf(propTypes.shape({ label: propTypes.string, value: propTypes.string.isRequired })).isRequired, transformItems: propTypes.func }, getProvidedProps: function getProvidedProps(props, searchState) { var currentRefinement = getCurrentRefinement$b(props, searchState, this.context); 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, this.context, resetPage); }, cleanUp: function cleanUp(props, searchState) { return cleanUpValue(searchState, this.context, getId$c()); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var selectedIndex = getCurrentRefinement$b(props, searchState, this.context); return searchParameters.setIndex(selectedIndex); }, getMetadata: function getMetadata() { return { id: getId$c() }; } }); /** * The `connectStateResults` connector provides a way to access the `searchState` and the `searchResults` * of InstantSearch. * For instance this connector allows you to create results/noResults or query/noQuery pages. * @name connectStateResults * @kind connector * @providedPropType {object} searchState - The search state of the instant search component. <br/><br/> See: [Search state structure](https://community.algolia.com/react-instantsearch/guide/Search_state.html) * @providedPropType {object} searchResults - The search results. <br/><br/> In case of multiple indices: if used under `<Index>`, results will be those of the corresponding index otherwise it'll be those of the root index See: [Search results structure](https://community.algolia.com/algoliasearch-helper-js/reference.html#searchresults) * @providedPropType {object} allSearchResults - In case of multiple indices you can retrieve all the results * @providedPropType {string} error - If the search failed, the error will be logged here. * @providedPropType {boolean} searching - If there is a search in progress. * @providedPropType {boolean} isSearchStalled - Flag that indicates if React InstantSearch has detected that searches are stalled. * @providedPropType {boolean} searchingForFacetValues - If there is a search in a list in progress. * @providedPropType {object} props - component props. * @example * import React from 'react'; * import { InstantSearch, SearchBox, Hits, connectStateResults } from 'react-instantsearch-dom'; * * const Content = connectStateResults(({ searchState, searchResults }) => { * const hasResults = searchResults && searchResults.nbHits !== 0; * * return ( * <div> * <div hidden={!hasResults}> * <Hits /> * </div> * <div hidden={hasResults}> * <div>No results has been found for {searchState.query}</div> * </div> * </div> * ); * }); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <SearchBox /> * <Content /> * </InstantSearch> * ); */ createConnector({ displayName: 'AlgoliaStateResults', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); return { searchState: searchState, searchResults: results, allSearchResults: searchResults.results, searching: searchResults.searching, isSearchStalled: searchResults.isSearchStalled, error: searchResults.error, searchingForFacetValues: searchResults.searchingForFacetValues, props: props }; } }); /** * connectStats connector provides the logic to build a widget that will * displays algolia search statistics (hits number and processing time). * @name connectStats * @kind connector * @providedPropType {number} nbHits - number of hits returned by Algolia. * @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results. */ var connectStats = createConnector({ displayName: 'AlgoliaStats', getProvidedProps: function getProvidedProps(props, searchState, searchResults) { var results = getResults(searchResults, this.context); if (!results) { return null; } return { nbHits: results.nbHits, processingTimeMS: results.processingTimeMS }; } }); function getId$d(props) { return props.attribute; } var namespace$6 = 'toggle'; function getCurrentRefinement$c(props, searchState, context) { return getCurrentRefinementValue(props, searchState, context, "".concat(namespace$6, ".").concat(getId$d(props)), false, function (currentRefinement) { if (currentRefinement) { return currentRefinement; } return false; }); } 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 = createConnector({ 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, this.context); var currentRefinement = getCurrentRefinement$c(props, searchState, this.context); 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_1(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, this.context); }, cleanUp: function cleanUp(props, searchState) { return _cleanUp$7(props, searchState, this.context); }, getSearchParameters: function getSearchParameters(searchParameters, props, searchState) { var attribute = props.attribute, value = props.value, filter = props.filter; var checked = getCurrentRefinement$c(props, searchState, this.context); 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 _this = this; var id = getId$d(props); var checked = getCurrentRefinement$c(props, searchState, this.context); var items = []; var index = getIndexId(this.context); if (checked) { items.push({ label: props.label, currentRefinement: checked, attribute: props.attribute, value: function value(nextState) { return _refine$a(props, nextState, false, _this.context); } }); } return { id: id, index: index, items: items }; } }); // Core var inherits_browser$1 = createCommonjsModule(function (module) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; }; } }); var hasOwn = Object.prototype.hasOwnProperty; var toString$1 = Object.prototype.toString; var foreach = function forEach (obj, fn, ctx) { if (toString$1.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); } } } }; // 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.. function AlgoliaSearchError(message, extraProperties) { var forEach = foreach; 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_browser$1(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_browser$1(AlgoliaSearchCustomError, AlgoliaSearchError); return AlgoliaSearchCustomError; } // late exports to let various fn defs and inherits take place var errors = { AlgoliaSearchError: AlgoliaSearchError, UnparsableJSON: createCustomError( 'UnparsableJSON', 'Could not parse the incoming response as JSON, see err.more for details' ), RequestTimeout: createCustomError( 'RequestTimeout', 'Request timed out 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' ) }; // 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 var exitPromise = function exitPromise(fn, _setTimeout) { _setTimeout(fn, 0); }; var buildSearchMethod_1 = buildSearchMethod; /** * Creates a search method to be used in clients * @param {string} queryParam the name of the attribute used for the query * @param {string} url the url * @return {function} the search method */ function buildSearchMethod(queryParam, url) { /** * The search method. Prepares the data and send the query to Algolia. * @param {string} query the string used for query search * @param {object} args additional parameters to send with the search * @param {function} [callback] the callback to be called with the client gets the answer * @return {undefined|Promise} If the callback is not provided then this methods returns a Promise */ return function search(query, args, callback) { // warn V2 users on how to search if (typeof query === 'function' && typeof args === 'object' || typeof callback === 'object') { // .search(query, params, cb) // .search(cb, params) throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)'); } // Normalizing the function signature if (arguments.length === 0 || typeof query === 'function') { // Usage : .search(), .search(cb) callback = query; query = ''; } else if (arguments.length === 1 || typeof args === 'function') { // Usage : .search(query/args), .search(query, cb) callback = args; args = undefined; } // At this point we have 3 arguments with values // Usage : .search(args) // careful: typeof null === 'object' if (typeof query === 'object' && query !== null) { args = query; query = undefined; } else if (query === undefined || query === null) { // .search(undefined/null) query = ''; } var params = ''; if (query !== undefined) { params += queryParam + '=' + encodeURIComponent(query); } var additionalUA; if (args !== undefined) { if (args.additionalUA) { additionalUA = args.additionalUA; delete args.additionalUA; } // `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if params = this.as._getSearchParams(args, params); } return this._search(params, url, callback, additionalUA); }; } var deprecate = function deprecate(fn, message) { var warned = false; function deprecated() { if (!warned) { /* eslint no-console:0 */ console.warn(message); warned = true; } return fn.apply(this, arguments); } return deprecated; }; var deprecatedMessage = function deprecatedMessage(previousUsage, newUsage) { var githubAnchorLink = previousUsage.toLowerCase() .replace(/[\.\(\)]/g, ''); return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage + '`. Please see https://github.com/algolia/algoliasearch-client-javascript/wiki/Deprecated#' + githubAnchorLink; }; var merge$1 = 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; }; var clone = function clone(obj) { return JSON.parse(JSON.stringify(obj)); }; var toStr = Object.prototype.toString; var isArguments$1 = 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; }; var keysShim; if (!Object.keys) { // modified from https://github.com/es-shims/es5-shim var has$2 = Object.prototype.hasOwnProperty; var toStr$1 = Object.prototype.toString; var isArgs = isArguments$1; // eslint-disable-line global-require 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 = { $applicationCache: true, $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$2.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; } }; keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr$1.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr$1.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$2.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$2.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$2.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; } var implementation = keysShim; var slice = Array.prototype.slice; var origKeys = Object.keys; var keysShim$1 = origKeys ? function keys(o) { return origKeys(o); } : implementation; var originalKeys = Object.keys; keysShim$1.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug var args = Object.keys(arguments); return args && args.length === arguments.length; }(1, 2)); if (!keysWorksWithArguments) { Object.keys = function keys(object) { // eslint-disable-line func-name-matching if (isArguments$1(object)) { return originalKeys(slice.call(object)); } return originalKeys(object); }; } } else { Object.keys = keysShim$1; } return Object.keys || keysShim$1; }; var objectKeys = keysShim$1; var omit$1 = function omit(obj, test) { var keys = objectKeys; var foreach$1 = foreach; var filtered = {}; foreach$1(keys(obj), function doFilter(keyName) { if (test(keyName) !== true) { filtered[keyName] = obj[keyName]; } }); return filtered; }; var toString$2 = {}.toString; var isarray = Array.isArray || function (arr) { return toString$2.call(arr) == '[object Array]'; }; var map$1 = function map(arr, fn) { var newArr = []; foreach(arr, function(item, itemIndex) { newArr.push(fn(item, itemIndex, arr)); }); return newArr; }; var IndexCore_1 = IndexCore; /* * Index class constructor. * You should not use this method directly but use initIndex() function */ function IndexCore(algoliasearch, indexName) { this.indexName = indexName; this.as = algoliasearch; this.typeAheadArgs = null; this.typeAheadValueOption = null; // make sure every index instance has it's own cache this.cache = {}; } /* * Clear all queries in cache */ IndexCore.prototype.clearCache = function() { this.cache = {}; }; /* * Search inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the full text query * @param {object} [args] (optional) if set, contains an object with query parameters: * - page: (integer) Pagination parameter used to select the page to retrieve. * Page is zero-based and defaults to 0. Thus, * to retrieve the 10th page you need to set page=9 * - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. * - attributesToRetrieve: a string that contains the list of object attributes * you want to retrieve (let you minimize the answer size). * Attributes are separated with a comma (for example "name,address"). * You can also use an array (for example ["name","address"]). * By default, all attributes are retrieved. You can also use '*' to retrieve all * values when an attributesToRetrieve setting is specified for your index. * - attributesToHighlight: a string that contains the list of attributes you * want to highlight according to the query. * Attributes are separated by a comma. You can also use an array (for example ["name","address"]). * If an attribute has no match for the query, the raw value is returned. * By default all indexed text attributes are highlighted. * You can use `*` if you want to highlight all textual attributes. * Numerical attributes are not highlighted. * A matchLevel is returned for each highlighted attribute and can contain: * - full: if all the query terms were found in the attribute, * - partial: if only some of the query terms were found, * - none: if none of the query terms were found. * - attributesToSnippet: a string that contains the list of attributes to snippet alongside * the number of words to return (syntax is `attributeName:nbWords`). * Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). * You can also use an array (Example: attributesToSnippet: ['name:10','content:10']). * By default no snippet is computed. * - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. * Defaults to 3. * - minWordSizefor2Typos: the minimum number of characters in a query word * to accept two typos in this word. Defaults to 7. * - getRankingInfo: if set to 1, the result hits will contain ranking * information in _rankingInfo attribute. * - aroundLatLng: search for entries around a given * latitude/longitude (specified as two floats separated by a comma). * For example aroundLatLng=47.316669,5.016670). * You can specify the maximum distance in meters with the aroundRadius parameter (in meters) * and the precision for ranking with aroundPrecision * (for example if you set aroundPrecision=100, two objects that are distant of * less than 100m will be considered as identical for "geo" ranking parameter). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - insideBoundingBox: search entries inside a given area defined by the two extreme points * of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). * For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). * At indexing, you should specify geoloc of an object with the _geoloc attribute * (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) * - numericFilters: a string that contains the list of numeric filters you want to * apply separated by a comma. * The syntax of one filter is `attributeName` followed by `operand` followed by `value`. * Supported operands are `<`, `<=`, `=`, `>` and `>=`. * You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. * You can also use an array (for example numericFilters: ["price>100","price<1000"]). * - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. * To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). * You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]] * means tag1 AND (tag2 OR tag3). * At indexing, tags should be added in the _tags** attribute * of objects (for example {"_tags":["tag1","tag2"]}). * - facetFilters: filter the query by a list of facets. * Facets are separated by commas and each facet is encoded as `attributeName:value`. * For example: `facetFilters=category:Book,author:John%20Doe`. * You can also use an array (for example `["category:Book","author:John%20Doe"]`). * - facets: List of object attributes that you want to use for faceting. * Comma separated list: `"category,author"` or array `['category','author']` * Only attributes that have been added in **attributesForFaceting** index setting * can be used in this parameter. * You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. * - queryType: select how the query words are interpreted, it can be one of the following value: * - prefixAll: all query words are interpreted as prefixes, * - prefixLast: only the last word is interpreted as a prefix (default behavior), * - prefixNone: no query word is interpreted as a prefix. This option is not recommended. * - optionalWords: a string that contains the list of words that should * be considered as optional when found in the query. * Comma separated and array are accepted. * - distinct: If set to 1, enable the distinct feature (disabled by default) * if the attributeForDistinct index setting is set. * This feature is similar to the SQL "distinct" keyword: when enabled * in a query with the distinct=1 parameter, * all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. * For example, if the chosen attribute is show_name and several hits have * the same value for show_name, then only the best * one is kept and others are removed. * - restrictSearchableAttributes: List of attributes you want to use for * textual search (must be a subset of the attributesToIndex index setting) * either comma separated or as an array * @param {function} [callback] the result callback called with two arguments: * error: null or Error('message'). If false, the content contains the error. * content: the server answer that contains the list of results. */ IndexCore.prototype.search = buildSearchMethod_1('query'); /* * -- BETA -- * Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to * minimize number of OPTIONS queries: Cross-Origin Resource Sharing). * * @param {string} [query] the similar query * @param {object} [args] (optional) if set, contains an object with query parameters. * All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters * are the two most useful to restrict the similar results and get more relevant content */ IndexCore.prototype.similarSearch = deprecate( buildSearchMethod_1('similarQuery'), deprecatedMessage( 'index.similarSearch(query[, callback])', 'index.search({ similarQuery: query }[, callback])' ) ); /* * 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 = merge$1; var indexObj = this; var page; var hitsPerPage; // we check variadic calls that are not the one defined // .browse()/.browse(fn) // => page = 0 if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') { page = 0; callback = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'number') { // .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn) page = arguments[0]; if (typeof arguments[1] === 'number') { hitsPerPage = arguments[1]; } else if (typeof arguments[1] === 'function') { callback = arguments[1]; hitsPerPage = undefined; } query = undefined; queryParameters = undefined; } else if (typeof arguments[0] === 'object') { // .browse(queryParameters)/.browse(queryParameters, cb) if (typeof arguments[1] === 'function') { callback = arguments[1]; } queryParameters = arguments[0]; query = undefined; } else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') { // .browse(query, cb) callback = arguments[1]; queryParameters = undefined; } // otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb) // get search query parameters combining various possible calls // to .browse(); queryParameters = merge({}, queryParameters || {}, { page: page, hitsPerPage: hitsPerPage, query: query }); var params = this.as._getSearchParams(queryParameters, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse', body: {params: params}, hostType: 'read', callback: callback }); }; /* * Continue browsing from a previous position (cursor), obtained via a call to `.browse()`. * * @param {string} query - The full text query * @param {Object} [queryParameters] - Any search query parameter * @param {Function} [callback] - The result callback called with two arguments * error: null or Error('message') * content: the server answer with the browse result * @return {Promise|undefined} Returns a promise if no callback given * @example * index.browseFrom('14lkfsakl32', callback); * @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation} */ IndexCore.prototype.browseFrom = function(cursor, callback) { return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse', body: {cursor: cursor}, hostType: 'read', callback: callback }); }; /* * Search for facet values * https://www.algolia.com/doc/rest-api/search#search-for-facet-values * * @param {string} params.facetName Facet name, name of the attribute to search for values in. * Must be declared as a facet * @param {string} params.facetQuery Query for the facet search * @param {string} [params.*] Any search parameter of Algolia, * see https://www.algolia.com/doc/api-client/javascript/search#search-parameters * Pagination is not supported. The page and hitsPerPage parameters will be ignored. * @param callback (optional) */ IndexCore.prototype.searchForFacetValues = function(params, callback) { var clone$1 = clone; var omit = omit$1; 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$1(params), function(keyName) { return keyName === 'facetName'; }); var searchParameters = this.as._getSearchParams(filteredParams, ''); return this.as._jsonRequest({ method: 'POST', url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query', hostType: 'read', body: {params: searchParameters}, callback: callback }); }; IndexCore.prototype.searchFacet = deprecate(function(params, callback) { return this.searchForFacetValues(params, callback); }, deprecatedMessage( 'index.searchFacet(params[, callback])', 'index.searchForFacetValues(params[, callback])' )); IndexCore.prototype._search = function(params, url, callback, additionalUA) { return this.as._jsonRequest({ cache: this.cache, method: 'POST', url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query', body: {params: params}, hostType: 'read', fallback: { method: 'GET', url: '/1/indexes/' + encodeURIComponent(this.indexName), body: {params: params} }, callback: callback, additionalUA: additionalUA }); }; /* * Get an object from this index * * @param objectID the unique identifier of the object to retrieve * @param attrs (optional) if set, contains the array of attribute names to retrieve * @param callback (optional) the result callback called with two arguments * error: null or Error('message') * content: the object to retrieve or the error message if a failure occurred */ 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 = isarray; var map = map$1; 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; /** * 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 */ var ms = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse$1(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$1(str) { str = String(str); if (str.length > 100) { 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'; } var debug = createCommonjsModule(function (module, exports) { /** * 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 = ms; /** * 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); exports.names = []; exports.skips = []; var split = (typeof namespaces === 'string' ? 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; } }); var debug_1 = debug.coerce; var debug_2 = debug.disable; var debug_3 = debug.enable; var debug_4 = debug.enabled; var debug_5 = debug.humanize; var debug_6 = debug.names; var debug_7 = debug.skips; var debug_8 = debug.formatters; var browser$1 = createCommonjsModule(function (module, exports) { /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug; 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.process && 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.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && 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.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() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * 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) {} } }); var browser_1 = browser$1.log; var browser_2 = browser$1.formatArgs; var browser_3 = browser$1.save; var browser_4 = browser$1.load; var browser_5 = browser$1.useColors; var browser_6 = browser$1.storage; var browser_7 = browser$1.colors; var debug$1 = browser$1('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(commonjsGlobal.localStorage[localStorageNamespace]); namespace[key] = data; commonjsGlobal.localStorage[localStorageNamespace] = JSON.stringify(namespace); return namespace[key]; } catch (e) { return localStorageFailure(key, e); } }, get: function(key) { try { return JSON.parse(commonjsGlobal.localStorage[localStorageNamespace])[key] || null; } catch (e) { return localStorageFailure(key, e); } } }; function localStorageFailure(key, e) { debug$1('localStorage failed with', e); cleanup(); store = moduleStore; return store.get(key); } store = supportsLocalStorage() ? localStorageStore : moduleStore; var store_1 = { 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 commonjsGlobal && commonjsGlobal.localStorage !== null) { if (!commonjsGlobal.localStorage[localStorageNamespace]) { // actual creation of the namespace commonjsGlobal.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 { commonjsGlobal.localStorage.removeItem(localStorageNamespace); } catch (_) { // nothing to do } } var AlgoliaSearchCore_1 = AlgoliaSearchCore; // We will always put the API KEY in the JSON body in case of too long API KEY, // to avoid query string being too long and failing in various conditions (our server limit, browser limit, // proxies limit) var MAX_API_KEY_LENGTH = 500; var RESET_APP_DATA_TIMER = process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) || 60 * 2 * 1000; // after 2 minutes reset to first host /* * Algolia Search library initialization * https://www.algolia.com/ * * @param {string} applicationID - Your applicationID, found in your dashboard * @param {string} apiKey - Your API key, found in your dashboard * @param {Object} [opts] * @param {number} [opts.timeout=2000] - The request timeout set in milliseconds, * another request will be issued after this timeout * @param {string} [opts.protocol='https:'] - The protocol used to query Algolia Search API. * Set to 'http:' to force using http. * @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 = browser$1('algoliasearch'); var clone$1 = clone; var isArray = isarray; var map = map$1; 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 || {}; 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; } var protocol = opts.protocol || 'https:'; // 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 (protocol !== 'http:' && 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 var mainSuffix = (opts.dsn === false ? '' : '-dsn') + '.algolia.net'; this.hosts.read = [this.applicationID + mainSuffix].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$1(opts.hosts); this.hosts.write = clone$1(opts.hosts); } else { this.hosts.read = clone$1(opts.hosts.read); this.hosts.write = clone$1(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._useRequestCache = this._useCache && opts._useRequestCache; 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_1(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[name.toLowerCase()] = value; }; /** * Get the value of an extra HTTP header * * @param name the header field name */ AlgoliaSearchCore.prototype.getExtraHeader = function(name) { return this.extraHeaders[name.toLowerCase()]; }; /** * Remove an extra field from the HTTP request * * @param name the header field name */ AlgoliaSearchCore.prototype.unsetExtraHeader = function(name) { delete this.extraHeaders[name.toLowerCase()]; }; /** * 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 = browser$1('algoliasearch:' + initialOpts.url); var body; var cacheID; var additionalUA = initialOpts.additionalUA || ''; var cache = initialOpts.cache; var client = this; var tries = 0; var usingFallback = false; var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback; var headers; if ( this.apiKey.length > MAX_API_KEY_LENGTH && initialOpts.body !== undefined && (initialOpts.body.params !== undefined || // index.search() initialOpts.body.requests !== undefined) // client.search() ) { initialOpts.body.apiKey = this.apiKey; headers = this._computeRequestHeaders({ additionalUA: additionalUA, withApiKey: false, headers: initialOpts.headers }); } else { headers = this._computeRequestHeaders({ additionalUA: additionalUA, headers: initialOpts.headers }); } if (initialOpts.body !== undefined) { body = safeJSONStringify(initialOpts.body); } requestDebug('request start'); var debugData = []; function doRequest(requester, reqOpts) { client._checkAppIdData(); var startTime = new Date(); if (client._useCache && !client._useRequestCache) { 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 && !client._useRequestCache && body) { cacheID += '_body_' + reqOpts.body; } // handle cache existence if (isCacheValidWithCurrentID(!client._useRequestCache, cache, cacheID)) { requestDebug('serving response from cache'); var responseText = cache[cacheID]; // Cache response must match the type of the original one return client._promise.resolve({ body: JSON.parse(responseText), responseText: responseText }); } // 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 support@algolia.com to report and resolve the issue.' + ' Application id was: ' + client.applicationID, {debugData: debugData} )); } requestDebug('switching to fallback'); // let's try the fallback starting from here tries = 0; // method, url and body are fallback dependent reqOpts.method = initialOpts.fallback.method; reqOpts.url = initialOpts.fallback.url; reqOpts.jsonBody = initialOpts.fallback.body; if (reqOpts.jsonBody) { reqOpts.body = safeJSONStringify(reqOpts.jsonBody); } // re-compute headers, they could be omitting the API KEY headers = client._computeRequestHeaders({ additionalUA: additionalUA, headers: initialOpts.headers }); 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, forceAuthHeaders: reqOpts.forceAuthHeaders }; 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 && !client._useRequestCache && cache) { cache[cacheID] = httpResponse.responseText; } return { responseText: httpResponse.responseText, body: 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 occurred, 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); } } function isCacheValidWithCurrentID( useRequestCache, currentCache, currentCacheID ) { return ( client._useCache && useRequestCache && currentCache && currentCache[currentCacheID] !== undefined ); } function interopCallbackReturn(request, callback) { if (isCacheValidWithCurrentID(client._useRequestCache, cache, cacheID)) { request.catch(function() { // Release the cache on error delete cache[cacheID]; }); } if (typeof initialOpts.callback === 'function') { // either we have a callback request.then(function okCb(content) { exitPromise(function() { initialOpts.callback(null, callback(content)); }, client._setTimeout || setTimeout); }, function nookCb(err) { exitPromise(function() { initialOpts.callback(err); }, client._setTimeout || setTimeout); }); } else { // either we are using promises return request.then(callback); } } if (client._useCache && client._useRequestCache) { 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 && client._useRequestCache && body) { cacheID += '_body_' + body; } if (isCacheValidWithCurrentID(client._useRequestCache, cache, cacheID)) { requestDebug('serving request from cache'); var maybePromiseForCache = cache[cacheID]; // In case the cache is warmup with value that is not a promise var promiseForCache = typeof maybePromiseForCache.then !== 'function' ? client._promise.resolve({responseText: maybePromiseForCache}) : maybePromiseForCache; return interopCallbackReturn(promiseForCache, function(content) { // In case of the cache request, return the original value return JSON.parse(content.responseText); }); } var request = doRequest( client._request, { url: initialOpts.url, method: initialOpts.method, body: body, jsonBody: initialOpts.body, timeouts: client._getTimeoutsForRequest(initialOpts.hostType), forceAuthHeaders: initialOpts.forceAuthHeaders } ); if (client._useCache && client._useRequestCache && cache) { cache[cacheID] = request; } return interopCallbackReturn(request, function(content) { // In case of the first request, return the JSON value return content.body; }); }; /* * Transform search param object in query string * @param {object} args arguments to add to the current query string * @param {string} params current query string * @return {string} the final query string */ AlgoliaSearchCore.prototype._getSearchParams = function(args, params) { if (args === undefined || args === null) { return params; } for (var key in args) { if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) { params += params === '' ? '' : '&'; params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]); } } return params; }; /** * Compute the headers for a request * * @param [string] options.additionalUA semi-colon separated string with other user agents to add * @param [boolean=true] options.withApiKey Send the api key as a header * @param [Object] options.headers Extra headers to send */ AlgoliaSearchCore.prototype._computeRequestHeaders = function(options) { var forEach = foreach; var ua = options.additionalUA ? this._ua + ';' + options.additionalUA : this._ua; var requestHeaders = { 'x-algolia-agent': ua, 'x-algolia-application-id': this.applicationID }; // browser will inline headers in the url, node.js will use http headers // but in some situations, the API KEY will be too long (big secured API keys) // so if the request is a POST and the KEY is very long, we will be asked to not put // it into headers but in the JSON body if (options.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; } forEach(this.extraHeaders, function addToRequestHeaders(value, key) { requestHeaders[key] = value; }); if (options.headers) { forEach(options.headers, function addToRequestHeaders(value, key) { requestHeaders[key] = 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 = isarray; var map = map$1; 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) { postObj.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 }); }; /** * Search for facet values * https://www.algolia.com/doc/rest-api/search#search-for-facet-values * This is the top-level API for SFFV. * * @param {object[]} queries An array of queries to run. * @param {string} queries[].indexName Index name, name of the index to search. * @param {object} queries[].params Query parameters. * @param {string} queries[].params.facetName Facet name, name of the attribute to search for values in. * Must be declared as a facet * @param {string} queries[].params.facetQuery Query for the facet search * @param {string} [queries[].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. */ AlgoliaSearchCore.prototype.searchForFacetValues = function(queries) { var isArray = isarray; var map = map$1; var usage = 'Usage: client.searchForFacetValues([{indexName, params: {facetName, facetQuery, ...params}}, ...queries])'; // eslint-disable-line max-len if (!isArray(queries)) { throw new Error(usage); } var client = this; return client._promise.all(map(queries, function performQuery(query) { if ( !query || query.indexName === undefined || query.params.facetName === undefined || query.params.facetQuery === undefined ) { throw new Error(usage); } var clone$1 = clone; var omit = omit$1; var indexName = query.indexName; var params = query.params; var facetName = params.facetName; var filteredParams = omit(clone$1(params), function(keyName) { return keyName === 'facetName'; }); var searchParameters = client._getSearchParams(filteredParams, ''); return client._jsonRequest({ cache: client.cache, method: 'POST', url: '/1/indexes/' + encodeURIComponent(indexName) + '/facets/' + encodeURIComponent(facetName) + '/query', hostType: 'read', body: {params: searchParameters} }); })); }; /** * 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_1.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_1.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$1 = foreach; var currentData = this._getAppIdData(); foreach$1(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$1 = clone; var newHostIndexes = clone$1(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; } var win; if (typeof window !== "undefined") { win = window; } else if (typeof commonjsGlobal !== "undefined") { win = commonjsGlobal; } else if (typeof self !== "undefined"){ win = self; } else { win = {}; } var window_1 = win; var es6Promise = createCommonjsModule(function (module, exports) { /*! * @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 v4.2.6+9869a4bc */ (function (global, factory) { module.exports = factory(); }(commonjsGlobal, (function () { function objectOrFunction(x) { var type = typeof x; return x !== null && (type === 'object' || type === 'function'); } function isFunction(x) { return typeof x === 'function'; } var _isArray = void 0; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } var isArray = _isArray; var len = 0; var vertxNext = void 0; var customSchedulerFn = void 0; 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 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 vertx = Function('return this')().require('vertx'); vertxNext = vertx.runOnLoop || vertx.runOnContext; return useVertxTimer(); } catch (e) { return useSetTimeout(); } } var scheduleFlush = void 0; // 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 && typeof commonjsRequire === 'function') { scheduleFlush = attemptVertx(); } else { scheduleFlush = useSetTimeout(); } function then(onFulfillment, onRejection) { var parent = this; var child = new this.constructor(noop); if (child[PROMISE_ID] === undefined) { makePromise(child); } var _state = parent._state; if (_state) { 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$1(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(2); function noop() {} var PENDING = void 0; var FULFILLED = 1; var REJECTED = 2; var TRY_CATCH_ERROR = { error: null }; 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) { TRY_CATCH_ERROR.error = error; return TRY_CATCH_ERROR; } } function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { try { then$$1.call(value, fulfillmentHandler, rejectionHandler); } catch (e) { return e; } } function handleForeignThenable(promise, thenable, then$$1) { asap(function (promise) { var sealed = false; var error = tryThen(then$$1, 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$$1) { if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { handleOwnThenable(promise, maybeThenable); } else { if (then$$1 === TRY_CATCH_ERROR) { reject(promise, TRY_CATCH_ERROR.error); TRY_CATCH_ERROR.error = null; } else if (then$$1 === undefined) { fulfill(promise, maybeThenable); } else if (isFunction(then$$1)) { handleForeignThenable(promise, maybeThenable, then$$1); } 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 = void 0, callback = void 0, 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 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 = void 0, error = void 0, succeeded = void 0, failed = void 0; if (hasCallback) { value = tryCatch(callback, detail); if (value === TRY_CATCH_ERROR) { failed = true; error = value.error; value.error = null; } else { succeeded = true; } if (promise === value) { reject(promise, cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== PENDING) ; 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 validationError() { return new Error('Array Methods must be provided an Array'); } var Enumerator = function () { function Enumerator(Constructor, input) { this._instanceConstructor = Constructor; this.promise = new Constructor(noop); if (!this.promise[PROMISE_ID]) { makePromise(this.promise); } if (isArray(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(input); if (this._remaining === 0) { fulfill(this.promise, this._result); } } } else { reject(this.promise, validationError()); } } Enumerator.prototype._enumerate = function _enumerate(input) { for (var i = 0; this._state === PENDING && i < input.length; i++) { this._eachEntry(input[i], i); } }; Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { var c = this._instanceConstructor; var resolve$$1 = c.resolve; if (resolve$$1 === resolve$1) { 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$1) { var promise = new c(noop); handleMaybeThenable(promise, entry, _then); this._willSettleAt(promise, i); } else { this._willSettleAt(new c(function (resolve$$1) { return resolve$$1(entry); }), i); } } else { this._willSettleAt(resolve$$1(entry), i); } }; Enumerator.prototype._settledAt = function _settledAt(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 _willSettleAt(promise, i) { var enumerator = this; subscribe(promise, undefined, function (value) { return enumerator._settledAt(FULFILLED, i, value); }, function (reason) { return enumerator._settledAt(REJECTED, i, reason); }); }; return Enumerator; }(); /** `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$1(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 */ var Promise$1 = function () { 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(); } } /** 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} */ /** `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} */ Promise.prototype.catch = function _catch(onRejection) { return this.then(null, onRejection); }; /** `finally` will be invoked regardless of the promise's fate just as native try/catch/finally behaves Synchronous example: ```js findAuthor() { if (Math.random() > 0.5) { throw new Error(); } return new Author(); } try { return findAuthor(); // succeed or fail } catch(error) { return findOtherAuther(); } finally { // always runs // doesn't affect the return value } ``` Asynchronous example: ```js findAuthor().catch(function(reason){ return findOtherAuther(); }).finally(function(){ // author was either found, or not }); ``` @method finally @param {Function} callback @return {Promise} */ Promise.prototype.finally = function _finally(callback) { var promise = this; var constructor = promise.constructor; if (isFunction(callback)) { return promise.then(function (value) { return constructor.resolve(callback()).then(function () { return value; }); }, function (reason) { return constructor.resolve(callback()).then(function () { throw reason; }); }); } return promise.then(callback, callback); }; return Promise; }(); Promise$1.prototype.then = then; Promise$1.all = all; Promise$1.race = race; Promise$1.resolve = resolve$1; Promise$1.reject = reject$1; Promise$1._setScheduler = setScheduler; Promise$1._setAsap = setAsap; Promise$1._asap = asap; /*global self*/ function polyfill() { var local = void 0; if (typeof commonjsGlobal !== 'undefined') { local = commonjsGlobal; } 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$1; } // Strange compat.. Promise$1.polyfill = polyfill; Promise$1.Promise = Promise$1; return Promise$1; }))); }); // Copyright Joyent, Inc. and other Node contributors. 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 ''; } }; var encode$1 = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map$2(objectKeys$1(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray$1(obj[k])) { return map$2(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$1 = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map$2 (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$1 = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; var inlineHeaders_1 = inlineHeaders; function inlineHeaders(url, headers) { if (/\?/.test(url)) { url += '&'; } else { url += '?'; } return url + encode$1(headers); } var jsonpRequest_1 = jsonpRequest; 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, responseText: JSON.stringify(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()); } } // Copyright Joyent, Inc. and other Node contributors. // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty$j(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } var decode = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty$j(obj, k)) { obj[k] = v; } else if (isArray$2(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray$2 = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; var querystringEs3 = createCommonjsModule(function (module, exports) { exports.decode = exports.parse = decode; exports.encode = exports.stringify = encode$1; }); var querystringEs3_1 = querystringEs3.decode; var querystringEs3_2 = querystringEs3.parse; var querystringEs3_3 = querystringEs3.encode; var querystringEs3_4 = querystringEs3.stringify; var places = createPlacesClient; function createPlacesClient(algoliasearch) { return function places(appID, apiKey, opts) { var cloneDeep = clone; 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_1('query', '/1/places/query'); index.reverse = function(options, callback) { var encoded = querystringEs3.encode(options); return this.as._jsonRequest({ method: 'GET', url: '/1/places/reverse?' + encoded, hostType: 'read', callback: callback }); }; index.getObject = function(objectID, callback) { return this.as._jsonRequest({ method: 'GET', url: '/1/places/' + encodeURIComponent(objectID), hostType: 'read', callback: callback }); }; return index; }; } var version$3 = '3.32.1'; var Promise$2 = window_1.Promise || es6Promise.Promise; // This is the standalone browser build entry point // Browser implementation of the Algolia Search JavaScript client, // using XMLHttpRequest, XDomainRequest and JSONP as fallback var createAlgoliasearch = function createAlgoliasearch(AlgoliaSearch, uaSuffix) { var inherits = inherits_browser$1; var errors$1 = errors; var inlineHeaders = inlineHeaders_1; var jsonpRequest = jsonpRequest_1; var places$1 = places; uaSuffix = uaSuffix || ''; function algoliasearch(applicationID, apiKey, opts) { var cloneDeep = clone; opts = cloneDeep(opts || {}); opts._ua = opts._ua || algoliasearch.ua; return new AlgoliaSearchBrowser(applicationID, apiKey, opts); } algoliasearch.version = version$3; algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version; algoliasearch.initPlaces = places$1(algoliasearch); // we expose into window no matter how we are used, this will allow // us to easily debug any website running algolia window_1.__algolia = { debug: browser$1, algoliasearch: algoliasearch }; var support = { hasXMLHttpRequest: 'XMLHttpRequest' in window_1, hasXDomainRequest: 'XDomainRequest' in window_1 }; 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$2(function wrapRequest(resolve, reject) { // no cors or XDomainRequest, no request if (!support.cors && !support.hasXDomainRequest) { // very old browser, not supported reject(new errors$1.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); // The Analytics API never accepts Auth headers as query string // this option exists specifically for them. if (opts.forceAuthHeaders) { req.setRequestHeader( 'x-algolia-application-id', opts.headers['x-algolia-application-id'] ); req.setRequestHeader( 'x-algolia-api-key', opts.headers['x-algolia-api-key'] ); } } 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'); } if (body) { req.send(body); } else { req.send(); } // 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$1.UnparsableJSON({ more: req.responseText }); } if (out instanceof errors$1.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$1.Network({ more: event }) ); } function onTimeout() { timedOut = true; req.abort(); reject(new errors$1.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$2(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$2.reject(val); }, resolve: function resolvePromise(val) { return Promise$2.resolve(val); }, delay: function delayPromise(ms) { return new Promise$2(function resolveOnTimeout(resolve/* , reject*/) { setTimeout(resolve, ms); }); }, all: function all(promises) { return Promise$2.all(promises); } }; return algoliasearch; }; var algoliasearchLite = createAlgoliasearch(AlgoliaSearchCore_1, '(lite) '); var InstantSearch$1 = createInstantSearch(algoliasearchLite, { Root: 'div', props: { className: 'ais-InstantSearch__root' } }); var Index$1 = createIndex({ Root: 'div', props: { className: 'ais-MultiIndex__root' } }); var PanelCallbackHandler = /*#__PURE__*/ function (_Component) { _inherits(PanelCallbackHandler, _Component); function PanelCallbackHandler() { _classCallCheck(this, PanelCallbackHandler); return _possibleConstructorReturn(this, _getPrototypeOf(PanelCallbackHandler).apply(this, arguments)); } _createClass(PanelCallbackHandler, [{ key: "componentWillMount", value: function componentWillMount() { if (this.context.setCanRefine) { this.context.setCanRefine(this.props.canRefine); } } }, { key: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { if (this.context.setCanRefine && this.props.canRefine !== nextProps.canRefine) { this.context.setCanRefine(nextProps.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 }); _defineProperty(PanelCallbackHandler, "contextTypes", { setCanRefine: propTypes.func }); 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)); }; 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({}, omit_1(this.props, 'onClick'), { onClick: this.onClick })); } }]); return Link; }(React.Component); _defineProperty(Link, "propTypes", { onClick: propTypes.func.isRequired }); var cx = 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('item') }, React__default.createElement(Link, { className: cx('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('item', isLast && 'item--selected'), key: idx }, React__default.createElement("span", { className: cx('separator') }, separator), !isLast ? React__default.createElement(Link, { className: cx('link'), onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }, item.label) : item.label); }); return React__default.createElement("div", { className: classnames(cx('', !canRefine && '-noRefinement'), className) }, React__default.createElement("ul", { className: cx('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 { Breadcrumb, InstantSearch, HierarchicalMenu } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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(PanelCallbackHandler, props, React__default.createElement(Breadcrumb$1, props)); }; var Breadcrumb$2 = connectBreadcrumb(BreadcrumbWidget); var cx$1 = 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$1(''), className) }, React__default.createElement("button", { className: cx$1('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 { InstantSearch, ClearRefinements, RefinementList } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <ClearRefinements /> * <RefinementList * attribute="brand" * defaultRefinement={['Apple']} * /> * </InstantSearch> * ); */ var ClearRefinementsWidget = function ClearRefinementsWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(ClearRefinements$1, props)); }; var ClearRefinements$2 = connectCurrentRefinements(ClearRefinementsWidget); var cx$2 = 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$2('', !canRefine && '-noRefinement'), className) }, React__default.createElement("ul", { className: cx$2('list', !canRefine && 'list--noRefinement') }, items.map(function (item) { return React__default.createElement("li", { key: item.label, className: cx$2('item') }, React__default.createElement("span", { className: cx$2('label') }, item.label), item.items ? item.items.map(function (nest) { return React__default.createElement("span", { key: nest.label, className: cx$2('category') }, React__default.createElement("span", { className: cx$2('categoryLabel') }, nest.label), React__default.createElement("button", { className: cx$2('delete'), onClick: function onClick() { return refine(nest.value); } }, translate('clearFilter', nest))); }) : React__default.createElement("span", { className: cx$2('category') }, React__default.createElement("button", { className: cx$2('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 { InstantSearch, CurrentRefinements, RefinementList } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <CurrentRefinements /> * <RefinementList * attribute="brand" * defaultRefinement={['Colors']} * /> * </InstantSearch> * ); */ var CurrentRefinementsWidget = function CurrentRefinementsWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(CurrentRefinements$1, props)); }; var CurrentRefinements$2 = connectCurrentRefinements(CurrentRefinementsWidget); var cx$3 = 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$3('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$3('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$3('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: "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 }); } } }, { 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$3(''), className) }, React__default.createElement("form", { noValidate: true, onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit, onReset: this.onReset, className: cx$3('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$3('input') })), React__default.createElement("button", { type: "submit", title: translate('submitTitle'), className: cx$3('submit') }, submit), React__default.createElement("button", { type: "reset", title: translate('resetTitle'), className: cx$3('reset'), hidden: !query || isSearchStalled }, reset), this.props.showLoadingIndicator && React__default.createElement("span", { hidden: !isSearchStalled, className: cx$3('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$4 = 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$4('link'), onClick: function onClick() { return refine(item.value); }, href: createURL(item.value) }, React__default.createElement("span", { className: cx$4('label') }, item.label), ' ', React__default.createElement("span", { className: cx$4('count') }, item.count)); }); return _this; } _createClass(HierarchicalMenu, [{ key: "render", value: function render() { return React__default.createElement(List, _extends({ renderItem: this.renderItem, cx: cx$4 }, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isEmpty', 'canRefine', '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 { InstantSearch, HierarchicalMenu } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <HierarchicalMenu * attributes={[ * 'hierarchicalCategories.lvl0', * 'hierarchicalCategories.lvl1', * 'hierarchicalCategories.lvl2', * ]} * /> * </InstantSearch> * ); */ var HierarchicalMenuWidget = function HierarchicalMenuWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(HierarchicalMenu$1, props)); }; var HierarchicalMenu$2 = connectHierarchicalMenu(HierarchicalMenuWidget); function generateKey(i, value) { return "split-".concat(i, "-").concat(value); } 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: generateKey(i, hit[attribute][i]) }, item.map(function (element, index) { return React__default.createElement(Highlight, { cx: cx, key: generateKey(index, element.value), 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: generateKey(i, item.value), value: item.value, highlightedTagName: tagName, nonHighlightedTagName: nonHighlightedTagName, isHighlighted: item.isHighlighted }); })); }; Highlighter.defaultProps = { tagName: 'em', nonHighlightedTagName: 'span', className: '', separator: ', ' }; var cx$5 = createClassNames('Highlight'); var Highlight$1 = function Highlight(props) { return React__default.createElement(Highlighter, _extends({}, props, { highlightProperty: "_highlightResult", cx: cx$5 })); }; /** * 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 { InstantSearch, SearchBox, Hits, Highlight } from 'react-instantsearch-dom'; * * const Hit = ({ hit }) => ( * <div> * <Highlight attribute="name" hit={hit} /> * </div> * ); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <SearchBox defaultRefinement="Pho" /> * <Hits hitComponent={Hit} /> * </InstantSearch> * ); */ var Highlight$2 = connectHighlight(Highlight$1); var cx$6 = createClassNames('Hits'); 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$6(''), className) }, React__default.createElement("ul", { className: cx$6('list') }, hits.map(function (hit) { return React__default.createElement("li", { className: cx$6('item'), key: hit.objectID }, React__default.createElement(HitComponent, { hit: hit })); }))); }; 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 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 { InstantSearch, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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: has_1(item, 'key') ? item.key : item.value, disabled: item.disabled, value: item.value }, has_1(item, 'label') ? item.label : item.value); })); } }]); 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$7 = 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$7(''), className) }, React__default.createElement(Select, { onSelect: refine, selectedItem: currentRefinement, items: items, cx: cx$7 })); } }]); 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 { InstantSearch, HitsPerPage, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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$8 = 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, hasMore = _this$props.hasMore, refine = _this$props.refine, translate = _this$props.translate, className = _this$props.className; return React__default.createElement("div", { className: classnames(cx$8(''), className) }, React__default.createElement("ul", { className: cx$8('list') }, hits.map(function (hit) { return React__default.createElement("li", { key: hit.objectID, className: cx$8('item') }, React__default.createElement(HitComponent, { hit: hit })); })), React__default.createElement("button", { className: cx$8('loadMore', !hasMore && 'loadMore--disabled'), onClick: function onClick() { return refine(); }, disabled: !hasMore }, translate('loadMore'))); } }]); return InfiniteHits; }(React.Component); InfiniteHits.defaultProps = { className: '', 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({ 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 { InstantSearch, InfiniteHits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <InfiniteHits /> * </InstantSearch> * ); */ var InfiniteHits$2 = connectInfiniteHits(InfiniteHits$1); var cx$9 = 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$9('link'), onClick: function onClick() { return _this.selectItem(item, resetQuery); }, href: createURL(item.value) }, React__default.createElement("span", { className: cx$9('label') }, label), ' ', React__default.createElement("span", { className: cx$9('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() { return React__default.createElement(List, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$9 }, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isFromSearch', 'searchForItems', 'searchable', 'canRefine', '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 { InstantSearch, Menu } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <Menu attribute="categories" /> * </InstantSearch> * ); */ var MenuWidget = function MenuWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(Menu$1, props)); }; var Menu$2 = connectMenu(MenuWidget); var cx$a = 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$a('', !canRefine && '-noRefinement'), className) }, React__default.createElement("select", { value: this.selectedValue, onChange: this.handleSelectChange, className: cx$a('select') }, React__default.createElement("option", { value: "ais__see__all__option", className: cx$a('option') }, translate('seeAllOption')), items.map(function (item) { return React__default.createElement("option", { key: item.value, value: item.value, className: cx$a('option') }, item.label, " (", item.count, ")"); }))); } }, { key: "selectedValue", get: function get() { var _ref2 = find_1(this.props.items, { 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 { InstantSearch, MenuSelect } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <MenuSelect attribute="categories" /> * </InstantSearch> * ); */ var MenuSelectWidget = function MenuSelectWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(MenuSelect$1, props)); }; var MenuSelect$2 = connectMenu(MenuSelectWidget); var cx$b = 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$b('label') }, React__default.createElement("input", { className: cx$b('radio'), type: "radio", checked: item.isRefined, disabled: item.noRefinement, onChange: function onChange() { return refine(item.value); } }), React__default.createElement("span", { className: cx$b('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$b, 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 { InstantSearch, NumericMenu } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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(PanelCallbackHandler, props, React__default.createElement(NumericMenu$1, props)); }; var NumericMenu$2 = connectNumericMenu(NumericMenuWidget); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeMax$7 = 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$7(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } var _baseRange = baseRange; /** * 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_1(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite_1(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite_1(step); return _baseRange(start, end, step, fromRight); }; } var _createRange = createRange; /** * 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(); var range_1 = range; 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: has_1(item, 'key') ? item.key : item.value, className: cx('item', item.selected && !item.disabled && 'item--selected', item.disabled && 'item--disabled', item.modifier) }, item.disabled ? React__default.createElement("span", { className: cx('link') }, has_1(item, 'label') ? item.label : item.value) : 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); } }, has_1(item, 'label') ? item.label : item.value)); })); } }]); 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$c = 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_1(1, maxPages + 1); var paddingLeft = calculatePaddingLeft(currentPage, padding, maxPages, size); var paddingRight = size - paddingLeft; var first = currentPage - paddingLeft; var last = currentPage + paddingRight; return range_1(first + 1, 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$c('', !canRefine && '-noRefinement'), className) }, React__default.createElement(ListComponent, _extends({}, otherProps, { cx: cx$c, 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 { InstantSearch, Pagination } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <Pagination /> * </InstantSearch> * ); */ var PaginationWidget = function PaginationWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(Pagination$1, props)); }; var Pagination$2 = connectPagination(PaginationWidget); var cx$d = createClassNames('Panel'); 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: "getChildContext", value: function getChildContext() { return { setCanRefine: this.setCanRefine }; } }, { 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$d('', !canRefine && '-noRefinement'), className) }, header && React__default.createElement("div", { className: cx$d('header') }, header), React__default.createElement("div", { className: cx$d('body') }, children), footer && React__default.createElement("div", { className: cx$d('footer') }, footer)); } }]); return Panel; }(React.Component); _defineProperty(Panel, "propTypes", { children: propTypes.node.isRequired, className: propTypes.string, header: propTypes.node, footer: propTypes.node }); _defineProperty(Panel, "childContextTypes", { setCanRefine: propTypes.func.isRequired }); _defineProperty(Panel, "defaultProps", { className: '', header: null, footer: null }); 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'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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: "componentWillReceiveProps", value: function componentWillReceiveProps(nextProps) { // In react@16.0.0 the call to setState on the inputs trigger this lifecycle hook // because the context has changed (for react). I don't think that the bug is related // to react because I failed to reproduce it with a simple hierarchy of components. // The workaround here is to check the differences between previous & next props in order // to avoid to override current state when values are not yet refined. In the react documentation, // they DON'T categorically say that setState never run componentWillReceiveProps. // see: https://reactjs.org/docs/react-component.html#componentwillreceiveprops if (nextProps.canRefine && (this.props.canRefine !== nextProps.canRefine || this.props.currentRefinement.min !== nextProps.currentRefinement.min || this.props.currentRefinement.max !== nextProps.currentRefinement.max)) { this.setState(this.normalizeStateForRendering(nextProps)); } } }, { 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 { InstantSearch, RangeInput } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <RangeInput attribute="price" /> * </InstantSearch> * ); */ var RangeInputWidget = function RangeInputWidget(props) { return React__default.createElement(PanelCallbackHandler, 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 } }; componentWillReceiveProps(sliderState) { if (sliderState.canRefine) { this.setState({ currentValues: { min: sliderState.currentRefinement.min, max: sliderState.currentRefinement.max } }); } } onValuesUpdated = sliderState => { this.setState({ currentValues: { min: sliderState.values[0], max: sliderState.values[1] } }); }; onChange = sliderState => { if ( this.props.currentRefinement.min !== sliderState.values[0] || this.props.currentRefinement.max !== sliderState.values[1] ) { this.props.refine({ min: sliderState.values[0], max: sliderState.values[1] }); } }; render() { const { min, max, currentRefinement } = this.props; const { currentValues } = this.state; return min !== max ? ( <div> <Rheostat 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/")); }); /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH$1 = 4294967295; /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is 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 convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? _baseClamp(toInteger_1(value), 0, MAX_ARRAY_LENGTH$1) : 0; } var toLength_1 = toLength; /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger_1(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger_1(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength_1(end); while (start < end) { array[start++] = value; } return array; } var _baseFill = baseFill; /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && _isIterateeCall(array, value, start)) { start = 0; end = length; } return _baseFill(array, value, start, end); } var fill_1 = fill; 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 safeInclusiveLength = Math.max(inclusiveLength, 0); var values = count.map(function (item) { return _objectSpread({}, item, { value: parseFloat(item.value) }); }).filter(function (item) { return item.value >= limitMin && item.value <= limitMax; }); var range = fill_1(new Array(safeInclusiveLength), null).map(function (_, index) { var element = find_1(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 })); }, []); var items = range.map(function (item, index) { return _this.buildItem({ lowerBound: item.value, count: item.total, isLastSelectableItem: range.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 { InstantSearch, RatingMenu } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <RatingMenu attribute="rating" /> * </InstantSearch> * ); */ var RatingMenuWidget = function RatingMenuWidget(props) { return React__default.createElement(PanelCallbackHandler, 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() { return React__default.createElement(List, _extends({ renderItem: this.renderItem, selectItem: this.selectItem, cx: cx$h }, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isFromSearch', 'searchForItems', 'searchable', 'canRefine', '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 { InstantSearch, RefinementList } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <RefinementList attribute="brand" /> * </InstantSearch> * ); */ var RefinementListWidget = function RefinementListWidget(props) { return React__default.createElement(PanelCallbackHandler, 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 { InstantSearch, ScrollTo, Hits } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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 { InstantSearch, SearchBox } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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 { InstantSearch, SearchBox, Hits, Snippet } from 'react-instantsearch-dom'; * * const Hit = ({ hit }) => ( * <div> * <Snippet attribute="description" hit={hit} /> * </div> * ); * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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 { InstantSearch, SortBy } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * 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 { InstantSearch, ToggleRefinement } from 'react-instantsearch-dom'; * * const App = () => ( * <InstantSearch * appId="latency" * apiKey="6be0576ff61c053d5f9a3225e2a90f76" * indexName="instant_search" * > * <ToggleRefinement * attribute="free_shipping" * label="Free Shipping" * value={true} * /> * </InstantSearch> * ); */ var ToggleRefinement$1 = connectToggleRefinement(ToggleRefinement); var cx$n = createClassNames('QueryRuleCustomData'); var QueryRuleCustomData = function QueryRuleCustomData(_ref) { var items = _ref.items, className = _ref.className, children = _ref.children; return React__default.createElement("div", { className: classnames(cx$n(''), className) }, children({ items: items })); }; var QueryRuleCustomDataWidget = function QueryRuleCustomDataWidget(props) { return React__default.createElement(PanelCallbackHandler, props, React__default.createElement(QueryRuleCustomData, props)); }; connectQueryRules(QueryRuleCustomDataWidget); // Core 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 = Index$1; exports.InfiniteHits = InfiniteHits$2; exports.InstantSearch = InstantSearch$1; 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/4.9.3/esm/Modal/SimpleBackdrop.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'; export var 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. */ var SimpleBackdrop = React.forwardRef(function SimpleBackdrop(props, ref) { var _props$invisible = props.invisible, invisible = _props$invisible === void 0 ? false : _props$invisible, open = props.open, other = _objectWithoutProperties(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/primereact/7.1.0/panel/panel.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { CSSTransition } from 'primereact/csstransition'; import { UniqueComponentId, IconUtils, ObjectUtils, classNames } from 'primereact/utils'; import { Ripple } from 'primereact/ripple'; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); 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 Panel = /*#__PURE__*/function (_Component) { _inherits(Panel, _Component); var _super = _createSuper(Panel); function Panel(props) { var _this; _classCallCheck(this, Panel); _this = _super.call(this, props); var state = { id: _this.props.id }; if (!_this.props.onToggle) { state = _objectSpread(_objectSpread({}, state), {}, { collapsed: _this.props.collapsed }); } _this.state = state; _this.toggle = _this.toggle.bind(_assertThisInitialized(_this)); _this.contentRef = /*#__PURE__*/React.createRef(); return _this; } _createClass(Panel, [{ key: "toggle", value: function toggle(event) { if (this.props.toggleable) { var collapsed = this.props.onToggle ? this.props.collapsed : this.state.collapsed; if (collapsed) this.expand(event);else this.collapse(event); if (this.props.onToggle) { this.props.onToggle({ originalEvent: event, value: !collapsed }); } } event.preventDefault(); } }, { key: "expand", value: function expand(event) { if (!this.props.onToggle) { this.setState({ collapsed: false }); } if (this.props.onExpand) { this.props.onExpand(event); } } }, { key: "collapse", value: function collapse(event) { if (!this.props.onToggle) { this.setState({ collapsed: true }); } if (this.props.onCollapse) { this.props.onCollapse(event); } } }, { key: "isCollapsed", value: function isCollapsed() { return this.props.toggleable ? this.props.onToggle ? this.props.collapsed : this.state.collapsed : false; } }, { key: "componentDidMount", value: function componentDidMount() { if (!this.state.id) { this.setState({ id: UniqueComponentId() }); } } }, { key: "renderToggleIcon", value: function renderToggleIcon(collapsed) { if (this.props.toggleable) { var id = this.state.id + '_label'; var ariaControls = this.state.id + '_content'; var toggleIcon = collapsed ? this.props.expandIcon : this.props.collapseIcon; return /*#__PURE__*/React.createElement("button", { className: "p-panel-header-icon p-panel-toggler p-link", onClick: this.toggle, id: id, "aria-controls": ariaControls, "aria-expanded": !collapsed, role: "tab" }, IconUtils.getJSXIcon(toggleIcon, { props: this.props, collapsed: collapsed }), /*#__PURE__*/React.createElement(Ripple, null)); } return null; } }, { key: "renderHeader", value: function renderHeader(collapsed) { var header = ObjectUtils.getJSXElement(this.props.header, this.props); var icons = ObjectUtils.getJSXElement(this.props.icons, this.props); var togglerElement = this.renderToggleIcon(collapsed); var titleElement = /*#__PURE__*/React.createElement("span", { className: "p-panel-title", id: this.state.id + '_header' }, header); var iconsElement = /*#__PURE__*/React.createElement("div", { className: "p-panel-icons" }, icons, togglerElement); var content = /*#__PURE__*/React.createElement("div", { className: "p-panel-header" }, titleElement, iconsElement); if (this.props.headerTemplate) { var defaultContentOptions = { className: 'p-panel-header', titleClassName: 'p-panel-title', iconsClassName: 'p-panel-icons', togglerClassName: 'p-panel-header-icon p-panel-toggler p-link', togglerIconClassName: collapsed ? this.props.expandIcon : this.props.collapseIcon, onTogglerClick: this.toggle, titleElement: titleElement, iconsElement: iconsElement, togglerElement: togglerElement, element: content, props: this.props, collapsed: collapsed }; return ObjectUtils.getJSXElement(this.props.headerTemplate, defaultContentOptions); } else if (this.props.header || this.props.toggleable) { return content; } return null; } }, { key: "renderContent", value: function renderContent(collapsed) { var id = this.state.id + '_content'; return /*#__PURE__*/React.createElement(CSSTransition, { nodeRef: this.contentRef, classNames: "p-toggleable-content", timeout: { enter: 1000, exit: 450 }, in: !collapsed, unmountOnExit: true, options: this.props.transitionOptions }, /*#__PURE__*/React.createElement("div", { ref: this.contentRef, className: "p-toggleable-content", "aria-hidden": collapsed, role: "region", id: id, "aria-labelledby": this.state.id + '_header' }, /*#__PURE__*/React.createElement("div", { className: "p-panel-content" }, this.props.children))); } }, { key: "render", value: function render() { var className = classNames('p-panel p-component', { 'p-panel-toggleable': this.props.toggleable }, this.props.className); var collapsed = this.isCollapsed(); var header = this.renderHeader(collapsed); var content = this.renderContent(collapsed); return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: className, style: this.props.style }, header, content); } }]); return Panel; }(Component); _defineProperty(Panel, "defaultProps", { id: null, header: null, headerTemplate: null, toggleable: null, style: null, className: null, collapsed: null, expandIcon: 'pi pi-plus', collapseIcon: 'pi pi-minus', icons: null, transitionOptions: null, onExpand: null, onCollapse: null, onToggle: null }); export { Panel };
ajax/libs/material-ui/4.9.2/es/internal/svg-icons/Person.js
cdnjs/cdnjs
import React from 'react'; import createSvgIcon from './createSvgIcon'; /** * @ignore - internal component. */ export default createSvgIcon(React.createElement("path", { d: "M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" }), 'Person');
ajax/libs/material-ui/4.9.4/esm/StepIcon/StepIcon.js
cdnjs/cdnjs
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import CheckCircle from '../internal/svg-icons/CheckCircle'; import Warning from '../internal/svg-icons/Warning'; import withStyles from '../styles/withStyles'; import SvgIcon from '../SvgIcon'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { display: 'block', color: theme.palette.text.disabled, '&$completed': { color: theme.palette.primary.main }, '&$active': { color: theme.palette.primary.main }, '&$error': { color: theme.palette.error.main } }, /* Styles applied to the SVG text element. */ text: { fill: theme.palette.primary.contrastText, fontSize: theme.typography.caption.fontSize, fontFamily: theme.typography.fontFamily }, /* Pseudo-class applied to the root element if `active={true}`. */ active: {}, /* Pseudo-class applied to the root element if `completed={true}`. */ completed: {}, /* Pseudo-class applied to the root element if `error={true}`. */ error: {} }; }; var _ref = React.createElement("circle", { cx: "12", cy: "12", r: "12" }); var StepIcon = React.forwardRef(function StepIcon(props, ref) { var _props$completed = props.completed, completed = _props$completed === void 0 ? false : _props$completed, icon = props.icon, _props$active = props.active, active = _props$active === void 0 ? false : _props$active, _props$error = props.error, error = _props$error === void 0 ? false : _props$error, classes = props.classes; if (typeof icon === 'number' || typeof icon === 'string') { var className = clsx(classes.root, active && classes.active, error && classes.error, completed && classes.completed); if (error) { return React.createElement(Warning, { className: className, ref: ref }); } if (completed) { return React.createElement(CheckCircle, { className: className, ref: ref }); } return React.createElement(SvgIcon, { className: className, ref: ref }, _ref, React.createElement("text", { className: classes.text, x: "12", y: "16", textAnchor: "middle" }, icon)); } return icon; }); process.env.NODE_ENV !== "production" ? StepIcon.propTypes = { /** * Whether this step is active. */ active: PropTypes.bool, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * Mark the step as completed. Is passed to child components. */ completed: PropTypes.bool, /** * Mark the step as failed. */ error: PropTypes.bool, /** * The label displayed in the step icon. */ icon: PropTypes.node.isRequired } : void 0; export default withStyles(styles, { name: 'MuiStepIcon' })(StepIcon);
ajax/libs/primereact/7.0.0-rc.1/listbox/listbox.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { FilterService } from 'primereact/api'; import { DomHandler, classNames, ObjectUtils, Ripple, tip } from 'primereact/core'; import { InputText } from 'primereact/inputtext'; import { VirtualScroller } from 'primereact/virtualscroller'; function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _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$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 ListBoxItem = /*#__PURE__*/function (_Component) { _inherits(ListBoxItem, _Component); var _super = _createSuper$2(ListBoxItem); function ListBoxItem(props) { var _this; _classCallCheck(this, ListBoxItem); _this = _super.call(this, props); _this.onClick = _this.onClick.bind(_assertThisInitialized(_this)); _this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this)); _this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this)); return _this; } _createClass(ListBoxItem, [{ key: "onClick", value: function onClick(event) { if (this.props.onClick) { this.props.onClick({ originalEvent: event, option: this.props.option }); } event.preventDefault(); } }, { key: "onTouchEnd", value: function onTouchEnd(event) { if (this.props.onTouchEnd) { this.props.onTouchEnd({ originalEvent: event, option: this.props.option }); } } }, { key: "onKeyDown", value: function onKeyDown(event) { var item = event.currentTarget; switch (event.which) { //down case 40: var nextItem = this.findNextItem(item); if (nextItem) { nextItem.focus(); } event.preventDefault(); break; //up case 38: var prevItem = this.findPrevItem(item); if (prevItem) { prevItem.focus(); } event.preventDefault(); break; //enter case 13: this.onClick(event); event.preventDefault(); break; } } }, { key: "findNextItem", value: function findNextItem(item) { var nextItem = item.nextElementSibling; if (nextItem) return DomHandler.hasClass(nextItem, 'p-disabled') || DomHandler.hasClass(nextItem, 'p-listbox-item-group') ? this.findNextItem(nextItem) : nextItem;else return null; } }, { key: "findPrevItem", value: function findPrevItem(item) { var prevItem = item.previousElementSibling; if (prevItem) return DomHandler.hasClass(prevItem, 'p-disabled') || DomHandler.hasClass(prevItem, 'p-listbox-item-group') ? this.findPrevItem(prevItem) : prevItem;else return null; } }, { key: "render", value: function render() { var className = classNames('p-listbox-item', { 'p-highlight': this.props.selected, 'p-disabled': this.props.disabled }, this.props.option.className); var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props.option) : this.props.label; return /*#__PURE__*/React.createElement("li", { className: className, onClick: this.onClick, onTouchEnd: this.onTouchEnd, onKeyDown: this.onKeyDown, tabIndex: this.props.tabIndex, "aria-label": this.props.label, key: this.props.label, role: "option", "aria-selected": this.props.selected }, content, /*#__PURE__*/React.createElement(Ripple, null)); } }]); return ListBoxItem; }(Component); _defineProperty(ListBoxItem, "defaultProps", { option: null, label: null, selected: false, disabled: false, tabIndex: null, onClick: null, onTouchEnd: null, 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 ListBoxHeader = /*#__PURE__*/function (_Component) { _inherits(ListBoxHeader, _Component); var _super = _createSuper$1(ListBoxHeader); function ListBoxHeader(props) { var _this; _classCallCheck(this, ListBoxHeader); _this = _super.call(this, props); _this.onFilter = _this.onFilter.bind(_assertThisInitialized(_this)); return _this; } _createClass(ListBoxHeader, [{ key: "onFilter", value: function onFilter(event) { if (this.props.onFilter) { this.props.onFilter({ originalEvent: event, value: event.target.value }); } } }, { key: "render", value: function render() { return /*#__PURE__*/React.createElement("div", { className: "p-listbox-header" }, /*#__PURE__*/React.createElement("div", { className: "p-listbox-filter-container" }, /*#__PURE__*/React.createElement(InputText, { type: "text", value: this.props.filter, onChange: this.onFilter, className: "p-listbox-filter", disabled: this.props.disabled, placeholder: this.props.filterPlaceholder }), /*#__PURE__*/React.createElement("span", { className: "p-listbox-filter-icon pi pi-search" }))); } }]); return ListBoxHeader; }(Component); _defineProperty(ListBoxHeader, "defaultProps", { filter: null, filterPlaceholder: null, disabled: false, onFilter: null }); function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var ListBox = /*#__PURE__*/function (_Component) { _inherits(ListBox, _Component); var _super = _createSuper(ListBox); function ListBox(props) { var _this; _classCallCheck(this, ListBox); _this = _super.call(this, props); _this.state = {}; if (!_this.props.onFilterValueChange) { _this.state.filterValue = ''; } _this.onFilter = _this.onFilter.bind(_assertThisInitialized(_this)); _this.onOptionSelect = _this.onOptionSelect.bind(_assertThisInitialized(_this)); _this.onOptionTouchEnd = _this.onOptionTouchEnd.bind(_assertThisInitialized(_this)); return _this; } _createClass(ListBox, [{ 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: "getFilterValue", value: function getFilterValue() { return (this.props.onFilterValueChange ? this.props.filterValue : this.state.filterValue) || ''; } }, { key: "onOptionSelect", value: function onOptionSelect(event) { var option = event.option; if (this.props.disabled || this.isOptionDisabled(option)) { return; } if (this.props.multiple) this.onOptionSelectMultiple(event.originalEvent, option);else this.onOptionSelectSingle(event.originalEvent, option); this.optionTouched = false; } }, { key: "onOptionTouchEnd", value: function onOptionTouchEnd() { if (this.props.disabled) { return; } this.optionTouched = true; } }, { key: "onOptionSelectSingle", value: function onOptionSelectSingle(event, option) { var selected = this.isSelected(option); var valueChanged = false; var value = null; var metaSelection = this.optionTouched ? false : this.props.metaKeySelection; if (metaSelection) { var metaKey = event.metaKey || event.ctrlKey; if (selected) { if (metaKey) { value = null; valueChanged = true; } } else { value = this.getOptionValue(option); valueChanged = true; } } else { value = selected ? null : this.getOptionValue(option); valueChanged = true; } if (valueChanged) { this.updateModel(event, value); } } }, { key: "onOptionSelectMultiple", value: function onOptionSelectMultiple(event, option) { var selected = this.isSelected(option); var valueChanged = false; var value = null; var metaSelection = this.optionTouched ? false : this.props.metaKeySelection; if (metaSelection) { var metaKey = event.metaKey || event.ctrlKey; if (selected) { if (metaKey) value = this.removeOption(option);else value = [this.getOptionValue(option)]; valueChanged = true; } else { value = metaKey ? this.props.value || [] : []; value = [].concat(_toConsumableArray(value), [this.getOptionValue(option)]); valueChanged = true; } } else { if (selected) value = this.removeOption(option);else value = [].concat(_toConsumableArray(this.props.value || []), [this.getOptionValue(option)]); valueChanged = true; } if (valueChanged) { this.props.onChange({ originalEvent: event, value: value, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: value } }); } } }, { key: "onFilter", value: function onFilter(event) { var originalEvent = event.originalEvent, value = event.value; if (this.props.onFilterValueChange) { this.props.onFilterValueChange({ originalEvent: originalEvent, value: value }); } else { this.setState({ filterValue: value }); } } }, { key: "updateModel", value: function updateModel(event, value) { if (this.props.onChange) { this.props.onChange({ originalEvent: event, value: value, stopPropagation: function stopPropagation() {}, preventDefault: function preventDefault() {}, target: { name: this.props.name, id: this.props.id, value: value } }); } } }, { key: "removeOption", value: function removeOption(option) { var _this2 = this; return this.props.value.filter(function (val) { return !ObjectUtils.equals(val, _this2.getOptionValue(option), _this2.props.dataKey); }); } }, { key: "isSelected", value: function isSelected(option) { var selected = false; var optionValue = this.getOptionValue(option); if (this.props.multiple) { if (this.props.value) { 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: "filter", value: function filter(option) { var filterValue = this.getFilterValue().trim().toLocaleLowerCase(this.props.filterLocale); var optionLabel = this.getOptionLabel(option).toLocaleLowerCase(this.props.filterLocale); return optionLabel.indexOf(filterValue) > -1; } }, { key: "hasFilter", value: function hasFilter() { var filter = this.getFilterValue(); return filter && filter.trim().length > 0; } }, { 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: "getOptionRenderKey", value: function getOptionRenderKey(option) { return this.props.dataKey ? ObjectUtils.resolveFieldData(option, this.props.dataKey) : this.getOptionLabel(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: "getOptionGroupRenderKey", value: function getOptionGroupRenderKey(optionGroup) { return ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupLabel", value: function getOptionGroupLabel(optionGroup) { return ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupLabel); } }, { key: "getOptionGroupChildren", value: function getOptionGroupChildren(optionGroup) { return ObjectUtils.resolveFieldData(optionGroup, this.props.optionGroupChildren); } }, { key: "getVisibleOptions", value: function getVisibleOptions() { if (this.hasFilter()) { var filterValue = this.getFilterValue().trim().toLocaleLowerCase(this.props.filterLocale); var searchFields = this.props.filterBy ? this.props.filterBy.split(',') : [this.props.optionLabel || 'label']; if (this.props.optionGroupLabel) { var filteredGroups = []; var _iterator2 = _createForOfIteratorHelper(this.props.options), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var optgroup = _step2.value; var filteredSubOptions = FilterService.filter(this.getOptionGroupChildren(optgroup), searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); if (filteredSubOptions && filteredSubOptions.length) { filteredGroups.push(_objectSpread(_objectSpread({}, optgroup), { items: filteredSubOptions })); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return filteredGroups; } else { return FilterService.filter(this.props.options, searchFields, filterValue, this.props.filterMatchMode, this.props.filterLocale); } } else { return this.props.options; } } }, { key: "renderGroupChildren", value: function renderGroupChildren(optionGroup) { var _this3 = this; var groupChildren = this.getOptionGroupChildren(optionGroup); return groupChildren.map(function (option, j) { var optionLabel = _this3.getOptionLabel(option); var optionKey = j + '_' + _this3.getOptionRenderKey(option); var disabled = _this3.isOptionDisabled(option); var tabIndex = disabled ? null : _this3.props.tabIndex || 0; return /*#__PURE__*/React.createElement(ListBoxItem, { key: optionKey, label: optionLabel, option: option, template: _this3.props.itemTemplate, selected: _this3.isSelected(option), onClick: _this3.onOptionSelect, onTouchEnd: _this3.onOptionTouchEnd, tabIndex: tabIndex, disabled: disabled }); }); } }, { key: "renderItem", value: function renderItem(option, index) { if (this.props.optionGroupLabel) { var groupContent = this.props.optionGroupTemplate ? ObjectUtils.getJSXElement(this.props.optionGroupTemplate, option, index) : this.getOptionGroupLabel(option); var groupChildrenContent = this.renderGroupChildren(option); var key = index + '_' + this.getOptionGroupRenderKey(option); return /*#__PURE__*/React.createElement(React.Fragment, { key: key }, /*#__PURE__*/React.createElement("li", { className: "p-listbox-item-group" }, groupContent), groupChildrenContent); } else { var optionLabel = this.getOptionLabel(option); var optionKey = index + '_' + this.getOptionRenderKey(option); var disabled = this.isOptionDisabled(option); var tabIndex = disabled ? null : this.props.tabIndex || 0; return /*#__PURE__*/React.createElement(ListBoxItem, { key: optionKey, label: optionLabel, option: option, template: this.props.itemTemplate, selected: this.isSelected(option), onClick: this.onOptionSelect, onTouchEnd: this.onOptionTouchEnd, tabIndex: tabIndex, disabled: disabled }); } } }, { key: "renderItems", value: function renderItems(visibleOptions) { var _this4 = this; if (visibleOptions && visibleOptions.length) { return visibleOptions.map(function (option, index) { return _this4.renderItem(option, index); }); } return null; } }, { key: "renderList", value: function renderList(visibleOptions) { var _this5 = this; if (this.props.virtualScrollerOptions) { var virtualScrollerProps = _objectSpread(_objectSpread({}, this.props.virtualScrollerOptions), { items: visibleOptions, onLazyLoad: function onLazyLoad(event) { return _this5.props.virtualScrollerOptions.onLazyLoad(_objectSpread(_objectSpread({}, event), { filter: _this5.getFilterValue() })); }, itemTemplate: function itemTemplate(item, options) { return item && _this5.renderItem(item, options.index); }, contentTemplate: function contentTemplate(options) { var className = classNames('p-listbox-list', options.className); return /*#__PURE__*/React.createElement("ul", { ref: options.contentRef, className: className, role: "listbox", "aria-multiselectable": _this5.props.multiple }, options.children); } }); return /*#__PURE__*/React.createElement(VirtualScroller, _extends({ ref: function ref(el) { return _this5.virtualScrollerRef = el; } }, virtualScrollerProps)); } else { var items = this.renderItems(visibleOptions); return /*#__PURE__*/React.createElement("ul", { className: "p-listbox-list", role: "listbox", "aria-multiselectable": this.props.multiple }, items); } } }, { key: "render", value: function render() { var _this6 = this; var className = classNames('p-listbox p-component', { 'p-disabled': this.props.disabled }, this.props.className); var listClassName = classNames('p-listbox-list-wrapper', this.props.listClassName); var visibleOptions = this.getVisibleOptions(); var list = this.renderList(visibleOptions); var header; if (this.props.filter) { header = /*#__PURE__*/React.createElement(ListBoxHeader, { filter: this.getFilterValue(), onFilter: this.onFilter, disabled: this.props.disabled, filterPlaceholder: this.props.filterPlaceholder }); } return /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this6.element = el; }, id: this.props.id, className: className, style: this.props.style }, header, /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this6.wrapper = el; }, className: listClassName, style: this.props.listStyle }, list)); } }]); return ListBox; }(Component); _defineProperty(ListBox, "defaultProps", { id: null, value: null, options: null, optionLabel: null, optionValue: null, optionDisabled: null, optionGroupLabel: null, optionGroupChildren: null, optionGroupTemplate: null, itemTemplate: null, style: null, listStyle: null, listClassName: null, className: null, virtualScrollerOptions: null, disabled: null, dataKey: null, multiple: false, metaKeySelection: false, filter: false, filterBy: null, filterValue: null, filterMatchMode: 'contains', filterPlaceholder: null, filterLocale: undefined, tabIndex: 0, tooltip: null, tooltipOptions: null, ariaLabelledBy: null, onChange: null, onFilterValueChange: null }); export { ListBox };
ajax/libs/react-native-web/0.13.15/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/5.0.0-alpha.12/es/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/material-ui/4.9.3/esm/Step/Step.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import React from 'react'; import { isFragment } from 'react-is'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; export var styles = { /* Styles applied to the root element. */ root: {}, /* Styles applied to the root element if `orientation="horizontal"`. */ horizontal: { paddingLeft: 8, paddingRight: 8 }, /* Styles applied to the root element if `orientation="vertical"`. */ vertical: {}, /* Styles applied to the root element if `alternativeLabel={true}`. */ alternativeLabel: { flex: 1, position: 'relative' }, /* Pseudo-class applied to the root element if `completed={true}`. */ completed: {} }; var Step = React.forwardRef(function Step(props, ref) { var _props$active = props.active, active = _props$active === void 0 ? false : _props$active, alternativeLabel = props.alternativeLabel, children = props.children, classes = props.classes, className = props.className, _props$completed = props.completed, completed = _props$completed === void 0 ? false : _props$completed, connector = props.connector, _props$disabled = props.disabled, disabled = _props$disabled === void 0 ? false : _props$disabled, _props$expanded = props.expanded, expanded = _props$expanded === void 0 ? false : _props$expanded, index = props.index, last = props.last, orientation = props.orientation, other = _objectWithoutProperties(props, ["active", "alternativeLabel", "children", "classes", "className", "completed", "connector", "disabled", "expanded", "index", "last", "orientation"]); return React.createElement("div", _extends({ className: clsx(classes.root, classes[orientation], className, alternativeLabel && classes.alternativeLabel, completed && classes.completed), ref: ref }, other), connector && alternativeLabel && index !== 0 && React.cloneElement(connector, { orientation: orientation, alternativeLabel: alternativeLabel, index: index, active: active, completed: completed, disabled: disabled }), React.Children.map(children, function (child) { if (!React.isValidElement(child)) { return null; } if (process.env.NODE_ENV !== 'production') { if (isFragment(child)) { console.error(["Material-UI: the Step component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n')); } } return React.cloneElement(child, _extends({ active: active, alternativeLabel: alternativeLabel, completed: completed, disabled: disabled, expanded: expanded, last: last, icon: index + 1, orientation: orientation }, child.props)); })); }); process.env.NODE_ENV !== "production" ? Step.propTypes = { /** * Sets the step as active. Is passed to child components. */ active: PropTypes.bool, /** * @ignore * Set internally by Stepper when it's supplied with the alternativeLabel property. */ alternativeLabel: PropTypes.bool, /** * Should be `Step` sub-components such as `StepLabel`, `StepContent`. */ 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, /** * Mark the step as completed. Is passed to child components. */ completed: PropTypes.bool, /** * @ignore * Passed down from Stepper if alternativeLabel is also set. */ connector: PropTypes.element, /** * Mark the step as disabled, will also disable the button if * `StepButton` is a child of `Step`. Is passed to child components. */ disabled: PropTypes.bool, /** * Expand the step. */ expanded: PropTypes.bool, /** * @ignore * Used internally for numbering. */ index: PropTypes.number, /** * @ignore */ last: PropTypes.bool, /** * @ignore */ orientation: PropTypes.oneOf(['horizontal', 'vertical']) } : void 0; export default withStyles(styles, { name: 'MuiStep' })(Step);
ajax/libs/material-ui/4.9.2/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; }