path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
ajax/libs/react-native-web/0.17.0/exports/Touchable/index.js | cdnjs/cdnjs | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import AccessibilityUtil from '../../modules/AccessibilityUtil';
import BoundingDimensions from './BoundingDimensions';
import findNodeHandle from '../findNodeHandle';
import normalizeColor from 'normalize-css-color';
import Position from './Position';
import React from 'react';
import UIManager from '../UIManager';
import View from '../View';
var extractSingleTouch = function extractSingleTouch(nativeEvent) {
var touches = nativeEvent.touches;
var changedTouches = nativeEvent.changedTouches;
var hasTouches = touches && touches.length > 0;
var hasChangedTouches = changedTouches && changedTouches.length > 0;
return !hasTouches && hasChangedTouches ? changedTouches[0] : hasTouches ? touches[0] : nativeEvent;
};
/**
* `Touchable`: Taps done right.
*
* You hook your `ResponderEventPlugin` events into `Touchable`. `Touchable`
* will measure time/geometry and tells you when to give feedback to the user.
*
* ====================== Touchable Tutorial ===============================
* The `Touchable` mixin helps you handle the "press" interaction. It analyzes
* the geometry of elements, and observes when another responder (scroll view
* etc) has stolen the touch lock. It notifies your component when it should
* give feedback to the user. (bouncing/highlighting/unhighlighting).
*
* - When a touch was activated (typically you highlight)
* - When a touch was deactivated (typically you unhighlight)
* - When a touch was "pressed" - a touch ended while still within the geometry
* of the element, and no other element (like scroller) has "stolen" touch
* lock ("responder") (Typically you bounce the element).
*
* A good tap interaction isn't as simple as you might think. There should be a
* slight delay before showing a highlight when starting a touch. If a
* subsequent touch move exceeds the boundary of the element, it should
* unhighlight, but if that same touch is brought back within the boundary, it
* should rehighlight again. A touch can move in and out of that boundary
* several times, each time toggling highlighting, but a "press" is only
* triggered if that touch ends while within the element's boundary and no
* scroller (or anything else) has stolen the lock on touches.
*
* To create a new type of component that handles interaction using the
* `Touchable` mixin, do the following:
*
* - Initialize the `Touchable` state.
*
* getInitialState: function() {
* return merge(this.touchableGetInitialState(), yourComponentState);
* }
*
* - Choose the rendered component who's touches should start the interactive
* sequence. On that rendered node, forward all `Touchable` responder
* handlers. You can choose any rendered node you like. Choose a node whose
* hit target you'd like to instigate the interaction sequence:
*
* // In render function:
* return (
* <View
* onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
* onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest}
* onResponderGrant={this.touchableHandleResponderGrant}
* onResponderMove={this.touchableHandleResponderMove}
* onResponderRelease={this.touchableHandleResponderRelease}
* onResponderTerminate={this.touchableHandleResponderTerminate}>
* <View>
* Even though the hit detection/interactions are triggered by the
* wrapping (typically larger) node, we usually end up implementing
* custom logic that highlights this inner one.
* </View>
* </View>
* );
*
* - You may set up your own handlers for each of these events, so long as you
* also invoke the `touchable*` handlers inside of your custom handler.
*
* - Implement the handlers on your component class in order to provide
* feedback to the user. See documentation for each of these class methods
* that you should implement.
*
* touchableHandlePress: function() {
* this.performBounceAnimation(); // or whatever you want to do.
* },
* touchableHandleActivePressIn: function() {
* this.beginHighlighting(...); // Whatever you like to convey activation
* },
* touchableHandleActivePressOut: function() {
* this.endHighlighting(...); // Whatever you like to convey deactivation
* },
*
* - There are more advanced methods you can implement (see documentation below):
* touchableGetHighlightDelayMS: function() {
* return 20;
* }
* // In practice, *always* use a predeclared constant (conserve memory).
* touchableGetPressRectOffset: function() {
* return {top: 20, left: 20, right: 20, bottom: 100};
* }
*/
/**
* Touchable states.
*/
var States = {
NOT_RESPONDER: 'NOT_RESPONDER',
// Not the responder
RESPONDER_INACTIVE_PRESS_IN: 'RESPONDER_INACTIVE_PRESS_IN',
// Responder, inactive, in the `PressRect`
RESPONDER_INACTIVE_PRESS_OUT: 'RESPONDER_INACTIVE_PRESS_OUT',
// Responder, inactive, out of `PressRect`
RESPONDER_ACTIVE_PRESS_IN: 'RESPONDER_ACTIVE_PRESS_IN',
// Responder, active, in the `PressRect`
RESPONDER_ACTIVE_PRESS_OUT: 'RESPONDER_ACTIVE_PRESS_OUT',
// Responder, active, out of `PressRect`
RESPONDER_ACTIVE_LONG_PRESS_IN: 'RESPONDER_ACTIVE_LONG_PRESS_IN',
// Responder, active, in the `PressRect`, after long press threshold
RESPONDER_ACTIVE_LONG_PRESS_OUT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT',
// Responder, active, out of `PressRect`, after long press threshold
ERROR: 'ERROR'
};
/*
* Quick lookup map for states that are considered to be "active"
*/
var baseStatesConditions = {
NOT_RESPONDER: false,
RESPONDER_INACTIVE_PRESS_IN: false,
RESPONDER_INACTIVE_PRESS_OUT: false,
RESPONDER_ACTIVE_PRESS_IN: false,
RESPONDER_ACTIVE_PRESS_OUT: false,
RESPONDER_ACTIVE_LONG_PRESS_IN: false,
RESPONDER_ACTIVE_LONG_PRESS_OUT: false,
ERROR: false
};
var IsActive = _objectSpread(_objectSpread({}, baseStatesConditions), {}, {
RESPONDER_ACTIVE_PRESS_OUT: true,
RESPONDER_ACTIVE_PRESS_IN: true
});
/**
* Quick lookup for states that are considered to be "pressing" and are
* therefore eligible to result in a "selection" if the press stops.
*/
var IsPressingIn = _objectSpread(_objectSpread({}, baseStatesConditions), {}, {
RESPONDER_INACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_LONG_PRESS_IN: true
});
var IsLongPressingIn = _objectSpread(_objectSpread({}, baseStatesConditions), {}, {
RESPONDER_ACTIVE_LONG_PRESS_IN: true
});
/**
* Inputs to the state machine.
*/
var Signals = {
DELAY: 'DELAY',
RESPONDER_GRANT: 'RESPONDER_GRANT',
RESPONDER_RELEASE: 'RESPONDER_RELEASE',
RESPONDER_TERMINATED: 'RESPONDER_TERMINATED',
ENTER_PRESS_RECT: 'ENTER_PRESS_RECT',
LEAVE_PRESS_RECT: 'LEAVE_PRESS_RECT',
LONG_PRESS_DETECTED: 'LONG_PRESS_DETECTED'
};
/**
* Mapping from States x Signals => States
*/
var Transitions = {
NOT_RESPONDER: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.ERROR,
RESPONDER_TERMINATED: States.ERROR,
ENTER_PRESS_RECT: States.ERROR,
LEAVE_PRESS_RECT: States.ERROR,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_INACTIVE_PRESS_IN: {
DELAY: States.RESPONDER_ACTIVE_PRESS_IN,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_INACTIVE_PRESS_OUT: {
DELAY: States.RESPONDER_ACTIVE_PRESS_OUT,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_ACTIVE_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN
},
RESPONDER_ACTIVE_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_ACTIVE_LONG_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT,
LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN
},
RESPONDER_ACTIVE_LONG_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
error: {
DELAY: States.NOT_RESPONDER,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.NOT_RESPONDER,
LEAVE_PRESS_RECT: States.NOT_RESPONDER,
LONG_PRESS_DETECTED: States.NOT_RESPONDER
}
}; // ==== Typical Constants for integrating into UI components ====
// var HIT_EXPAND_PX = 20;
// var HIT_VERT_OFFSET_PX = 10;
var HIGHLIGHT_DELAY_MS = 130;
var PRESS_EXPAND_PX = 20;
var LONG_PRESS_THRESHOLD = 500;
var LONG_PRESS_DELAY_MS = LONG_PRESS_THRESHOLD - HIGHLIGHT_DELAY_MS;
var LONG_PRESS_ALLOWED_MOVEMENT = 10; // Default amount "active" region protrudes beyond box
/**
* By convention, methods prefixed with underscores are meant to be @private,
* and not @protected. Mixers shouldn't access them - not even to provide them
* as callback handlers.
*
*
* ========== Geometry =========
* `Touchable` only assumes that there exists a `HitRect` node. The `PressRect`
* is an abstract box that is extended beyond the `HitRect`.
*
* +--------------------------+
* | | - "Start" events in `HitRect` cause `HitRect`
* | +--------------------+ | to become the responder.
* | | +--------------+ | | - `HitRect` is typically expanded around
* | | | | | | the `VisualRect`, but shifted downward.
* | | | VisualRect | | | - After pressing down, after some delay,
* | | | | | | and before letting up, the Visual React
* | | +--------------+ | | will become "active". This makes it eligible
* | | HitRect | | for being highlighted (so long as the
* | +--------------------+ | press remains in the `PressRect`).
* | PressRect o |
* +----------------------|---+
* Out Region |
* +-----+ This gap between the `HitRect` and
* `PressRect` allows a touch to move far away
* from the original hit rect, and remain
* highlighted, and eligible for a "Press".
* Customize this via
* `touchableGetPressRectOffset()`.
*
*
*
* ======= State Machine =======
*
* +-------------+ <---+ RESPONDER_RELEASE
* |NOT_RESPONDER|
* +-------------+ <---+ RESPONDER_TERMINATED
* +
* | RESPONDER_GRANT (HitRect)
* v
* +---------------------------+ DELAY +-------------------------+ T + DELAY +------------------------------+
* |RESPONDER_INACTIVE_PRESS_IN|+-------->|RESPONDER_ACTIVE_PRESS_IN| +------------> |RESPONDER_ACTIVE_LONG_PRESS_IN|
* +---------------------------+ +-------------------------+ +------------------------------+
* + ^ + ^ + ^
* |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ |LEAVE_ |ENTER_
* |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT
* | | | | | |
* v + v + v +
* +----------------------------+ DELAY +--------------------------+ +-------------------------------+
* |RESPONDER_INACTIVE_PRESS_OUT|+------->|RESPONDER_ACTIVE_PRESS_OUT| |RESPONDER_ACTIVE_LONG_PRESS_OUT|
* +----------------------------+ +--------------------------+ +-------------------------------+
*
* T + DELAY => LONG_PRESS_DELAY_MS + DELAY
*
* Not drawn are the side effects of each transition. The most important side
* effect is the `touchableHandlePress` abstract method invocation that occurs
* when a responder is released while in either of the "Press" states.
*
* The other important side effects are the highlight abstract method
* invocations (internal callbacks) to be implemented by the mixer.
*
*
* @lends Touchable.prototype
*/
var TouchableMixin = {
// HACK (part 1): basic support for touchable interactions using a keyboard
componentDidMount: function componentDidMount() {
var _this = this;
this._touchableNode = findNodeHandle(this);
if (this._touchableNode && this._touchableNode.addEventListener) {
this._touchableBlurListener = function (e) {
if (_this._isTouchableKeyboardActive) {
if (_this.state.touchable.touchState && _this.state.touchable.touchState !== States.NOT_RESPONDER) {
_this.touchableHandleResponderTerminate({
nativeEvent: e
});
}
_this._isTouchableKeyboardActive = false;
}
};
this._touchableNode.addEventListener('blur', this._touchableBlurListener);
}
},
/**
* Clear all timeouts on unmount
*/
componentWillUnmount: function componentWillUnmount() {
if (this._touchableNode && this._touchableNode.addEventListener) {
this._touchableNode.removeEventListener('blur', this._touchableBlurListener);
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout); // Clear DOM nodes
this.pressInLocation = null;
this.state.touchable.responderID = null;
this._touchableNode = null;
},
/**
* It's prefer that mixins determine state in this way, having the class
* explicitly mix the state in the one and only `getInitialState` method.
*
* @return {object} State object to be placed inside of
* `this.state.touchable`.
*/
touchableGetInitialState: function touchableGetInitialState() {
return {
touchable: {
touchState: undefined,
responderID: null
}
};
},
// ==== Hooks to Gesture Responder system ====
/**
* Must return true if embedded in a native platform scroll view.
*/
touchableHandleResponderTerminationRequest: function touchableHandleResponderTerminationRequest() {
return !this.props.rejectResponderTermination;
},
/**
* Must return true to start the process of `Touchable`.
*/
touchableHandleStartShouldSetResponder: function touchableHandleStartShouldSetResponder() {
return !this.props.disabled;
},
/**
* Return true to cancel press on long press.
*/
touchableLongPressCancelsPress: function touchableLongPressCancelsPress() {
return true;
},
/**
* Place as callback for a DOM element's `onResponderGrant` event.
* @param {SyntheticEvent} e Synthetic event from event system.
*
*/
touchableHandleResponderGrant: function touchableHandleResponderGrant(e) {
var dispatchID = e.currentTarget; // Since e is used in a callback invoked on another event loop
// (as in setTimeout etc), we need to call e.persist() on the
// event to make sure it doesn't get reused in the event object pool.
e.persist();
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
this.pressOutDelayTimeout = null;
this.state.touchable.touchState = States.NOT_RESPONDER;
this.state.touchable.responderID = dispatchID;
this._receiveSignal(Signals.RESPONDER_GRANT, e);
var delayMS = this.touchableGetHighlightDelayMS !== undefined ? Math.max(this.touchableGetHighlightDelayMS(), 0) : HIGHLIGHT_DELAY_MS;
delayMS = isNaN(delayMS) ? HIGHLIGHT_DELAY_MS : delayMS;
if (delayMS !== 0) {
this.touchableDelayTimeout = setTimeout(this._handleDelay.bind(this, e), delayMS);
} else {
this._handleDelay(e);
}
var longDelayMS = this.touchableGetLongPressDelayMS !== undefined ? Math.max(this.touchableGetLongPressDelayMS(), 10) : LONG_PRESS_DELAY_MS;
longDelayMS = isNaN(longDelayMS) ? LONG_PRESS_DELAY_MS : longDelayMS;
this.longPressDelayTimeout = setTimeout(this._handleLongDelay.bind(this, e), longDelayMS + delayMS);
},
/**
* Place as callback for a DOM element's `onResponderRelease` event.
*/
touchableHandleResponderRelease: function touchableHandleResponderRelease(e) {
this.pressInLocation = null;
this._receiveSignal(Signals.RESPONDER_RELEASE, e);
},
/**
* Place as callback for a DOM element's `onResponderTerminate` event.
*/
touchableHandleResponderTerminate: function touchableHandleResponderTerminate(e) {
this.pressInLocation = null;
this._receiveSignal(Signals.RESPONDER_TERMINATED, e);
},
/**
* Place as callback for a DOM element's `onResponderMove` event.
*/
touchableHandleResponderMove: function touchableHandleResponderMove(e) {
// Measurement may not have returned yet.
if (!this.state.touchable.positionOnActivate) {
return;
}
var positionOnActivate = this.state.touchable.positionOnActivate;
var dimensionsOnActivate = this.state.touchable.dimensionsOnActivate;
var pressRectOffset = this.touchableGetPressRectOffset ? this.touchableGetPressRectOffset() : {
left: PRESS_EXPAND_PX,
right: PRESS_EXPAND_PX,
top: PRESS_EXPAND_PX,
bottom: PRESS_EXPAND_PX
};
var pressExpandLeft = pressRectOffset.left;
var pressExpandTop = pressRectOffset.top;
var pressExpandRight = pressRectOffset.right;
var pressExpandBottom = pressRectOffset.bottom;
var hitSlop = this.touchableGetHitSlop ? this.touchableGetHitSlop() : null;
if (hitSlop) {
pressExpandLeft += hitSlop.left || 0;
pressExpandTop += hitSlop.top || 0;
pressExpandRight += hitSlop.right || 0;
pressExpandBottom += hitSlop.bottom || 0;
}
var touch = extractSingleTouch(e.nativeEvent);
var pageX = touch && touch.pageX;
var pageY = touch && touch.pageY;
if (this.pressInLocation) {
var movedDistance = this._getDistanceBetweenPoints(pageX, pageY, this.pressInLocation.pageX, this.pressInLocation.pageY);
if (movedDistance > LONG_PRESS_ALLOWED_MOVEMENT) {
this._cancelLongPressDelayTimeout();
}
}
var isTouchWithinActive = pageX > positionOnActivate.left - pressExpandLeft && pageY > positionOnActivate.top - pressExpandTop && pageX < positionOnActivate.left + dimensionsOnActivate.width + pressExpandRight && pageY < positionOnActivate.top + dimensionsOnActivate.height + pressExpandBottom;
if (isTouchWithinActive) {
var prevState = this.state.touchable.touchState;
this._receiveSignal(Signals.ENTER_PRESS_RECT, e);
var curState = this.state.touchable.touchState;
if (curState === States.RESPONDER_INACTIVE_PRESS_IN && prevState !== States.RESPONDER_INACTIVE_PRESS_IN) {
// fix for t7967420
this._cancelLongPressDelayTimeout();
}
} else {
this._cancelLongPressDelayTimeout();
this._receiveSignal(Signals.LEAVE_PRESS_RECT, e);
}
},
/**
* Invoked when the item receives focus. Mixers might override this to
* visually distinguish the `VisualRect` so that the user knows that it
* currently has the focus. Most platforms only support a single element being
* focused at a time, in which case there may have been a previously focused
* element that was blurred just prior to this. This can be overridden when
* using `Touchable.Mixin.withoutDefaultFocusAndBlur`.
*/
touchableHandleFocus: function touchableHandleFocus(e) {
this.props.onFocus && this.props.onFocus(e);
},
/**
* Invoked when the item loses focus. Mixers might override this to
* visually distinguish the `VisualRect` so that the user knows that it
* no longer has focus. Most platforms only support a single element being
* focused at a time, in which case the focus may have moved to another.
* This can be overridden when using
* `Touchable.Mixin.withoutDefaultFocusAndBlur`.
*/
touchableHandleBlur: function touchableHandleBlur(e) {
this.props.onBlur && this.props.onBlur(e);
},
// ==== Abstract Application Callbacks ====
/**
* Invoked when the item should be highlighted. Mixers should implement this
* to visually distinguish the `VisualRect` so that the user knows that
* releasing a touch will result in a "selection" (analog to click).
*
* @abstract
* touchableHandleActivePressIn: function,
*/
/**
* Invoked when the item is "active" (in that it is still eligible to become
* a "select") but the touch has left the `PressRect`. Usually the mixer will
* want to unhighlight the `VisualRect`. If the user (while pressing) moves
* back into the `PressRect` `touchableHandleActivePressIn` will be invoked
* again and the mixer should probably highlight the `VisualRect` again. This
* event will not fire on an `touchEnd/mouseUp` event, only move events while
* the user is depressing the mouse/touch.
*
* @abstract
* touchableHandleActivePressOut: function
*/
/**
* Invoked when the item is "selected" - meaning the interaction ended by
* letting up while the item was either in the state
* `RESPONDER_ACTIVE_PRESS_IN` or `RESPONDER_INACTIVE_PRESS_IN`.
*
* @abstract
* touchableHandlePress: function
*/
/**
* Invoked when the item is long pressed - meaning the interaction ended by
* letting up while the item was in `RESPONDER_ACTIVE_LONG_PRESS_IN`. If
* `touchableHandleLongPress` is *not* provided, `touchableHandlePress` will
* be called as it normally is. If `touchableHandleLongPress` is provided, by
* default any `touchableHandlePress` callback will not be invoked. To
* override this default behavior, override `touchableLongPressCancelsPress`
* to return false. As a result, `touchableHandlePress` will be called when
* lifting up, even if `touchableHandleLongPress` has also been called.
*
* @abstract
* touchableHandleLongPress: function
*/
/**
* Returns the number of millis to wait before triggering a highlight.
*
* @abstract
* touchableGetHighlightDelayMS: function
*/
/**
* Returns the amount to extend the `HitRect` into the `PressRect`. Positive
* numbers mean the size expands outwards.
*
* @abstract
* touchableGetPressRectOffset: function
*/
// ==== Internal Logic ====
/**
* Measures the `HitRect` node on activation. The Bounding rectangle is with
* respect to viewport - not page, so adding the `pageXOffset/pageYOffset`
* should result in points that are in the same coordinate system as an
* event's `globalX/globalY` data values.
*
* - Consider caching this for the lifetime of the component, or possibly
* being able to share this cache between any `ScrollMap` view.
*
* @sideeffects
* @private
*/
_remeasureMetricsOnActivation: function _remeasureMetricsOnActivation() {
var tag = this.state.touchable.responderID;
if (tag == null) {
return;
}
UIManager.measure(tag, this._handleQueryLayout);
},
_handleQueryLayout: function _handleQueryLayout(l, t, w, h, globalX, globalY) {
//don't do anything UIManager failed to measure node
if (!l && !t && !w && !h && !globalX && !globalY) {
return;
}
this.state.touchable.positionOnActivate && Position.release(this.state.touchable.positionOnActivate);
this.state.touchable.dimensionsOnActivate && // $FlowFixMe
BoundingDimensions.release(this.state.touchable.dimensionsOnActivate);
this.state.touchable.positionOnActivate = Position.getPooled(globalX, globalY); // $FlowFixMe
this.state.touchable.dimensionsOnActivate = BoundingDimensions.getPooled(w, h);
},
_handleDelay: function _handleDelay(e) {
this.touchableDelayTimeout = null;
this._receiveSignal(Signals.DELAY, e);
},
_handleLongDelay: function _handleLongDelay(e) {
this.longPressDelayTimeout = null;
var curState = this.state.touchable.touchState;
if (curState !== States.RESPONDER_ACTIVE_PRESS_IN && curState !== States.RESPONDER_ACTIVE_LONG_PRESS_IN) {
console.error('Attempted to transition from state `' + curState + '` to `' + States.RESPONDER_ACTIVE_LONG_PRESS_IN + '`, which is not supported. This is ' + 'most likely due to `Touchable.longPressDelayTimeout` not being cancelled.');
} else {
this._receiveSignal(Signals.LONG_PRESS_DETECTED, e);
}
},
/**
* Receives a state machine signal, performs side effects of the transition
* and stores the new state. Validates the transition as well.
*
* @param {Signals} signal State machine signal.
* @throws Error if invalid state transition or unrecognized signal.
* @sideeffects
*/
_receiveSignal: function _receiveSignal(signal, e) {
var responderID = this.state.touchable.responderID;
var curState = this.state.touchable.touchState;
var nextState = Transitions[curState] && Transitions[curState][signal];
if (!responderID && signal === Signals.RESPONDER_RELEASE) {
return;
}
if (!nextState) {
throw new Error('Unrecognized signal `' + signal + '` or state `' + curState + '` for Touchable responder `' + responderID + '`');
}
if (nextState === States.ERROR) {
throw new Error('Touchable cannot transition from `' + curState + '` to `' + signal + '` for responder `' + responderID + '`');
}
if (curState !== nextState) {
this._performSideEffectsForTransition(curState, nextState, signal, e);
this.state.touchable.touchState = nextState;
}
},
_cancelLongPressDelayTimeout: function _cancelLongPressDelayTimeout() {
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.longPressDelayTimeout = null;
},
_isHighlight: function _isHighlight(state) {
return state === States.RESPONDER_ACTIVE_PRESS_IN || state === States.RESPONDER_ACTIVE_LONG_PRESS_IN;
},
_savePressInLocation: function _savePressInLocation(e) {
var touch = extractSingleTouch(e.nativeEvent);
var pageX = touch && touch.pageX;
var pageY = touch && touch.pageY;
var locationX = touch && touch.locationX;
var locationY = touch && touch.locationY;
this.pressInLocation = {
pageX: pageX,
pageY: pageY,
locationX: locationX,
locationY: locationY
};
},
_getDistanceBetweenPoints: function _getDistanceBetweenPoints(aX, aY, bX, bY) {
var deltaX = aX - bX;
var deltaY = aY - bY;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
},
/**
* Will perform a transition between touchable states, and identify any
* highlighting or unhighlighting that must be performed for this particular
* transition.
*
* @param {States} curState Current Touchable state.
* @param {States} nextState Next Touchable state.
* @param {Signal} signal Signal that triggered the transition.
* @param {Event} e Native event.
* @sideeffects
*/
_performSideEffectsForTransition: function _performSideEffectsForTransition(curState, nextState, signal, e) {
var curIsHighlight = this._isHighlight(curState);
var newIsHighlight = this._isHighlight(nextState);
var isFinalSignal = signal === Signals.RESPONDER_TERMINATED || signal === Signals.RESPONDER_RELEASE;
if (isFinalSignal) {
this._cancelLongPressDelayTimeout();
}
var isInitialTransition = curState === States.NOT_RESPONDER && nextState === States.RESPONDER_INACTIVE_PRESS_IN;
var isActiveTransition = !IsActive[curState] && IsActive[nextState];
if (isInitialTransition || isActiveTransition) {
this._remeasureMetricsOnActivation();
}
if (IsPressingIn[curState] && signal === Signals.LONG_PRESS_DETECTED) {
this.touchableHandleLongPress && this.touchableHandleLongPress(e);
}
if (newIsHighlight && !curIsHighlight) {
this._startHighlight(e);
} else if (!newIsHighlight && curIsHighlight) {
this._endHighlight(e);
}
if (IsPressingIn[curState] && signal === Signals.RESPONDER_RELEASE) {
var hasLongPressHandler = !!this.props.onLongPress;
var pressIsLongButStillCallOnPress = IsLongPressingIn[curState] && ( // We *are* long pressing.. // But either has no long handler
!hasLongPressHandler || !this.touchableLongPressCancelsPress()); // or we're told to ignore it.
var shouldInvokePress = !IsLongPressingIn[curState] || pressIsLongButStillCallOnPress;
if (shouldInvokePress && this.touchableHandlePress) {
if (!newIsHighlight && !curIsHighlight) {
// we never highlighted because of delay, but we should highlight now
this._startHighlight(e);
this._endHighlight(e);
}
this.touchableHandlePress(e);
}
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.touchableDelayTimeout = null;
},
_playTouchSound: function _playTouchSound() {
UIManager.playTouchSound();
},
_startHighlight: function _startHighlight(e) {
this._savePressInLocation(e);
this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e);
},
_endHighlight: function _endHighlight(e) {
var _this2 = this;
if (this.touchableHandleActivePressOut) {
if (this.touchableGetPressOutDelayMS && this.touchableGetPressOutDelayMS()) {
this.pressOutDelayTimeout = setTimeout(function () {
_this2.touchableHandleActivePressOut(e);
}, this.touchableGetPressOutDelayMS());
} else {
this.touchableHandleActivePressOut(e);
}
}
},
// HACK (part 2): basic support for touchable interactions using a keyboard (including
// delays and longPress)
touchableHandleKeyEvent: function touchableHandleKeyEvent(e) {
var type = e.type,
key = e.key;
if (key === 'Enter' || key === ' ') {
if (type === 'keydown') {
if (!this._isTouchableKeyboardActive) {
if (!this.state.touchable.touchState || this.state.touchable.touchState === States.NOT_RESPONDER) {
this.touchableHandleResponderGrant(e);
this._isTouchableKeyboardActive = true;
}
}
} else if (type === 'keyup') {
if (this._isTouchableKeyboardActive) {
if (this.state.touchable.touchState && this.state.touchable.touchState !== States.NOT_RESPONDER) {
this.touchableHandleResponderRelease(e);
this._isTouchableKeyboardActive = false;
}
}
}
e.stopPropagation(); // prevent the default behaviour unless the Touchable functions as a link
// and Enter is pressed
if (!(key === 'Enter' && AccessibilityUtil.propsToAriaRole(this.props) === 'link')) {
e.preventDefault();
}
}
},
withoutDefaultFocusAndBlur: {}
};
/**
* Provide an optional version of the mixin where `touchableHandleFocus` and
* `touchableHandleBlur` can be overridden. This allows appropriate defaults to
* be set on TV platforms, without breaking existing implementations of
* `Touchable`.
*/
var touchableHandleFocus = TouchableMixin.touchableHandleFocus,
touchableHandleBlur = TouchableMixin.touchableHandleBlur,
TouchableMixinWithoutDefaultFocusAndBlur = _objectWithoutPropertiesLoose(TouchableMixin, ["touchableHandleFocus", "touchableHandleBlur"]);
TouchableMixin.withoutDefaultFocusAndBlur = TouchableMixinWithoutDefaultFocusAndBlur;
var Touchable = {
Mixin: TouchableMixin,
TOUCH_TARGET_DEBUG: false,
// Highlights all touchable targets. Toggle with Inspector.
/**
* Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android).
*/
renderDebugView: function renderDebugView(_ref) {
var color = _ref.color,
hitSlop = _ref.hitSlop;
if (!Touchable.TOUCH_TARGET_DEBUG) {
return null;
}
if (process.env.NODE_ENV !== 'production') {
throw Error('Touchable.TOUCH_TARGET_DEBUG should not be enabled in prod!');
}
var debugHitSlopStyle = {};
hitSlop = hitSlop || {
top: 0,
bottom: 0,
left: 0,
right: 0
};
for (var key in hitSlop) {
debugHitSlopStyle[key] = -hitSlop[key];
}
var normalizedColor = normalizeColor(color);
if (typeof normalizedColor !== 'number') {
return null;
}
var hexColor = '#' + ('00000000' + normalizedColor.toString(16)).substr(-8);
return /*#__PURE__*/React.createElement(View, {
pointerEvents: "none",
style: _objectSpread({
position: 'absolute',
borderColor: hexColor.slice(0, -2) + '55',
// More opaque
borderWidth: 1,
borderStyle: 'dashed',
backgroundColor: hexColor.slice(0, -2) + '0F'
}, debugHitSlopStyle)
});
}
};
export default Touchable; |
ajax/libs/material-ui/4.9.2/esm/utils/useEventCallback.js | cdnjs/cdnjs | import React from 'react';
var useEnhancedEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
/**
* https://github.com/facebook/react/issues/14099#issuecomment-440013892
*
* @param {function} fn
*/
export default function useEventCallback(fn) {
var ref = React.useRef(fn);
useEnhancedEffect(function () {
ref.current = fn;
});
return React.useCallback(function () {
return (0, ref.current).apply(void 0, arguments);
}, []);
} |
ajax/libs/react-native-web/0.0.0-5806b249d/exports/createElement/index.js | cdnjs/cdnjs | /**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import AccessibilityUtil from '../../modules/AccessibilityUtil';
import createDOMProps from '../../modules/createDOMProps';
import React from 'react';
var createElement = function createElement(component, props) {
// Use equivalent platform elements where possible.
var accessibilityComponent;
if (component && component.constructor === String) {
accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props);
}
var Component = accessibilityComponent || component;
var domProps = createDOMProps(Component, props);
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
children[_key - 2] = arguments[_key];
}
return React.createElement.apply(React, [Component, domProps].concat(children));
};
export default createElement; |
ajax/libs/material-ui/4.9.2/esm/utils/useForkRef.js | cdnjs/cdnjs | import React from 'react';
import setRef from './setRef';
export default function useForkRef(refA, refB) {
/**
* This will create a new function if the ref props change and are defined.
* This means react will call the old forkRef with `null` and the new forkRef
* with the ref. Cleanup naturally emerges from this behavior
*/
return React.useMemo(function () {
if (refA == null && refB == null) {
return null;
}
return function (refValue) {
setRef(refA, refValue);
setRef(refB, refValue);
};
}, [refA, refB]);
} |
ajax/libs/react-native-web/0.0.0-5806b249d/exports/AppRegistry/renderApplication.js | cdnjs/cdnjs | function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import AppContainer from './AppContainer';
import invariant from 'fbjs/lib/invariant';
import render, { hydrate } from '../render';
import styleResolver from '../StyleSheet/styleResolver';
import React from 'react';
export default function renderApplication(RootComponent, WrapperComponent, callback, options) {
var shouldHydrate = options.hydrate,
initialProps = options.initialProps,
rootTag = options.rootTag;
var renderFn = shouldHydrate ? hydrate : render;
invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag);
renderFn(React.createElement(AppContainer, {
rootTag: rootTag,
WrapperComponent: WrapperComponent
}, React.createElement(RootComponent, initialProps)), rootTag, callback);
}
export function getApplication(RootComponent, initialProps, WrapperComponent) {
var element = React.createElement(AppContainer, {
rootTag: {},
WrapperComponent: WrapperComponent
}, React.createElement(RootComponent, initialProps)); // Don't escape CSS text
var getStyleElement = function getStyleElement(props) {
var sheet = styleResolver.getStyleSheet();
return React.createElement("style", _extends({}, props, {
dangerouslySetInnerHTML: {
__html: sheet.textContent
},
id: sheet.id
}));
};
return {
element: element,
getStyleElement: getStyleElement
};
} |
ajax/libs/material-ui/5.0.0-alpha.4/esm/styles/useTheme.js | cdnjs/cdnjs | import { useTheme as useThemeWithoutDefault } from '@material-ui/styles';
import React from 'react';
import defaultTheme from './defaultTheme';
export default function useTheme() {
var theme = useThemeWithoutDefault() || defaultTheme;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useDebugValue(theme);
}
return theme;
} |
ajax/libs/material-ui/4.9.3/es/Slider/ValueLabel.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
const styles = theme => ({
thumb: {
'&$open': {
'& $offset': {
transform: 'scale(1) translateY(-10px)'
}
}
},
open: {},
offset: _extends({
zIndex: 1
}, theme.typography.body2, {
fontSize: theme.typography.pxToRem(12),
lineHeight: 1.2,
transition: theme.transitions.create(['transform'], {
duration: theme.transitions.duration.shortest
}),
top: -34,
transformOrigin: 'bottom center',
transform: 'scale(0)',
position: 'absolute'
}),
circle: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: 32,
height: 32,
borderRadius: '50% 50% 50% 0',
backgroundColor: 'currentColor',
transform: 'rotate(-45deg)'
},
label: {
color: theme.palette.primary.contrastText,
transform: 'rotate(45deg)'
}
});
/**
* @ignore - internal component.
*/
function ValueLabel(props) {
const {
children,
classes,
className,
open,
value,
valueLabelDisplay
} = props;
if (valueLabelDisplay === 'off') {
return children;
}
return React.cloneElement(children, {
className: clsx(children.props.className, (open || valueLabelDisplay === 'on') && classes.open, classes.thumb)
}, React.createElement("span", {
className: clsx(classes.offset, className)
}, React.createElement("span", {
className: classes.circle
}, React.createElement("span", {
className: classes.label
}, value))));
}
export default withStyles(styles, {
name: 'PrivateValueLabel'
})(ValueLabel); |
ajax/libs/material-ui/4.9.4/es/NativeSelect/NativeSelectInput.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 capitalize from '../utils/capitalize';
/**
* @ignore - internal component.
*/
const NativeSelectInput = React.forwardRef(function NativeSelectInput(props, ref) {
const {
classes,
className,
disabled,
IconComponent,
inputRef,
variant = 'standard'
} = props,
other = _objectWithoutPropertiesLoose(props, ["classes", "className", "disabled", "IconComponent", "inputRef", "variant"]);
return React.createElement(React.Fragment, null, React.createElement("select", _extends({
className: clsx(classes.root, // TODO v5: merge root and select
classes.select, classes[variant], className, disabled && classes.disabled),
disabled: disabled,
ref: inputRef || ref
}, other)), props.multiple ? null : React.createElement(IconComponent, {
className: clsx(classes.icon, classes[`icon${capitalize(variant)}`])
}));
});
process.env.NODE_ENV !== "production" ? NativeSelectInput.propTypes = {
/**
* The option elements to populate the select with.
* Can be some `<option>` elements.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* The CSS class name of the select element.
*/
className: PropTypes.string,
/**
* If `true`, the select will be disabled.
*/
disabled: PropTypes.bool,
/**
* The icon that displays the arrow.
*/
IconComponent: PropTypes.elementType.isRequired,
/**
* Use that prop to pass a ref to the native select element.
* @deprecated
*/
inputRef: refType,
/**
* @ignore
*/
multiple: PropTypes.bool,
/**
* Name attribute of the `select` or hidden `input` element.
*/
name: PropTypes.string,
/**
* Callback function fired when a menu item is selected.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* The input value.
*/
value: PropTypes.any,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['standard', 'outlined', 'filled'])
} : void 0;
export default NativeSelectInput; |
ajax/libs/material-ui/4.9.4/es/CircularProgress/CircularProgress.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 { chainPropTypes } from '@material-ui/utils';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
const SIZE = 44;
function getRelativeValue(value, min, max) {
return (Math.min(Math.max(min, value), max) - min) / (max - min);
}
function easeOut(t) {
t = getRelativeValue(t, 0, 1); // https://gist.github.com/gre/1650294
t = (t -= 1) * t * t + 1;
return t;
}
function easeIn(t) {
return t * t;
}
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
display: 'inline-block'
},
/* Styles applied to the root element if `variant="static"`. */
static: {
transition: theme.transitions.create('transform')
},
/* Styles applied to the root element if `variant="indeterminate"`. */
indeterminate: {
animation: '$circular-rotate 1.4s linear infinite'
},
/* Styles applied to the root element if `color="primary"`. */
colorPrimary: {
color: theme.palette.primary.main
},
/* Styles applied to the root element if `color="secondary"`. */
colorSecondary: {
color: theme.palette.secondary.main
},
/* Styles applied to the `svg` element. */
svg: {
display: 'block' // Keeps the progress centered
},
/* Styles applied to the `circle` svg path. */
circle: {
stroke: 'currentColor' // Use butt to follow the specification, by chance, it's already the default CSS value.
// strokeLinecap: 'butt',
},
/* Styles applied to the `circle` svg path if `variant="static"`. */
circleStatic: {
transition: theme.transitions.create('stroke-dashoffset')
},
/* Styles applied to the `circle` svg path if `variant="indeterminate"`. */
circleIndeterminate: {
animation: '$circular-dash 1.4s ease-in-out infinite',
// Some default value that looks fine waiting for the animation to kicks in.
strokeDasharray: '80px, 200px',
strokeDashoffset: '0px' // Add the unit to fix a Edge 16 and below bug.
},
'@keyframes circular-rotate': {
'100%': {
transform: 'rotate(360deg)'
}
},
'@keyframes circular-dash': {
'0%': {
strokeDasharray: '1px, 200px',
strokeDashoffset: '0px'
},
'50%': {
strokeDasharray: '100px, 200px',
strokeDashoffset: '-15px'
},
'100%': {
strokeDasharray: '100px, 200px',
strokeDashoffset: '-125px'
}
},
/* Styles applied to the `circle` svg path if `disableShrink={true}`. */
circleDisableShrink: {
animation: 'none'
}
});
/**
* ## ARIA
*
* If the progress bar is describing the loading progress of a particular region of a page,
* you should use `aria-describedby` to point to the progress bar, and set the `aria-busy`
* attribute to `true` on that region until it has finished loading.
*/
const CircularProgress = React.forwardRef(function CircularProgress(props, ref) {
const {
classes,
className,
color = 'primary',
disableShrink = false,
size = 40,
style,
thickness = 3.6,
value = 0,
variant = 'indeterminate'
} = props,
other = _objectWithoutPropertiesLoose(props, ["classes", "className", "color", "disableShrink", "size", "style", "thickness", "value", "variant"]);
const circleStyle = {};
const rootStyle = {};
const rootProps = {};
if (variant === 'determinate' || variant === 'static') {
const circumference = 2 * Math.PI * ((SIZE - thickness) / 2);
circleStyle.strokeDasharray = circumference.toFixed(3);
rootProps['aria-valuenow'] = Math.round(value);
if (variant === 'static') {
circleStyle.strokeDashoffset = `${((100 - value) / 100 * circumference).toFixed(3)}px`;
rootStyle.transform = 'rotate(-90deg)';
} else {
circleStyle.strokeDashoffset = `${(easeIn((100 - value) / 100) * circumference).toFixed(3)}px`;
rootStyle.transform = `rotate(${(easeOut(value / 70) * 270).toFixed(3)}deg)`;
}
}
return React.createElement("div", _extends({
className: clsx(classes.root, className, color !== 'inherit' && classes[`color${capitalize(color)}`], {
'indeterminate': classes.indeterminate,
'static': classes.static
}[variant]),
style: _extends({
width: size,
height: size
}, rootStyle, {}, style),
ref: ref,
role: "progressbar"
}, rootProps, other), React.createElement("svg", {
className: classes.svg,
viewBox: `${SIZE / 2} ${SIZE / 2} ${SIZE} ${SIZE}`
}, React.createElement("circle", {
className: clsx(classes.circle, disableShrink && classes.circleDisableShrink, {
'indeterminate': classes.circleIndeterminate,
'static': classes.circleStatic
}[variant]),
style: circleStyle,
cx: SIZE,
cy: SIZE,
r: (SIZE - thickness) / 2,
fill: "none",
strokeWidth: thickness
})));
});
process.env.NODE_ENV !== "production" ? CircularProgress.propTypes = {
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['primary', 'secondary', 'inherit']),
/**
* If `true`, the shrink animation is disabled.
* This only works if variant is `indeterminate`.
*/
disableShrink: chainPropTypes(PropTypes.bool, props => {
if (props.disableShrink && props.variant && props.variant !== 'indeterminate') {
return new Error('Material-UI: you have provided the `disableShrink` prop ' + 'with a variant other than `indeterminate`. This will have no effect.');
}
return null;
}),
/**
* The size of the circle.
* If using a number, the pixel unit is assumed.
* If using a string, you need to provide the CSS unit, e.g '3rem'.
*/
size: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* @ignore
*/
style: PropTypes.object,
/**
* The thickness of the circle.
*/
thickness: PropTypes.number,
/**
* The value of the progress indicator for the determinate and static variants.
* Value between 0 and 100.
*/
value: PropTypes.number,
/**
* The variant to use.
* Use indeterminate when there is no progress value.
*/
variant: PropTypes.oneOf(['determinate', 'indeterminate', 'static'])
} : void 0;
export default withStyles(styles, {
name: 'MuiCircularProgress',
flip: false
})(CircularProgress); |
ajax/libs/boardgame-io/0.45.2/esm/react-native.js | cdnjs/cdnjs | import 'nanoid';
import { _ as _inherits, a as _createSuper, b as _createClass, c as _defineProperty, d as _classCallCheck, e as _objectWithoutProperties, f as _objectSpread2 } from './Debug-dda4b5bc.js';
import 'redux';
import './turn-order-62966a9c.js';
import 'immer';
import 'lodash.isplainobject';
import './reducer-763b001e.js';
import 'rfc6902';
import './initialize-ca65fd4a.js';
import './transport-0079de87.js';
import { C as Client$1 } from './client-974472d4.js';
import 'flatted';
import './ai-92d44551.js';
import React from 'react';
import PropTypes from 'prop-types';
/**
* 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,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages
}));
}
return _board;
}
}]);
return WrappedBoard;
}(React.Component), _defineProperty(_class, "propTypes", {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string
}), _defineProperty(_class, "defaultProps", {
matchID: 'default',
playerID: null,
credentials: null
}), _temp;
}
export { Client };
|
ajax/libs/primereact/7.2.0/avatar/avatar.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { IconUtils, classNames, ObjectUtils } from 'primereact/utils';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Avatar = /*#__PURE__*/function (_Component) {
_inherits(Avatar, _Component);
var _super = _createSuper(Avatar);
function Avatar() {
_classCallCheck(this, Avatar);
return _super.apply(this, arguments);
}
_createClass(Avatar, [{
key: "renderContent",
value: function renderContent() {
var _this = this;
if (this.props.label) {
return /*#__PURE__*/React.createElement("span", {
className: "p-avatar-text"
}, this.props.label);
} else if (this.props.icon) {
return IconUtils.getJSXIcon(this.props.icon, {
className: 'p-avatar-icon'
}, {
props: this.props
});
} else if (this.props.image) {
var onError = function onError(e) {
if (_this.props.onImageError) {
_this.props.onImageError(e);
}
};
return /*#__PURE__*/React.createElement("img", {
src: this.props.image,
alt: this.props.imageAlt,
onError: onError
});
}
return null;
}
}, {
key: "render",
value: function render() {
var containerClassName = classNames('p-avatar p-component', {
'p-avatar-image': this.props.image != null,
'p-avatar-circle': this.props.shape === 'circle',
'p-avatar-lg': this.props.size === 'large',
'p-avatar-xl': this.props.size === 'xlarge',
'p-avatar-clickable': !!this.props.onClick
}, this.props.className);
var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props) : this.renderContent();
return /*#__PURE__*/React.createElement("div", {
className: containerClassName,
style: this.props.style,
onClick: this.props.onClick
}, content, this.props.children);
}
}]);
return Avatar;
}(Component);
_defineProperty(Avatar, "defaultProps", {
label: null,
icon: null,
image: null,
size: 'normal',
shape: 'square',
style: null,
className: null,
template: null,
imageAlt: 'avatar',
onImageError: null,
onClick: null
});
export { Avatar };
|
ajax/libs/material-ui/4.9.3/es/ListItemAvatar/ListItemAvatar.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 '../List/ListContext';
export const styles = {
/* Styles applied to the root element. */
root: {
minWidth: 56,
flexShrink: 0
},
/* Styles applied to the root element when the parent `ListItem` uses `alignItems="flex-start"`. */
alignItemsFlexStart: {
marginTop: 8
}
};
/**
* A simple wrapper to apply `List` styles to an `Avatar`.
*/
const ListItemAvatar = React.forwardRef(function ListItemAvatar(props, ref) {
const {
classes,
className
} = props,
other = _objectWithoutPropertiesLoose(props, ["classes", "className"]);
const context = React.useContext(ListContext);
return React.createElement("div", _extends({
className: clsx(classes.root, className, context.alignItems === 'flex-start' && classes.alignItemsFlexStart),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? ListItemAvatar.propTypes = {
/**
* The content of the component – normally `Avatar`.
*/
children: PropTypes.element.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: 'MuiListItemAvatar'
})(ListItemAvatar); |
ajax/libs/react-native-web/0.13.14/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/primereact/7.0.0/picklist/picklist.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames, ObjectUtils, DomHandler } from 'primereact/utils';
import { Ripple } from 'primereact/ripple';
import { Button } from 'primereact/button';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var PickListItem = /*#__PURE__*/function (_Component) {
_inherits(PickListItem, _Component);
var _super = _createSuper$4(PickListItem);
function PickListItem(props) {
var _this;
_classCallCheck(this, PickListItem);
_this = _super.call(this, props);
_this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
_this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(PickListItem, [{
key: "onClick",
value: function onClick(event) {
if (this.props.onClick) {
this.props.onClick({
originalEvent: event,
value: this.props.value
});
}
}
}, {
key: "onKeyDown",
value: function onKeyDown(event) {
if (this.props.onKeyDown) {
this.props.onKeyDown({
originalEvent: event,
value: this.props.value
});
}
}
}, {
key: "render",
value: function render() {
var content = this.props.template ? this.props.template(this.props.value) : this.props.value;
var className = classNames('p-picklist-item', {
'p-highlight': this.props.selected
}, this.props.className);
return /*#__PURE__*/React.createElement("li", {
className: className,
onClick: this.onClick,
onKeyDown: this.onKeyDown,
tabIndex: this.props.tabIndex,
role: "option",
"aria-selected": this.props.selected
}, content, /*#__PURE__*/React.createElement(Ripple, null));
}
}]);
return PickListItem;
}(Component);
_defineProperty(PickListItem, "defaultProps", {
value: null,
className: null,
template: null,
selected: false,
tabIndex: null,
onClick: null,
onKeyDown: null
});
function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var PickListSubListComponent = /*#__PURE__*/function (_Component) {
_inherits(PickListSubListComponent, _Component);
var _super = _createSuper$3(PickListSubListComponent);
function PickListSubListComponent(props) {
var _this;
_classCallCheck(this, PickListSubListComponent);
_this = _super.call(this, props);
_this.onItemClick = _this.onItemClick.bind(_assertThisInitialized(_this));
_this.onItemKeyDown = _this.onItemKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(PickListSubListComponent, [{
key: "onItemClick",
value: function onItemClick(event) {
var originalEvent = event.originalEvent;
var item = event.value;
var selection = _toConsumableArray(this.props.selection);
var index = ObjectUtils.findIndexInList(item, selection, this.props.dataKey);
var selected = index !== -1;
var metaSelection = this.props.metaKeySelection;
if (metaSelection) {
var metaKey = originalEvent.metaKey || originalEvent.ctrlKey;
if (selected && metaKey) {
selection.splice(index, 1);
} else {
if (!metaKey) {
selection.length = 0;
}
selection.push(item);
}
} else {
if (selected) selection.splice(index, 1);else selection.push(item);
}
if (this.props.onSelectionChange) {
this.props.onSelectionChange({
event: originalEvent,
value: selection
});
}
}
}, {
key: "onItemKeyDown",
value: function onItemKeyDown(event) {
var listItem = event.originalEvent.currentTarget;
switch (event.originalEvent.which) {
//down
case 40:
var nextItem = this.findNextItem(listItem);
if (nextItem) {
nextItem.focus();
}
event.originalEvent.preventDefault();
break;
//up
case 38:
var prevItem = this.findPrevItem(listItem);
if (prevItem) {
prevItem.focus();
}
event.originalEvent.preventDefault();
break;
//enter
case 13:
this.onItemClick(event);
event.originalEvent.preventDefault();
break;
}
}
}, {
key: "findNextItem",
value: function findNextItem(item) {
var nextItem = item.nextElementSibling;
if (nextItem) return !DomHandler.hasClass(nextItem, 'p-picklist-item') ? this.findNextItem(nextItem) : nextItem;else return null;
}
}, {
key: "findPrevItem",
value: function findPrevItem(item) {
var prevItem = item.previousElementSibling;
if (prevItem) return !DomHandler.hasClass(prevItem, 'p-picklist-item') ? this.findPrevItem(prevItem) : prevItem;else return null;
}
}, {
key: "isSelected",
value: function isSelected(item) {
return ObjectUtils.findIndexInList(item, this.props.selection, this.props.dataKey) !== -1;
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var header = null;
var items = null;
var wrapperClassName = classNames('p-picklist-list-wrapper', this.props.className);
var listClassName = classNames('p-picklist-list', this.props.listClassName);
if (this.props.header) {
header = /*#__PURE__*/React.createElement("div", {
className: "p-picklist-header"
}, ObjectUtils.getJSXElement(this.props.header, this.props));
}
if (this.props.list) {
items = this.props.list.map(function (item, i) {
return /*#__PURE__*/React.createElement(PickListItem, {
key: JSON.stringify(item),
value: item,
template: _this2.props.itemTemplate,
selected: _this2.isSelected(item),
onClick: _this2.onItemClick,
onKeyDown: _this2.onItemKeyDown,
tabIndex: _this2.props.tabIndex
});
});
}
return /*#__PURE__*/React.createElement("div", {
ref: this.props.forwardRef,
className: wrapperClassName
}, header, /*#__PURE__*/React.createElement("ul", {
className: listClassName,
style: this.props.style,
role: "listbox",
"aria-multiselectable": true
}, items));
}
}]);
return PickListSubListComponent;
}(Component);
var PickListSubList = /*#__PURE__*/React.forwardRef(function (props, ref) {
return /*#__PURE__*/React.createElement(PickListSubListComponent, _extends({
forwardRef: ref
}, props));
});
function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var PickListControls = /*#__PURE__*/function (_Component) {
_inherits(PickListControls, _Component);
var _super = _createSuper$2(PickListControls);
function PickListControls(props) {
var _this;
_classCallCheck(this, PickListControls);
_this = _super.call(this, props);
_this.moveUp = _this.moveUp.bind(_assertThisInitialized(_this));
_this.moveTop = _this.moveTop.bind(_assertThisInitialized(_this));
_this.moveDown = _this.moveDown.bind(_assertThisInitialized(_this));
_this.moveBottom = _this.moveBottom.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(PickListControls, [{
key: "moveUp",
value: function moveUp(event) {
var selectedItems = this.props.selection;
if (selectedItems && selectedItems.length) {
var list = _toConsumableArray(this.props.list);
for (var i = 0; i < selectedItems.length; i++) {
var selectedItem = selectedItems[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list, this.props.dataKey);
if (selectedItemIndex !== 0) {
var movedItem = list[selectedItemIndex];
var temp = list[selectedItemIndex - 1];
list[selectedItemIndex - 1] = movedItem;
list[selectedItemIndex] = temp;
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: list,
direction: 'up'
});
}
}
}
}, {
key: "moveTop",
value: function moveTop(event) {
var selectedItems = this.props.selection;
if (selectedItems && selectedItems.length) {
var list = _toConsumableArray(this.props.list);
for (var i = 0; i < selectedItems.length; i++) {
var selectedItem = selectedItems[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list, this.props.dataKey);
if (selectedItemIndex !== 0) {
var movedItem = list.splice(selectedItemIndex, 1)[0];
list.unshift(movedItem);
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: list,
direction: 'top'
});
}
}
}
}, {
key: "moveDown",
value: function moveDown(event) {
var selectedItems = this.props.selection;
if (selectedItems && selectedItems.length) {
var list = _toConsumableArray(this.props.list);
for (var i = selectedItems.length - 1; i >= 0; i--) {
var selectedItem = selectedItems[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list, this.props.dataKey);
if (selectedItemIndex !== list.length - 1) {
var movedItem = list[selectedItemIndex];
var temp = list[selectedItemIndex + 1];
list[selectedItemIndex + 1] = movedItem;
list[selectedItemIndex] = temp;
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: list,
direction: 'down'
});
}
this.movedDown = true;
}
}
}, {
key: "moveBottom",
value: function moveBottom(event) {
var selectedItems = this.props.selection;
if (selectedItems && selectedItems.length) {
var list = _toConsumableArray(this.props.list);
for (var i = selectedItems.length - 1; i >= 0; i--) {
var selectedItem = selectedItems[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list, this.props.dataKey);
if (selectedItemIndex !== list.length - 1) {
var movedItem = list.splice(selectedItemIndex, 1)[0];
list.push(movedItem);
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: list,
direction: 'bottom'
});
}
}
}
}, {
key: "render",
value: function render() {
var moveDisabled = !this.props.selection.length;
var className = classNames('p-picklist-buttons', this.props.className);
return /*#__PURE__*/React.createElement("div", {
className: className
}, /*#__PURE__*/React.createElement(Button, {
disabled: moveDisabled,
type: "button",
icon: "pi pi-angle-up",
onClick: this.moveUp
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveDisabled,
type: "button",
icon: "pi pi-angle-double-up",
onClick: this.moveTop
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveDisabled,
type: "button",
icon: "pi pi-angle-down",
onClick: this.moveDown
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveDisabled,
type: "button",
icon: "pi pi-angle-double-down",
onClick: this.moveBottom
}));
}
}]);
return PickListControls;
}(Component);
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var PickListTransferControls = /*#__PURE__*/function (_Component) {
_inherits(PickListTransferControls, _Component);
var _super = _createSuper$1(PickListTransferControls);
function PickListTransferControls(props) {
var _this;
_classCallCheck(this, PickListTransferControls);
_this = _super.call(this, props);
_this.moveRight = _this.moveRight.bind(_assertThisInitialized(_this));
_this.moveAllRight = _this.moveAllRight.bind(_assertThisInitialized(_this));
_this.moveLeft = _this.moveLeft.bind(_assertThisInitialized(_this));
_this.moveAllLeft = _this.moveAllLeft.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(PickListTransferControls, [{
key: "moveRight",
value: function moveRight(event) {
var selection = this.props.sourceSelection;
if (ObjectUtils.isNotEmpty(selection)) {
var targetList = _toConsumableArray(this.props.target);
var sourceList = _toConsumableArray(this.props.source);
for (var i = 0; i < selection.length; i++) {
var selectedItem = selection[i];
if (ObjectUtils.findIndexInList(selectedItem, targetList, this.props.dataKey) === -1) {
targetList.push(sourceList.splice(ObjectUtils.findIndexInList(selectedItem, sourceList, this.props.dataKey), 1)[0]);
}
}
if (this.props.onTransfer) {
this.props.onTransfer({
originalEvent: event,
source: sourceList,
target: targetList,
direction: 'toTarget'
});
}
}
}
}, {
key: "moveAllRight",
value: function moveAllRight(event) {
if (this.props.source) {
var targetList = [].concat(_toConsumableArray(this.props.target), _toConsumableArray(this.props.source));
var sourceList = [];
if (this.props.onTransfer) {
this.props.onTransfer({
originalEvent: event,
source: sourceList,
target: targetList,
direction: 'allToTarget'
});
}
}
}
}, {
key: "moveLeft",
value: function moveLeft(event) {
var selection = this.props.targetSelection;
if (ObjectUtils.isNotEmpty(selection)) {
var targetList = _toConsumableArray(this.props.target);
var sourceList = _toConsumableArray(this.props.source);
for (var i = 0; i < selection.length; i++) {
var selectedItem = selection[i];
if (ObjectUtils.findIndexInList(selectedItem, sourceList, this.props.dataKey) === -1) {
sourceList.push(targetList.splice(ObjectUtils.findIndexInList(selectedItem, targetList, this.props.dataKey), 1)[0]);
}
}
if (this.props.onTransfer) {
this.props.onTransfer({
originalEvent: event,
source: sourceList,
target: targetList,
direction: 'toSource'
});
}
}
}
}, {
key: "moveAllLeft",
value: function moveAllLeft(event) {
if (this.props.source) {
var sourceList = [].concat(_toConsumableArray(this.props.source), _toConsumableArray(this.props.target));
var targetList = [];
if (this.props.onTransfer) {
this.props.onTransfer({
originalEvent: event,
source: sourceList,
target: targetList,
direction: 'allToSource'
});
}
}
}
}, {
key: "render",
value: function render() {
var moveRightDisabled = ObjectUtils.isEmpty(this.props.sourceSelection);
var moveLeftDisabled = ObjectUtils.isEmpty(this.props.targetSelection);
var moveAllRightDisabled = ObjectUtils.isEmpty(this.props.source);
var moveAllLeftDisabled = ObjectUtils.isEmpty(this.props.target);
var className = classNames('p-picklist-buttons p-picklist-transfer-buttons', this.props.className);
return /*#__PURE__*/React.createElement("div", {
className: className
}, /*#__PURE__*/React.createElement(Button, {
disabled: moveRightDisabled,
type: "button",
icon: "pi pi-angle-right",
onClick: this.moveRight
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveAllRightDisabled,
type: "button",
icon: "pi pi-angle-double-right",
onClick: this.moveAllRight
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveLeftDisabled,
type: "button",
icon: "pi pi-angle-left",
onClick: this.moveLeft
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveAllLeftDisabled,
type: "button",
icon: "pi pi-angle-double-left",
onClick: this.moveAllLeft
}));
}
}]);
return PickListTransferControls;
}(Component);
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var PickList = /*#__PURE__*/function (_Component) {
_inherits(PickList, _Component);
var _super = _createSuper(PickList);
function PickList(props) {
var _this;
_classCallCheck(this, PickList);
_this = _super.call(this, props);
_this.state = {};
if (!_this.props.onSourceSelectionChange) {
_this.state.sourceSelection = [];
}
if (!_this.props.onTargetSelectionChange) {
_this.state.targetSelection = [];
}
_this.onSourceReorder = _this.onSourceReorder.bind(_assertThisInitialized(_this));
_this.onTargetReorder = _this.onTargetReorder.bind(_assertThisInitialized(_this));
_this.onTransfer = _this.onTransfer.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(PickList, [{
key: "getSourceSelection",
value: function getSourceSelection() {
return this.props.onSourceSelectionChange ? this.props.sourceSelection : this.state.sourceSelection;
}
}, {
key: "getTargetSelection",
value: function getTargetSelection() {
return this.props.onTargetSelectionChange ? this.props.targetSelection : this.state.targetSelection;
}
}, {
key: "onSourceReorder",
value: function onSourceReorder(event) {
this.handleChange(event, event.value, this.props.target);
this.reorderedListElement = this.sourceListElement;
this.reorderDirection = event.direction;
}
}, {
key: "onTargetReorder",
value: function onTargetReorder(event) {
this.handleChange(event, this.props.source, event.value);
this.reorderedListElement = this.targetListElement;
this.reorderDirection = event.direction;
}
}, {
key: "handleScrollPosition",
value: function handleScrollPosition(listElement, direction) {
if (listElement) {
var listContainer = DomHandler.findSingle(listElement, '.p-picklist-list');
switch (direction) {
case 'up':
this.scrollInView(listContainer, -1);
break;
case 'top':
listContainer.scrollTop = 0;
break;
case 'down':
this.scrollInView(listContainer, 1);
break;
case 'bottom':
listContainer.scrollTop = listContainer.scrollHeight;
break;
}
}
}
}, {
key: "handleChange",
value: function handleChange(event, source, target) {
if (this.props.onChange) {
this.props.onChange({
originalEvent: event.originalEvent,
source: source,
target: target
});
}
}
}, {
key: "onTransfer",
value: function onTransfer(event) {
var originalEvent = event.originalEvent,
source = event.source,
target = event.target,
direction = event.direction;
switch (direction) {
case 'toTarget':
if (this.props.onMoveToTarget) {
this.props.onMoveToTarget({
originalEvent: originalEvent,
value: this.getSourceSelection()
});
}
break;
case 'allToTarget':
if (this.props.onMoveAllToTarget) {
this.props.onMoveAllToTarget({
originalEvent: originalEvent,
value: this.props.source
});
}
break;
case 'toSource':
if (this.props.onMoveToSource) {
this.props.onMoveToSource({
originalEvent: originalEvent,
value: this.getTargetSelection()
});
}
break;
case 'allToSource':
if (this.props.onMoveAllToSource) {
this.props.onMoveAllToSource({
originalEvent: originalEvent,
value: this.props.target
});
}
break;
}
this.onSelectionChange({
originalEvent: originalEvent,
value: []
}, 'sourceSelection', this.props.onSourceSelectionChange);
this.onSelectionChange({
originalEvent: originalEvent,
value: []
}, 'targetSelection', this.props.onTargetSelectionChange);
this.handleChange(event, source, target);
}
}, {
key: "scrollInView",
value: function scrollInView(listContainer) {
var direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var selectedItems = listContainer.getElementsByClassName('p-highlight');
if (ObjectUtils.isNotEmpty(selectedItems)) {
DomHandler.scrollInView(listContainer, direction === -1 ? selectedItems[0] : selectedItems[selectedItems.length - 1]);
}
}
}, {
key: "onSelectionChange",
value: function onSelectionChange(e, stateKey, callback) {
if (callback) {
callback(e);
} else {
this.setState(_defineProperty({}, stateKey, e.value));
}
if (ObjectUtils.isNotEmpty(this.state.sourceSelection) && stateKey === 'targetSelection') {
this.setState({
sourceSelection: []
});
} else if (ObjectUtils.isNotEmpty(this.state.targetSelection) && stateKey === 'sourceSelection') {
this.setState({
targetSelection: []
});
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
if (this.reorderedListElement) {
this.handleScrollPosition(this.reorderedListElement, this.reorderDirection);
this.reorderedListElement = null;
this.reorderDirection = null;
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var className = classNames('p-picklist p-component', this.props.className);
var sourceSelection = this.getSourceSelection();
var targetSelection = this.getTargetSelection();
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
className: className,
style: this.props.style
}, this.props.showSourceControls && /*#__PURE__*/React.createElement(PickListControls, {
list: this.props.source,
selection: sourceSelection,
onReorder: this.onSourceReorder,
className: "p-picklist-source-controls",
dataKey: this.props.dataKey
}), /*#__PURE__*/React.createElement(PickListSubList, {
ref: function ref(el) {
return _this2.sourceListElement = el;
},
list: this.props.source,
selection: sourceSelection,
onSelectionChange: function onSelectionChange(e) {
return _this2.onSelectionChange(e, 'sourceSelection', _this2.props.onSourceSelectionChange);
},
itemTemplate: this.props.itemTemplate,
header: this.props.sourceHeader,
style: this.props.sourceStyle,
className: "p-picklist-source-wrapper",
listClassName: "p-picklist-source",
metaKeySelection: this.props.metaKeySelection,
tabIndex: this.props.tabIndex,
dataKey: this.props.dataKey
}), /*#__PURE__*/React.createElement(PickListTransferControls, {
onTransfer: this.onTransfer,
source: this.props.source,
target: this.props.target,
sourceSelection: sourceSelection,
targetSelection: targetSelection,
dataKey: this.props.dataKey
}), /*#__PURE__*/React.createElement(PickListSubList, {
ref: function ref(el) {
return _this2.targetListElement = el;
},
list: this.props.target,
selection: targetSelection,
onSelectionChange: function onSelectionChange(e) {
return _this2.onSelectionChange(e, 'targetSelection', _this2.props.onTargetSelectionChange);
},
itemTemplate: this.props.itemTemplate,
header: this.props.targetHeader,
style: this.props.targetStyle,
className: "p-picklist-target-wrapper",
listClassName: "p-picklist-target",
metaKeySelection: this.props.metaKeySelection,
tabIndex: this.props.tabIndex,
dataKey: this.props.dataKey
}), this.props.showTargetControls && /*#__PURE__*/React.createElement(PickListControls, {
list: this.props.target,
selection: targetSelection,
onReorder: this.onTargetReorder,
className: "p-picklist-target-controls",
dataKey: this.props.dataKey
}));
}
}]);
return PickList;
}(Component);
_defineProperty(PickList, "defaultProps", {
id: null,
source: null,
target: null,
sourceHeader: null,
targetHeader: null,
style: null,
className: null,
sourceStyle: null,
targetStyle: null,
sourceSelection: null,
targetSelection: null,
showSourceControls: true,
showTargetControls: true,
metaKeySelection: true,
tabIndex: 0,
dataKey: null,
itemTemplate: null,
onChange: null,
onMoveToSource: null,
onMoveAllToSource: null,
onMoveToTarget: null,
onMoveAllToTarget: null,
onSourceSelectionChange: null,
onTargetSelectionChange: null
});
export { PickList };
|
ajax/libs/react-native-web/0.0.0-a55272399/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 setAndForwardRef from '../../../modules/setAndForwardRef';
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 = setAndForwardRef({
getForwardedRef: function getForwardedRef() {
return _this.props.forwardedRef;
},
setLocalRef: function setLocalRef(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.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/material-ui/4.9.2/esm/InputAdornment/InputAdornment.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 Typography from '../Typography';
import withStyles from '../styles/withStyles';
import FormControlContext, { useFormControl } from '../FormControl/FormControlContext';
export var styles = {
/* Styles applied to the root element. */
root: {
display: 'flex',
height: '0.01em',
// Fix IE 11 flexbox alignment. To remove at some point.
maxHeight: '2em',
alignItems: 'center',
whiteSpace: 'nowrap'
},
/* Styles applied to the root element if `variant="filled"`. */
filled: {
'&$positionStart:not($hiddenLabel)': {
marginTop: 16
}
},
/* Styles applied to the root element if `position="start"`. */
positionStart: {
marginRight: 8
},
/* Styles applied to the root element if `position="end"`. */
positionEnd: {
marginLeft: 8
},
/* Styles applied to the root element if `disablePointerEvents=true`. */
disablePointerEvents: {
pointerEvents: 'none'
},
/* Styles applied if the adornment is used inside <FormControl hiddenLabel />. */
hiddenLabel: {},
/* Styles applied if the adornment is used inside <FormControl margin="dense" />. */
marginDense: {}
};
var InputAdornment = React.forwardRef(function InputAdornment(props, ref) {
var children = props.children,
classes = props.classes,
className = props.className,
_props$component = props.component,
Component = _props$component === void 0 ? 'div' : _props$component,
_props$disablePointer = props.disablePointerEvents,
disablePointerEvents = _props$disablePointer === void 0 ? false : _props$disablePointer,
_props$disableTypogra = props.disableTypography,
disableTypography = _props$disableTypogra === void 0 ? false : _props$disableTypogra,
position = props.position,
variantProp = props.variant,
other = _objectWithoutProperties(props, ["children", "classes", "className", "component", "disablePointerEvents", "disableTypography", "position", "variant"]);
var muiFormControl = useFormControl() || {};
var variant = variantProp;
if (variantProp && muiFormControl.variant) {
if (process.env.NODE_ENV !== 'production') {
if (variantProp === muiFormControl.variant) {
console.error('Material-UI: The `InputAdornment` variant infers the variant prop ' + 'you do not have to provide one.');
}
}
}
if (muiFormControl && !variant) {
variant = muiFormControl.variant;
}
return React.createElement(FormControlContext.Provider, {
value: null
}, React.createElement(Component, _extends({
className: clsx(classes.root, className, disablePointerEvents && classes.disablePointerEvents, muiFormControl.hiddenLabel && classes.hiddenLabel, {
filled: classes.filled
}[variant], {
start: classes.positionStart,
end: classes.positionEnd
}[position], {
dense: classes.marginDense
}[muiFormControl.margin]),
ref: ref
}, other), typeof children === 'string' && !disableTypography ? React.createElement(Typography, {
color: "textSecondary"
}, children) : children));
});
process.env.NODE_ENV !== "production" ? InputAdornment.propTypes = {
/**
* The content of the component, normally an `IconButton` or string.
*/
children: PropTypes.node.isRequired,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: PropTypes.elementType,
/**
* Disable pointer events on the root.
* This allows for the content of the adornment to focus the input on click.
*/
disablePointerEvents: PropTypes.bool,
/**
* If children is a string then disable wrapping in a Typography component.
*/
disableTypography: PropTypes.bool,
/**
* @ignore
*/
muiFormControl: PropTypes.object,
/**
* The position this adornment should appear relative to the `Input`.
*/
position: PropTypes.oneOf(['start', 'end']),
/**
* The variant to use.
* Note: If you are using the `TextField` component or the `FormControl` component
* you do not have to set this manually.
*/
variant: PropTypes.oneOf(['standard', 'outlined', 'filled'])
} : void 0;
export default withStyles(styles, {
name: 'MuiInputAdornment'
})(InputAdornment); |
ajax/libs/primereact/7.2.0/toolbar/toolbar.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames, ObjectUtils } from 'primereact/utils';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Toolbar = /*#__PURE__*/function (_Component) {
_inherits(Toolbar, _Component);
var _super = _createSuper(Toolbar);
function Toolbar() {
_classCallCheck(this, Toolbar);
return _super.apply(this, arguments);
}
_createClass(Toolbar, [{
key: "render",
value: function render() {
var toolbarClass = classNames('p-toolbar p-component', this.props.className);
var left = ObjectUtils.getJSXElement(this.props.left, this.props);
var right = ObjectUtils.getJSXElement(this.props.right, this.props);
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
className: toolbarClass,
style: this.props.style,
role: "toolbar"
}, /*#__PURE__*/React.createElement("div", {
className: "p-toolbar-group-left"
}, left), /*#__PURE__*/React.createElement("div", {
className: "p-toolbar-group-right"
}, right));
}
}]);
return Toolbar;
}(Component);
_defineProperty(Toolbar, "defaultProps", {
id: null,
style: null,
className: null,
left: null,
right: null
});
export { Toolbar };
|
ajax/libs/primereact/6.5.0-rc.1/picklist/picklist.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames, ObjectUtils, DomHandler } from 'primereact/utils';
import { Ripple } from 'primereact/ripple';
import { Button } from 'primereact/button';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
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 _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _createSuper$4(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$4(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$4() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var PickListItem = /*#__PURE__*/function (_Component) {
_inherits(PickListItem, _Component);
var _super = _createSuper$4(PickListItem);
function PickListItem(props) {
var _this;
_classCallCheck(this, PickListItem);
_this = _super.call(this, props);
_this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
_this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(PickListItem, [{
key: "onClick",
value: function onClick(event) {
if (this.props.onClick) {
this.props.onClick({
originalEvent: event,
value: this.props.value
});
}
}
}, {
key: "onKeyDown",
value: function onKeyDown(event) {
if (this.props.onKeyDown) {
this.props.onKeyDown({
originalEvent: event,
value: this.props.value
});
}
}
}, {
key: "render",
value: function render() {
var content = this.props.template ? this.props.template(this.props.value) : this.props.value;
var className = classNames('p-picklist-item', {
'p-highlight': this.props.selected
}, this.props.className);
return /*#__PURE__*/React.createElement("li", {
className: className,
onClick: this.onClick,
onKeyDown: this.onKeyDown,
tabIndex: this.props.tabIndex,
role: "option",
"aria-selected": this.props.selected
}, content, /*#__PURE__*/React.createElement(Ripple, null));
}
}]);
return PickListItem;
}(Component);
_defineProperty(PickListItem, "defaultProps", {
value: null,
className: null,
template: null,
selected: false,
tabIndex: null,
onClick: null,
onKeyDown: null
});
_defineProperty(PickListItem, "propTypes", {
value: PropTypes.any,
className: PropTypes.string,
template: PropTypes.func,
selected: PropTypes.bool,
tabIndex: PropTypes.number,
onClick: PropTypes.func,
onKeyDown: PropTypes.func
});
function _createSuper$3(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$3(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$3() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var PickListSubListComponent = /*#__PURE__*/function (_Component) {
_inherits(PickListSubListComponent, _Component);
var _super = _createSuper$3(PickListSubListComponent);
function PickListSubListComponent(props) {
var _this;
_classCallCheck(this, PickListSubListComponent);
_this = _super.call(this, props);
_this.onItemClick = _this.onItemClick.bind(_assertThisInitialized(_this));
_this.onItemKeyDown = _this.onItemKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(PickListSubListComponent, [{
key: "onItemClick",
value: function onItemClick(event) {
var originalEvent = event.originalEvent;
var item = event.value;
var selection = _toConsumableArray(this.props.selection);
var index = ObjectUtils.findIndexInList(item, selection);
var selected = index !== -1;
var metaSelection = this.props.metaKeySelection;
if (metaSelection) {
var metaKey = originalEvent.metaKey || originalEvent.ctrlKey;
if (selected && metaKey) {
selection.splice(index, 1);
} else {
if (!metaKey) {
selection.length = 0;
}
selection.push(item);
}
} else {
if (selected) selection.splice(index, 1);else selection.push(item);
}
if (this.props.onSelectionChange) {
this.props.onSelectionChange({
event: originalEvent,
value: selection
});
}
}
}, {
key: "onItemKeyDown",
value: function onItemKeyDown(event) {
var listItem = event.originalEvent.currentTarget;
switch (event.originalEvent.which) {
//down
case 40:
var nextItem = this.findNextItem(listItem);
if (nextItem) {
nextItem.focus();
}
event.originalEvent.preventDefault();
break;
//up
case 38:
var prevItem = this.findPrevItem(listItem);
if (prevItem) {
prevItem.focus();
}
event.originalEvent.preventDefault();
break;
//enter
case 13:
this.onItemClick(event);
event.originalEvent.preventDefault();
break;
}
}
}, {
key: "findNextItem",
value: function findNextItem(item) {
var nextItem = item.nextElementSibling;
if (nextItem) return !DomHandler.hasClass(nextItem, 'p-picklist-item') ? this.findNextItem(nextItem) : nextItem;else return null;
}
}, {
key: "findPrevItem",
value: function findPrevItem(item) {
var prevItem = item.previousElementSibling;
if (prevItem) return !DomHandler.hasClass(prevItem, 'p-picklist-item') ? this.findPrevItem(prevItem) : prevItem;else return null;
}
}, {
key: "isSelected",
value: function isSelected(item) {
return ObjectUtils.findIndexInList(item, this.props.selection) !== -1;
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var header = null;
var items = null;
var wrapperClassName = classNames('p-picklist-list-wrapper', this.props.className);
var listClassName = classNames('p-picklist-list', this.props.listClassName);
if (this.props.header) {
header = /*#__PURE__*/React.createElement("div", {
className: "p-picklist-header"
}, ObjectUtils.getJSXElement(this.props.header, this.props));
}
if (this.props.list) {
items = this.props.list.map(function (item, i) {
return /*#__PURE__*/React.createElement(PickListItem, {
key: JSON.stringify(item),
value: item,
template: _this2.props.itemTemplate,
selected: _this2.isSelected(item),
onClick: _this2.onItemClick,
onKeyDown: _this2.onItemKeyDown,
tabIndex: _this2.props.tabIndex
});
});
}
return /*#__PURE__*/React.createElement("div", {
ref: this.props.forwardRef,
className: wrapperClassName
}, header, /*#__PURE__*/React.createElement("ul", {
className: listClassName,
style: this.props.style,
role: "listbox",
"aria-multiselectable": true
}, items));
}
}]);
return PickListSubListComponent;
}(Component);
_defineProperty(PickListSubListComponent, "defaultProps", {
forwardRef: null,
list: null,
selection: null,
header: null,
className: null,
listClassName: null,
style: null,
showControls: true,
metaKeySelection: true,
tabIndex: null,
itemTemplate: null,
onItemClick: null,
onSelectionChange: null
});
_defineProperty(PickListSubListComponent, "propTypes", {
forwardRef: PropTypes.any,
list: PropTypes.array,
selection: PropTypes.array,
header: PropTypes.string,
className: PropTypes.string,
listClassName: PropTypes.string,
style: PropTypes.object,
showControls: PropTypes.bool,
metaKeySelection: PropTypes.bool,
tabIndex: PropTypes.number,
itemTemplate: PropTypes.func,
onItemClick: PropTypes.func,
onSelectionChange: PropTypes.func
});
var PickListSubList = /*#__PURE__*/React.forwardRef(function (props, ref) {
return /*#__PURE__*/React.createElement(PickListSubListComponent, _extends({
forwardRef: ref
}, props));
});
function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var PickListControls = /*#__PURE__*/function (_Component) {
_inherits(PickListControls, _Component);
var _super = _createSuper$2(PickListControls);
function PickListControls() {
var _this;
_classCallCheck(this, PickListControls);
_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(PickListControls, [{
key: "moveUp",
value: function moveUp(event) {
var selectedItems = this.props.selection;
if (selectedItems && selectedItems.length) {
var list = _toConsumableArray(this.props.list);
for (var i = 0; i < selectedItems.length; i++) {
var selectedItem = selectedItems[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list);
if (selectedItemIndex !== 0) {
var movedItem = list[selectedItemIndex];
var temp = list[selectedItemIndex - 1];
list[selectedItemIndex - 1] = movedItem;
list[selectedItemIndex] = temp;
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: list,
direction: 'up'
});
}
}
}
}, {
key: "moveTop",
value: function moveTop(event) {
var selectedItems = this.props.selection;
if (selectedItems && selectedItems.length) {
var list = _toConsumableArray(this.props.list);
for (var i = 0; i < selectedItems.length; i++) {
var selectedItem = selectedItems[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list);
if (selectedItemIndex !== 0) {
var movedItem = list.splice(selectedItemIndex, 1)[0];
list.unshift(movedItem);
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: list,
direction: 'top'
});
}
}
}
}, {
key: "moveDown",
value: function moveDown(event) {
var selectedItems = this.props.selection;
if (selectedItems && selectedItems.length) {
var list = _toConsumableArray(this.props.list);
for (var i = selectedItems.length - 1; i >= 0; i--) {
var selectedItem = selectedItems[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list);
if (selectedItemIndex !== list.length - 1) {
var movedItem = list[selectedItemIndex];
var temp = list[selectedItemIndex + 1];
list[selectedItemIndex + 1] = movedItem;
list[selectedItemIndex] = temp;
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: list,
direction: 'down'
});
}
this.movedDown = true;
}
}
}, {
key: "moveBottom",
value: function moveBottom(event) {
var selectedItems = this.props.selection;
if (selectedItems && selectedItems.length) {
var list = _toConsumableArray(this.props.list);
for (var i = selectedItems.length - 1; i >= 0; i--) {
var selectedItem = selectedItems[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, list);
if (selectedItemIndex !== list.length - 1) {
var movedItem = list.splice(selectedItemIndex, 1)[0];
list.push(movedItem);
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: list,
direction: 'bottom'
});
}
}
}
}, {
key: "render",
value: function render() {
var moveDisabled = !this.props.selection.length;
var className = classNames('p-picklist-buttons', this.props.className);
return /*#__PURE__*/React.createElement("div", {
className: className
}, /*#__PURE__*/React.createElement(Button, {
disabled: moveDisabled,
type: "button",
icon: "pi pi-angle-up",
onClick: this.moveUp
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveDisabled,
type: "button",
icon: "pi pi-angle-double-up",
onClick: this.moveTop
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveDisabled,
type: "button",
icon: "pi pi-angle-down",
onClick: this.moveDown
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveDisabled,
type: "button",
icon: "pi pi-angle-double-down",
onClick: this.moveBottom
}));
}
}]);
return PickListControls;
}(Component);
_defineProperty(PickListControls, "defaultProps", {
className: null,
list: null,
selection: null,
onReorder: null
});
_defineProperty(PickListControls, "propTypes", {
className: PropTypes.string,
list: PropTypes.array,
selection: PropTypes.array,
onReorder: PropTypes.func
});
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var PickListTransferControls = /*#__PURE__*/function (_Component) {
_inherits(PickListTransferControls, _Component);
var _super = _createSuper$1(PickListTransferControls);
function PickListTransferControls() {
var _this;
_classCallCheck(this, PickListTransferControls);
_this = _super.call(this);
_this.moveRight = _this.moveRight.bind(_assertThisInitialized(_this));
_this.moveAllRight = _this.moveAllRight.bind(_assertThisInitialized(_this));
_this.moveLeft = _this.moveLeft.bind(_assertThisInitialized(_this));
_this.moveAllLeft = _this.moveAllLeft.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(PickListTransferControls, [{
key: "moveRight",
value: function moveRight(event) {
var selection = this.props.sourceSelection;
if (selection && selection.length) {
var targetList = _toConsumableArray(this.props.target);
var sourceList = _toConsumableArray(this.props.source);
for (var i = 0; i < selection.length; i++) {
var selectedItem = selection[i];
if (ObjectUtils.findIndexInList(selectedItem, targetList) === -1) {
targetList.push(sourceList.splice(ObjectUtils.findIndexInList(selectedItem, sourceList), 1)[0]);
}
}
if (this.props.onTransfer) {
this.props.onTransfer({
originalEvent: event,
source: sourceList,
target: targetList,
direction: 'toTarget'
});
}
}
}
}, {
key: "moveAllRight",
value: function moveAllRight(event) {
if (this.props.source) {
var targetList = [].concat(_toConsumableArray(this.props.target), _toConsumableArray(this.props.source));
var sourceList = [];
if (this.props.onTransfer) {
this.props.onTransfer({
originalEvent: event,
source: sourceList,
target: targetList,
direction: 'allToTarget'
});
}
}
}
}, {
key: "moveLeft",
value: function moveLeft(event) {
var selection = this.props.targetSelection;
if (selection && selection.length) {
var targetList = _toConsumableArray(this.props.target);
var sourceList = _toConsumableArray(this.props.source);
for (var i = 0; i < selection.length; i++) {
var selectedItem = selection[i];
if (ObjectUtils.findIndexInList(selectedItem, sourceList) === -1) {
sourceList.push(targetList.splice(ObjectUtils.findIndexInList(selectedItem, targetList), 1)[0]);
}
}
if (this.props.onTransfer) {
this.props.onTransfer({
originalEvent: event,
source: sourceList,
target: targetList,
direction: 'toSource'
});
}
}
}
}, {
key: "moveAllLeft",
value: function moveAllLeft(event) {
if (this.props.source) {
var sourceList = [].concat(_toConsumableArray(this.props.source), _toConsumableArray(this.props.target));
var targetList = [];
if (this.props.onTransfer) {
this.props.onTransfer({
originalEvent: event,
source: sourceList,
target: targetList,
direction: 'allToSource'
});
}
}
}
}, {
key: "render",
value: function render() {
var moveRightDisabled = !this.props.sourceSelection.length;
var moveLeftDisabled = !this.props.targetSelection.length;
var moveAllRightDisabled = !this.props.source.length;
var moveAllLeftDisabled = !this.props.target.length;
var className = classNames('p-picklist-buttons p-picklist-transfer-buttons', this.props.className);
return /*#__PURE__*/React.createElement("div", {
className: className
}, /*#__PURE__*/React.createElement(Button, {
disabled: moveRightDisabled,
type: "button",
icon: "pi pi-angle-right",
onClick: this.moveRight
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveAllRightDisabled,
type: "button",
icon: "pi pi-angle-double-right",
onClick: this.moveAllRight
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveLeftDisabled,
type: "button",
icon: "pi pi-angle-left",
onClick: this.moveLeft
}), /*#__PURE__*/React.createElement(Button, {
disabled: moveAllLeftDisabled,
type: "button",
icon: "pi pi-angle-double-left",
onClick: this.moveAllLeft
}));
}
}]);
return PickListTransferControls;
}(Component);
_defineProperty(PickListTransferControls, "defaultProps", {
source: null,
target: null,
sourceSelection: null,
targetSelection: null,
onTransfer: null
});
_defineProperty(PickListTransferControls, "propTypes", {
source: PropTypes.array,
target: PropTypes.array,
sourceSelection: PropTypes.array,
targetSelection: PropTypes.array,
onTransfer: PropTypes.func
});
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var PickList = /*#__PURE__*/function (_Component) {
_inherits(PickList, _Component);
var _super = _createSuper(PickList);
function PickList(props) {
var _this;
_classCallCheck(this, PickList);
_this = _super.call(this, props);
_this.state = {};
if (!_this.props.onSourceSelectionChange) {
_this.state.sourceSelection = [];
}
if (!_this.props.onTargetSelectionChange) {
_this.state.targetSelection = [];
}
_this.onSourceReorder = _this.onSourceReorder.bind(_assertThisInitialized(_this));
_this.onTargetReorder = _this.onTargetReorder.bind(_assertThisInitialized(_this));
_this.onTransfer = _this.onTransfer.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(PickList, [{
key: "getSourceSelection",
value: function getSourceSelection() {
return this.props.onSourceSelectionChange ? this.props.sourceSelection : this.state.sourceSelection;
}
}, {
key: "getTargetSelection",
value: function getTargetSelection() {
return this.props.onTargetSelectionChange ? this.props.targetSelection : this.state.targetSelection;
}
}, {
key: "onSourceReorder",
value: function onSourceReorder(event) {
this.handleChange(event, event.value, this.props.target);
this.reorderedListElement = this.sourceListElement;
this.reorderDirection = event.direction;
}
}, {
key: "onTargetReorder",
value: function onTargetReorder(event) {
this.handleChange(event, this.props.source, event.value);
this.reorderedListElement = this.targetListElement;
this.reorderDirection = event.direction;
}
}, {
key: "handleScrollPosition",
value: function handleScrollPosition(listElement, direction) {
if (listElement) {
var listContainer = DomHandler.findSingle(listElement, '.p-picklist-list');
switch (direction) {
case 'up':
this.scrollInView(listContainer, -1);
break;
case 'top':
listContainer.scrollTop = 0;
break;
case 'down':
this.scrollInView(listContainer, 1);
break;
case 'bottom':
listContainer.scrollTop = listContainer.scrollHeight;
break;
}
}
}
}, {
key: "handleChange",
value: function handleChange(event, source, target) {
if (this.props.onChange) {
this.props.onChange({
originalEvent: event.originalEvent,
source: source,
target: target
});
}
}
}, {
key: "onTransfer",
value: function onTransfer(event) {
var originalEvent = event.originalEvent,
source = event.source,
target = event.target,
direction = event.direction;
switch (direction) {
case 'toTarget':
if (this.props.onMoveToTarget) {
this.props.onMoveToTarget({
originalEvent: originalEvent,
value: this.getSourceSelection()
});
}
break;
case 'allToTarget':
if (this.props.onMoveAllToTarget) {
this.props.onMoveAllToTarget({
originalEvent: originalEvent,
value: this.props.source
});
}
break;
case 'toSource':
if (this.props.onMoveToSource) {
this.props.onMoveToSource({
originalEvent: originalEvent,
value: this.getTargetSelection()
});
}
break;
case 'allToSource':
if (this.props.onMoveAllToSource) {
this.props.onMoveAllToSource({
originalEvent: originalEvent,
value: this.props.target
});
}
break;
}
this.onSelectionChange({
originalEvent: originalEvent,
value: []
}, 'sourceSelection', this.props.onSourceSelectionChange);
this.onSelectionChange({
originalEvent: originalEvent,
value: []
}, 'targetSelection', this.props.onTargetSelectionChange);
this.handleChange(event, source, target);
}
}, {
key: "scrollInView",
value: function scrollInView(listContainer) {
var direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var selectedItems = listContainer.getElementsByClassName('p-highlight');
DomHandler.scrollInView(listContainer, direction === -1 ? selectedItems[0] : selectedItems[selectedItems.length - 1]);
}
}, {
key: "onSelectionChange",
value: function onSelectionChange(e, stateKey, callback) {
if (callback) {
callback(e);
} else {
this.setState(_defineProperty({}, stateKey, e.value));
}
if (this.state.sourceSelection && this.state.sourceSelection.length && stateKey === 'targetSelection') {
this.setState({
sourceSelection: []
});
} else if (this.state.targetSelection && this.state.targetSelection.length && stateKey === 'sourceSelection') {
this.setState({
targetSelection: []
});
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
if (this.reorderedListElement) {
this.handleScrollPosition(this.reorderedListElement, this.reorderDirection);
this.reorderedListElement = null;
this.reorderDirection = null;
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var className = classNames('p-picklist p-component', this.props.className);
var sourceSelection = this.getSourceSelection();
var targetSelection = this.getTargetSelection();
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
className: className,
style: this.props.style
}, this.props.showSourceControls && /*#__PURE__*/React.createElement(PickListControls, {
list: this.props.source,
selection: sourceSelection,
onReorder: this.onSourceReorder,
className: "p-picklist-source-controls"
}), /*#__PURE__*/React.createElement(PickListSubList, {
ref: function ref(el) {
return _this2.sourceListElement = el;
},
list: this.props.source,
selection: sourceSelection,
onSelectionChange: function onSelectionChange(e) {
return _this2.onSelectionChange(e, 'sourceSelection', _this2.props.onSourceSelectionChange);
},
itemTemplate: this.props.itemTemplate,
header: this.props.sourceHeader,
style: this.props.sourceStyle,
className: "p-picklist-source-wrapper",
listClassName: "p-picklist-source",
metaKeySelection: this.props.metaKeySelection,
tabIndex: this.props.tabIndex
}), /*#__PURE__*/React.createElement(PickListTransferControls, {
onTransfer: this.onTransfer,
source: this.props.source,
target: this.props.target,
sourceSelection: sourceSelection,
targetSelection: targetSelection
}), /*#__PURE__*/React.createElement(PickListSubList, {
ref: function ref(el) {
return _this2.targetListElement = el;
},
list: this.props.target,
selection: targetSelection,
onSelectionChange: function onSelectionChange(e) {
return _this2.onSelectionChange(e, 'targetSelection', _this2.props.onTargetSelectionChange);
},
itemTemplate: this.props.itemTemplate,
header: this.props.targetHeader,
style: this.props.targetStyle,
className: "p-picklist-target-wrapper",
listClassName: "p-picklist-target",
metaKeySelection: this.props.metaKeySelection,
tabIndex: this.props.tabIndex
}), this.props.showTargetControls && /*#__PURE__*/React.createElement(PickListControls, {
list: this.props.target,
selection: targetSelection,
onReorder: this.onTargetReorder,
className: "p-picklist-target-controls"
}));
}
}]);
return PickList;
}(Component);
_defineProperty(PickList, "defaultProps", {
id: null,
source: null,
target: null,
sourceHeader: null,
targetHeader: null,
style: null,
className: null,
sourceStyle: null,
targetStyle: null,
sourceSelection: null,
targetSelection: null,
showSourceControls: true,
showTargetControls: true,
metaKeySelection: true,
tabIndex: 0,
itemTemplate: null,
onChange: null,
onMoveToSource: null,
onMoveAllToSource: null,
onMoveToTarget: null,
onMoveAllToTarget: null,
onSourceSelectionChange: null,
onTargetSelectionChange: null
});
_defineProperty(PickList, "propTypes", {
id: PropTypes.string,
source: PropTypes.array,
target: PropTypes.array,
sourceHeader: PropTypes.any,
targetHeader: PropTypes.any,
style: PropTypes.object,
className: PropTypes.string,
sourcestyle: PropTypes.object,
targetstyle: PropTypes.object,
sourceSelection: PropTypes.any,
targetSelection: PropTypes.any,
showSourceControls: PropTypes.bool,
showTargetControls: PropTypes.bool,
metaKeySelection: PropTypes.bool,
tabIndex: PropTypes.number,
itemTemplate: PropTypes.func,
onChange: PropTypes.func,
onMoveToSource: PropTypes.func,
onMoveAllToSource: PropTypes.func,
onMoveToTarget: PropTypes.func,
onMoveAllToTarget: PropTypes.func,
onSourceSelectionChange: PropTypes.func,
onTargetSelectionChange: PropTypes.func
});
export { PickList };
|
ajax/libs/react-native-web/0.11.7/exports/View/index.js | cdnjs/cdnjs | function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import applyLayout from '../../modules/applyLayout';
import applyNativeMethods from '../../modules/applyNativeMethods';
import { bool } from 'prop-types';
import createElement from '../createElement';
import css from '../StyleSheet/css';
import filterSupportedProps from './filterSupportedProps';
import invariant from 'fbjs/lib/invariant';
import warning from 'fbjs/lib/warning';
import StyleSheet from '../StyleSheet';
import ViewPropTypes from './ViewPropTypes';
import React, { Component } from 'react';
var calculateHitSlopStyle = function calculateHitSlopStyle(hitSlop) {
var hitStyle = {};
for (var prop in hitSlop) {
if (hitSlop.hasOwnProperty(prop)) {
var value = hitSlop[prop];
hitStyle[prop] = value > 0 ? -1 * value : 0;
}
}
return hitStyle;
};
var View =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(View, _Component);
function View() {
return _Component.apply(this, arguments) || this;
}
var _proto = View.prototype;
_proto.render = function render() {
var hitSlop = this.props.hitSlop;
var supportedProps = filterSupportedProps(this.props);
if (process.env.NODE_ENV !== 'production') {
warning(this.props.className == null, 'Using the "className" prop on <View> is deprecated.');
React.Children.toArray(this.props.children).forEach(function (item) {
invariant(typeof item !== 'string', "Unexpected text node: " + item + ". A text node cannot be a child of a <View>.");
});
}
var isInAParentText = this.context.isInAParentText;
supportedProps.classList = [this.props.className, classes.view];
supportedProps.style = StyleSheet.compose(isInAParentText && styles.inline, this.props.style);
if (hitSlop) {
var hitSlopStyle = calculateHitSlopStyle(hitSlop);
var hitSlopChild = createElement('span', {
classList: [classes.hitSlop],
style: hitSlopStyle
});
supportedProps.children = React.Children.toArray([hitSlopChild, supportedProps.children]);
}
return createElement('div', supportedProps);
};
return View;
}(Component);
View.displayName = 'View';
View.contextTypes = {
isInAParentText: bool
};
View.propTypes = process.env.NODE_ENV !== "production" ? ViewPropTypes : {};
var classes = css.create({
view: {
alignItems: 'stretch',
border: '0 solid black',
boxSizing: 'border-box',
display: 'flex',
flexBasis: 'auto',
flexDirection: 'column',
flexShrink: 0,
margin: 0,
minHeight: 0,
minWidth: 0,
padding: 0,
position: 'relative',
zIndex: 0
},
// this zIndex-ordering positions the hitSlop above the View but behind
// its children
hitSlop: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: -1
}
});
var styles = StyleSheet.create({
inline: {
display: 'inline-flex'
}
});
export default applyLayout(applyNativeMethods(View)); |
ajax/libs/primereact/7.0.0/dataview/dataview.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { Paginator } from 'primereact/paginator';
import { classNames, ObjectUtils } from 'primereact/utils';
import { Ripple } from 'primereact/ripple';
import { localeOption } from 'primereact/api';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var DataViewLayoutOptions = /*#__PURE__*/function (_Component) {
_inherits(DataViewLayoutOptions, _Component);
var _super = _createSuper(DataViewLayoutOptions);
function DataViewLayoutOptions(props) {
var _this;
_classCallCheck(this, DataViewLayoutOptions);
_this = _super.call(this, props);
_this.changeLayout = _this.changeLayout.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(DataViewLayoutOptions, [{
key: "changeLayout",
value: function changeLayout(event, layoutMode) {
this.props.onChange({
originalEvent: event,
value: layoutMode
});
event.preventDefault();
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var className = classNames('p-dataview-layout-options p-selectbutton p-buttonset', this.props.className);
var buttonListClass = classNames('p-button p-button-icon-only', {
'p-highlight': this.props.layout === 'list'
});
var buttonGridClass = classNames('p-button p-button-icon-only', {
'p-highlight': this.props.layout === 'grid'
});
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
style: this.props.style,
className: className
}, /*#__PURE__*/React.createElement("button", {
type: "button",
className: buttonListClass,
onClick: function onClick(event) {
return _this2.changeLayout(event, 'list');
}
}, /*#__PURE__*/React.createElement("i", {
className: "pi pi-bars"
}), /*#__PURE__*/React.createElement(Ripple, null)), /*#__PURE__*/React.createElement("button", {
type: "button",
className: buttonGridClass,
onClick: function onClick(event) {
return _this2.changeLayout(event, 'grid');
}
}, /*#__PURE__*/React.createElement("i", {
className: "pi pi-th-large"
}), /*#__PURE__*/React.createElement(Ripple, null)));
}
}]);
return DataViewLayoutOptions;
}(Component);
_defineProperty(DataViewLayoutOptions, "defaultProps", {
id: null,
style: null,
className: null,
layout: null,
onChange: null
});
var DataViewItem = /*#__PURE__*/function (_Component2) {
_inherits(DataViewItem, _Component2);
var _super2 = _createSuper(DataViewItem);
function DataViewItem() {
_classCallCheck(this, DataViewItem);
return _super2.apply(this, arguments);
}
_createClass(DataViewItem, [{
key: "render",
value: function render() {
return this.props.template(this.props.item, this.props.layout);
}
}]);
return DataViewItem;
}(Component);
_defineProperty(DataViewItem, "defaultProps", {
template: null,
item: null,
layout: null
});
var DataView = /*#__PURE__*/function (_Component3) {
_inherits(DataView, _Component3);
var _super3 = _createSuper(DataView);
function DataView(props) {
var _this3;
_classCallCheck(this, DataView);
_this3 = _super3.call(this, props);
if (!_this3.props.onPage) {
_this3.state = {
first: _this3.props.first,
rows: _this3.props.rows
};
}
_this3.sortChange = false;
_this3.onPageChange = _this3.onPageChange.bind(_assertThisInitialized(_this3));
return _this3;
}
_createClass(DataView, [{
key: "getItemRenderKey",
value: function getItemRenderKey(value) {
return this.props.dataKey ? ObjectUtils.resolveFieldData(value, this.props.dataKey) : null;
}
}, {
key: "getTotalRecords",
value: function getTotalRecords() {
if (this.props.totalRecords) return this.props.totalRecords;else return this.props.value ? this.props.value.length : 0;
}
}, {
key: "createPaginator",
value: function createPaginator(position) {
var className = classNames('p-paginator-' + position, this.props.paginatorClassName);
var first = this.props.onPage ? this.props.first : this.state.first;
var rows = this.props.onPage ? this.props.rows : this.state.rows;
var totalRecords = this.getTotalRecords();
return /*#__PURE__*/React.createElement(Paginator, {
first: first,
rows: rows,
pageLinkSize: this.props.pageLinkSize,
className: className,
onPageChange: this.onPageChange,
template: this.props.paginatorTemplate,
totalRecords: totalRecords,
rowsPerPageOptions: this.props.rowsPerPageOptions,
currentPageReportTemplate: this.props.currentPageReportTemplate,
leftContent: this.props.paginatorLeft,
rightContent: this.props.paginatorRight,
alwaysShow: this.props.alwaysShowPaginator,
dropdownAppendTo: this.props.paginatorDropdownAppendTo
});
}
}, {
key: "onPageChange",
value: function onPageChange(event) {
if (this.props.onPage) {
this.props.onPage(event);
} else {
this.setState({
first: event.first,
rows: event.rows
});
}
}
}, {
key: "isEmpty",
value: function isEmpty() {
return !this.props.value || this.props.value.length === 0;
}
}, {
key: "sort",
value: function sort() {
var _this4 = this;
if (this.props.value) {
var value = _toConsumableArray(this.props.value);
value.sort(function (data1, data2) {
var value1 = ObjectUtils.resolveFieldData(data1, _this4.props.sortField);
var value2 = ObjectUtils.resolveFieldData(data2, _this4.props.sortField);
var result = null;
if (value1 == null && value2 != null) result = -1;else if (value1 != null && value2 == null) result = 1;else if (value1 == null && value2 == null) result = 0;else if (typeof value1 === 'string' && typeof value2 === 'string') result = value1.localeCompare(value2, undefined, {
numeric: true
});else result = value1 < value2 ? -1 : value1 > value2 ? 1 : 0;
return _this4.props.sortOrder * result;
});
return value;
} else {
return null;
}
}
}, {
key: "renderLoader",
value: function renderLoader() {
if (this.props.loading) {
var iconClassName = classNames('p-dataview-loading-icon pi-spin', this.props.loadingIcon);
return /*#__PURE__*/React.createElement("div", {
className: "p-dataview-loading-overlay p-component-overlay"
}, /*#__PURE__*/React.createElement("i", {
className: iconClassName
}));
}
return null;
}
}, {
key: "renderTopPaginator",
value: function renderTopPaginator() {
if (this.props.paginator && (this.props.paginatorPosition !== 'bottom' || this.props.paginatorPosition === 'both')) {
return this.createPaginator('top');
}
return null;
}
}, {
key: "renderBottomPaginator",
value: function renderBottomPaginator() {
if (this.props.paginator && (this.props.paginatorPosition !== 'top' || this.props.paginatorPosition === 'both')) {
return this.createPaginator('bottom');
}
return null;
}
}, {
key: "renderEmptyMessage",
value: function renderEmptyMessage() {
if (!this.props.loading) {
var content = this.props.emptyMessage || localeOption('emptyMessage');
return /*#__PURE__*/React.createElement("div", {
className: "p-col-12 col-12 p-dataview-emptymessage"
}, content);
}
return null;
}
}, {
key: "renderHeader",
value: function renderHeader() {
if (this.props.header) {
return /*#__PURE__*/React.createElement("div", {
className: "p-dataview-header"
}, this.props.header);
}
return null;
}
}, {
key: "renderFooter",
value: function renderFooter() {
if (this.props.footer) {
return /*#__PURE__*/React.createElement("div", {
className: "p-dataview-footer"
}, " ", this.props.footer);
}
return null;
}
}, {
key: "renderItems",
value: function renderItems(value) {
var _this5 = this;
if (value && value.length) {
if (this.props.paginator) {
var rows = this.props.onPage ? this.props.rows : this.state.rows;
var first = this.props.lazy ? 0 : this.props.onPage ? this.props.first : this.state.first;
var totalRecords = this.getTotalRecords();
var last = Math.min(rows + first, totalRecords);
var items = [];
for (var i = first; i < last; i++) {
var val = value[i];
val && items.push( /*#__PURE__*/React.createElement(DataViewItem, {
key: this.getItemRenderKey(value) || i,
template: this.props.itemTemplate,
layout: this.props.layout,
item: val
}));
}
return items;
} else {
return value.map(function (item, index) {
return /*#__PURE__*/React.createElement(DataViewItem, {
key: _this5.getItemRenderKey(item) || index,
template: _this5.props.itemTemplate,
layout: _this5.props.layout,
item: item
});
});
}
} else {
return this.renderEmptyMessage();
}
}
}, {
key: "renderContent",
value: function renderContent(value) {
var items = this.renderItems(value);
return /*#__PURE__*/React.createElement("div", {
className: "p-dataview-content"
}, /*#__PURE__*/React.createElement("div", {
className: "p-grid p-nogutter grid grid-nogutter"
}, items));
}
}, {
key: "processData",
value: function processData() {
var data = this.props.value;
if (data && data.length) {
if (this.props.sortField) {
data = this.sort();
}
}
return data;
}
}, {
key: "render",
value: function render() {
var value = this.processData();
var className = classNames('p-dataview p-component', {
'p-dataview-list': this.props.layout === 'list',
'p-dataview-grid': this.props.layout === 'grid',
'p-dataview-loading': this.props.loading
}, this.props.className);
var loader = this.renderLoader();
var topPaginator = this.renderTopPaginator();
var bottomPaginator = this.renderBottomPaginator();
var header = this.renderHeader();
var footer = this.renderFooter();
var content = this.renderContent(value);
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
style: this.props.style,
className: className
}, loader, header, topPaginator, content, bottomPaginator, footer);
}
}]);
return DataView;
}(Component);
_defineProperty(DataView, "defaultProps", {
id: null,
header: null,
footer: null,
value: null,
layout: 'list',
dataKey: null,
rows: null,
first: 0,
totalRecords: null,
paginator: false,
paginatorPosition: 'bottom',
alwaysShowPaginator: true,
paginatorClassName: null,
paginatorTemplate: 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown',
paginatorLeft: null,
paginatorRight: null,
paginatorDropdownAppendTo: null,
pageLinkSize: 5,
rowsPerPageOptions: null,
currentPageReportTemplate: '({currentPage} of {totalPages})',
emptyMessage: null,
sortField: null,
sortOrder: null,
style: null,
className: null,
lazy: false,
loading: false,
loadingIcon: 'pi pi-spinner',
itemTemplate: null,
onPage: null
});
export { DataView, DataViewLayoutOptions };
|
ajax/libs/react-native-web/0.13.2/exports/AppRegistry/renderApplication.js | cdnjs/cdnjs | function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import AppContainer from './AppContainer';
import invariant from 'fbjs/lib/invariant';
import render, { hydrate } from '../render';
import styleResolver from '../StyleSheet/styleResolver';
import React from 'react';
export default function renderApplication(RootComponent, WrapperComponent, callback, options) {
var shouldHydrate = options.hydrate,
initialProps = options.initialProps,
rootTag = options.rootTag;
var renderFn = shouldHydrate ? hydrate : render;
invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag);
renderFn(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.3/es/Grow/Grow.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 useTheme from '../styles/useTheme';
import { reflow, getTransitionProps } from '../transitions/utils';
import useForkRef from '../utils/useForkRef';
function getScale(value) {
return `scale(${value}, ${value ** 2})`;
}
const styles = {
entering: {
opacity: 1,
transform: getScale(1)
},
entered: {
opacity: 1,
transform: 'none'
}
};
/**
* The Grow transition is used by the [Tooltip](/components/tooltips/) and
* [Popover](/components/popover/) components.
* It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
*/
const Grow = React.forwardRef(function Grow(props, ref) {
const {
children,
in: inProp,
onEnter,
onExit,
style,
timeout = 'auto'
} = props,
other = _objectWithoutPropertiesLoose(props, ["children", "in", "onEnter", "onExit", "style", "timeout"]);
const timer = React.useRef();
const autoTimeout = React.useRef();
const handleRef = useForkRef(children.ref, ref);
const theme = useTheme();
const handleEnter = (node, isAppearing) => {
reflow(node); // So the animation always start from the start.
const {
duration: transitionDuration,
delay
} = getTransitionProps({
style,
timeout
}, {
mode: 'enter'
});
let duration;
if (timeout === 'auto') {
duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
autoTimeout.current = duration;
} else {
duration = transitionDuration;
}
node.style.transition = [theme.transitions.create('opacity', {
duration,
delay
}), theme.transitions.create('transform', {
duration: duration * 0.666,
delay
})].join(',');
if (onEnter) {
onEnter(node, isAppearing);
}
};
const handleExit = node => {
const {
duration: transitionDuration,
delay
} = getTransitionProps({
style,
timeout
}, {
mode: 'exit'
});
let duration;
if (timeout === 'auto') {
duration = theme.transitions.getAutoHeightDuration(node.clientHeight);
autoTimeout.current = duration;
} else {
duration = transitionDuration;
}
node.style.transition = [theme.transitions.create('opacity', {
duration,
delay
}), theme.transitions.create('transform', {
duration: duration * 0.666,
delay: delay || duration * 0.333
})].join(',');
node.style.opacity = '0';
node.style.transform = getScale(0.75);
if (onExit) {
onExit(node);
}
};
const addEndListener = (_, next) => {
if (timeout === 'auto') {
timer.current = setTimeout(next, autoTimeout.current || 0);
}
};
React.useEffect(() => {
return () => {
clearTimeout(timer.current);
};
}, []);
return React.createElement(Transition, _extends({
appear: true,
in: inProp,
onEnter: handleEnter,
onExit: handleExit,
addEndListener: addEndListener,
timeout: timeout === 'auto' ? null : timeout
}, other), (state, childProps) => {
return React.cloneElement(children, _extends({
style: _extends({
opacity: 0,
transform: getScale(0.75),
visibility: state === 'exited' && !inProp ? 'hidden' : undefined
}, styles[state], {}, style, {}, children.props.style),
ref: handleRef
}, childProps));
});
});
process.env.NODE_ENV !== "production" ? Grow.propTypes = {
/**
* A single child content element.
*/
children: PropTypes.element,
/**
* If `true`, show the component; triggers the enter or exit animation.
*/
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.
*
* Set to 'auto' to automatically calculate transition time based on height.
*/
timeout: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
enter: PropTypes.number,
exit: PropTypes.number
}), PropTypes.oneOf(['auto'])])
} : void 0;
Grow.muiSupportAuto = true;
export default Grow; |
ajax/libs/react-native-web/0.0.0-7cbe1609b/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.10/exports/KeyboardAvoidingView/index.js | cdnjs/cdnjs | function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import View from '../View';
import React from 'react';
var KeyboardAvoidingView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(KeyboardAvoidingView, _React$Component);
function KeyboardAvoidingView() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.frame = null;
_this.onLayout = function (event) {
_this.frame = event.nativeEvent.layout;
};
return _this;
}
var _proto = KeyboardAvoidingView.prototype;
_proto.relativeKeyboardHeight = function relativeKeyboardHeight(keyboardFrame) {
var frame = this.frame;
if (!frame || !keyboardFrame) {
return 0;
}
var keyboardY = keyboardFrame.screenY - (this.props.keyboardVerticalOffset || 0);
return Math.max(frame.y + frame.height - keyboardY, 0);
};
_proto.onKeyboardChange = function onKeyboardChange(event) {};
_proto.render = function render() {
var _this$props = this.props,
behavior = _this$props.behavior,
contentContainerStyle = _this$props.contentContainerStyle,
keyboardVerticalOffset = _this$props.keyboardVerticalOffset,
rest = _objectWithoutPropertiesLoose(_this$props, ["behavior", "contentContainerStyle", "keyboardVerticalOffset"]);
return React.createElement(View, _extends({
onLayout: this.onLayout
}, rest));
};
return KeyboardAvoidingView;
}(React.Component);
export default KeyboardAvoidingView; |
ajax/libs/material-ui/4.9.3/esm/Tabs/TabScrollButton.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
/* eslint-disable jsx-a11y/aria-role */
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import KeyboardArrowLeft from '../internal/svg-icons/KeyboardArrowLeft';
import KeyboardArrowRight from '../internal/svg-icons/KeyboardArrowRight';
import withStyles from '../styles/withStyles';
import ButtonBase from '../ButtonBase';
export var styles = {
root: {
width: 40,
flexShrink: 0
},
vertical: {
width: '100%',
height: 40,
'& svg': {
transform: 'rotate(90deg)'
}
}
};
/**
* @ignore - internal component.
*/
var _ref = React.createElement(KeyboardArrowLeft, {
fontSize: "small"
});
var _ref2 = React.createElement(KeyboardArrowRight, {
fontSize: "small"
});
var TabScrollButton = React.forwardRef(function TabScrollButton(props, ref) {
var classes = props.classes,
classNameProp = props.className,
direction = props.direction,
orientation = props.orientation,
visible = props.visible,
other = _objectWithoutProperties(props, ["classes", "className", "direction", "orientation", "visible"]);
var className = clsx(classes.root, classNameProp, orientation === 'vertical' && classes.vertical);
if (!visible) {
return React.createElement("div", {
className: className
});
}
return React.createElement(ButtonBase, _extends({
component: "div",
className: className,
ref: ref,
role: null,
tabIndex: null
}, other), direction === 'left' ? _ref : _ref2);
});
process.env.NODE_ENV !== "production" ? TabScrollButton.propTypes = {
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Which direction should the button indicate?
*/
direction: PropTypes.oneOf(['left', 'right']).isRequired,
/**
* The tabs orientation (layout flow direction).
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']).isRequired,
/**
* Should the button be present or just consume space.
*/
visible: PropTypes.bool.isRequired
} : void 0;
export default withStyles(styles, {
name: 'PrivateTabScrollButton'
})(TabScrollButton); |
ajax/libs/react-instantsearch/4.1.0-beta.5/Connectors.js | cdnjs/cdnjs | /*! ReactInstantSearch 4.1.0-beta.5 | © Algolia, inc. | https://community.algolia.com/react-instantsearch/ */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["Connectors"] = factory(require("react"));
else
root["ReactInstantSearch"] = root["ReactInstantSearch"] || {}, root["ReactInstantSearch"]["Connectors"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_4__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 436);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
if (false) {
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = require('./factoryWithTypeCheckers')(isValidElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = __webpack_require__(159)();
}
/***/ }),
/* 1 */
/***/ (function(module, exports) {
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = isArray;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEqual2 = __webpack_require__(81);
var _isEqual3 = _interopRequireDefault(_isEqual2);
var _has2 = __webpack_require__(58);
var _has3 = _interopRequireDefault(_has2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.default = createConnector;
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _react = __webpack_require__(4);
var _react2 = _interopRequireDefault(_react);
var _utils = __webpack_require__(44);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* @typedef {object} ConnectorDescription
* @property {string} displayName - the displayName used by the wrapper
* @property {function} refine - a function to filter the local state
* @property {function} getSearchParameters - function transforming the local state to a SearchParameters
* @property {function} getMetadata - metadata of the widget
* @property {function} transitionState - hook after the state has changed
* @property {function} getProvidedProps - transform the state into props passed to the wrapped component.
* Receives (props, widgetStates, searchState, metadata) and returns the local state.
* @property {function} getId - Receives props and return the id that will be used to identify the widget
* @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state.
* @property {object} propTypes - PropTypes forwarded to the wrapped component.
* @property {object} defaultProps - default values for the props
*/
/**
* Connectors are the HOC used to transform React components
* into InstantSearch widgets.
* In order to simplify the construction of such connectors
* `createConnector` takes a description and transform it into
* a connector.
* @param {ConnectorDescription} connectorDesc the description of the connector
* @return {Connector} a function that wraps a component into
* an instantsearch connected one.
*/
function createConnector(connectorDesc) {
if (!connectorDesc.displayName) {
throw new Error('`createConnector` requires you to provide a `displayName` property.');
}
var hasRefine = (0, _has3.default)(connectorDesc, 'refine');
var hasSearchForFacetValues = (0, _has3.default)(connectorDesc, 'searchForFacetValues');
var hasSearchParameters = (0, _has3.default)(connectorDesc, 'getSearchParameters');
var hasMetadata = (0, _has3.default)(connectorDesc, 'getMetadata');
var hasTransitionState = (0, _has3.default)(connectorDesc, 'transitionState');
var hasCleanUp = (0, _has3.default)(connectorDesc, 'cleanUp');
var isWidget = hasSearchParameters || hasMetadata || hasTransitionState;
return function (Composed) {
var _class, _temp, _initialiseProps;
return _temp = _class = function (_Component) {
_inherits(Connector, _Component);
function Connector(props, context) {
_classCallCheck(this, Connector);
var _this = _possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context));
_initialiseProps.call(_this);
var _context$ais = context.ais,
store = _context$ais.store,
widgetsManager = _context$ais.widgetsManager,
multiIndexContext = context.multiIndexContext;
var canRender = false;
_this.state = {
props: _this.getProvidedProps(_extends({}, props, { canRender: canRender })),
canRender: canRender // use to know if a component is rendered (browser), or not (server).
};
_this.unsubscribe = store.subscribe(function () {
if (_this.state.canRender) {
_this.setState({
props: _this.getProvidedProps(_extends({}, _this.props, {
canRender: _this.state.canRender
}))
});
}
});
var getSearchParameters = hasSearchParameters ? function (searchParameters) {
return connectorDesc.getSearchParameters.call(_this, searchParameters, _this.props, store.getState().widgets);
} : null;
var getMetadata = hasMetadata ? function (nextWidgetsState) {
return connectorDesc.getMetadata.call(_this, _this.props, nextWidgetsState);
} : null;
var transitionState = hasTransitionState ? function (prevWidgetsState, nextWidgetsState) {
return connectorDesc.transitionState.call(_this, _this.props, prevWidgetsState, nextWidgetsState);
} : null;
if (isWidget) {
_this.unregisterWidget = widgetsManager.registerWidget({
getSearchParameters: getSearchParameters,
getMetadata: getMetadata,
transitionState: transitionState,
multiIndexContext: multiIndexContext
});
}
return _this;
}
_createClass(Connector, [{
key: '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 (!(0, _isEqual3.default)(this.props, nextProps)) {
this.setState({
props: this.getProvidedProps(nextProps)
});
if (isWidget) {
// Since props might have changed, we need to re-run getSearchParameters
// and getMetadata with the new props.
this.context.ais.widgetsManager.update();
if (connectorDesc.transitionState) {
this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets));
}
}
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.unsubscribe();
if (isWidget) {
this.unregisterWidget(); // will schedule an update
if (hasCleanUp) {
var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets);
this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), {
widgets: newState
}));
this.context.ais.onSearchStateChange((0, _utils.removeEmptyKey)(newState));
}
}
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
var propsEqual = (0, _utils.shallowEqual)(this.props, nextProps);
if (this.state.props === null || nextState.props === null) {
if (this.state.props === nextState.props) {
return !propsEqual;
}
return true;
}
return !propsEqual || !(0, _utils.shallowEqual)(this.state.props, nextState.props);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
if (this.state.props === null) {
return null;
}
var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {};
var searchForFacetValuesProps = hasSearchForFacetValues ? {
searchForItems: this.searchForFacetValues,
searchForFacetValues: function searchForFacetValues(facetName, query) {
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`searchForItems`, this will break in the next major version.');
}
_this2.searchForFacetValues(facetName, query);
}
} : {};
return _react2.default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps));
}
}]);
return Connector;
}(_react.Component), _class.displayName = connectorDesc.displayName + '(' + (0, _utils.getDisplayName)(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = {
// @TODO: more precise state manager propType
ais: _propTypes2.default.object.isRequired,
multiIndexContext: _propTypes2.default.object
}, _initialiseProps = function _initialiseProps() {
var _this3 = this;
this.getProvidedProps = function (props) {
var store = _this3.context.ais.store;
var _store$getState = store.getState(),
results = _store$getState.results,
searching = _store$getState.searching,
error = _store$getState.error,
widgets = _store$getState.widgets,
metadata = _store$getState.metadata,
resultsFacetValues = _store$getState.resultsFacetValues,
searchingForFacetValues = _store$getState.searchingForFacetValues;
var searchState = {
results: results,
searching: searching,
error: error,
searchingForFacetValues: searchingForFacetValues
};
return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchState, metadata, resultsFacetValues);
};
this.refine = function () {
var _connectorDesc$refine;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this3.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.searchForFacetValues = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this3.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.createURL = function () {
var _connectorDesc$refine2;
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return _this3.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this3, _this3.props, _this3.context.ais.store.getState().widgets].concat(args)));
};
this.cleanUp = function () {
var _connectorDesc$cleanU;
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this3].concat(args));
};
}, _temp;
};
}
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
var freeGlobal = __webpack_require__(76);
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;
/***/ }),
/* 4 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_4__;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _get2 = __webpack_require__(72);
var _get3 = _interopRequireDefault(_get2);
var _omit2 = __webpack_require__(35);
var _omit3 = _interopRequireDefault(_omit2);
var _has2 = __webpack_require__(58);
var _has3 = _interopRequireDefault(_has2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.getIndex = getIndex;
exports.getResults = getResults;
exports.hasMultipleIndex = hasMultipleIndex;
exports.refineValue = refineValue;
exports.getCurrentRefinementValue = getCurrentRefinementValue;
exports.cleanUpValue = cleanUpValue;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getIndex(context) {
return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex;
}
function getResults(searchResults, context) {
if (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 {
return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage);
}
}
function refineMultiIndex(searchState, nextRefinement, context, resetPage) {
var page = resetPage ? { page: 1 } : undefined;
var index = getIndex(context);
var state = (0, _has3.default)(searchState, 'indices.' + index) ? _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], nextRefinement, page))) : _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, nextRefinement, page)));
return _extends({}, searchState, { indices: state });
}
function refineSingleIndex(searchState, nextRefinement, resetPage) {
var page = resetPage ? { page: 1 } : undefined;
return _extends({}, searchState, nextRefinement, page);
}
// eslint-disable-next-line max-params
function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) {
var _extends4;
var index = getIndex(context);
var page = resetPage ? { page: 1 } : undefined;
var state = (0, _has3.default)(searchState, 'indices.' + index) ? _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], (_extends4 = {}, _defineProperty(_extends4, namespace, _extends({}, searchState.indices[index][namespace], nextRefinement)), _defineProperty(_extends4, 'page', 1), _extends4)))) : _extends({}, searchState.indices, _defineProperty({}, index, _extends(_defineProperty({}, namespace, nextRefinement), page)));
return _extends({}, searchState, { indices: state });
}
function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) {
var page = resetPage ? { page: 1 } : undefined;
return _extends({}, searchState, _defineProperty({}, namespace, _extends({}, searchState[namespace], nextRefinement)), page);
}
function getNamespaceAndAttributeName(id) {
var parts = id.match(/^([^.]*)\.(.*)/);
var namespace = parts && parts[1];
var attributeName = parts && parts[2];
return { namespace: namespace, attributeName: attributeName };
}
// eslint-disable-next-line max-params
function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) {
var index = getIndex(context);
var _getNamespaceAndAttri = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri.namespace,
attributeName = _getNamespaceAndAttri.attributeName;
var refinements = hasMultipleIndex(context) && searchState.indices && namespace && searchState.indices['' + index] && (0, _has3.default)(searchState.indices['' + index][namespace], '' + attributeName) || hasMultipleIndex(context) && searchState.indices && (0, _has3.default)(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && namespace && (0, _has3.default)(searchState[namespace], attributeName) || !hasMultipleIndex(context) && (0, _has3.default)(searchState, id);
if (refinements) {
var currentRefinement = void 0;
if (hasMultipleIndex(context)) {
currentRefinement = namespace ? (0, _get3.default)(searchState.indices['' + index][namespace], attributeName) : (0, _get3.default)(searchState.indices[index], id);
} else {
currentRefinement = namespace ? (0, _get3.default)(searchState[namespace], attributeName) : (0, _get3.default)(searchState, id);
}
return refinementsCallback(currentRefinement);
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return defaultValue;
}
function cleanUpValue(searchState, context, id) {
var index = getIndex(context);
var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri2.namespace,
attributeName = _getNamespaceAndAttri2.attributeName;
if (hasMultipleIndex(context)) {
return namespace ? _extends({}, searchState, {
indices: _extends({}, searchState.indices, _defineProperty({}, index, _extends({}, searchState.indices[index], _defineProperty({}, namespace, (0, _omit3.default)(searchState.indices[index][namespace], '' + attributeName)))))
}) : (0, _omit3.default)(searchState, 'indices.' + index + '.' + id);
} else {
return namespace ? _extends({}, searchState, _defineProperty({}, namespace, (0, _omit3.default)(searchState[namespace], '' + attributeName))) : (0, _omit3.default)(searchState, '' + id);
}
}
/***/ }),
/* 6 */
/***/ (function(module, exports) {
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
module.exports = isObject;
/***/ }),
/* 7 */
/***/ (function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16),
getRawTag = __webpack_require__(124),
objectToString = __webpack_require__(125);
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
module.exports = baseGetTag;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(89),
baseKeys = __webpack_require__(79),
isArrayLike = __webpack_require__(11);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = keys;
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsNative = __webpack_require__(123),
getValue = __webpack_require__(128);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
module.exports = getNative;
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(19),
isLength = __webpack_require__(42);
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
module.exports = isArrayLike;
/***/ }),
/* 12 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
module.exports = arrayMap;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
var baseMatches = __webpack_require__(257),
baseMatchesProperty = __webpack_require__(260),
identity = __webpack_require__(26),
isArray = __webpack_require__(1),
property = __webpack_require__(262);
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
module.exports = baseIteratee;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
var baseKeys = __webpack_require__(79),
getTag = __webpack_require__(57),
isArguments = __webpack_require__(20),
isArray = __webpack_require__(1),
isArrayLike = __webpack_require__(11),
isBuffer = __webpack_require__(21),
isPrototype = __webpack_require__(38),
isTypedArray = __webpack_require__(34);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
setTag = '[object Set]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
module.exports = isEmpty;
/***/ }),
/* 15 */,
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12),
baseIteratee = __webpack_require__(13),
baseMap = __webpack_require__(183),
isArray = __webpack_require__(1);
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, baseIteratee(iteratee, 3));
}
module.exports = map;
/***/ }),
/* 18 */
/***/ (function(module, exports) {
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
module.exports = eq;
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObject = __webpack_require__(6);
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
module.exports = isFunction;
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsArguments = __webpack_require__(147),
isObjectLike = __webpack_require__(7);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
module.exports = isArguments;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3),
stubFalse = __webpack_require__(148);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
module.exports = isBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(56)(module)))
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(1),
isKey = __webpack_require__(64),
stringToPath = __webpack_require__(156),
toString = __webpack_require__(65);
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
module.exports = castPath;
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
module.exports = isSymbol;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(23);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = toKey;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(26),
overRest = __webpack_require__(166),
setToString = __webpack_require__(93);
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
module.exports = baseRest;
/***/ }),
/* 26 */
/***/ (function(module, exports) {
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(96),
baseAssignValue = __webpack_require__(47);
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
module.exports = copyObject;
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
var listCacheClear = __webpack_require__(113),
listCacheDelete = __webpack_require__(114),
listCacheGet = __webpack_require__(115),
listCacheHas = __webpack_require__(116),
listCacheSet = __webpack_require__(117);
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(18);
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
module.exports = assocIndexOf;
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10);
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
var isKeyable = __webpack_require__(137);
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
module.exports = getMapData;
/***/ }),
/* 32 */
/***/ (function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
/***/ }),
/* 33 */,
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(149),
baseUnary = __webpack_require__(43),
nodeUtil = __webpack_require__(150);
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
module.exports = isTypedArray;
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12),
baseClone = __webpack_require__(229),
baseUnset = __webpack_require__(245),
castPath = __webpack_require__(22),
copyObject = __webpack_require__(27),
customOmitClone = __webpack_require__(247),
flatRest = __webpack_require__(176),
getAllKeysIn = __webpack_require__(97);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
module.exports = omit;
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
var arrayEach = __webpack_require__(95),
baseEach = __webpack_require__(73),
castFunction = __webpack_require__(179),
isArray = __webpack_require__(1);
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, castFunction(iteratee));
}
module.exports = forEach;
/***/ }),
/* 37 */
/***/ (function(module, exports) {
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
module.exports = replaceHolders;
/***/ }),
/* 38 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
module.exports = isPrototype;
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(28),
stackClear = __webpack_require__(118),
stackDelete = __webpack_require__(119),
stackGet = __webpack_require__(120),
stackHas = __webpack_require__(121),
stackSet = __webpack_require__(122);
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
module.exports = Map;
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
var mapCacheClear = __webpack_require__(129),
mapCacheDelete = __webpack_require__(136),
mapCacheGet = __webpack_require__(138),
mapCacheHas = __webpack_require__(139),
mapCacheSet = __webpack_require__(140);
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;
/***/ }),
/* 42 */
/***/ (function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
/***/ }),
/* 43 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
module.exports = baseUnary;
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.defer = undefined;
var _isPlainObject2 = __webpack_require__(45);
var _isPlainObject3 = _interopRequireDefault(_isPlainObject2);
var _isEmpty2 = __webpack_require__(14);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
exports.shallowEqual = shallowEqual;
exports.isSpecialClick = isSpecialClick;
exports.capitalize = capitalize;
exports.assertFacetDefined = assertFacetDefined;
exports.getDisplayName = getDisplayName;
exports.removeEmptyKey = removeEmptyKey;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
function isSpecialClick(event) {
var isMiddleClick = event.button === 1;
return Boolean(isMiddleClick || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);
}
function capitalize(key) {
return key.length === 0 ? '' : '' + key[0].toUpperCase() + key.slice(1);
}
function assertFacetDefined(searchParameters, searchResults, facet) {
var wasRequested = searchParameters.isConjunctiveFacet(facet) || searchParameters.isDisjunctiveFacet(facet);
var wasReceived = Boolean(searchResults.getFacetByName(facet));
if (searchResults.nbHits > 0 && wasRequested && !wasReceived) {
// eslint-disable-next-line no-console
console.warn('A component requested values for facet "' + facet + '", but no facet ' + 'values were retrieved from the API. This means that you should add ' + ('the attribute "' + facet + '" to the list of attributes for faceting in ') + 'your index settings.');
}
}
function getDisplayName(Component) {
return Component.displayName || Component.name || 'UnknownComponent';
}
var resolved = Promise.resolve();
var defer = exports.defer = function defer(f) {
resolved.then(f);
};
function removeEmptyKey(obj) {
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if ((0, _isEmpty3.default)(value) && (0, _isPlainObject3.default)(value)) {
delete obj[key];
} else if ((0, _isPlainObject3.default)(value)) {
removeEmptyKey(value);
}
});
return obj;
}
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
getPrototype = __webpack_require__(67),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
module.exports = isPlainObject;
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(163),
baseIsNaN = __webpack_require__(225),
strictIndexOf = __webpack_require__(226);
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
module.exports = baseIndexOf;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
var defineProperty = __webpack_require__(168);
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
module.exports = baseAssignValue;
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(89),
baseKeysIn = __webpack_require__(232),
isArrayLike = __webpack_require__(11);
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
module.exports = keysIn;
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
var baseFor = __webpack_require__(178),
keys = __webpack_require__(9);
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
module.exports = baseForOwn;
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
var arrayReduce = __webpack_require__(99),
baseEach = __webpack_require__(73),
baseIteratee = __webpack_require__(13),
baseReduce = __webpack_require__(265),
isArray = __webpack_require__(1);
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce,
initAccum = arguments.length < 3;
return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}
module.exports = reduce;
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
var toFinite = __webpack_require__(213);
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
module.exports = toInteger;
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isArray = __webpack_require__(1),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var stringTag = '[object String]';
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
module.exports = isString;
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
var createFind = __webpack_require__(267),
findIndex = __webpack_require__(186);
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find = createFind(findIndex);
module.exports = find;
/***/ }),
/* 54 */
/***/ (function(module, exports) {
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = func;
return object.placeholder;
}
module.exports = getHolder;
/***/ }),
/* 55 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 56 */
/***/ (function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if(!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
var DataView = __webpack_require__(152),
Map = __webpack_require__(40),
Promise = __webpack_require__(153),
Set = __webpack_require__(154),
WeakMap = __webpack_require__(90),
baseGetTag = __webpack_require__(8),
toSource = __webpack_require__(77);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
setTag = '[object Set]',
weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
module.exports = getTag;
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
var baseHas = __webpack_require__(155),
hasPath = __webpack_require__(91);
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}
module.exports = has;
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqualDeep = __webpack_require__(112),
isObjectLike = __webpack_require__(7);
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
module.exports = baseIsEqual;
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(41),
setCacheAdd = __webpack_require__(141),
setCacheHas = __webpack_require__(142);
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
module.exports = SetCache;
/***/ }),
/* 61 */
/***/ (function(module, exports) {
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
module.exports = cacheHas;
/***/ }),
/* 62 */
/***/ (function(module, exports) {
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
module.exports = arrayPush;
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
var arrayFilter = __webpack_require__(87),
stubArray = __webpack_require__(88);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
module.exports = getSymbols;
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(1),
isSymbol = __webpack_require__(23);
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
module.exports = isKey;
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(66);
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
module.exports = toString;
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16),
arrayMap = __webpack_require__(12),
isArray = __webpack_require__(1),
isSymbol = __webpack_require__(23);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = baseToString;
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(80);
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
module.exports = getPrototype;
/***/ }),
/* 68 */
/***/ (function(module, exports) {
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
module.exports = apply;
/***/ }),
/* 69 */
/***/ (function(module, exports) {
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = copyArray;
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(6);
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
module.exports = baseCreate;
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(22),
toKey = __webpack_require__(24);
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
module.exports = baseGet;
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(71);
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
module.exports = get;
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(49),
createBaseEach = __webpack_require__(255);
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
module.exports = baseEach;
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(46),
toInteger = __webpack_require__(51);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
module.exports = indexOf;
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(70),
isObject = __webpack_require__(6);
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
module.exports = createCtor;
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
module.exports = freeGlobal;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)))
/***/ }),
/* 77 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
module.exports = toSource;
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(60),
arraySome = __webpack_require__(143),
cacheHas = __webpack_require__(61);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
module.exports = equalArrays;
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
var isPrototype = __webpack_require__(38),
nativeKeys = __webpack_require__(151);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
module.exports = baseKeys;
/***/ }),
/* 80 */
/***/ (function(module, exports) {
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(59);
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
module.exports = isEqual;
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;
/***/ }),
/* 83 */
/***/ (function(module, exports) {
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
module.exports = mapToArray;
/***/ }),
/* 84 */
/***/ (function(module, exports) {
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
module.exports = setToArray;
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(86),
getSymbols = __webpack_require__(63),
keys = __webpack_require__(9);
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
module.exports = getAllKeys;
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(62),
isArray = __webpack_require__(1);
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
module.exports = baseGetAllKeys;
/***/ }),
/* 87 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = arrayFilter;
/***/ }),
/* 88 */
/***/ (function(module, exports) {
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
module.exports = stubArray;
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
var baseTimes = __webpack_require__(146),
isArguments = __webpack_require__(20),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(21),
isIndex = __webpack_require__(32),
isTypedArray = __webpack_require__(34);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
module.exports = arrayLikeKeys;
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
module.exports = WeakMap;
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(22),
isArguments = __webpack_require__(20),
isArray = __webpack_require__(1),
isIndex = __webpack_require__(32),
isLength = __webpack_require__(42),
toKey = __webpack_require__(24);
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
module.exports = hasPath;
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(46);
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf(array, value, 0) > -1;
}
module.exports = arrayIncludes;
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetToString = __webpack_require__(228),
shortOut = __webpack_require__(169);
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
module.exports = setToString;
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(11),
isObjectLike = __webpack_require__(7);
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
module.exports = isArrayLikeObject;
/***/ }),
/* 95 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(47),
eq = __webpack_require__(18);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignValue;
/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(86),
getSymbolsIn = __webpack_require__(171),
keysIn = __webpack_require__(48);
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
module.exports = getAllKeysIn;
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
var Uint8Array = __webpack_require__(82);
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
module.exports = cloneArrayBuffer;
/***/ }),
/* 99 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
module.exports = arrayReduce;
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var keys = __webpack_require__(9);
var intersection = __webpack_require__(250);
var forOwn = __webpack_require__(253);
var forEach = __webpack_require__(36);
var filter = __webpack_require__(101);
var map = __webpack_require__(17);
var reduce = __webpack_require__(50);
var omit = __webpack_require__(35);
var indexOf = __webpack_require__(74);
var isNaN = __webpack_require__(214);
var isArray = __webpack_require__(1);
var isEmpty = __webpack_require__(14);
var isEqual = __webpack_require__(81);
var isUndefined = __webpack_require__(185);
var isString = __webpack_require__(52);
var isFunction = __webpack_require__(19);
var find = __webpack_require__(53);
var trim = __webpack_require__(187);
var defaults = __webpack_require__(102);
var merge = __webpack_require__(103);
var valToNumber = __webpack_require__(280);
var filterState = __webpack_require__(281);
var RefinementList = __webpack_require__(282);
/**
* like _.find but using _.isEqual to be able to use it
* to find arrays.
* @private
* @param {any[]} array array to search into
* @param {any} searchedValue the value we're looking for
* @return {any} the searched value or undefined
*/
function findArray(array, searchedValue) {
return find(array, function(currentValue) {
return isEqual(currentValue, searchedValue);
});
}
/**
* The facet list is the structure used to store the list of values used to
* filter a single attribute.
* @typedef {string[]} SearchParameters.FacetList
*/
/**
* Structure to store numeric filters with the operator as the key. The supported operators
* are `=`, `>`, `<`, `>=`, `<=` and `!=`.
* @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList
*/
/**
* SearchParameters is the data structure that contains all the information
* usable for making a search to Algolia API. It doesn't do the search itself,
* nor does it contains logic about the parameters.
* It is an immutable object, therefore it has been created in a way that each
* changes does not change the object itself but returns a copy with the
* modification.
* This object should probably not be instantiated outside of the helper. It will
* be provided when needed. This object is documented for reference as you'll
* get it from events generated by the {@link AlgoliaSearchHelper}.
* If need be, instantiate the Helper from the factory function {@link SearchParameters.make}
* @constructor
* @classdesc contains all the parameters of a search
* @param {object|SearchParameters} newParameters existing parameters or partial object
* for the properties of a new SearchParameters
* @see SearchParameters.make
* @example <caption>SearchParameters of the first query in
* <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption>
{
"query": "",
"disjunctiveFacets": [
"customerReviewCount",
"category",
"salePrice_range",
"manufacturer"
],
"maxValuesPerFacet": 30,
"page": 0,
"hitsPerPage": 10,
"facets": [
"type",
"shipping"
]
}
*/
function SearchParameters(newParameters) {
var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {};
/**
* Targeted index. This parameter is mandatory.
* @member {string}
*/
this.index = params.index || '';
// Query
/**
* Query string of the instant search. The empty string is a valid query.
* @member {string}
* @see https://www.algolia.com/doc/rest#param-query
*/
this.query = params.query || '';
// Facets
/**
* This attribute contains the list of all the conjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.facets = params.facets || [];
/**
* This attribute contains the list of all the disjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.disjunctiveFacets = params.disjunctiveFacets || [];
/**
* This attribute contains the list of all the hierarchical facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* Hierarchical facets are a sub type of disjunctive facets that
* let you filter faceted attributes hierarchically.
* @member {string[]|object[]}
*/
this.hierarchicalFacets = params.hierarchicalFacets || [];
// Refinements
/**
* This attribute contains all the filters that need to be
* applied on the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `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(params, function checkForUnknownParameter(paramValue, paramName) {
if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) {
self[paramName] = paramValue;
}
});
}
/**
* List all the properties in SearchParameters and therefore all the known Algolia properties
* This doesn't contain any beta/hidden features.
* @private
*/
SearchParameters.PARAMETERS = keys(new SearchParameters());
/**
* @private
* @param {object} partialState full or part of a state
* @return {object} a new object with the number keys as number
*/
SearchParameters._parseNumbers = function(partialState) {
// Do not reparse numbers in SearchParameters, they ought to be parsed already
if (partialState instanceof SearchParameters) return partialState;
var numbers = {};
var numberKeys = [
'aroundPrecision',
'aroundRadius',
'getRankingInfo',
'minWordSizefor2Typos',
'minWordSizefor1Typo',
'page',
'maxValuesPerFacet',
'distinct',
'minimumAroundRadius',
'hitsPerPage',
'minProximity'
];
forEach(numberKeys, function(k) {
var value = partialState[k];
if (isString(value)) {
var parsedValue = parseFloat(value);
numbers[k] = isNaN(parsedValue) ? value : parsedValue;
}
});
if (partialState.numericRefinements) {
var numericRefinements = {};
forEach(partialState.numericRefinements, function(operators, attribute) {
numericRefinements[attribute] = {};
forEach(operators, function(values, operator) {
var parsedValues = map(values, function(v) {
if (isArray(v)) {
return map(v, function(vPrime) {
if (isString(vPrime)) {
return parseFloat(vPrime);
}
return vPrime;
});
} else if (isString(v)) {
return parseFloat(v);
}
return v;
});
numericRefinements[attribute][operator] = parsedValues;
});
});
numbers.numericRefinements = numericRefinements;
}
return merge({}, partialState, numbers);
};
/**
* Factory for SearchParameters
* @param {object|SearchParameters} newParameters existing parameters or partial
* object for the properties of a new SearchParameters
* @return {SearchParameters} frozen instance of SearchParameters
*/
SearchParameters.make = function makeSearchParameters(newParameters) {
var instance = new SearchParameters(newParameters);
forEach(newParameters.hierarchicalFacets, function(facet) {
if (facet.rootPath) {
var currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) {
instance = instance.clearRefinements(facet.name);
}
// get it again in case it has been cleared
currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length === 0) {
instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath);
}
}
});
return instance;
};
/**
* Validates the new parameters based on the previous state
* @param {SearchParameters} currentState the current state
* @param {object|SearchParameters} parameters the new parameters to set
* @return {Error|null} Error if the modification is invalid, null otherwise
*/
SearchParameters.validate = function(currentState, parameters) {
var params = parameters || {};
if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) {
return new Error(
'[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' +
'an error, if it is really what you want, you should first clear the tags with clearTags method.');
}
if (currentState.tagRefinements.length > 0 && params.tagFilters) {
return new Error(
'[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' +
'an error, if it is not, you should first clear the tags with clearTags method.');
}
if (currentState.numericFilters && params.numericRefinements && !isEmpty(params.numericRefinements)) {
return new Error(
"[Numeric filters] Can't switch from the advanced to the managed API. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
if (!isEmpty(currentState.numericRefinements) && params.numericFilters) {
return new Error(
"[Numeric filters] Can't switch from the managed API to the advanced. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
return null;
};
SearchParameters.prototype = {
constructor: SearchParameters,
/**
* Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)
* @method
* @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {SearchParameters}
*/
clearRefinements: function clearRefinements(attribute) {
var clear = RefinementList.clearRefinement;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(attribute),
facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'),
facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'),
disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'),
hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet')
});
},
/**
* Remove all the refined tags from the SearchParameters
* @method
* @return {SearchParameters}
*/
clearTags: function clearTags() {
if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this;
return this.setQueryParameters({
tagFilters: undefined,
tagRefinements: []
});
},
/**
* Set the index.
* @method
* @param {string} index the index name
* @return {SearchParameters}
*/
setIndex: function setIndex(index) {
if (index === this.index) return this;
return this.setQueryParameters({
index: index
});
},
/**
* Query setter
* @method
* @param {string} newQuery value for the new query
* @return {SearchParameters}
*/
setQuery: function setQuery(newQuery) {
if (newQuery === this.query) return this;
return this.setQueryParameters({
query: newQuery
});
},
/**
* Page setter
* @method
* @param {number} newPage new page number
* @return {SearchParameters}
*/
setPage: function setPage(newPage) {
if (newPage === this.page) return this;
return this.setQueryParameters({
page: newPage
});
},
/**
* Facets setter
* The facets are the simple facets, used for conjunctive (and) faceting.
* @method
* @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting
* @return {SearchParameters}
*/
setFacets: function setFacets(facets) {
return this.setQueryParameters({
facets: facets
});
},
/**
* Disjunctive facets setter
* Change the list of disjunctive (or) facets the helper chan handle.
* @method
* @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting
* @return {SearchParameters}
*/
setDisjunctiveFacets: function setDisjunctiveFacets(facets) {
return this.setQueryParameters({
disjunctiveFacets: facets
});
},
/**
* HitsPerPage setter
* Hits per page represents the number of hits retrieved for this query
* @method
* @param {number} n number of hits retrieved per page of results
* @return {SearchParameters}
*/
setHitsPerPage: function setHitsPerPage(n) {
if (this.hitsPerPage === n) return this;
return this.setQueryParameters({
hitsPerPage: n
});
},
/**
* typoTolerance setter
* Set the value of typoTolerance
* @method
* @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict")
* @return {SearchParameters}
*/
setTypoTolerance: function setTypoTolerance(typoTolerance) {
if (this.typoTolerance === typoTolerance) return this;
return this.setQueryParameters({
typoTolerance: typoTolerance
});
},
/**
* Add a numeric filter for a given attribute
* When value is an array, they are combined with OR
* When value is a single value, it will combined with AND
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number | number[]} value value of the filter
* @return {SearchParameters}
* @example
* // for price = 50 or 40
* searchparameter.addNumericRefinement('price', '=', [50, 40]);
* @example
* // for size = 38 and 40
* searchparameter.addNumericRefinement('size', '=', 38);
* searchparameter.addNumericRefinement('size', '=', 40);
*/
addNumericRefinement: function(attribute, operator, v) {
var value = valToNumber(v);
if (this.isNumericRefined(attribute, operator, value)) return this;
var mod = merge({}, this.numericRefinements);
mod[attribute] = merge({}, mod[attribute]);
if (mod[attribute][operator]) {
// Array copy
mod[attribute][operator] = mod[attribute][operator].slice();
// Add the element. Concat can't be used here because value can be an array.
mod[attribute][operator].push(value);
} else {
mod[attribute][operator] = [value];
}
return this.setQueryParameters({
numericRefinements: mod
});
},
/**
* Get the list of conjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for 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(paramValue);
if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator && isEqual(value.val, paramValueAsNumber);
})
});
} else if (operator !== undefined) {
if (!this.isNumericRefined(attribute, operator)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator;
})
});
}
if (!this.isNumericRefined(attribute)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute;
})
});
},
/**
* Get the list of numeric refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {SearchParameters.OperatorList[]} list of refinements
*/
getNumericRefinements: function(facetName) {
return this.numericRefinements[facetName] || {};
},
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
getNumericRefinement: function(attribute, operator) {
return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator];
},
/**
* Clear numeric filters.
* @method
* @private
* @param {string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {Object.<string, OperatorList>}
*/
_clearNumericRefinements: function _clearNumericRefinements(attribute) {
if (isUndefined(attribute)) {
return {};
} else if (isString(attribute)) {
return omit(this.numericRefinements, attribute);
} else if (isFunction(attribute)) {
return reduce(this.numericRefinements, function(memo, operators, key) {
var operatorList = {};
forEach(operators, function(values, operator) {
var outValues = [];
forEach(values, function(value) {
var predicateResult = attribute({val: value, op: operator}, key, 'numeric');
if (!predicateResult) outValues.push(value);
});
if (!isEmpty(outValues)) operatorList[operator] = outValues;
});
if (!isEmpty(operatorList)) memo[key] = operatorList;
return memo;
}, {});
}
},
/**
* Add a facet to the facets attribute of the helper configuration, if it
* isn't already present.
* @method
* @param {string} facet facet name to add
* @return {SearchParameters}
*/
addFacet: function addFacet(facet) {
if (this.isConjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
facets: this.facets.concat([facet])
});
},
/**
* Add a disjunctive facet to the disjunctiveFacets attribute of the helper
* configuration, if it isn't already present.
* @method
* @param {string} facet disjunctive facet name to add
* @return {SearchParameters}
*/
addDisjunctiveFacet: function addDisjunctiveFacet(facet) {
if (this.isDisjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
disjunctiveFacets: this.disjunctiveFacets.concat([facet])
});
},
/**
* Add a hierarchical facet to the hierarchicalFacets attribute of the helper
* configuration.
* @method
* @param {object} hierarchicalFacet hierarchical facet to add
* @return {SearchParameters}
* @throws will throw an error if a hierarchical facet with the same name was already declared
*/
addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) {
if (this.isHierarchicalFacet(hierarchicalFacet.name)) {
throw new Error(
'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`');
}
return this.setQueryParameters({
hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet])
});
},
/**
* Add a refinement on a "normal" facet
* @method
* @param {string} facet attribute to apply the 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(this.facets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a disjunctive facet from the disjunctiveFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet disjunctive facet name to remove
* @return {SearchParameters}
*/
removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) {
if (!this.isDisjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
disjunctiveFacets: filter(this.disjunctiveFacets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a hierarchical facet from the hierarchicalFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet hierarchical facet name to remove
* @return {SearchParameters}
*/
removeHierarchicalFacet: function removeHierarchicalFacet(facet) {
if (!this.isHierarchicalFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
hierarchicalFacets: filter(this.hierarchicalFacets, function(f) {
return f.name !== facet;
})
});
},
/**
* Remove a refinement set on facet. If a value is provided, it will clear the
* refinement for the given value, otherwise it will clear all the refinement
* values for the 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(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({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Adds a refinement on a hierarchical facet.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is refined
*/
addHierarchicalFacetRefinement: function(facet, path) {
if (this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is already refined.');
}
var mod = {};
mod[facet] = [path];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is not refined
*/
removeHierarchicalFacetRefinement: function(facet) {
if (!this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is not refined.');
}
var mod = {};
mod[facet] = [];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Switch the tag refinement
* @method
* @param {string} tag the tag to remove or add
* @return {SearchParameters}
*/
toggleTagRefinement: function toggleTagRefinement(tag) {
if (this.isTagRefined(tag)) {
return this.removeTagRefinement(tag);
}
return this.addTagRefinement(tag);
},
/**
* Test if the facet name is from one of the disjunctive facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isDisjunctiveFacet: function(facet) {
return indexOf(this.disjunctiveFacets, facet) > -1;
},
/**
* Test if the facet name is from one of the hierarchical facets
* @method
* @param {string} facetName facet name to test
* @return {boolean}
*/
isHierarchicalFacet: function(facetName) {
return this.getHierarchicalFacetByName(facetName) !== undefined;
},
/**
* Test if the facet name is from one of the conjunctive/normal facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isConjunctiveFacet: function(facet) {
return indexOf(this.facets, facet) > -1;
},
/**
* Returns true if the facet is refined, either for a specific value or in
* general.
* @method
* @param {string} facet name of the attribute for used for 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(refinements, value) !== -1;
},
/**
* Test if the triple (attribute, operator, value) is already refined.
* If only the attribute and the operator are provided, it tests if the
* contains any refinement value.
* @method
* @param {string} attribute attribute for which the refinement is applied
* @param {string} [operator] operator of the refinement
* @param {string} [value] value of the refinement
* @return {boolean} true if it is refined
*/
isNumericRefined: function isNumericRefined(attribute, operator, value) {
if (isUndefined(value) && isUndefined(operator)) {
return !!this.numericRefinements[attribute];
}
var isOperatorDefined = this.numericRefinements[attribute] &&
!isUndefined(this.numericRefinements[attribute][operator]);
if (isUndefined(value) || !isOperatorDefined) {
return isOperatorDefined;
}
var parsedValue = valToNumber(value);
var isAttributeValueDefined = !isUndefined(
findArray(this.numericRefinements[attribute][operator], parsedValue)
);
return isOperatorDefined && isAttributeValueDefined;
},
/**
* Returns true if the tag refined, false otherwise
* @method
* @param {string} tag the tag to check
* @return {boolean}
*/
isTagRefined: function isTagRefined(tag) {
return indexOf(this.tagRefinements, tag) !== -1;
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for 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(
keys(this.numericRefinements),
this.disjunctiveFacets
);
return keys(this.disjunctiveFacetsRefinements)
.concat(disjunctiveNumericRefinedFacets)
.concat(this.getRefinedHierarchicalFacets());
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() {
return intersection(
// enforce the order between the two arrays,
// so that refinement name index === hierarchical facet index
map(this.hierarchicalFacets, 'name'),
keys(this.hierarchicalFacetsRefinements)
);
},
/**
* Returned the list of all disjunctive facets not refined
* @method
* @return {string[]}
*/
getUnrefinedDisjunctiveFacets: function() {
var refinedFacets = this.getRefinedDisjunctiveFacets();
return filter(this.disjunctiveFacets, function(f) {
return indexOf(refinedFacets, f) === -1;
});
},
managedParameters: [
'index',
'facets', 'disjunctiveFacets', 'facetsRefinements',
'facetsExcludes', 'disjunctiveFacetsRefinements',
'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'
],
getQueryParams: function getQueryParams() {
var managedParameters = this.managedParameters;
var queryParams = {};
forOwn(this, function(paramValue, paramName) {
if (indexOf(managedParameters, paramName) === -1 && paramValue !== undefined) {
queryParams[paramName] = paramValue;
}
});
return queryParams;
},
/**
* Let the user retrieve any parameter value from the SearchParameters
* @param {string} paramName name of the parameter
* @return {any} the value of the parameter
*/
getQueryParameter: function getQueryParameter(paramName) {
if (!this.hasOwnProperty(paramName)) {
throw new Error(
"Parameter '" + paramName + "' is not an attribute of SearchParameters " +
'(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)');
}
return this[paramName];
},
/**
* Let the user set a specific value for a given parameter. Will return the
* same instance if the parameter is invalid or if the value is the same as the
* previous one.
* @method
* @param {string} parameter the parameter name
* @param {any} value the value to be set, must be compliant with the definition
* of the attribute on the object
* @return {SearchParameters} the updated state
*/
setQueryParameter: function setParameter(parameter, value) {
if (this[parameter] === value) return this;
var modification = {};
modification[parameter] = value;
return this.setQueryParameters(modification);
},
/**
* Let the user set any of the parameters with a plain object.
* @method
* @param {object} params all the keys and the values to be updated
* @return {SearchParameters} a new updated instance
*/
setQueryParameters: function setQueryParameters(params) {
if (!params) return this;
var error = SearchParameters.validate(this, params);
if (error) {
throw error;
}
var parsedParams = SearchParameters._parseNumbers(params);
return this.mutateMe(function mergeWith(newInstance) {
var ks = keys(params);
forEach(ks, function(k) {
newInstance[k] = parsedParams[k];
});
return newInstance;
});
},
/**
* Returns an object with only the selected attributes.
* @param {string[]} filters filters to retrieve only a subset of the state. It
* accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage)
* or attributes of the index with the notation 'attribute:nameOfMyAttribute'
* @return {object}
*/
filter: function(filters) {
return filterState(this, filters);
},
/**
* Helper function to make it easier to build new instances from a mutating
* function
* @private
* @param {function} fn newMutableState -> previousState -> () function that will
* change the value of the newMutable to the desired state
* @return {SearchParameters} a new instance with the specified modifications applied
*/
mutateMe: function mutateMe(fn) {
var newState = new this.constructor(this);
fn(newState, this);
return newState;
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSortBy: function(hierarchicalFacet) {
return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc'];
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSeparator: function(hierarchicalFacet) {
return hierarchicalFacet.separator || ' > ';
},
/**
* Helper function to get the hierarchicalFacet prefix path or null
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.rootPath or null as default
*/
_getHierarchicalRootPath: function(hierarchicalFacet) {
return hierarchicalFacet.rootPath || null;
},
/**
* Helper function to check if we show the parent level of the hierarchicalFacet
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.showParentLevel or true as default
*/
_getHierarchicalShowParentLevel: function(hierarchicalFacet) {
if (typeof hierarchicalFacet.showParentLevel === 'boolean') {
return hierarchicalFacet.showParentLevel;
}
return true;
},
/**
* Helper function to get the hierarchicalFacet by it's name
* @param {string} hierarchicalFacetName
* @return {object} a hierarchicalFacet
*/
getHierarchicalFacetByName: function(hierarchicalFacetName) {
return find(
this.hierarchicalFacets,
{name: hierarchicalFacetName}
);
},
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
getHierarchicalFacetBreadcrumb: function(facetName) {
if (!this.isHierarchicalFacet(facetName)) {
throw new Error(
'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`');
}
var refinement = this.getHierarchicalRefinement(facetName)[0];
if (!refinement) return [];
var separator = this._getHierarchicalFacetSeparator(
this.getHierarchicalFacetByName(facetName)
);
var path = refinement.split(separator);
return map(path, trim);
}
};
/**
* Callback used for clearRefinement method
* @callback SearchParameters.clearCallback
* @param {OperatorList|FacetList} value the value of the filter
* @param {string} key the current attribute name
* @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude`
* depending on the type of facet
* @return {boolean} `true` if the element should be removed. `false` otherwise.
*/
module.exports = SearchParameters;
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
var arrayFilter = __webpack_require__(87),
baseFilter = __webpack_require__(256),
baseIteratee = __webpack_require__(13),
isArray = __webpack_require__(1);
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*/
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, baseIteratee(predicate, 3));
}
module.exports = filter;
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(68),
assignInWith = __webpack_require__(275),
baseRest = __webpack_require__(25),
customDefaultsAssignIn = __webpack_require__(276);
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = baseRest(function(args) {
args.push(undefined, customDefaultsAssignIn);
return apply(assignInWith, undefined, args);
});
module.exports = defaults;
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
var baseMerge = __webpack_require__(277),
createAssigner = __webpack_require__(188);
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
module.exports = merge;
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
var baseOrderBy = __webpack_require__(289),
isArray = __webpack_require__(1);
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
module.exports = orderBy;
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetData = __webpack_require__(191),
createBind = __webpack_require__(294),
createCurry = __webpack_require__(295),
createHybrid = __webpack_require__(193),
createPartial = __webpack_require__(307),
getData = __webpack_require__(197),
mergeData = __webpack_require__(308),
setData = __webpack_require__(199),
setWrapToString = __webpack_require__(200),
toInteger = __webpack_require__(51);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
module.exports = createWrap;
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(70),
baseLodash = __webpack_require__(107);
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
module.exports = LazyWrapper;
/***/ }),
/* 107 */
/***/ (function(module, exports) {
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
module.exports = baseLodash;
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = Object.prototype.hasOwnProperty;
var hexTable = (function () {
var array = [];
for (var i = 0; i < 256; ++i) {
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
}
return array;
}());
exports.arrayToObject = function (source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
exports.merge = function (target, source, options) {
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (Array.isArray(target)) {
target.push(source);
} else if (typeof target === 'object') {
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 (str) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = typeof str === 'string' ? str : String(str);
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D // -
|| c === 0x2E // .
|| c === 0x5F // _
|| c === 0x7E // ~
|| (c >= 0x30 && c <= 0x39) // 0-9
|| (c >= 0x41 && c <= 0x5A) // a-z
|| (c >= 0x61 && c <= 0x7A) // A-Z
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)]
+ hexTable[0x80 | ((c >> 12) & 0x3F)]
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
+ hexTable[0x80 | (c & 0x3F)];
}
return out;
};
exports.compact = function (obj, references) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
var refs = references || [];
var lookup = refs.indexOf(obj);
if (lookup !== -1) {
return refs[lookup];
}
refs.push(obj);
if (Array.isArray(obj)) {
var compacted = [];
for (var i = 0; i < obj.length; ++i) {
if (obj[i] && typeof obj[i] === 'object') {
compacted.push(exports.compact(obj[i], refs));
} else if (typeof obj[i] !== 'undefined') {
compacted.push(obj[i]);
}
}
return compacted;
}
var keys = Object.keys(obj);
keys.forEach(function (key) {
obj[key] = exports.compact(obj[key], refs);
});
return obj;
};
exports.isRegExp = function (obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
exports.isBuffer = function (obj) {
if (obj === null || typeof obj === 'undefined') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
/***/ }),
/* 109 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
var basePick = __webpack_require__(326),
flatRest = __webpack_require__(176);
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = flatRest(function(object, paths) {
return object == null ? {} : basePick(object, paths);
});
module.exports = pick;
/***/ }),
/* 111 */,
/* 112 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
equalArrays = __webpack_require__(78),
equalByTag = __webpack_require__(144),
equalObjects = __webpack_require__(145),
getTag = __webpack_require__(57),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(21),
isTypedArray = __webpack_require__(34);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
module.exports = baseIsEqualDeep;
/***/ }),
/* 113 */
/***/ (function(module, exports) {
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(29);
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
module.exports = listCacheDelete;
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(29);
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
module.exports = listCacheGet;
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(29);
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
module.exports = listCacheHas;
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(29);
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(28);
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
module.exports = stackClear;
/***/ }),
/* 119 */
/***/ (function(module, exports) {
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
module.exports = stackDelete;
/***/ }),
/* 120 */
/***/ (function(module, exports) {
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
module.exports = stackGet;
/***/ }),
/* 121 */
/***/ (function(module, exports) {
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
module.exports = stackHas;
/***/ }),
/* 122 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(28),
Map = __webpack_require__(40),
MapCache = __webpack_require__(41);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
module.exports = stackSet;
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(19),
isMasked = __webpack_require__(126),
isObject = __webpack_require__(6),
toSource = __webpack_require__(77);
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
module.exports = baseIsNative;
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
module.exports = getRawTag;
/***/ }),
/* 125 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
module.exports = objectToString;
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
var coreJsData = __webpack_require__(127);
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
module.exports = isMasked;
/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(3);
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
module.exports = coreJsData;
/***/ }),
/* 128 */
/***/ (function(module, exports) {
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
module.exports = getValue;
/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {
var Hash = __webpack_require__(130),
ListCache = __webpack_require__(28),
Map = __webpack_require__(40);
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
module.exports = mapCacheClear;
/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {
var hashClear = __webpack_require__(131),
hashDelete = __webpack_require__(132),
hashGet = __webpack_require__(133),
hashHas = __webpack_require__(134),
hashSet = __webpack_require__(135);
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;
/***/ }),
/* 131 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(30);
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
/***/ }),
/* 132 */
/***/ (function(module, exports) {
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
module.exports = hashDelete;
/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(30);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
module.exports = hashGet;
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(30);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
module.exports = hashHas;
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(30);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
module.exports = hashSet;
/***/ }),
/* 136 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(31);
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
module.exports = mapCacheDelete;
/***/ }),
/* 137 */
/***/ (function(module, exports) {
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
module.exports = isKeyable;
/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(31);
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
module.exports = mapCacheGet;
/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(31);
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
module.exports = mapCacheHas;
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(31);
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
module.exports = mapCacheSet;
/***/ }),
/* 141 */
/***/ (function(module, exports) {
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
module.exports = setCacheAdd;
/***/ }),
/* 142 */
/***/ (function(module, exports) {
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
module.exports = setCacheHas;
/***/ }),
/* 143 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
module.exports = arraySome;
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16),
Uint8Array = __webpack_require__(82),
eq = __webpack_require__(18),
equalArrays = __webpack_require__(78),
mapToArray = __webpack_require__(83),
setToArray = __webpack_require__(84);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
module.exports = equalByTag;
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
var getAllKeys = __webpack_require__(85);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
module.exports = equalObjects;
/***/ }),
/* 146 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
module.exports = baseTimes;
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
module.exports = baseIsArguments;
/***/ }),
/* 148 */
/***/ (function(module, exports) {
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = stubFalse;
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isLength = __webpack_require__(42),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
module.exports = baseIsTypedArray;
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(76);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(56)(module)))
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(80);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
/***/ }),
/* 152 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
module.exports = DataView;
/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
module.exports = Promise;
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10),
root = __webpack_require__(3);
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
module.exports = Set;
/***/ }),
/* 155 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
return object != null && hasOwnProperty.call(object, key);
}
module.exports = baseHas;
/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {
var memoizeCapped = __webpack_require__(157);
/** Used to match property names within property paths. */
var reLeadingDot = /^\./,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (reLeadingDot.test(string)) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
module.exports = stringToPath;
/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {
var memoize = __webpack_require__(158);
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
module.exports = memoizeCapped;
/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(41);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
module.exports = memoize;
/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var emptyFunction = __webpack_require__(160);
var invariant = __webpack_require__(161);
var ReactPropTypesSecret = __webpack_require__(162);
module.exports = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
invariant(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
};
shim.isRequired = shim;
function getShim() {
return shim;
};
// 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
};
ReactPropTypes.checkPropTypes = emptyFunction;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
if (false) {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/***/ }),
/* 162 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ }),
/* 163 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
module.exports = baseFindIndex;
/***/ }),
/* 164 */
/***/ (function(module, exports) {
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
module.exports = arrayIncludesWith;
/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(62),
isFlattenable = __webpack_require__(227);
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
module.exports = baseFlatten;
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(68);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
module.exports = overRest;
/***/ }),
/* 167 */
/***/ (function(module, exports) {
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
module.exports = constant;
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(10);
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
module.exports = defineProperty;
/***/ }),
/* 169 */
/***/ (function(module, exports) {
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
module.exports = shortOut;
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(3);
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
module.exports = cloneBuffer;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(56)(module)))
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(62),
getPrototype = __webpack_require__(67),
getSymbols = __webpack_require__(63),
stubArray = __webpack_require__(88);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
module.exports = getSymbolsIn;
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(98);
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
module.exports = cloneTypedArray;
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(70),
getPrototype = __webpack_require__(67),
isPrototype = __webpack_require__(38);
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
module.exports = initCloneObject;
/***/ }),
/* 174 */
/***/ (function(module, exports) {
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
module.exports = last;
/***/ }),
/* 175 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
module.exports = baseSlice;
/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {
var flatten = __webpack_require__(177),
overRest = __webpack_require__(166),
setToString = __webpack_require__(93);
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
module.exports = flatRest;
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
var baseFlatten = __webpack_require__(165);
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
module.exports = flatten;
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
var createBaseFor = __webpack_require__(254);
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
module.exports = baseFor;
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(26);
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity;
}
module.exports = castFunction;
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(6);
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
module.exports = isStrictComparable;
/***/ }),
/* 181 */
/***/ (function(module, exports) {
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
module.exports = matchesStrictComparable;
/***/ }),
/* 182 */
/***/ (function(module, exports, __webpack_require__) {
var baseHasIn = __webpack_require__(261),
hasPath = __webpack_require__(91);
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
module.exports = hasIn;
/***/ }),
/* 183 */
/***/ (function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(73),
isArrayLike = __webpack_require__(11);
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
module.exports = baseMap;
/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(8),
isObjectLike = __webpack_require__(7);
/** `Object#toString` result references. */
var numberTag = '[object Number]';
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && baseGetTag(value) == numberTag);
}
module.exports = isNumber;
/***/ }),
/* 185 */
/***/ (function(module, exports) {
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
module.exports = isUndefined;
/***/ }),
/* 186 */
/***/ (function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(163),
baseIteratee = __webpack_require__(13),
toInteger = __webpack_require__(51);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, baseIteratee(predicate, 3), index);
}
module.exports = findIndex;
/***/ }),
/* 187 */
/***/ (function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(66),
castSlice = __webpack_require__(268),
charsEndIndex = __webpack_require__(269),
charsStartIndex = __webpack_require__(270),
stringToArray = __webpack_require__(271),
toString = __webpack_require__(65);
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrim, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars),
start = charsStartIndex(strSymbols, chrSymbols),
end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}
module.exports = trim;
/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(25),
isIterateeCall = __webpack_require__(215);
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
/***/ }),
/* 189 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(47),
eq = __webpack_require__(18);
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignMergeValue;
/***/ }),
/* 190 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(36);
var compact = __webpack_require__(283);
var indexOf = __webpack_require__(74);
var findIndex = __webpack_require__(186);
var get = __webpack_require__(72);
var sumBy = __webpack_require__(284);
var find = __webpack_require__(53);
var includes = __webpack_require__(286);
var map = __webpack_require__(17);
var orderBy = __webpack_require__(104);
var defaults = __webpack_require__(102);
var merge = __webpack_require__(103);
var isArray = __webpack_require__(1);
var isFunction = __webpack_require__(19);
var partial = __webpack_require__(293);
var partialRight = __webpack_require__(309);
var formatSort = __webpack_require__(201);
var generateHierarchicalTree = __webpack_require__(312);
/**
* @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} value the facet value itself
* @property {number} count times this facet appears in the results
* @property {boolean} isRefined is the facet currently selected
* @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets)
*/
/**
* @typedef Refinement
* @type {object}
* @property {string} type the type of filter used:
* `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical`
* @property {string} attributeName name of the attribute used for filtering
* @property {string} name the value of the filter
* @property {number} numericValue the value as a number. Only for numeric 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(obj, function(val, idx) { indices[val] = idx; });
return indices;
}
function assignFacetStats(dest, facetStats, key) {
if (facetStats && facetStats[key]) {
dest.stats = facetStats[key];
}
}
function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) {
return find(
hierarchicalFacets,
function facetKeyMatchesAttribute(hierarchicalFacet) {
return includes(hierarchicalFacet.attributes, hierarchicalAttributeName);
}
);
}
/*eslint-disable */
/**
* Constructor for SearchResults
* @class
* @classdesc SearchResults contains the results of a query to Algolia using the
* {@link AlgoliaSearchHelper}.
* @param {SearchParameters} state state that led to the response
* @param {array.<object>} results the results from algolia client
* @example <caption>SearchResults of the first query in
* <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption>
{
"hitsPerPage": 10,
"processingTimeMS": 2,
"facets": [
{
"name": "type",
"data": {
"HardGood": 6627,
"BlackTie": 550,
"Music": 665,
"Software": 131,
"Game": 456,
"Movie": 1571
},
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"Free shipping": 5507
},
"name": "shipping"
}
],
"hits": [
{
"thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
"_highlightResult": {
"shortDescription": {
"matchLevel": "none",
"value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"matchedWords": []
},
"category": {
"matchLevel": "none",
"value": "Computer Security Software",
"matchedWords": []
},
"manufacturer": {
"matchedWords": [],
"value": "Webroot",
"matchLevel": "none"
},
"name": {
"value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"matchedWords": [],
"matchLevel": "none"
}
},
"image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
"shipping": "Free shipping",
"bestSellingRank": 4,
"shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
"name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"category": "Computer Security Software",
"salePrice_range": "1 - 50",
"objectID": "1688832",
"type": "Software",
"customerReviewCount": 5980,
"salePrice": 49.99,
"manufacturer": "Webroot"
},
....
],
"nbHits": 10000,
"disjunctiveFacets": [
{
"exhaustive": false,
"data": {
"5": 183,
"12": 112,
"7": 149,
...
},
"name": "customerReviewCount",
"stats": {
"max": 7461,
"avg": 157.939,
"min": 1
}
},
{
"data": {
"Printer Ink": 142,
"Wireless Speakers": 60,
"Point & Shoot Cameras": 48,
...
},
"name": "category",
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"> 5000": 2,
"1 - 50": 6524,
"501 - 2000": 566,
"201 - 500": 1501,
"101 - 200": 1360,
"2001 - 5000": 47
},
"name": "salePrice_range"
},
{
"data": {
"Dynex™": 202,
"Insignia™": 230,
"PNY": 72,
...
},
"name": "manufacturer",
"exhaustive": false
}
],
"query": "",
"nbPages": 100,
"page": 0,
"index": "bestbuy"
}
**/
/*eslint-enable */
function SearchResults(state, results) {
var mainSubResponse = results[0];
this._rawResults = results;
/**
* query used to generate the results
* @member {string}
*/
this.query = mainSubResponse.query;
/**
* The query as parsed by the engine given all the rules.
* @member {string}
*/
this.parsedQuery = mainSubResponse.parsedQuery;
/**
* all the records that match the search parameters. Each record is
* augmented with a new attribute `_highlightResult`
* which is an object keyed by attribute and with the following properties:
* - `value` : the value of the facet highlighted (html)
* - `matchLevel`: full, partial or none depending on how the query terms match
* @member {object[]}
*/
this.hits = mainSubResponse.hits;
/**
* index where the results come from
* @member {string}
*/
this.index = mainSubResponse.index;
/**
* number of hits per page requested
* @member {number}
*/
this.hitsPerPage = mainSubResponse.hitsPerPage;
/**
* total number of hits of this query on the index
* @member {number}
*/
this.nbHits = mainSubResponse.nbHits;
/**
* total number of pages with respect to the number of hits per page and the total number of hits
* @member {number}
*/
this.nbPages = mainSubResponse.nbPages;
/**
* current page
* @member {number}
*/
this.page = mainSubResponse.page;
/**
* sum of the processing time of all the queries
* @member {number}
*/
this.processingTimeMS = sumBy(results, 'processingTimeMS');
/**
* The position if the position was guessed by IP.
* @member {string}
* @example "48.8637,2.3615",
*/
this.aroundLatLng = mainSubResponse.aroundLatLng;
/**
* The radius computed by Algolia.
* @member {string}
* @example "126792922",
*/
this.automaticRadius = mainSubResponse.automaticRadius;
/**
* String identifying the server used to serve this request.
* @member {string}
* @example "c7-use-2.algolia.net",
*/
this.serverUsed = mainSubResponse.serverUsed;
/**
* Boolean that indicates if the computation of the counts did time out.
* @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;
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
this.disjunctiveFacets = [];
/**
* disjunctive facets results
* @member {SearchResults.HierarchicalFacet[]}
*/
this.hierarchicalFacets = map(state.hierarchicalFacets, function initFutureTree() {
return [];
});
/**
* other facets results
* @member {SearchResults.Facet[]}
*/
this.facets = [];
var disjunctiveFacets = state.getRefinedDisjunctiveFacets();
var facetsIndices = getIndices(state.facets);
var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets);
var nextDisjunctiveResult = 1;
var self = this;
// Since we send request only for disjunctive facets that have been refined,
// we get the facets informations from the first, general, response.
forEach(mainSubResponse.facets, function(facetValueObject, facetKey) {
var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName(
state.hierarchicalFacets,
facetKey
);
if (hierarchicalFacet) {
// Place the hierarchicalFacet data at the correct index depending on
// the attributes order that was defined at the helper initialization
var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey);
var idxAttributeName = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
self.hierarchicalFacets[idxAttributeName][facetIndex] = {
attribute: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
} else {
var isFacetDisjunctive = indexOf(state.disjunctiveFacets, facetKey) !== -1;
var isFacetConjunctive = indexOf(state.facets, facetKey) !== -1;
var position;
if (isFacetDisjunctive) {
position = disjunctiveFacetsIndices[facetKey];
self.disjunctiveFacets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey);
}
if (isFacetConjunctive) {
position = facetsIndices[facetKey];
self.facets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey);
}
}
});
// Make sure we do not keep holes within the hierarchical facets
this.hierarchicalFacets = compact(this.hierarchicalFacets);
// aggregate the refined disjunctive facets
forEach(disjunctiveFacets, function(disjunctiveFacet) {
var result = results[nextDisjunctiveResult];
var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet);
// There should be only item in facets.
forEach(result.facets, function(facetResults, dfacet) {
var position;
if (hierarchicalFacet) {
position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
self.hierarchicalFacets[position][attributeIndex].data = merge(
{},
self.hierarchicalFacets[position][attributeIndex].data,
facetResults
);
} else {
position = disjunctiveFacetsIndices[dfacet];
var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {};
self.disjunctiveFacets[position] = {
name: dfacet,
data: defaults({}, facetResults, dataFromMainRequest),
exhaustive: result.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet);
if (state.disjunctiveFacetsRefinements[dfacet]) {
forEach(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) {
// add the disjunctive refinements if it is no more retrieved
if (!self.disjunctiveFacets[position].data[refinementValue] &&
indexOf(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) {
self.disjunctiveFacets[position].data[refinementValue] = 0;
}
});
}
}
});
nextDisjunctiveResult++;
});
// if we have some root level values for hierarchical facets, merge them
forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are already at a root refinement (or no refinement at all), there is no
// root level values request
if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) {
return;
}
var result = results[nextDisjunctiveResult];
forEach(result.facets, function(facetResults, dfacet) {
var position = findIndex(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
// when we always get root levels, if the hits refinement is `beers > IPA` (count: 5),
// then the disjunctive values will be `beers` (count: 100),
// but we do not want to display
// | beers (100)
// > IPA (5)
// We want
// | beers (5)
// > IPA (5)
var defaultData = {};
if (currentRefinement.length > 0) {
var root = currentRefinement[0].split(separator)[0];
defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root];
}
self.hierarchicalFacets[position][attributeIndex].data = defaults(
defaultData,
facetResults,
self.hierarchicalFacets[position][attributeIndex].data
);
});
nextDisjunctiveResult++;
});
// add the excludes
forEach(state.facetsExcludes, function(excludes, facetName) {
var position = facetsIndices[facetName];
self.facets[position] = {
name: facetName,
data: mainSubResponse.facets[facetName],
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
forEach(excludes, function(facetValue) {
self.facets[position] = self.facets[position] || {name: facetName};
self.facets[position].data = self.facets[position].data || {};
self.facets[position].data[facetValue] = 0;
});
});
this.hierarchicalFacets = map(this.hierarchicalFacets, generateHierarchicalTree(state));
this.facets = compact(this.facets);
this.disjunctiveFacets = compact(this.disjunctiveFacets);
this._state = state;
}
/**
* Get a facet object with its name
* @deprecated
* @param {string} name name of the faceted attribute
* @return {SearchResults.Facet} the facet object
*/
SearchResults.prototype.getFacetByName = function(name) {
var predicate = {name: name};
return find(this.facets, predicate) ||
find(this.disjunctiveFacets, predicate) ||
find(this.hierarchicalFacets, predicate);
};
/**
* Get the facet values of a specified attribute from a SearchResults object.
* @private
* @param {SearchResults} results the search results to search in
* @param {string} attribute name of the 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(results.facets, predicate);
if (!facet) return [];
return map(facet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isFacetRefined(attribute, k),
isExcluded: results._state.isExcludeRefined(attribute, k)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return map(disjunctiveFacet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isDisjunctiveFacetRefined(attribute, k)
};
});
} else if (results._state.isHierarchicalFacet(attribute)) {
return find(results.hierarchicalFacets, predicate);
}
}
/**
* Sort nodes of a hierarchical facet results
* @private
* @param {HierarchicalFacet} node node to upon which we want to apply the sort
*/
function recSort(sortFn, node) {
if (!node.data || node.data.length === 0) {
return node;
}
var children = map(node.data, partial(recSort, sortFn));
var sortedChildren = sortFn(children);
var newNode = merge({}, node, {data: sortedChildren});
return newNode;
}
SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc'];
function vanillaSortFn(order, data) {
return data.sort(order);
}
/**
* Get a the list of values for a given facet attribute. Those values are sorted
* refinement first, descending count (bigger value on top), and name ascending
* (alphabetical order). The sort formula can overridden using either string based
* predicates or a function.
*
* This method will return all the values returned by the Algolia engine plus all
* the values already refined. This means that it can happen that the
* `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet)
* might not be respected if you have facet values that are already refined.
* @param {string} attribute attribute name
* @param {object} opts configuration options.
* @param {Array.<string> | function} opts.sortBy
* When using strings, it consists of
* the name of the [FacetValue](#SearchResults.FacetValue) or the
* [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the
* order (`asc` or `desc`). For example to order the value by count, the
* argument would be `['count:asc']`.
*
* If only the attribute name is specified, the ordering defaults to the one
* specified in the default value for this attribute.
*
* When not specified, the order is
* ascending. This parameter can also be a function which takes two facet
* values and should return a number, 0 if equal, 1 if the first argument is
* bigger or -1 otherwise.
*
* The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']`
* @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('results', function(content){
* //get values ordered only by name ascending using the string predicate
* content.getFacetValues('city', {sortBy: ['name:asc']});
* //get values ordered only by count ascending using a function
* content.getFacetValues('city', {
* // this is equivalent to ['count:asc']
* sortBy: function(a, b) {
* if (a.count === b.count) return 0;
* if (a.count > b.count) return 1;
* if (b.count > a.count) return -1;
* }
* });
* });
*/
SearchResults.prototype.getFacetValues = function(attribute, opts) {
var facetValues = extractNormalizedFacetValues(this, attribute);
if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.');
var options = defaults({}, opts, {sortBy: SearchResults.DEFAULT_SORT});
if (isArray(options.sortBy)) {
var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT);
if (isArray(facetValues)) {
return orderBy(facetValues, order[0], order[1]);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partialRight(orderBy, order[0], order[1]), facetValues);
} else if (isFunction(options.sortBy)) {
if (isArray(facetValues)) {
return facetValues.sort(options.sortBy);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partial(vanillaSortFn, options.sortBy), facetValues);
}
throw new Error(
'options.sortBy is optional but if defined it must be ' +
'either an array of string (predicates) or a sorting function'
);
};
/**
* Returns the facet stats if attribute is defined and the facet contains some.
* Otherwise returns undefined.
* @param {string} attribute name of the 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(facetList, {name: facetName});
return data && data.stats;
}
/**
* Returns all refinements for all filters + tags. It also provides
* additional information: count and exhausistivity for each filter.
*
* See the [refinement type](#Refinement) for an exhaustive view of the available
* data.
*
* @return {Array.<Refinement>} all the refinements
*/
SearchResults.prototype.getRefinements = function() {
var state = this._state;
var results = this;
var res = [];
forEach(state.facetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'facet', attributeName, name, results.facets));
});
});
forEach(state.facetsExcludes, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'exclude', attributeName, name, results.facets));
});
});
forEach(state.disjunctiveFacetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets));
});
});
forEach(state.hierarchicalFacetsRefinements, function(refinements, attributeName) {
forEach(refinements, function(name) {
res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets));
});
});
forEach(state.numericRefinements, function(operators, attributeName) {
forEach(operators, function(values, operator) {
forEach(values, function(value) {
res.push({
type: 'numeric',
attributeName: attributeName,
name: value,
numericValue: value,
operator: operator
});
});
});
});
forEach(state.tagRefinements, function(name) {
res.push({type: 'tag', attributeName: '_tags', name: name});
});
return res;
};
function getRefinement(state, type, attributeName, name, resultsFacets) {
var facet = find(resultsFacets, {name: attributeName});
var count = get(facet, 'data[' + name + ']');
var exhaustive = get(facet, 'exhaustive');
return {
type: type,
attributeName: attributeName,
name: name,
count: count || 0,
exhaustive: exhaustive || false
};
}
function getHierarchicalRefinement(state, attributeName, name, resultsFacets) {
var facet = find(resultsFacets, {name: attributeName});
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var splitted = name.split(facetDeclaration.separator);
var configuredName = splitted[splitted.length - 1];
for (var i = 0; facet !== undefined && i < splitted.length; ++i) {
facet = find(facet.data, {name: splitted[i]});
}
var count = get(facet, 'count');
var exhaustive = get(facet, 'exhaustive');
return {
type: 'hierarchical',
attributeName: attributeName,
name: configuredName,
count: count || 0,
exhaustive: exhaustive || false
};
}
module.exports = SearchResults;
/***/ }),
/* 191 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(26),
metaMap = __webpack_require__(192);
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
module.exports = baseSetData;
/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {
var WeakMap = __webpack_require__(90);
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
module.exports = metaMap;
/***/ }),
/* 193 */
/***/ (function(module, exports, __webpack_require__) {
var composeArgs = __webpack_require__(194),
composeArgsRight = __webpack_require__(195),
countHolders = __webpack_require__(296),
createCtor = __webpack_require__(75),
createRecurry = __webpack_require__(196),
getHolder = __webpack_require__(54),
reorder = __webpack_require__(306),
replaceHolders = __webpack_require__(37),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_ARY_FLAG = 128,
WRAP_FLIP_FLAG = 512;
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG,
isBind = bitmask & WRAP_BIND_FLAG,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
isFlip = bitmask & WRAP_FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = getHolder(wrapper),
holdersCount = countHolders(args, placeholder);
}
if (partials) {
args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
fn = Ctor || createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
module.exports = createHybrid;
/***/ }),
/* 194 */
/***/ (function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
module.exports = composeArgs;
/***/ }),
/* 195 */
/***/ (function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
module.exports = composeArgsRight;
/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {
var isLaziable = __webpack_require__(297),
setData = __webpack_require__(199),
setWrapToString = __webpack_require__(200);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64;
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return setWrapToString(result, func, bitmask);
}
module.exports = createRecurry;
/***/ }),
/* 197 */
/***/ (function(module, exports, __webpack_require__) {
var metaMap = __webpack_require__(192),
noop = __webpack_require__(298);
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
module.exports = getData;
/***/ }),
/* 198 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(70),
baseLodash = __webpack_require__(107);
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
module.exports = LodashWrapper;
/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetData = __webpack_require__(191),
shortOut = __webpack_require__(169);
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = shortOut(baseSetData);
module.exports = setData;
/***/ }),
/* 200 */
/***/ (function(module, exports, __webpack_require__) {
var getWrapDetails = __webpack_require__(303),
insertWrapDetails = __webpack_require__(304),
setToString = __webpack_require__(93),
updateWrapDetails = __webpack_require__(305);
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/
function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
}
module.exports = setWrapToString;
/***/ }),
/* 201 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var reduce = __webpack_require__(50);
var find = __webpack_require__(53);
var startsWith = __webpack_require__(310);
/**
* Transform sort format from user friendly notation to lodash format
* @param {string[]} sortBy array of predicate of the form "attribute:order"
* @return {array.<string[]>} array containing 2 elements : attributes, orders
*/
module.exports = function formatSort(sortBy, defaults) {
return reduce(sortBy, function preparePredicate(out, sortInstruction) {
var sortInstructions = sortInstruction.split(':');
if (defaults && sortInstructions.length === 1) {
var similarDefault = find(defaults, function(predicate) {
return startsWith(predicate, sortInstruction[0]);
});
if (similarDefault) {
sortInstructions = similarDefault.split(':');
}
}
out[0].push(sortInstructions[0]);
out[1].push(sortInstructions[1]);
return out;
}, [[], []]);
};
/***/ }),
/* 202 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(71),
baseSet = __webpack_require__(314),
castPath = __webpack_require__(22);
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = baseGet(object, path);
if (predicate(value, path)) {
baseSet(result, castPath(path, object), value);
}
}
return result;
}
module.exports = basePickBy;
/***/ }),
/* 203 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = __webpack_require__(316);
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = __webpack_require__(317);
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55), __webpack_require__(109)))
/***/ }),
/* 204 */
/***/ (function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
/***/ }),
/* 205 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Module containing the functions to serialize and deserialize
* {SearchParameters} in the query string format
* @module algoliasearchHelper.url
*/
var shortener = __webpack_require__(319);
var SearchParameters = __webpack_require__(100);
var qs = __webpack_require__(322);
var bind = __webpack_require__(325);
var forEach = __webpack_require__(36);
var pick = __webpack_require__(110);
var map = __webpack_require__(17);
var mapKeys = __webpack_require__(327);
var mapValues = __webpack_require__(328);
var isString = __webpack_require__(52);
var isPlainObject = __webpack_require__(45);
var isArray = __webpack_require__(1);
var isEmpty = __webpack_require__(14);
var invert = __webpack_require__(206);
var encode = __webpack_require__(108).encode;
function recursiveEncode(input) {
if (isPlainObject(input)) {
return mapValues(input, recursiveEncode);
}
if (isArray(input)) {
return map(input, recursiveEncode);
}
if (isString(input)) {
return encode(input);
}
return input;
}
var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR'];
var stateKeys = shortener.ENCODED_PARAMETERS;
function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) {
if (prefixRegexp !== null) {
a = a.replace(prefixRegexp, '');
b = b.replace(prefixRegexp, '');
}
a = invertedMapping[a] || a;
b = invertedMapping[b] || b;
if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) {
if (a === 'q') return -1;
if (b === 'q') return 1;
var isARefinements = refinementsParameters.indexOf(a) !== -1;
var isBRefinements = refinementsParameters.indexOf(b) !== -1;
if (isARefinements && !isBRefinements) {
return 1;
} else if (isBRefinements && !isARefinements) {
return -1;
}
}
return a.localeCompare(b);
}
/**
* Read a query string and return an object containing the state
* @param {string} queryString the query string that will be decoded
* @param {object} [options] accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
*/
exports.getStateFromQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var invertedMapping = invert(mapping);
var partialStateWithPrefix = qs.parse(queryString);
var prefixRegexp = new RegExp('^' + prefixForParameters);
var partialState = mapKeys(
partialStateWithPrefix,
function(v, k) {
var hasPrefix = prefixForParameters && prefixRegexp.test(k);
var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k;
var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey);
return decodedKey || unprefixedKey;
}
);
var partialStateWithParsedNumbers = SearchParameters._parseNumbers(partialState);
return pick(partialStateWithParsedNumbers, SearchParameters.PARAMETERS);
};
/**
* Retrieve an object of all the properties that are not understandable as helper
* parameters.
* @param {string} queryString the query string to read
* @param {object} [options] the options
* - prefixForParameters : prefix used for the helper configuration keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
exports.getUnrecognizedParametersInQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix;
var mapping = options && options.mapping || {};
var invertedMapping = invert(mapping);
var foreignConfig = {};
var config = qs.parse(queryString);
if (prefixForParameters) {
var prefixRegexp = new RegExp('^' + prefixForParameters);
forEach(config, function(v, key) {
if (!prefixRegexp.test(key)) foreignConfig[key] = v;
});
} else {
forEach(config, function(v, key) {
if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v;
});
}
return foreignConfig;
};
/**
* Generate a query string for the state passed according to the options
* @param {SearchParameters} state state to serialize
* @param {object} [options] May contain the following parameters :
* - prefix : prefix in front of the keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* - moreAttributes : more values to be added in the query string. Those values
* won't be prefixed.
* - safe : get safe urls for use in emails, chat apps or any application auto linking urls.
* All parameters and values will be encoded in a way that it's safe to share them.
* Default to false for legacy reasons ()
* @return {string} the query string
*/
exports.getQueryStringFromState = function(state, options) {
var moreAttributes = options && options.moreAttributes;
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var safe = options && options.safe || false;
var invertedMapping = invert(mapping);
var stateForUrl = safe ? state : recursiveEncode(state);
var encodedState = mapKeys(
stateForUrl,
function(v, k) {
var shortK = shortener.encode(k);
return prefixForParameters + (mapping[shortK] || shortK);
}
);
var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters);
var sort = bind(sortQueryStringValues, null, prefixRegexp, invertedMapping);
if (!isEmpty(moreAttributes)) {
var stateQs = qs.stringify(encodedState, {encode: safe, sort: sort});
var moreQs = qs.stringify(moreAttributes, {encode: safe});
if (!stateQs) return moreQs;
return stateQs + '&' + moreQs;
}
return qs.stringify(encodedState, {encode: safe, sort: sort});
};
/***/ }),
/* 206 */
/***/ (function(module, exports, __webpack_require__) {
var constant = __webpack_require__(167),
createInverter = __webpack_require__(320),
identity = __webpack_require__(26);
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = createInverter(function(result, value, key) {
result[value] = key;
}, constant(identity));
module.exports = invert;
/***/ }),
/* 207 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
module.exports = {
'default': 'RFC3986',
formatters: {
RFC1738: function (value) {
return replace.call(value, percentTwenties, '+');
},
RFC3986: function (value) {
return value;
}
},
RFC1738: 'RFC1738',
RFC3986: 'RFC3986'
};
/***/ }),
/* 208 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = '2.21.2';
/***/ }),
/* 209 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _indexUtils = __webpack_require__(5);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* connectRange connector provides the logic to create connected
* components that will give the ability for a user to refine results using
* a numeric range.
* @name connectRange
* @kind connector
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @propType {string} attributeName - Name of the attribute for faceting
* @propType {{min: number, max: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
*/
function getId(props) {
return props.attributeName;
}
var namespace = 'range';
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), {}, function (currentRefinement) {
var min = currentRefinement.min,
max = currentRefinement.max;
if (typeof min === 'string') {
min = parseInt(min, 10);
}
if (typeof max === 'string') {
max = parseInt(max, 10);
}
return { min: min, max: max };
});
}
function _refine(props, searchState, nextRefinement, context) {
if (!isFinite(nextRefinement.min) || !isFinite(nextRefinement.max)) {
throw new Error("You can't provide non finite values to the range connector");
}
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaRange',
propTypes: {
id: _propTypes2.default.string,
attributeName: _propTypes2.default.string.isRequired,
defaultRefinement: _propTypes2.default.shape({
min: _propTypes2.default.number.isRequired,
max: _propTypes2.default.number.isRequired
}),
min: _propTypes2.default.number,
max: _propTypes2.default.number
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attributeName = props.attributeName;
var min = props.min,
max = props.max;
var hasMin = typeof min !== 'undefined';
var hasMax = typeof max !== 'undefined';
var results = (0, _indexUtils.getResults)(searchResults, this.context);
if (!hasMin || !hasMax) {
if (!results) {
return {
canRefine: false
};
}
var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null;
if (!stats) {
return {
canRefine: false
};
}
if (!hasMin) {
min = stats.min;
}
if (!hasMax) {
max = stats.max;
}
}
var count = results ? results.getFacetValues(attributeName).map(function (v) {
return {
value: v.name,
count: v.count
};
}) : [];
var _getCurrentRefinement = getCurrentRefinement(props, searchState, this.context),
_getCurrentRefinement2 = _getCurrentRefinement.min,
valueMin = _getCurrentRefinement2 === undefined ? min : _getCurrentRefinement2,
_getCurrentRefinement3 = _getCurrentRefinement.max,
valueMax = _getCurrentRefinement3 === undefined ? max : _getCurrentRefinement3;
return {
min: min,
max: max,
currentRefinement: { min: valueMin, max: valueMax },
count: count,
canRefine: count.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(params, props, searchState) {
var attributeName = props.attributeName;
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
params = params.addDisjunctiveFacet(attributeName);
var min = currentRefinement.min,
max = currentRefinement.max;
if (typeof min !== 'undefined') {
params = params.addNumericRefinement(attributeName, '>=', min);
}
if (typeof max !== 'undefined') {
params = params.addNumericRefinement(attributeName, '<=', max);
}
return params;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var item = void 0;
var hasMin = typeof currentRefinement.min !== 'undefined';
var hasMax = typeof currentRefinement.max !== 'undefined';
if (hasMin || hasMax) {
var itemLabel = '';
if (hasMin) {
itemLabel += currentRefinement.min + ' <= ';
}
itemLabel += props.attributeName;
if (hasMax) {
itemLabel += ' <= ' + currentRefinement.max;
}
item = {
label: itemLabel,
currentRefinement: currentRefinement,
attributeName: props.attributeName,
value: function value(nextState) {
return _cleanUp(props, nextState, _this.context);
}
};
}
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: item ? [item] : []
};
}
});
/***/ }),
/* 210 */,
/* 211 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectCurrentRefinements connector provides the logic to build a widget that will
* give the user the ability to remove all or some of the filters that were
* set.
* @name connectCurrentRefinements
* @kind connector
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {function} [clearsQuery=false] - Pass true to also clear the search query
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {array.<{label: string, attributeName: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attributeName` and `currentRefinement` are metadata containing row values.
* @providedPropType {string} query - the search query
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaCurrentRefinements',
propTypes: {
transformItems: _propTypes2.default.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) {
var items = metadata.reduce(function (res, meta) {
if (typeof meta.items !== 'undefined') {
if (!props.clearsQuery && meta.id === 'query') {
return res;
} else {
if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') {
return res;
}
return res.concat(meta.items);
}
}
return res;
}, []);
return {
items: props.transformItems ? props.transformItems(items) : items,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, items) {
// `value` corresponds to our internal clear function computed in each connector metadata.
var refinementsToClear = items instanceof Array ? items.map(function (item) {
return item.value;
}) : [items];
return refinementsToClear.reduce(function (res, clear) {
return clear(res);
}, searchState);
}
});
/***/ }),
/* 212 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var AlgoliaSearchHelper = __webpack_require__(249);
var SearchParameters = __webpack_require__(100);
var SearchResults = __webpack_require__(190);
/**
* The algoliasearchHelper module is the function that will let its
* contains everything needed to use the Algoliasearch
* Helper. It is a also a function that instanciate the helper.
* To use the helper, you also need the Algolia JS client v3.
* @example
* //using the UMD build
* var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
* var helper = algoliasearchHelper(client, 'bestbuy', {
* facets: ['shipping'],
* disjunctiveFacets: ['category']
* });
* helper.on('result', function(result) {
* console.log(result);
* });
* helper.toggleRefine('Movies & TV Shows')
* .toggleRefine('Free shipping')
* .search();
* @example
* // The helper is an event emitter using the node API
* helper.on('result', updateTheResults);
* helper.once('result', updateTheResults);
* helper.removeListener('result', updateTheResults);
* helper.removeAllListeners('result');
* @module algoliasearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the name of the index to query
* @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
* @return {AlgoliaSearchHelper}
*/
function algoliasearchHelper(client, index, opts) {
return new AlgoliaSearchHelper(client, index, opts);
}
/**
* The version currently used
* @member module:algoliasearchHelper.version
* @type {number}
*/
algoliasearchHelper.version = __webpack_require__(208);
/**
* Constructor for the Helper.
* @member module:algoliasearchHelper.AlgoliaSearchHelper
* @type {AlgoliaSearchHelper}
*/
algoliasearchHelper.AlgoliaSearchHelper = AlgoliaSearchHelper;
/**
* Constructor for the object containing all the parameters of the search.
* @member module:algoliasearchHelper.SearchParameters
* @type {SearchParameters}
*/
algoliasearchHelper.SearchParameters = SearchParameters;
/**
* Constructor for the object containing the results of the search.
* @member module:algoliasearchHelper.SearchResults
* @type {SearchResults}
*/
algoliasearchHelper.SearchResults = SearchResults;
/**
* URL tools to generate query string and parse them from/into
* SearchParameters
* @member module:algoliasearchHelper.url
* @type {object} {@link url}
*
*/
algoliasearchHelper.url = __webpack_require__(205);
module.exports = algoliasearchHelper;
/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {
var toNumber = __webpack_require__(266);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
module.exports = toFinite;
/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {
var isNumber = __webpack_require__(184);
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}
module.exports = isNaN;
/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(18),
isArrayLike = __webpack_require__(11),
isIndex = __webpack_require__(32),
isObject = __webpack_require__(6);
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
module.exports = isIterateeCall;
/***/ }),
/* 216 */,
/* 217 */,
/* 218 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _highlight = __webpack_require__(330);
var _highlight2 = _interopRequireDefault(_highlight);
var _highlightTags = __webpack_require__(219);
var _highlightTags2 = _interopRequireDefault(_highlightTags);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var highlight = function highlight(_ref) {
var attributeName = _ref.attributeName,
hit = _ref.hit,
highlightProperty = _ref.highlightProperty;
return (0, _highlight2.default)({
attributeName: attributeName,
hit: hit,
preTag: _highlightTags2.default.highlightPreTag,
postTag: _highlightTags2.default.highlightPostTag,
highlightProperty: highlightProperty
});
};
/**
* connectHighlight connector provides the logic to create an highlighter
* component that will retrieve, parse and render an highlighted attribute
* from an Algolia hit.
* @name connectHighlight
* @kind connector
* @category connector
* @providedPropType {function} highlight - the function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attribute: `highlightProperty` which is the property that contains the highlight structure from the records, `attributeName` which is the name of the attribute to look for and `hit` which is the hit from Algolia. It returns an array of object `{value: string, isHighlighted: boolean}`.
* @example
* import React from 'react';
* import { connectHighlight } from 'react-instantsearch/connectors';
* import { InstantSearch, Hits } from 'react-instantsearch/dom';
*
* const CustomHighlight = connectHighlight(
* ({ highlight, attributeName, hit, highlightProperty }) => {
* const parsedHit = highlight({ attributeName, hit, highlightProperty: '_highlightResult' });
* const highlightedHits = parsedHit.map(part => {
* if (part.isHighlighted) return <mark>{part.value}</mark>;
* return part.value;
* });
* return <div>{highlightedHits}</div>;
* }
* );
*
* const Hit = ({hit}) =>
* <p>
* <CustomHighlight attributeName="description" hit={hit} />
* </p>;
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea">
* <Hits hitComponent={Hit} />
* </InstantSearch>
* );
* }
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHighlighter',
propTypes: {},
getProvidedProps: function getProvidedProps() {
return { highlight: highlight };
}
});
/***/ }),
/* 219 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
highlightPreTag: "<ais-highlight>",
highlightPostTag: "</ais-highlight>"
};
/***/ }),
/* 220 */,
/* 221 */,
/* 222 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys2 = __webpack_require__(9);
var _keys3 = _interopRequireDefault(_keys2);
var _difference2 = __webpack_require__(223);
var _difference3 = _interopRequireDefault(_difference2);
var _omit2 = __webpack_require__(35);
var _omit3 = _interopRequireDefault(_omit2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'configure';
}
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaConfigure',
getProvidedProps: function getProvidedProps() {
return {};
},
getSearchParameters: function getSearchParameters(searchParameters, props) {
var items = (0, _omit3.default)(props, 'children');
return searchParameters.setQueryParameters(items);
},
transitionState: function transitionState(props, prevSearchState, nextSearchState) {
var id = getId();
var items = (0, _omit3.default)(props, 'children');
var nonPresentKeys = this._props ? (0, _difference3.default)((0, _keys3.default)(this._props), (0, _keys3.default)(props)) : [];
this._props = props;
var nextValue = _defineProperty({}, id, _extends({}, (0, _omit3.default)(nextSearchState[id], nonPresentKeys), items));
return (0, _indexUtils.refineValue)(nextSearchState, nextValue, this.context);
},
cleanUp: function cleanUp(props, searchState) {
var id = getId();
var index = (0, _indexUtils.getIndex)(this.context);
var subState = (0, _indexUtils.hasMultipleIndex)(this.context) && searchState.indices ? searchState.indices[index] : searchState;
var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : [];
var configureState = configureKeys.reduce(function (acc, item) {
if (!props[item]) {
acc[item] = subState[id][item];
}
return acc;
}, {});
var nextValue = _defineProperty({}, id, configureState);
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context);
}
});
/***/ }),
/* 223 */
/***/ (function(module, exports, __webpack_require__) {
var baseDifference = __webpack_require__(224),
baseFlatten = __webpack_require__(165),
baseRest = __webpack_require__(25),
isArrayLikeObject = __webpack_require__(94);
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
: [];
});
module.exports = difference;
/***/ }),
/* 224 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(60),
arrayIncludes = __webpack_require__(92),
arrayIncludesWith = __webpack_require__(164),
arrayMap = __webpack_require__(12),
baseUnary = __webpack_require__(43),
cacheHas = __webpack_require__(61);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
module.exports = baseDifference;
/***/ }),
/* 225 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
module.exports = baseIsNaN;
/***/ }),
/* 226 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
module.exports = strictIndexOf;
/***/ }),
/* 227 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16),
isArguments = __webpack_require__(20),
isArray = __webpack_require__(1);
/** Built-in value references. */
var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
module.exports = isFlattenable;
/***/ }),
/* 228 */
/***/ (function(module, exports, __webpack_require__) {
var constant = __webpack_require__(167),
defineProperty = __webpack_require__(168),
identity = __webpack_require__(26);
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
module.exports = baseSetToString;
/***/ }),
/* 229 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
arrayEach = __webpack_require__(95),
assignValue = __webpack_require__(96),
baseAssign = __webpack_require__(230),
baseAssignIn = __webpack_require__(231),
cloneBuffer = __webpack_require__(170),
copyArray = __webpack_require__(69),
copySymbols = __webpack_require__(234),
copySymbolsIn = __webpack_require__(235),
getAllKeys = __webpack_require__(85),
getAllKeysIn = __webpack_require__(97),
getTag = __webpack_require__(57),
initCloneArray = __webpack_require__(236),
initCloneByTag = __webpack_require__(237),
initCloneObject = __webpack_require__(173),
isArray = __webpack_require__(1),
isBuffer = __webpack_require__(21),
isObject = __webpack_require__(6),
keys = __webpack_require__(9);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, baseClone, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
module.exports = baseClone;
/***/ }),
/* 230 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
keys = __webpack_require__(9);
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
module.exports = baseAssign;
/***/ }),
/* 231 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
keysIn = __webpack_require__(48);
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
module.exports = baseAssignIn;
/***/ }),
/* 232 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(6),
isPrototype = __webpack_require__(38),
nativeKeysIn = __webpack_require__(233);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = baseKeysIn;
/***/ }),
/* 233 */
/***/ (function(module, exports) {
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
module.exports = nativeKeysIn;
/***/ }),
/* 234 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
getSymbols = __webpack_require__(63);
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
module.exports = copySymbols;
/***/ }),
/* 235 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
getSymbolsIn = __webpack_require__(171);
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
module.exports = copySymbolsIn;
/***/ }),
/* 236 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
module.exports = initCloneArray;
/***/ }),
/* 237 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(98),
cloneDataView = __webpack_require__(238),
cloneMap = __webpack_require__(239),
cloneRegExp = __webpack_require__(241),
cloneSet = __webpack_require__(242),
cloneSymbol = __webpack_require__(244),
cloneTypedArray = __webpack_require__(172);
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, cloneFunc, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return cloneMap(object, isDeep, cloneFunc);
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return cloneSet(object, isDeep, cloneFunc);
case symbolTag:
return cloneSymbol(object);
}
}
module.exports = initCloneByTag;
/***/ }),
/* 238 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(98);
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
module.exports = cloneDataView;
/***/ }),
/* 239 */
/***/ (function(module, exports, __webpack_require__) {
var addMapEntry = __webpack_require__(240),
arrayReduce = __webpack_require__(99),
mapToArray = __webpack_require__(83);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a clone of `map`.
*
* @private
* @param {Object} map The map to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned map.
*/
function cloneMap(map, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map);
return arrayReduce(array, addMapEntry, new map.constructor);
}
module.exports = cloneMap;
/***/ }),
/* 240 */
/***/ (function(module, exports) {
/**
* Adds the key-value `pair` to `map`.
*
* @private
* @param {Object} map The map to modify.
* @param {Array} pair The key-value pair to add.
* @returns {Object} Returns `map`.
*/
function addMapEntry(map, pair) {
// Don't return `map.set` because it's not chainable in IE 11.
map.set(pair[0], pair[1]);
return map;
}
module.exports = addMapEntry;
/***/ }),
/* 241 */
/***/ (function(module, exports) {
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
module.exports = cloneRegExp;
/***/ }),
/* 242 */
/***/ (function(module, exports, __webpack_require__) {
var addSetEntry = __webpack_require__(243),
arrayReduce = __webpack_require__(99),
setToArray = __webpack_require__(84);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a clone of `set`.
*
* @private
* @param {Object} set The set to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned set.
*/
function cloneSet(set, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set);
return arrayReduce(array, addSetEntry, new set.constructor);
}
module.exports = cloneSet;
/***/ }),
/* 243 */
/***/ (function(module, exports) {
/**
* Adds `value` to `set`.
*
* @private
* @param {Object} set The set to modify.
* @param {*} value The value to add.
* @returns {Object} Returns `set`.
*/
function addSetEntry(set, value) {
// Don't return `set.add` because it's not chainable in IE 11.
set.add(value);
return set;
}
module.exports = addSetEntry;
/***/ }),
/* 244 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(16);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
module.exports = cloneSymbol;
/***/ }),
/* 245 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(22),
last = __webpack_require__(174),
parent = __webpack_require__(246),
toKey = __webpack_require__(24);
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
module.exports = baseUnset;
/***/ }),
/* 246 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(71),
baseSlice = __webpack_require__(175);
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
module.exports = parent;
/***/ }),
/* 247 */
/***/ (function(module, exports, __webpack_require__) {
var isPlainObject = __webpack_require__(45);
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject(value) ? undefined : value;
}
module.exports = customOmitClone;
/***/ }),
/* 248 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getId = undefined;
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _algoliasearchHelper = __webpack_require__(212);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var getId = exports.getId = function getId(props) {
return props.attributes[0];
};
var namespace = 'hierarchicalMenu';
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), null, function (currentRefinement) {
if (currentRefinement === '') {
return null;
}
return currentRefinement;
});
}
function getValue(path, props, searchState, context) {
var id = props.id,
attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel;
var currentRefinement = getCurrentRefinement(props, searchState, context);
var nextRefinement = void 0;
if (currentRefinement === null) {
nextRefinement = path;
} else {
var tmpSearchParameters = new _algoliasearchHelper.SearchParameters({
hierarchicalFacets: [{
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}]
});
nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0];
}
return nextRefinement;
}
function transformValue(value, limit, props, searchState, context) {
return value.slice(0, limit).map(function (v) {
return {
label: v.name,
value: getValue(v.path, props, searchState, context),
count: v.count,
isRefined: v.isRefined,
items: v.data && transformValue(v.data, limit, props, searchState, context)
};
});
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement || '');
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
var sortBy = ['name:asc'];
/**
* connectHierarchicalMenu connector provides the logic to build a widget that will
* give the user the ability to explore a tree-like structure.
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
* @name connectHierarchicalMenu
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax.
* @propType {number} [limitMin=10] - The maximum number of items displayed.
* @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string[]} [rootPath=null] - The already selected and hidden path.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHierarchicalMenu',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings');
}
return undefined;
},
separator: _propTypes2.default.string,
rootPath: _propTypes2.default.string,
showParentLevel: _propTypes2.default.bool,
defaultRefinement: _propTypes2.default.string,
showMore: _propTypes2.default.bool,
limitMin: _propTypes2.default.number,
limitMax: _propTypes2.default.number,
transformItems: _propTypes2.default.func
},
defaultProps: {
showMore: false,
limitMin: 10,
limitMax: 20,
separator: ' > ',
rootPath: null,
showParentLevel: true
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var id = getId(props);
var results = (0, _indexUtils.getResults)(searchResults, this.context);
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: false
};
}
var limit = showMore ? limitMax : limitMin;
var value = results.getFacetValues(id, { sortBy: sortBy });
var items = value.data ? transformValue(value.data, limit, props, searchState, this.context) : [];
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var id = getId(props);
var limit = showMore ? limitMax : limitMin;
searchParameters = searchParameters.addHierarchicalFacet({
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}).setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
if (currentRefinement !== null) {
searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var rootAttribute = props.attributes[0];
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: !currentRefinement ? [] : [{
label: rootAttribute + ': ' + currentRefinement,
attributeName: rootAttribute,
value: function value(nextState) {
return _refine(props, nextState, '', _this.context);
},
currentRefinement: currentRefinement
}]
};
}
});
/***/ }),
/* 249 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var SearchParameters = __webpack_require__(100);
var SearchResults = __webpack_require__(190);
var DerivedHelper = __webpack_require__(315);
var requestBuilder = __webpack_require__(318);
var util = __webpack_require__(203);
var events = __webpack_require__(204);
var flatten = __webpack_require__(177);
var forEach = __webpack_require__(36);
var isEmpty = __webpack_require__(14);
var map = __webpack_require__(17);
var url = __webpack_require__(205);
var version = __webpack_require__(208);
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {SearchParameters} state the current parameters with the latest changes applied
* @property {SearchResults} lastResults the previous results received from Algolia. `null` before
* the first request
* @example
* helper.on('change', function(state, lastResults) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when a main search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {SearchParameters} state the parameters used for this search
* @property {SearchResults} lastResults the results from the previous search. `null` if
* it is the first search.
* @example
* helper.on('search', function(state, lastResults) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when a search using `searchForFacetValues` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchForFacetValues
* @property {SearchParameters} state the parameters used for this search
* it is the first search.
* @property {string} facet the facet searched into
* @property {string} query the query used to search in the facets
* @example
* helper.on('searchForFacetValues', function(state, facet, query) {
* console.log('searchForFacetValues sent');
* });
*/
/**
* Event triggered when a search using `searchOnce` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchOnce
* @property {SearchParameters} state the parameters used for this search
* it is the first search.
* @example
* helper.on('searchOnce', function(state) {
* console.log('searchOnce sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {SearchResults} results the results received from Algolia
* @property {SearchParameters} state the parameters used to query Algolia. Those might
* be different from the one in the helper instance (for example if the network is unreliable).
* @example
* helper.on('result', function(results, state) {
* console.log('Search results received');
* });
*/
/**
* Event triggered when Algolia sends back an error. For example, if an unknown parameter is
* used, the error can be caught using this event.
* @event AlgoliaSearchHelper#event:error
* @property {Error} error the error returned by the Algolia.
* @example
* helper.on('error', function(error) {
* console.log('Houston we got a problem.');
* });
*/
/**
* Event triggered when the queue of queries have been depleted (with any result or outdated queries)
* @event AlgoliaSearchHelper#event:searchQueueEmpty
* @example
* helper.on('searchQueueEmpty', function() {
* console.log('No more search pending');
* // This is received before the result event if we're not expecting new results
* });
*
* helper.search();
*/
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
* search. It provides an event based interface for search callbacks:
* - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the
* {@link SearchResults} of the last result if any.
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial
* config of the search. It doesn't have to be a {SearchParameters},
* just an object containing the properties you need from it.
*/
function AlgoliaSearchHelper(client, index, options) {
if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line
else if (!doesClientAgentContainsHelper(client)) client.addAlgoliaAgent('JS Helper ' + version);
this.setClient(client);
var opts = options || {};
opts.index = index;
this.state = SearchParameters.make(opts);
this.lastResults = null;
this._queryId = 0;
this._lastQueryIdReceived = -1;
this.derivedHelpers = [];
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._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._getQueries(tempState.index, tempState);
var self = this;
this._currentNbQueries++;
this.emit('searchOnce', tempState);
if (cb) {
return this.client.search(
queries,
function(err, content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
if (err) cb(err, null, tempState);
else cb(err, new SearchResults(tempState, content.results), tempState);
}
);
}
return this.client.search(queries).then(function(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
return {
content: new SearchResults(tempState, content.results),
state: tempState,
_originalResponse: content
};
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Structure of each result when using
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* @typedef FacetSearchHit
* @type {object}
* @property {string} value the facet value
* @property {string} highlighted the facet value highlighted with the query string
* @property {number} count number of occurrence of this facet value
* @property {boolean} isRefined true if the value is already refined
*/
/**
* Structure of the data resolved by the
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* promise.
* @typedef FacetSearchResult
* @type {object}
* @property {FacetSearchHit} facetHits the results for this search for facet values
* @property {number} processingTimeMS time taken by the query inside the engine
*/
/**
* Search for facet values based on an query and the name of a faceted attribute. This
* triggers a search and will return a promise. On top of using the query, it also sends
* the parameters from the state so that the search is narrowed down to only the possible values.
*
* See the description of [FacetSearchResult](reference.html#FacetSearchResult)
* @param {string} facet the name of the faceted attribute
* @param {string} query the string query for the search
* @param {number} maxFacetHits the maximum number values returned. Should be > 0 and <= 100
* @return {promise<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits) {
var state = this.state;
var index = this.client.initIndex(this.state.index);
var isDisjunctive = state.isDisjunctiveFacet(facet);
var algoliaQuery = requestBuilder.getSearchForFacetQuery(facet, query, maxFacetHits, this.state);
this._currentNbQueries++;
var self = this;
this.emit('searchForFacetValues', state, facet, query);
return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
content.facetHits = forEach(content.facetHits, function(f) {
f.isRefined = isDisjunctive ?
state.isDisjunctiveFacetRefined(facet, f.value) :
state.isFacetRefined(facet, f.value);
});
return content;
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Sets the text query used for the search.
*
* This method resets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setQuery = function(q) {
this.state = this.state.setPage(0).setQuery(q);
this._change();
return this;
};
/**
* Remove all the types of refinements except tags. A string can be provided to remove
* only the refinements of a specific attribute. For more advanced use case, you can
* provide a function instead. This function should follow the
* [clearCallback definition](#SearchParameters.clearCallback).
*
* This method resets the current page to 0.
* @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* // Removing all the refinements
* helper.clearRefinements().search();
* @example
* // Removing all the filters on a the category attribute.
* helper.clearRefinements('category').search();
* @example
* // Removing only the exclude filters on the category facet.
* helper.clearRefinements(function(value, attribute, type) {
* return type === 'exclude' && attribute === 'category';
* }).search();
*/
AlgoliaSearchHelper.prototype.clearRefinements = function(name) {
this.state = this.state.setPage(0).clearRefinements(name);
this._change();
return this;
};
/**
* Remove all the tag filters.
*
* This method resets the current page to 0.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.clearTags = function() {
this.state = this.state.setPage(0).clearTags();
this._change();
return this;
};
/**
* Adds a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() {
return this.addDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Adds a refinement on a hierarchical facet. It will throw
* an exception if the facet is not defined or if the facet
* is already refined.
*
* This method resets the current page to 0.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is refined
* @chainable
* @fires change
*/
AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value);
this._change();
return this;
};
/**
* Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} operator the operator of the filter
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Adds a filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addRefine = function() {
return this.addFacetRefinement.apply(this, arguments);
};
/**
* Adds a an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).addExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion}
*/
AlgoliaSearchHelper.prototype.addExclude = function() {
return this.addFacetExclusion.apply(this, arguments);
};
/**
* Adds a tag filter with the `tag` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addTag = function(tag) {
this.state = this.state.setPage(0).addTagRefinement(tag);
this._change();
return this;
};
/**
* Removes an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* Some parameters are optional, triggering different behavior:
* - if the value is not provided, then all the numeric value will be removed for the
* specified attribute/operator couple.
* - if the operator is not provided either, then all the numeric filter on this attribute
* will be removed.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} [operator] the operator of the filter
* @param {number} [value] the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Removes a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() {
return this.removeDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is not refined
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) {
this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet);
this._change();
return this;
};
/**
* Removes a filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeRefine = function() {
return this.removeFacetRefinement.apply(this, arguments);
};
/**
* Removes an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).removeExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion}
*/
AlgoliaSearchHelper.prototype.removeExclude = function() {
return this.removeFacetExclusion.apply(this, arguments);
};
/**
* Removes a tag filter with the `tag` provided. If the
* filter is not set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeTag = function(tag) {
this.state = this.state.setPage(0).removeTagRefinement(tag);
this._change();
return this;
};
/**
* Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion}
*/
AlgoliaSearchHelper.prototype.toggleExclude = function() {
return this.toggleFacetExclusion.apply(this, arguments);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
* @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) {
return this.toggleFacetRefinement(facet, value);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).toggleFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefine = function() {
return this.toggleFacetRefinement.apply(this, arguments);
};
/**
* Adds or removes a tag filter with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleTag = function(tag) {
this.state = this.state.setPage(0).toggleTagRefinement(tag);
this._change();
return this;
};
/**
* Increments the page number by one.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setPage(0).nextPage().getPage();
* // returns 1
*/
AlgoliaSearchHelper.prototype.nextPage = function() {
return this.setPage(this.state.page + 1);
};
/**
* Decrements the page number by one.
* @fires change
* @return {AlgoliaSearchHelper}
* @chainable
* @example
* helper.setPage(1).previousPage().getPage();
* // returns 0
*/
AlgoliaSearchHelper.prototype.previousPage = function() {
return this.setPage(this.state.page - 1);
};
/**
* @private
*/
function setCurrentPage(page) {
if (page < 0) throw new Error('Page requested below 0.');
this.state = this.state.setPage(page);
this._change();
return this;
}
/**
* Change the current page
* @deprecated
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage;
/**
* Updates the current page.
* @function
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setPage = setCurrentPage;
/**
* Updates the name of the index that will be targeted by the query.
*
* This method resets the current page to 0.
* @param {string} name the index name
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setIndex = function(name) {
this.state = this.state.setPage(0).setIndex(name);
this._change();
return this;
};
/**
* Update a parameter of the search. This method reset the page
*
* The complete list of parameters is available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters and facets have their own API)
*
* This method resets the current page to 0.
* @param {string} parameter name of the parameter to update
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setQueryParameter('hitsPerPage', 20).search();
*/
AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) {
var newState = this.state.setPage(0).setQueryParameter(parameter, value);
if (this.state === newState) return this;
this.state = newState;
this._change();
return this;
};
/**
* Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setState = function(newState) {
this.state = new SearchParameters(newState);
this._change();
return this;
};
/**
* Get the current search state stored in the helper. This object is immutable.
* @param {string[]} [filters] optional filters to retrieve only a subset of the state
* @return {SearchParameters|object} if filters is specified a plain object is
* returned containing only the requested fields, otherwise return the unfiltered
* state
* @example
* // Get the complete state as stored in the helper
* helper.getState();
* @example
* // Get a part of the state with all the refinements on attributes and the query
* helper.getState(['query', 'attribute:category']);
*/
AlgoliaSearchHelper.prototype.getState = function(filters) {
if (filters === undefined) return this.state;
return this.state.filter(filters);
};
/**
* DEPRECATED Get part of the state as a query string. By default, the output keys will not
* be prefixed and will only take the applied refinements and the query.
* @deprecated
* @param {object} [options] May contain the following parameters :
*
* **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for
* the index, all the refinements with `attribute:*` or for some specific attributes with
* `attribute:theAttribute`
*
* **prefix** : prefix in front of the keys
*
* **moreAttributes** : more values to be added in the query string. Those values
* won't be prefixed.
* @return {string} the query string
*/
AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) {
var filters = options && options.filters || ['query', 'attribute:*'];
var partialState = this.getState(filters);
return url.getQueryStringFromState(partialState, options);
};
/**
* DEPRECATED Read a query string and return an object containing the state. Use
* url module.
* @deprecated
* @static
* @param {string} queryString the query string that will be decoded
* @param {object} options accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
* @see {@link url#getStateFromQueryString}
*/
AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString;
/**
* DEPRECATED Retrieve an object of all the properties that are not understandable as helper
* parameters. Use url module.
* @deprecated
* @static
* @param {string} queryString the query string to read
* @param {object} options the options
* - prefixForParameters : prefix used for the helper configuration keys
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString;
/**
* DEPRECATED Overrides part of the state with the properties stored in the provided query
* string.
* @deprecated
* @param {string} queryString the query string containing the informations to url the state
* @param {object} options optional parameters :
* - prefix : prefix used for the algolia parameters
* - triggerChange : if set to true the state update will trigger a change event
*/
AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) {
var triggerChange = options && options.triggerChange || false;
var configuration = url.getStateFromQueryString(queryString, options);
var updatedState = this.state.setQueryParameters(configuration);
if (triggerChange) this.setState(updatedState);
else this.overrideStateWithoutTriggeringChangeEvent(updatedState);
};
/**
* Override the current state without triggering a change event.
* Do not use this method unless you know what you are doing. (see the example
* for a legit use case)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @example
* helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
* updateYourURL(state)
* })
* window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
* helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
* @chainable
*/
AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) {
this.state = new SearchParameters(newState);
return this;
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isRefined = function(facet, value) {
if (this.state.isConjunctiveFacet(facet)) {
return this.state.isFacetRefined(facet, value);
} else if (this.state.isDisjunctiveFacet(facet)) {
return this.state.isDisjunctiveFacetRefined(facet, value);
}
throw new Error(facet +
' is not properly defined in this helper configuration' +
'(use the facets or disjunctiveFacets keys to configure it)');
};
/**
* Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
* @example
* // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
* helper.hasRefinements('price'); // false
* helper.addNumericRefinement('price', '>', 100);
* helper.hasRefinements('price'); // true
*
* helper.hasRefinements('color'); // false
* helper.addFacetRefinement('color', 'blue');
* helper.hasRefinements('color'); // true
*
* helper.hasRefinements('material'); // false
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* helper.hasRefinements('material'); // true
*
* helper.hasRefinements('categories'); // false
* helper.toggleFacetRefinement('categories', 'kitchen > knife');
* helper.hasRefinements('categories'); // true
*
*/
AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) {
if (!isEmpty(this.state.getNumericRefinements(attribute))) {
return true;
} else if (this.state.isConjunctiveFacet(attribute)) {
return this.state.isFacetRefined(attribute);
} else if (this.state.isDisjunctiveFacet(attribute)) {
return this.state.isDisjunctiveFacetRefined(attribute);
} else if (this.state.isHierarchicalFacet(attribute)) {
return this.state.isHierarchicalFacetRefined(attribute);
}
// there's currently no way to know that the user did call `addNumericRefinement` at some point
// thus we cannot distinguish if there once was a numeric refinement that was cleared
// so we will return false in every other situations to be consistent
// while what we should do here is throw because we did not find the attribute in any type
// of refinement
return false;
};
/**
* Check if a value is excluded for a specific 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(conjRefinements, function(r) {
refinements.push({
value: r,
type: 'conjunctive'
});
});
var excludeRefinements = this.state.getExcludeRefinements(facetName);
forEach(excludeRefinements, function(r) {
refinements.push({
value: r,
type: 'exclude'
});
});
} else if (this.state.isDisjunctiveFacet(facetName)) {
var disjRefinements = this.state.getDisjunctiveRefinements(facetName);
forEach(disjRefinements, function(r) {
refinements.push({
value: r,
type: 'disjunctive'
});
});
}
var numericRefinements = this.state.getNumericRefinements(facetName);
forEach(numericRefinements, function(value, operator) {
refinements.push({
value: value,
operator: operator,
type: 'numeric'
});
});
return refinements;
};
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) {
return this.state.getNumericRefinement(attribute, operator);
};
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) {
return this.state.getHierarchicalFacetBreadcrumb(facetName);
};
// /////////// PRIVATE
/**
* Perform the underlying queries
* @private
* @return {undefined}
* @fires search
* @fires result
* @fires error
*/
AlgoliaSearchHelper.prototype._search = function() {
var state = this.state;
var mainQueries = requestBuilder._getQueries(state.index, state);
var states = [{
state: state,
queriesCount: mainQueries.length,
helper: this
}];
this.emit('search', state, this.lastResults);
var derivedQueries = map(this.derivedHelpers, function(derivedHelper) {
var derivedState = derivedHelper.getModifiedState(state);
var queries = requestBuilder._getQueries(derivedState.index, derivedState);
states.push({
state: derivedState,
queriesCount: queries.length,
helper: derivedHelper
});
derivedHelper.emit('search', derivedState, derivedHelper.lastResults);
return queries;
});
var queries = mainQueries.concat(flatten(derivedQueries));
var queryId = this._queryId++;
this._currentNbQueries++;
this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId));
};
/**
* Transform the responses as sent by the server and transform them into a user
* usable object that merge the results of all the batch requests. It will dispatch
* over the different helper + derived helpers (when there are some).
* @private
* @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>}
* state state used for to generate the request
* @param {number} queryId id of the current request
* @param {Error} err error if any, null otherwise
* @param {object} content content of the response
* @return {undefined}
*/
AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) {
// FIXME remove the number of outdated queries discarded instead of just one
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._currentNbQueries -= (queryId - this._lastQueryIdReceived);
this._lastQueryIdReceived = queryId;
if (err) {
this.emit('error', err);
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
} else {
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
var results = content.results;
forEach(states, function(s) {
var state = s.state;
var queriesCount = s.queriesCount;
var helper = s.helper;
var specificResults = results.splice(0, queriesCount);
var formattedResponse = helper.lastResults = new SearchResults(state, specificResults);
helper.emit('result', formattedResponse, state);
});
}
};
AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) {
return query ||
facetFilters.length !== 0 ||
numericFilters.length !== 0 ||
tagFilters.length !== 0;
};
/**
* Test if there are some disjunctive refinements on the facet
* @private
* @param {string} facet the attribute to test
* @return {boolean}
*/
AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) {
return this.state.disjunctiveRefinements[facet] &&
this.state.disjunctiveRefinements[facet].length > 0;
};
AlgoliaSearchHelper.prototype._change = function() {
this.emit('change', this.state, this.lastResults);
};
/**
* Clears the cache of the underlying Algolia client.
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.clearCache = function() {
this.client.clearCache();
return this;
};
/**
* Updates the internal client instance. If the reference of the clients
* are equal then no update is actually done.
* @param {AlgoliaSearch} newClient an AlgoliaSearch client
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.setClient = function(newClient) {
if (this.client === newClient) return this;
if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version);
this.client = newClient;
return this;
};
/**
* Gets the instance of the currently used client.
* @return {AlgoliaSearch}
*/
AlgoliaSearchHelper.prototype.getClient = function() {
return this.client;
};
/**
* Creates an derived instance of the Helper. A derived helper
* is a way to request other indices synchronised with the lifecycle
* of the main Helper. This mechanism uses the multiqueries feature
* of Algolia to aggregate all the requests in a single network call.
*
* This method takes a function that is used to create a new SearchParameter
* that will be used to create requests to Algolia. Those new requests
* are created just before the `search` event. The signature of the function
* is `SearchParameters -> SearchParameters`.
*
* This method returns a new DerivedHelper which is an EventEmitter
* that fires the same `search`, `result` and `error` events. Those
* events, however, will receive data specific to this DerivedHelper
* and the SearchParameters that is returned by the call of the
* parameter function.
* @param {function} fn SearchParameters -> SearchParameters
* @return {DerivedHelper}
*/
AlgoliaSearchHelper.prototype.derive = function(fn) {
var derivedHelper = new DerivedHelper(this, fn);
this.derivedHelpers.push(derivedHelper);
return derivedHelper;
};
/**
* This method detaches a derived Helper from the main one. Prefer using the one from the
* derived helper itself, to remove the event listeners too.
* @private
* @return {undefined}
* @throws Error
*/
AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) {
var pos = this.derivedHelpers.indexOf(derivedHelper);
if (pos === -1) throw new Error('Derived helper already detached');
this.derivedHelpers.splice(pos, 1);
};
/**
* 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;
}
module.exports = AlgoliaSearchHelper;
/***/ }),
/* 250 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12),
baseIntersection = __webpack_require__(251),
baseRest = __webpack_require__(25),
castArrayLikeObject = __webpack_require__(252);
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/
var intersection = baseRest(function(arrays) {
var mapped = arrayMap(arrays, castArrayLikeObject);
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped)
: [];
});
module.exports = intersection;
/***/ }),
/* 251 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(60),
arrayIncludes = __webpack_require__(92),
arrayIncludesWith = __webpack_require__(164),
arrayMap = __webpack_require__(12),
baseUnary = __webpack_require__(43),
cacheHas = __webpack_require__(61);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/
function baseIntersection(arrays, iteratee, comparator) {
var includes = comparator ? arrayIncludesWith : arrayIncludes,
length = arrays[0].length,
othLength = arrays.length,
othIndex = othLength,
caches = Array(othLength),
maxLength = Infinity,
result = [];
while (othIndex--) {
var array = arrays[othIndex];
if (othIndex && iteratee) {
array = arrayMap(array, baseUnary(iteratee));
}
maxLength = nativeMin(array.length, maxLength);
caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
? new SetCache(othIndex && array)
: undefined;
}
array = arrays[0];
var index = -1,
seen = caches[0];
outer:
while (++index < length && result.length < maxLength) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (!(seen
? cacheHas(seen, computed)
: includes(result, computed, comparator)
)) {
othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if (!(cache
? cacheHas(cache, computed)
: includes(arrays[othIndex], computed, comparator))
) {
continue outer;
}
}
if (seen) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
module.exports = baseIntersection;
/***/ }),
/* 252 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLikeObject = __webpack_require__(94);
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject(value) ? value : [];
}
module.exports = castArrayLikeObject;
/***/ }),
/* 253 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(49),
castFunction = __webpack_require__(179);
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forOwn(object, iteratee) {
return object && baseForOwn(object, castFunction(iteratee));
}
module.exports = forOwn;
/***/ }),
/* 254 */
/***/ (function(module, exports) {
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
/***/ }),
/* 255 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(11);
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
module.exports = createBaseEach;
/***/ }),
/* 256 */
/***/ (function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(73);
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
module.exports = baseFilter;
/***/ }),
/* 257 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsMatch = __webpack_require__(258),
getMatchData = __webpack_require__(259),
matchesStrictComparable = __webpack_require__(181);
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
module.exports = baseMatches;
/***/ }),
/* 258 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
baseIsEqual = __webpack_require__(59);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
module.exports = baseIsMatch;
/***/ }),
/* 259 */
/***/ (function(module, exports, __webpack_require__) {
var isStrictComparable = __webpack_require__(180),
keys = __webpack_require__(9);
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
module.exports = getMatchData;
/***/ }),
/* 260 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(59),
get = __webpack_require__(72),
hasIn = __webpack_require__(182),
isKey = __webpack_require__(64),
isStrictComparable = __webpack_require__(180),
matchesStrictComparable = __webpack_require__(181),
toKey = __webpack_require__(24);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
module.exports = baseMatchesProperty;
/***/ }),
/* 261 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
module.exports = baseHasIn;
/***/ }),
/* 262 */
/***/ (function(module, exports, __webpack_require__) {
var baseProperty = __webpack_require__(263),
basePropertyDeep = __webpack_require__(264),
isKey = __webpack_require__(64),
toKey = __webpack_require__(24);
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
module.exports = property;
/***/ }),
/* 263 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
module.exports = baseProperty;
/***/ }),
/* 264 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(71);
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
module.exports = basePropertyDeep;
/***/ }),
/* 265 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
module.exports = baseReduce;
/***/ }),
/* 266 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(6),
isSymbol = __webpack_require__(23);
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
module.exports = toNumber;
/***/ }),
/* 267 */
/***/ (function(module, exports, __webpack_require__) {
var baseIteratee = __webpack_require__(13),
isArrayLike = __webpack_require__(11),
keys = __webpack_require__(9);
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = baseIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
module.exports = createFind;
/***/ }),
/* 268 */
/***/ (function(module, exports, __webpack_require__) {
var baseSlice = __webpack_require__(175);
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
module.exports = castSlice;
/***/ }),
/* 269 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(46);
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsEndIndex;
/***/ }),
/* 270 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(46);
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsStartIndex;
/***/ }),
/* 271 */
/***/ (function(module, exports, __webpack_require__) {
var asciiToArray = __webpack_require__(272),
hasUnicode = __webpack_require__(273),
unicodeToArray = __webpack_require__(274);
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return hasUnicode(string)
? unicodeToArray(string)
: asciiToArray(string);
}
module.exports = stringToArray;
/***/ }),
/* 272 */
/***/ (function(module, exports) {
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
module.exports = asciiToArray;
/***/ }),
/* 273 */
/***/ (function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsZWJ = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
module.exports = hasUnicode;
/***/ }),
/* 274 */
/***/ (function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
module.exports = unicodeToArray;
/***/ }),
/* 275 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
createAssigner = __webpack_require__(188),
keysIn = __webpack_require__(48);
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keysIn(source), object, customizer);
});
module.exports = assignInWith;
/***/ }),
/* 276 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(18);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
return srcValue;
}
return objValue;
}
module.exports = customDefaultsAssignIn;
/***/ }),
/* 277 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(39),
assignMergeValue = __webpack_require__(189),
baseFor = __webpack_require__(178),
baseMergeDeep = __webpack_require__(278),
isObject = __webpack_require__(6),
keysIn = __webpack_require__(48);
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
baseFor(source, function(srcValue, key) {
if (isObject(srcValue)) {
stack || (stack = new Stack);
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(object[key], srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
module.exports = baseMerge;
/***/ }),
/* 278 */
/***/ (function(module, exports, __webpack_require__) {
var assignMergeValue = __webpack_require__(189),
cloneBuffer = __webpack_require__(170),
cloneTypedArray = __webpack_require__(172),
copyArray = __webpack_require__(69),
initCloneObject = __webpack_require__(173),
isArguments = __webpack_require__(20),
isArray = __webpack_require__(1),
isArrayLikeObject = __webpack_require__(94),
isBuffer = __webpack_require__(21),
isFunction = __webpack_require__(19),
isObject = __webpack_require__(6),
isPlainObject = __webpack_require__(45),
isTypedArray = __webpack_require__(34),
toPlainObject = __webpack_require__(279);
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = object[key],
srcValue = source[key],
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
module.exports = baseMergeDeep;
/***/ }),
/* 279 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(27),
keysIn = __webpack_require__(48);
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
module.exports = toPlainObject;
/***/ }),
/* 280 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var map = __webpack_require__(17);
var isArray = __webpack_require__(1);
var isNumber = __webpack_require__(184);
var isString = __webpack_require__(52);
function valToNumber(v) {
if (isNumber(v)) {
return v;
} else if (isString(v)) {
return parseFloat(v);
} else if (isArray(v)) {
return map(v, valToNumber);
}
throw new Error('The value should be a number, a parseable string or an array of those.');
}
module.exports = valToNumber;
/***/ }),
/* 281 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(36);
var filter = __webpack_require__(101);
var map = __webpack_require__(17);
var isEmpty = __webpack_require__(14);
var indexOf = __webpack_require__(74);
function filterState(state, filters) {
var partialState = {};
var attributeFilters = filter(filters, function(f) { return f.indexOf('attribute:') !== -1; });
var attributes = map(attributeFilters, function(aF) { return aF.split(':')[1]; });
if (indexOf(attributes, '*') === -1) {
forEach(attributes, function(attr) {
if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) {
if (!partialState.facetsRefinements) partialState.facetsRefinements = {};
partialState.facetsRefinements[attr] = state.facetsRefinements[attr];
}
if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) {
if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {};
partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr];
}
if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) {
if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {};
partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr];
}
var numericRefinements = state.getNumericRefinements(attr);
if (!isEmpty(numericRefinements)) {
if (!partialState.numericRefinements) partialState.numericRefinements = {};
partialState.numericRefinements[attr] = state.numericRefinements[attr];
}
});
} else {
if (!isEmpty(state.numericRefinements)) {
partialState.numericRefinements = state.numericRefinements;
}
if (!isEmpty(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements;
if (!isEmpty(state.disjunctiveFacetsRefinements)) {
partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements;
}
if (!isEmpty(state.hierarchicalFacetsRefinements)) {
partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements;
}
}
var searchParameters = filter(
filters,
function(f) {
return f.indexOf('attribute:') === -1;
}
);
forEach(
searchParameters,
function(parameterKey) {
partialState[parameterKey] = state[parameterKey];
}
);
return partialState;
}
module.exports = filterState;
/***/ }),
/* 282 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Functions to manipulate refinement lists
*
* The RefinementList is not formally defined through a prototype but is based
* on a specific structure.
*
* @module SearchParameters.refinementList
*
* @typedef {string[]} SearchParameters.refinementList.Refinements
* @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList
*/
var isUndefined = __webpack_require__(185);
var isString = __webpack_require__(52);
var isFunction = __webpack_require__(19);
var isEmpty = __webpack_require__(14);
var defaults = __webpack_require__(102);
var reduce = __webpack_require__(50);
var filter = __webpack_require__(101);
var omit = __webpack_require__(35);
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({}, mod, refinementList);
},
/**
* Removes refinement(s) for an attribute:
* - if the value is specified removes the refinement for the value on the attribute
* - if no value is specified removes all the refinements for this attribute
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} [value] the value of the refinement
* @return {RefinementList} a new and updated refinement lst
*/
removeRefinement: function removeRefinement(refinementList, attribute, value) {
if (isUndefined(value)) {
return lib.clearRefinement(refinementList, attribute);
}
var valueAsString = '' + value;
return lib.clearRefinement(refinementList, function(v, f) {
return attribute === f && valueAsString === v;
});
},
/**
* Toggles the refinement value for an attribute.
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement
* @return {RefinementList} a new and updated list
*/
toggleRefinement: function toggleRefinement(refinementList, attribute, value) {
if (isUndefined(value)) throw new Error('toggleRefinement should be used with a value');
if (lib.isRefined(refinementList, attribute, value)) {
return lib.removeRefinement(refinementList, attribute, value);
}
return lib.addRefinement(refinementList, attribute, value);
},
/**
* Clear all or parts of a RefinementList. Depending on the arguments, three
* 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(attribute)) {
return {};
} else if (isString(attribute)) {
return omit(refinementList, attribute);
} else if (isFunction(attribute)) {
return reduce(refinementList, function(memo, values, key) {
var facetList = filter(values, function(value) {
return !attribute(value, key, refinementType);
});
if (!isEmpty(facetList)) memo[key] = facetList;
return memo;
}, {});
}
},
/**
* Test if the refinement value is used for the attribute. If no refinement value
* is provided, test if the refinementList contains any refinement for the
* given attribute.
* @param {RefinementList} refinementList the list of refinement
* @param {string} attribute name of the attribute
* @param {string} [refinementValue] value of the filter/refinement
* @return {boolean}
*/
isRefined: function isRefined(refinementList, attribute, refinementValue) {
var indexOf = __webpack_require__(74);
var containsRefinements = !!refinementList[attribute] &&
refinementList[attribute].length > 0;
if (isUndefined(refinementValue) || !containsRefinements) {
return containsRefinements;
}
var refinementValueAsString = '' + refinementValue;
return indexOf(refinementList[attribute], refinementValueAsString) !== -1;
}
};
module.exports = lib;
/***/ }),
/* 283 */
/***/ (function(module, exports) {
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = compact;
/***/ }),
/* 284 */
/***/ (function(module, exports, __webpack_require__) {
var baseIteratee = __webpack_require__(13),
baseSum = __webpack_require__(285);
/**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, baseIteratee(iteratee, 2))
: 0;
}
module.exports = sumBy;
/***/ }),
/* 285 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(array, iteratee) {
var result,
index = -1,
length = array.length;
while (++index < length) {
var current = iteratee(array[index]);
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}
}
return result;
}
module.exports = baseSum;
/***/ }),
/* 286 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(46),
isArrayLike = __webpack_require__(11),
isString = __webpack_require__(52),
toInteger = __webpack_require__(51),
values = __webpack_require__(287);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
module.exports = includes;
/***/ }),
/* 287 */
/***/ (function(module, exports, __webpack_require__) {
var baseValues = __webpack_require__(288),
keys = __webpack_require__(9);
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
module.exports = values;
/***/ }),
/* 288 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12);
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
module.exports = baseValues;
/***/ }),
/* 289 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12),
baseIteratee = __webpack_require__(13),
baseMap = __webpack_require__(183),
baseSortBy = __webpack_require__(290),
baseUnary = __webpack_require__(43),
compareMultiple = __webpack_require__(291),
identity = __webpack_require__(26);
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
var index = -1;
iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(baseIteratee));
var result = baseMap(collection, function(value, key, collection) {
var criteria = arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
module.exports = baseOrderBy;
/***/ }),
/* 290 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
module.exports = baseSortBy;
/***/ }),
/* 291 */
/***/ (function(module, exports, __webpack_require__) {
var compareAscending = __webpack_require__(292);
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
module.exports = compareMultiple;
/***/ }),
/* 292 */
/***/ (function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(23);
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
module.exports = compareAscending;
/***/ }),
/* 293 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(25),
createWrap = __webpack_require__(105),
getHolder = __webpack_require__(54),
replaceHolders = __webpack_require__(37);
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partial));
return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
});
// Assign default placeholders.
partial.placeholder = {};
module.exports = partial;
/***/ }),
/* 294 */
/***/ (function(module, exports, __webpack_require__) {
var createCtor = __webpack_require__(75),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
module.exports = createBind;
/***/ }),
/* 295 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(68),
createCtor = __webpack_require__(75),
createHybrid = __webpack_require__(193),
createRecurry = __webpack_require__(196),
getHolder = __webpack_require__(54),
replaceHolders = __webpack_require__(37),
root = __webpack_require__(3);
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return apply(fn, this, args);
}
return wrapper;
}
module.exports = createCurry;
/***/ }),
/* 296 */
/***/ (function(module, exports) {
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
module.exports = countHolders;
/***/ }),
/* 297 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(106),
getData = __webpack_require__(197),
getFuncName = __webpack_require__(299),
lodash = __webpack_require__(301);
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func),
other = lodash[funcName];
if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = getData(other);
return !!data && func === data[0];
}
module.exports = isLaziable;
/***/ }),
/* 298 */
/***/ (function(module, exports) {
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
module.exports = noop;
/***/ }),
/* 299 */
/***/ (function(module, exports, __webpack_require__) {
var realNames = __webpack_require__(300);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
module.exports = getFuncName;
/***/ }),
/* 300 */
/***/ (function(module, exports) {
/** Used to lookup unminified function names. */
var realNames = {};
module.exports = realNames;
/***/ }),
/* 301 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(106),
LodashWrapper = __webpack_require__(198),
baseLodash = __webpack_require__(107),
isArray = __webpack_require__(1),
isObjectLike = __webpack_require__(7),
wrapperClone = __webpack_require__(302);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
module.exports = lodash;
/***/ }),
/* 302 */
/***/ (function(module, exports, __webpack_require__) {
var LazyWrapper = __webpack_require__(106),
LodashWrapper = __webpack_require__(198),
copyArray = __webpack_require__(69);
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
module.exports = wrapperClone;
/***/ }),
/* 303 */
/***/ (function(module, exports) {
/** Used to match wrap detail comments. */
var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
module.exports = getWrapDetails;
/***/ }),
/* 304 */
/***/ (function(module, exports) {
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
module.exports = insertWrapDetails;
/***/ }),
/* 305 */
/***/ (function(module, exports, __webpack_require__) {
var arrayEach = __webpack_require__(95),
arrayIncludes = __webpack_require__(92);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256,
WRAP_FLIP_FLAG = 512;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
module.exports = updateWrapDetails;
/***/ }),
/* 306 */
/***/ (function(module, exports, __webpack_require__) {
var copyArray = __webpack_require__(69),
isIndex = __webpack_require__(32);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
module.exports = reorder;
/***/ }),
/* 307 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(68),
createCtor = __webpack_require__(75),
root = __webpack_require__(3);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
module.exports = createPartial;
/***/ }),
/* 308 */
/***/ (function(module, exports, __webpack_require__) {
var composeArgs = __webpack_require__(194),
composeArgsRight = __webpack_require__(195),
replaceHolders = __webpack_require__(37);
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value;
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
module.exports = mergeData;
/***/ }),
/* 309 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(25),
createWrap = __webpack_require__(105),
getHolder = __webpack_require__(54),
replaceHolders = __webpack_require__(37);
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_RIGHT_FLAG = 64;
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partialRight));
return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
});
// Assign default placeholders.
partialRight.placeholder = {};
module.exports = partialRight;
/***/ }),
/* 310 */
/***/ (function(module, exports, __webpack_require__) {
var baseClamp = __webpack_require__(311),
baseToString = __webpack_require__(66),
toInteger = __webpack_require__(51),
toString = __webpack_require__(65);
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString(string);
position = position == null
? 0
: baseClamp(toInteger(position), 0, string.length);
target = baseToString(target);
return string.slice(position, position + target.length) == target;
}
module.exports = startsWith;
/***/ }),
/* 311 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
module.exports = baseClamp;
/***/ }),
/* 312 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = generateTrees;
var last = __webpack_require__(174);
var map = __webpack_require__(17);
var reduce = __webpack_require__(50);
var orderBy = __webpack_require__(104);
var trim = __webpack_require__(187);
var find = __webpack_require__(53);
var pickBy = __webpack_require__(313);
var prepareHierarchicalFacetSortBy = __webpack_require__(201);
function generateTrees(state) {
return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) {
var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex];
var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] &&
state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || '';
var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet);
var sortBy = prepareHierarchicalFacetSortBy(state._getHierarchicalFacetSortBy(hierarchicalFacet));
var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, hierarchicalFacetRefinement);
var results = hierarchicalFacetResult;
if (hierarchicalRootPath) {
results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length);
}
return reduce(results, generateTreeFn, {
name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
count: null, // root level, no count
isRefined: true, // root level, always refined
path: null, // root level, no path
data: null
});
};
}
function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, currentRefinement) {
return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) {
var parent = hierarchicalTree;
if (currentHierarchicalLevel > 0) {
var level = 0;
parent = hierarchicalTree;
while (level < currentHierarchicalLevel) {
parent = parent && find(parent.data, {isRefined: true});
level++;
}
}
// we found a refined parent, let's add current level data under it
if (parent) {
// filter values in case an object has multiple categories:
// {
// categories: {
// level0: ['beers', 'bières'],
// level1: ['beers > IPA', 'bières > Belges']
// }
// }
//
// If parent refinement is `beers`, then we do not want to have `bières > Belges`
// showing up
var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath,
currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel);
parent.data = orderBy(
map(
pickBy(hierarchicalFacetResult.data, onlyMatchingValuesFn),
formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement)
),
sortBy[0], sortBy[1]
);
}
return hierarchicalTree;
};
}
function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel) {
return function(facetCount, facetValue) {
// we want the facetValue is a child of hierarchicalRootPath
if (hierarchicalRootPath &&
(facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) {
return false;
}
// we always want root levels (only when there is no prefix path)
return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 ||
// if there is a rootPath, being root level mean 1 level under rootPath
hierarchicalRootPath &&
facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 ||
// if current refinement is a root level and current facetValue is a root level,
// keep the facetValue
facetValue.indexOf(hierarchicalSeparator) === -1 &&
currentRefinement.indexOf(hierarchicalSeparator) === -1 ||
// currentRefinement is a child of the facet value
currentRefinement.indexOf(facetValue) === 0 ||
// facetValue is a child of the current parent, add it
facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 &&
(hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0);
};
}
function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) {
return function format(facetCount, facetValue) {
return {
name: trim(last(facetValue.split(hierarchicalSeparator))),
path: facetValue,
count: facetCount,
isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0,
data: null
};
};
}
/***/ }),
/* 313 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(12),
baseIteratee = __webpack_require__(13),
basePickBy = __webpack_require__(202),
getAllKeysIn = __webpack_require__(97);
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = arrayMap(getAllKeysIn(object), function(prop) {
return [prop];
});
predicate = baseIteratee(predicate);
return basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
module.exports = pickBy;
/***/ }),
/* 314 */
/***/ (function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(96),
castPath = __webpack_require__(22),
isIndex = __webpack_require__(32),
isObject = __webpack_require__(6),
toKey = __webpack_require__(24);
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject(object)) {
return object;
}
path = castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = toKey(path[index]),
newValue = value;
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject(objValue)
? objValue
: (isIndex(path[index + 1]) ? [] : {});
}
}
assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
module.exports = baseSet;
/***/ }),
/* 315 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var util = __webpack_require__(203);
var events = __webpack_require__(204);
/**
* A DerivedHelper is a way to create sub requests to
* Algolia from a main helper.
* @class
* @classdesc The DerivedHelper provides an event based interface for search callbacks:
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
*/
function DerivedHelper(mainHelper, fn) {
this.main = mainHelper;
this.fn = fn;
this.lastResults = null;
}
util.inherits(DerivedHelper, events.EventEmitter);
/**
* Detach this helper from the main helper
* @return {undefined}
* @throws Error if the derived helper is already detached
*/
DerivedHelper.prototype.detach = function() {
this.removeAllListeners();
this.main.detachDerivedHelper(this);
};
DerivedHelper.prototype.getModifiedState = function(parameters) {
return this.fn(parameters);
};
module.exports = DerivedHelper;
/***/ }),
/* 316 */
/***/ (function(module, exports) {
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
/***/ }),
/* 317 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ }),
/* 318 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(36);
var map = __webpack_require__(17);
var reduce = __webpack_require__(50);
var merge = __webpack_require__(103);
var isArray = __webpack_require__(1);
var requestBuilder = {
/**
* Get all the queries to send to the client, those queries can used directly
* with the Algolia client.
* @private
* @return {object[]} The queries
*/
_getQueries: function getQueries(index, state) {
var queries = [];
// One query for the hits
queries.push({
indexName: index,
params: requestBuilder._getHitsSearchParams(state)
});
// One for each disjunctive facets
forEach(state.getRefinedDisjunctiveFacets(), function(refinedFacet) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet)
});
});
// maybe more to get the root level of hierarchical facets when activated
forEach(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are deeper than level 0 (starting from `beer > IPA`)
// we want to get the root values
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true)
});
}
});
return queries;
},
/**
* Build search parameters used to fetch hits
* @private
* @return {object.<string, any>}
*/
_getHitsSearchParams: function(state) {
var facets = state.facets
.concat(state.disjunctiveFacets)
.concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state));
var facetFilters = requestBuilder._getFacetFilters(state);
var numericFilters = requestBuilder._getNumericFilters(state);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
facets: facets,
tagFilters: tagFilters
};
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
return merge(state.getQueryParams(), additionalParams);
},
/**
* Build search parameters used to fetch a disjunctive facet
* @private
* @param {string} facet the associated facet name
* @param {boolean} hierarchicalRootLevel ?? FIXME
* @return {object}
*/
_getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) {
var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel);
var numericFilters = requestBuilder._getNumericFilters(state, facet);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
hitsPerPage: 1,
page: 0,
attributesToRetrieve: [],
attributesToHighlight: [],
attributesToSnippet: [],
tagFilters: tagFilters
};
var hierarchicalFacet = state.getHierarchicalFacetByName(facet);
if (hierarchicalFacet) {
additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute(
state,
hierarchicalFacet,
hierarchicalRootLevel
);
} else {
additionalParams.facets = facet;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
return merge(state.getQueryParams(), additionalParams);
},
/**
* Return the numeric filters in an algolia request fashion
* @private
* @param {string} [facetName] the name of the attribute for which the filters should be excluded
* @return {string[]} the numeric filters in the algolia format
*/
_getNumericFilters: function(state, facetName) {
if (state.numericFilters) {
return state.numericFilters;
}
var numericFilters = [];
forEach(state.numericRefinements, function(operators, attribute) {
forEach(operators, function(values, operator) {
if (facetName !== attribute) {
forEach(values, function(value) {
if (isArray(value)) {
var vs = map(value, function(v) {
return attribute + operator + v;
});
numericFilters.push(vs);
} else {
numericFilters.push(attribute + operator + value);
}
});
}
});
});
return numericFilters;
},
/**
* Return the tags filters depending
* @private
* @return {string}
*/
_getTagFilters: function(state) {
if (state.tagFilters) {
return state.tagFilters;
}
return state.tagRefinements.join(',');
},
/**
* Build facetFilters parameter based on current refinements. The array returned
* contains strings representing the facet filters in the algolia format.
* @private
* @param {string} [facet] if set, the current disjunctive facet
* @return {array.<string>}
*/
_getFacetFilters: function(state, facet, hierarchicalRootLevel) {
var facetFilters = [];
forEach(state.facetsRefinements, function(facetValues, facetName) {
forEach(facetValues, function(facetValue) {
facetFilters.push(facetName + ':' + facetValue);
});
});
forEach(state.facetsExcludes, function(facetValues, facetName) {
forEach(facetValues, function(facetValue) {
facetFilters.push(facetName + ':-' + facetValue);
});
});
forEach(state.disjunctiveFacetsRefinements, function(facetValues, facetName) {
if (facetName === facet || !facetValues || facetValues.length === 0) return;
var orFilters = [];
forEach(facetValues, function(facetValue) {
orFilters.push(facetName + ':' + facetValue);
});
facetFilters.push(orFilters);
});
forEach(state.hierarchicalFacetsRefinements, function(facetValues, facetName) {
var facetValue = facetValues[0];
if (facetValue === undefined) {
return;
}
var hierarchicalFacet = state.getHierarchicalFacetByName(facetName);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeToRefine;
var attributesIndex;
// we ask for parent facet values only when the `facet` is the current hierarchical facet
if (facet === facetName) {
// if we are at the root level already, no need to ask for facet values, we get them from
// the hits query
if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) ||
(rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) {
return;
}
if (!rootPath) {
attributesIndex = facetValue.split(separator).length - 2;
facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator));
} else {
attributesIndex = rootPath.split(separator).length - 1;
facetValue = rootPath;
}
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
} else {
attributesIndex = facetValue.split(separator).length - 1;
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
}
if (attributeToRefine) {
facetFilters.push([attributeToRefine + ':' + facetValue]);
}
});
return facetFilters;
},
_getHitsHierarchicalFacetsAttributes: function(state) {
var out = [];
return reduce(
state.hierarchicalFacets,
// ask for as much levels as there's hierarchical refinements
function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) {
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0];
// if no refinement, ask for root level
if (!hierarchicalRefinement) {
allAttributes.push(hierarchicalFacet.attributes[0]);
return allAttributes;
}
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var level = hierarchicalRefinement.split(separator).length;
var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1);
return allAttributes.concat(newAttributes);
}, out);
},
_getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) {
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (rootLevel === true) {
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeIndex = 0;
if (rootPath) {
attributeIndex = rootPath.split(separator).length;
}
return [hierarchicalFacet.attributes[attributeIndex]];
}
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || '';
// if refinement is 'beers > IPA > Flying dog',
// then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values)
var parentLevel = hierarchicalRefinement.split(separator).length - 1;
return hierarchicalFacet.attributes.slice(0, parentLevel + 1);
},
getSearchForFacetQuery: function(facetName, query, 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(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters);
return queries;
}
};
module.exports = requestBuilder;
/***/ }),
/* 319 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var invert = __webpack_require__(206);
var keys = __webpack_require__(9);
var keys2Short = {
advancedSyntax: 'aS',
allowTyposOnNumericTokens: 'aTONT',
analyticsTags: 'aT',
analytics: 'a',
aroundLatLngViaIP: 'aLLVIP',
aroundLatLng: 'aLL',
aroundPrecision: 'aP',
aroundRadius: 'aR',
attributesToHighlight: 'aTH',
attributesToRetrieve: 'aTR',
attributesToSnippet: 'aTS',
disjunctiveFacetsRefinements: 'dFR',
disjunctiveFacets: 'dF',
distinct: 'd',
facetsExcludes: 'fE',
facetsRefinements: 'fR',
facets: 'f',
getRankingInfo: 'gRI',
hierarchicalFacetsRefinements: 'hFR',
hierarchicalFacets: 'hF',
highlightPostTag: 'hPoT',
highlightPreTag: 'hPrT',
hitsPerPage: 'hPP',
ignorePlurals: 'iP',
index: 'idx',
insideBoundingBox: 'iBB',
insidePolygon: 'iPg',
length: 'l',
maxValuesPerFacet: 'mVPF',
minimumAroundRadius: 'mAR',
minProximity: 'mP',
minWordSizefor1Typo: 'mWS1T',
minWordSizefor2Typos: 'mWS2T',
numericFilters: 'nF',
numericRefinements: 'nR',
offset: 'o',
optionalWords: 'oW',
page: 'p',
queryType: 'qT',
query: 'q',
removeWordsIfNoResults: 'rWINR',
replaceSynonymsInHighlight: 'rSIH',
restrictSearchableAttributes: 'rSA',
synonyms: 's',
tagFilters: 'tF',
tagRefinements: 'tR',
typoTolerance: 'tT',
optionalTagFilters: 'oTF',
optionalFacetFilters: 'oFF',
snippetEllipsisText: 'sET',
disableExactOnAttributes: 'dEOA',
enableExactOnSingleWordQuery: 'eEOSWQ'
};
var short2Keys = invert(keys2Short);
module.exports = {
/**
* All the keys of the state, encoded.
* @const
*/
ENCODED_PARAMETERS: keys(short2Keys),
/**
* Decode a shorten attribute
* @param {string} shortKey the shorten attribute
* @return {string} the decoded attribute, undefined otherwise
*/
decode: function(shortKey) {
return short2Keys[shortKey];
},
/**
* Encode an attribute into a short version
* @param {string} key the attribute
* @return {string} the shorten attribute
*/
encode: function(key) {
return keys2Short[key];
}
};
/***/ }),
/* 320 */
/***/ (function(module, exports, __webpack_require__) {
var baseInverter = __webpack_require__(321);
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
};
}
module.exports = createInverter;
/***/ }),
/* 321 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(49);
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
module.exports = baseInverter;
/***/ }),
/* 322 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var stringify = __webpack_require__(323);
var parse = __webpack_require__(324);
var formats = __webpack_require__(207);
module.exports = {
formats: formats,
parse: parse,
stringify: stringify
};
/***/ }),
/* 323 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(108);
var formats = __webpack_require__(207);
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 = {
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.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.encoder);
return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.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;
};
module.exports = 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.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.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.serializeDate;
var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.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 : '';
};
/***/ }),
/* 324 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(108);
var has = Object.prototype.hasOwnProperty;
var defaults = {
allowDots: false,
allowPrototypes: false,
arrayLimit: 20,
decoder: utils.decode,
delimiter: '&',
depth: 5,
parameterLimit: 1000,
plainObjects: false,
strictNullHandling: false
};
var parseValues = function 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.decoder);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos), defaults.decoder);
val = options.decoder(part.slice(pos + 1), defaults.decoder);
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function parseObjectRecursive(chain, val, options) {
if (!chain.length) {
return val;
}
var root = chain.shift();
var obj;
if (root === '[]') {
obj = [];
obj = obj.concat(parseObject(chain, val, options));
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root.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] = parseObject(chain, val, options);
} else {
obj[cleanRoot] = parseObject(chain, val, options);
}
}
return obj;
};
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);
};
module.exports = 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.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
options.parseArrays = options.parseArrays !== false;
options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options);
obj = utils.merge(obj, newObj, options);
}
return utils.compact(obj);
};
/***/ }),
/* 325 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(25),
createWrap = __webpack_require__(105),
getHolder = __webpack_require__(54),
replaceHolders = __webpack_require__(37);
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(func, bitmask, thisArg, partials, holders);
});
// Assign default placeholders.
bind.placeholder = {};
module.exports = bind;
/***/ }),
/* 326 */
/***/ (function(module, exports, __webpack_require__) {
var basePickBy = __webpack_require__(202),
hasIn = __webpack_require__(182);
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return basePickBy(object, paths, function(value, path) {
return hasIn(object, path);
});
}
module.exports = basePick;
/***/ }),
/* 327 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(47),
baseForOwn = __webpack_require__(49),
baseIteratee = __webpack_require__(13);
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/
function mapKeys(object, iteratee) {
var result = {};
iteratee = baseIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
module.exports = mapKeys;
/***/ }),
/* 328 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(47),
baseForOwn = __webpack_require__(49),
baseIteratee = __webpack_require__(13);
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = baseIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
module.exports = mapValues;
/***/ }),
/* 329 */,
/* 330 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _get2 = __webpack_require__(72);
var _get3 = _interopRequireDefault(_get2);
exports.default = parseAlgoliaHit;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Find an highlighted attribute given an `attributeName` and an `highlightProperty`, parses it,
* and provided an array of objects with the string value and a boolean if this
* value is highlighted.
*
* In order to use this feature, highlight must be activated in the configuration of
* the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and
* highligtPostTag in Algolia configuration.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightProperty - the property that contains the highlight structure in the results
* @param {string} attributeName - the highlighted attribute to look for
* @param {object} hit - the actual hit returned by Algolia.
* @return {object[]} - An array of {value: string, isDefined: boolean}.
*/
function parseAlgoliaHit(_ref) {
var _ref$preTag = _ref.preTag,
preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag,
_ref$postTag = _ref.postTag,
postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag,
highlightProperty = _ref.highlightProperty,
attributeName = _ref.attributeName,
hit = _ref.hit;
if (!hit) throw new Error('`hit`, the matching record, must be provided');
var highlightObject = (0, _get3.default)(hit[highlightProperty], attributeName);
var highlightedValue = !highlightObject ? '' : highlightObject.value;
return parseHighlightedAttribute({ preTag: preTag, postTag: postTag, highlightedValue: highlightedValue });
}
/**
* Parses an highlighted attribute into an array of objects with the string value, and
* a boolean that indicated if this part is highlighted.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature
* @return {object[]} - An array of {value: string, isDefined: boolean}.
*/
function parseHighlightedAttribute(_ref2) {
var preTag = _ref2.preTag,
postTag = _ref2.postTag,
highlightedValue = _ref2.highlightedValue;
var splitByPreTag = highlightedValue.split(preTag);
var firstValue = splitByPreTag.shift();
var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }];
if (postTag === preTag) {
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;
}
/***/ }),
/* 331 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectHits connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* prop to a [Configure](guide/Search_parameters.html) widget.
* @name connectHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = (0, _indexUtils.getResults)(searchResults, this.context);
var hits = results ? results.hits : [];
return { hits: hits };
},
/* Hits needs to be considered as a widget to trigger a search if no others widgets are used.
* To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState
* See createConnector.js
* */
getSearchParameters: function getSearchParameters(searchParameters) {
return searchParameters;
}
});
/***/ }),
/* 332 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'hitsPerPage';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId();
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, null, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
/**
* connectHitsPerPage connector provides the logic to create connected
* components that will allow a user to choose to display more or less results from Algolia.
* @name connectHitsPerPage
* @kind connector
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {{value: number, label: string}[]} items - List of hits per page options.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaHitsPerPage',
propTypes: {
defaultRefinement: _propTypes2.default.number.isRequired,
items: _propTypes2.default.arrayOf(_propTypes2.default.shape({
label: _propTypes2.default.string,
value: _propTypes2.default.number.isRequired
})).isRequired,
transformItems: _propTypes2.default.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false });
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setHitsPerPage(getCurrentRefinement(props, searchState, this.context));
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 333 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function getId() {
return 'page';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId();
var page = 1;
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, page, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
currentRefinement = parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
/**
* InfiniteHits connector provides the logic to create connected
* components that will render an continuous list of results retrieved from
* Algolia. This connector provides a function to load more results.
* @name connectInfiniteHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @providedPropType {boolean} hasMore - indicates if there are more pages to load
* @providedPropType {function} refine - call to load more results
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaInfiniteHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = (0, _indexUtils.getResults)(searchResults, this.context);
if (!results) {
this._allResults = [];
return {
hits: this._allResults,
hasMore: false
};
}
var hits = results.hits,
page = results.page,
nbPages = results.nbPages;
// If it is the same page we do not touch the page result list
if (page === 0) {
this._allResults = hits;
} else if (page > this.previousPage) {
this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hits));
} else if (page < this.previousPage) {
this._allResults = hits;
}
var lastPageIndex = nbPages - 1;
var hasMore = page < lastPageIndex;
this.previousPage = page;
return {
hits: this._allResults,
hasMore: hasMore
};
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQueryParameters({
page: getCurrentRefinement(props, searchState, this.context) - 1
});
},
refine: function refine(props, searchState) {
var id = getId();
var nextPage = getCurrentRefinement(props, searchState, this.context) + 1;
var nextValue = _defineProperty({}, id, nextPage);
var resetPage = false;
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage);
}
});
/***/ }),
/* 334 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _orderBy2 = __webpack_require__(104);
var _orderBy3 = _interopRequireDefault(_orderBy2);
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var namespace = 'menu';
function getId(props) {
return props.attributeName;
}
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), null, function (currentRefinement) {
if (currentRefinement === '') {
return null;
}
return currentRefinement;
});
}
function getValue(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement(props, searchState, context);
return name === currentRefinement ? '' : name;
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : '');
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
var sortBy = ['count:desc', 'name:asc'];
/**
* connectMenu connector provides the logic to build a widget that will
* give the user the ability to choose a single value for a specific facet.
* @name connectMenu
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @kind connector
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of diplayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {boolean} [withSearchBox=false] - allow search inside values
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaMenu',
propTypes: {
attributeName: _propTypes2.default.string.isRequired,
showMore: _propTypes2.default.bool,
limitMin: _propTypes2.default.number,
limitMax: _propTypes2.default.number,
defaultRefinement: _propTypes2.default.string,
transformItems: _propTypes2.default.func,
withSearchBox: _propTypes2.default.bool,
searchForFacetValues: _propTypes2.default.bool // @deprecated
},
defaultProps: {
showMore: false,
limitMin: 10,
limitMax: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) {
var _this = this;
var attributeName = props.attributeName,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var results = (0, _indexUtils.getResults)(searchResults, this.context);
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== '');
var withSearchBox = props.withSearchBox || props.searchForFacetValues;
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.');
}
// Search For Facet Values is not available with derived helper (used for multi index search)
if (props.withSearchBox && this.context.multiIndexContext) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: canRefine
};
}
var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) {
return {
label: v.value,
value: getValue(v.value, props, searchState, _this.context),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) {
return {
label: v.name,
value: getValue(v.name, props, searchState, _this.context),
count: v.count,
isRefined: v.isRefined
};
});
var sortedItems = withSearchBox && !isFromSearch ? (0, _orderBy3.default)(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items;
var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems;
return {
items: transformedItems.slice(0, limit),
currentRefinement: getCurrentRefinement(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return { facetName: props.attributeName, query: nextRefinement };
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
searchParameters = searchParameters.addDisjunctiveFacet(attributeName);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
if (currentRefinement !== null) {
searchParameters = searchParameters.addDisjunctiveFacetRefinement(attributeName, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this2 = this;
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: currentRefinement === null ? [] : [{
label: props.attributeName + ': ' + currentRefinement,
attributeName: props.attributeName,
value: function value(nextState) {
return _refine(props, nextState, '', _this2.context);
},
currentRefinement: currentRefinement
}]
};
}
});
/***/ }),
/* 335 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _isEmpty2 = __webpack_require__(14);
var _isEmpty3 = _interopRequireDefault(_isEmpty2);
var _find3 = __webpack_require__(53);
var _find4 = _interopRequireDefault(_find3);
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _indexUtils = __webpack_require__(5);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function stringifyItem(item) {
if (typeof item.start === 'undefined' && typeof item.end === 'undefined') {
return '';
}
return (item.start ? item.start : '') + ':' + (item.end ? item.end : '');
}
function parseItem(value) {
if (value.length === 0) {
return { start: null, end: null };
}
var _value$split = value.split(':'),
_value$split2 = _slicedToArray(_value$split, 2),
startStr = _value$split2[0],
endStr = _value$split2[1];
return {
start: startStr.length > 0 ? parseInt(startStr, 10) : null,
end: endStr.length > 0 ? parseInt(endStr, 10) : null
};
}
var namespace = 'multiRange';
function getId(props) {
return props.attributeName;
}
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), '', function (currentRefinement) {
if (currentRefinement === '') {
return '';
}
return currentRefinement;
});
}
function isRefinementsRangeIncludesInsideItemRange(stats, start, end) {
return stats.min > start && stats.min < end || stats.max > start && stats.max < end;
}
function isItemRangeIncludedInsideRefinementsRange(stats, start, end) {
return start > stats.min && start < stats.max || end > stats.min && end < stats.max;
}
function itemHasRefinement(attributeName, results, value) {
var stats = results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null;
var range = value.split(':');
var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]);
var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]);
return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end)));
}
function _refine(props, searchState, nextRefinement, context) {
var nextValue = _defineProperty({}, getId(props, searchState), nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
/**
* connectMultiRange connector provides the logic to build a widget that will
* give the user the ability to select a range value for a numeric attribute.
* Ranges are defined statically.
* @name connectMultiRange
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @kind connector
* @propType {string} attributeName - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string.
* @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the MultiRange can display.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaMultiRange',
propTypes: {
id: _propTypes2.default.string,
attributeName: _propTypes2.default.string.isRequired,
items: _propTypes2.default.arrayOf(_propTypes2.default.shape({
label: _propTypes2.default.node,
start: _propTypes2.default.number,
end: _propTypes2.default.number
})).isRequired,
transformItems: _propTypes2.default.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attributeName = props.attributeName;
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var results = (0, _indexUtils.getResults)(searchResults, this.context);
var items = props.items.map(function (item) {
var value = stringifyItem(item);
return {
label: item.label,
value: value,
isRefined: value === currentRefinement,
noRefinement: results ? itemHasRefinement(getId(props), results, value) : false
};
});
var stats = results && results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null;
var refinedItem = (0, _find4.default)(items, function (item) {
return item.isRefined === true;
});
if (!items.some(function (item) {
return item.value === '';
})) {
items.push({
value: '',
isRefined: (0, _isEmpty3.default)(refinedItem),
noRefinement: !stats,
label: 'All'
});
}
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement,
canRefine: items.length > 0 && items.some(function (item) {
return item.noRefinement === false;
})
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName;
var _parseItem = parseItem(getCurrentRefinement(props, searchState, this.context)),
start = _parseItem.start,
end = _parseItem.end;
searchParameters = searchParameters.addDisjunctiveFacet(attributeName);
if (start) {
searchParameters = searchParameters.addNumericRefinement(attributeName, '>=', start);
}
if (end) {
searchParameters = searchParameters.addNumericRefinement(attributeName, '<=', end);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var value = getCurrentRefinement(props, searchState, this.context);
var items = [];
var index = (0, _indexUtils.getIndex)(this.context);
if (value !== '') {
var _find2 = (0, _find4.default)(props.items, function (item) {
return stringifyItem(item) === value;
}),
label = _find2.label;
items.push({
label: props.attributeName + ': ' + label,
attributeName: props.attributeName,
currentRefinement: label,
value: function value(nextState) {
return _refine(props, nextState, '', _this.context);
}
});
}
return { id: id, index: index, items: items };
}
});
/***/ }),
/* 336 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _indexUtils = __webpack_require__(5);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'page';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId();
var page = 1;
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, page, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
function _refine(props, searchState, nextPage, context) {
var id = getId();
var nextValue = _defineProperty({}, id, nextPage);
var resetPage = false;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage);
}
/**
* connectPagination connector provides the logic to build a widget that will
* let the user displays hits corresponding to a certain page.
* @name connectPagination
* @kind connector
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [pagesPadding=3] - How many page links to display around the current page.
* @propType {number} [maxPages=Infinity] - Maximum number of pages to display.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {number} nbPages - the total of existing pages
* @providedPropType {number} currentRefinement - the page refinement currently applied
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaPagination',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = (0, _indexUtils.getResults)(searchResults, this.context);
if (!results) {
return null;
}
var nbPages = results.nbPages;
return {
nbPages: nbPages,
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: nbPages > 1
};
},
refine: function refine(props, searchState, nextPage) {
return _refine(props, searchState, nextPage, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setPage(getCurrentRefinement(props, searchState, this.context) - 1);
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 337 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectPoweredBy connector provides the logic to build a widget that
* will display a link to algolia.
* @name connectPoweredBy
* @kind connector
* @providedPropType {string} url - the url to redirect to algolia
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaPoweredBy',
propTypes: {},
getProvidedProps: function getProvidedProps(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 };
}
});
/***/ }),
/* 338 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _indexUtils = __webpack_require__(5);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var namespace = 'refinementList';
function getId(props) {
return props.attributeName;
}
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), [], function (currentRefinement) {
if (typeof currentRefinement === 'string') {
// All items were unselected
if (currentRefinement === '') {
return [];
}
// Only one item was in the searchState but we know it should be an array
return [currentRefinement];
}
return currentRefinement;
});
}
function getValue(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement(props, searchState, context);
var isAnewValue = currentRefinement.indexOf(name) === -1;
var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates
: currentRefinement.filter(function (selectedValue) {
return selectedValue !== name;
}); // cannot use .splice(), it mutates
return nextRefinement;
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
// Setting the value to an empty string ensures that it is persisted in
// the URL as an empty value.
// This is necessary in the case where `defaultRefinement` contains one
// item and we try to deselect it. `nextSelected` would be an empty array,
// which would not be persisted to the URL.
// {foo: ['bar']} => "foo[0]=bar"
// {foo: []} => ""
var nextValue = _defineProperty({}, id, nextRefinement.length > 0 ? nextRefinement : '');
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
/**
* connectRefinementList connector provides the logic to build a widget that will
* give the user the ability to choose multiple values for a specific facet.
* @name connectRefinementList
* @kind connector
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [withSearchBox=false] - allow search inside values
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of displayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
var sortBy = ['isRefined', 'count:desc', 'name:asc'];
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaRefinementList',
propTypes: {
id: _propTypes2.default.string,
attributeName: _propTypes2.default.string.isRequired,
operator: _propTypes2.default.oneOf(['and', 'or']),
showMore: _propTypes2.default.bool,
limitMin: _propTypes2.default.number,
limitMax: _propTypes2.default.number,
defaultRefinement: _propTypes2.default.arrayOf(_propTypes2.default.string),
withSearchBox: _propTypes2.default.bool,
searchForFacetValues: _propTypes2.default.bool, // @deprecated
transformItems: _propTypes2.default.func
},
defaultProps: {
operator: 'or',
showMore: false,
limitMin: 10,
limitMax: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) {
var _this = this;
var attributeName = props.attributeName,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var results = (0, _indexUtils.getResults)(searchResults, this.context);
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== '');
var withSearchBox = props.withSearchBox || props.searchForFacetValues;
if (false) {
// eslint-disable-next-line no-console
console.warn('react-instantsearch: `searchForFacetValues` has been renamed to' + '`withSearchBox`, this will break in the next major version.');
}
// Search For Facet Values is not available with derived helper (used for multi index search)
if (props.withSearchBox && this.context.multiIndexContext) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: canRefine,
isFromSearch: isFromSearch,
withSearchBox: withSearchBox
};
}
var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) {
return {
label: v.value,
value: getValue(v.value, props, searchState, _this.context),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attributeName, { sortBy: sortBy }).map(function (v) {
return {
label: v.name,
value: getValue(v.name, props, searchState, _this.context),
count: v.count,
isRefined: v.isRefined
};
});
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, limit),
currentRefinement: getCurrentRefinement(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return { facetName: props.attributeName, query: nextRefinement };
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName,
operator = props.operator,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet';
var addRefinementKey = addKey + 'Refinement';
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
searchParameters = searchParameters[addKey](attributeName);
return getCurrentRefinement(props, searchState, this.context).reduce(function (res, val) {
return res[addRefinementKey](attributeName, val);
}, searchParameters);
},
getMetadata: function getMetadata(props, searchState) {
var id = getId(props);
var context = this.context;
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: getCurrentRefinement(props, searchState, context).length > 0 ? [{
attributeName: props.attributeName,
label: props.attributeName + ': ',
currentRefinement: getCurrentRefinement(props, searchState, context),
value: function value(nextState) {
return _refine(props, nextState, [], context);
},
items: getCurrentRefinement(props, searchState, context).map(function (item) {
return {
label: '' + item,
value: function value(nextState) {
var nextSelectedItems = getCurrentRefinement(props, nextState, context).filter(function (other) {
return other !== item;
});
return _refine(props, searchState, nextSelectedItems, context);
}
};
})
}] : []
};
}
});
/***/ }),
/* 339 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _omit2 = __webpack_require__(35);
var _omit3 = _interopRequireDefault(_omit2);
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
var _utils = __webpack_require__(44);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectScrollTo connector provides the logic to build a widget that will
* let the page scroll to a certain point.
* @name connectScrollTo
* @kind connector
* @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget.
* @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo
* @providedPropType {boolean} hasNotChanged - indicates whether the refinement came from the scrollOn argument (for instance page by default)
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaScrollTo',
propTypes: {
scrollOn: _propTypes2.default.string
},
defaultProps: {
scrollOn: 'page'
},
getProvidedProps: function getProvidedProps(props, searchState) {
var id = props.scrollOn;
var value = (0, _indexUtils.getCurrentRefinementValue)(props, searchState, this.context, id, null, function (currentRefinement) {
return currentRefinement;
});
if (!this._prevSearchState) {
this._prevSearchState = {};
}
/* Get the subpart of the state that interest us*/
if ((0, _indexUtils.hasMultipleIndex)(this.context)) {
var index = (0, _indexUtils.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 = (0, _omit3.default)((0, _omit3.default)(searchState, 'configure'), id);
var hasNotChanged = (0, _utils.shallowEqual)(this._prevSearchState, cleanedSearchState);
this._prevSearchState = cleanedSearchState;
return { value: value, hasNotChanged: hasNotChanged };
}
});
/***/ }),
/* 340 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'query';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId(props);
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, '', function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return '';
});
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, getId());
}
/**
* connectSearchBox connector provides the logic to build a widget that will
* let the user search for a query.
* @name connectSearchBox
* @kind connector
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the query to search for.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaSearchBox',
propTypes: {
defaultRefinement: _propTypes2.default.string
},
getProvidedProps: function getProvidedProps(props, searchState) {
return {
currentRefinement: getCurrentRefinement(props, searchState, this.context)
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement(props, searchState, this.context));
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return {
id: id,
index: (0, _indexUtils.getIndex)(this.context),
items: currentRefinement === null ? [] : [{
label: id + ': ' + currentRefinement,
value: function value(nextState) {
return _refine(props, nextState, '', _this.context);
},
currentRefinement: currentRefinement
}]
};
}
});
/***/ }),
/* 341 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _indexUtils = __webpack_require__(5);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId() {
return 'sortBy';
}
function getCurrentRefinement(props, searchState, context) {
var id = getId(props);
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, id, null, function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return null;
});
}
/**
* 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.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaSortBy',
propTypes: {
defaultRefinement: _propTypes2.default.string,
items: _propTypes2.default.arrayOf(_propTypes2.default.shape({
label: _propTypes2.default.string,
value: _propTypes2.default.string.isRequired
})).isRequired,
transformItems: _propTypes2.default.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _extends({}, item, { isRefined: true }) : _extends({}, item, { isRefined: false });
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, this.context, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return (0, _indexUtils.cleanUpValue)(searchState, this.context, getId());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var selectedIndex = getCurrentRefinement(props, searchState, this.context);
return searchParameters.setIndex(selectedIndex);
},
getMetadata: function getMetadata() {
return { id: getId() };
}
});
/***/ }),
/* 342 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* connectStats connector provides the logic to build a widget that will
* displays algolia search statistics (hits number and processing time).
* @name connectStats
* @kind connector
* @providedPropType {number} nbHits - number of hits returned by Algolia.
* @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaStats',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = (0, _indexUtils.getResults)(searchResults, this.context);
if (!results) {
return null;
}
return {
nbHits: results.nbHits,
processingTimeMS: results.processingTimeMS
};
}
});
/***/ }),
/* 343 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function getId(props) {
return props.attributeName;
}
var namespace = 'toggle';
function getCurrentRefinement(props, searchState, context) {
return (0, _indexUtils.getCurrentRefinementValue)(props, searchState, context, namespace + '.' + getId(props), false, function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return false;
});
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : false);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, namespace + '.' + getId(props));
}
/**
* connectToggle connector provides the logic to build a widget that will
* provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization.
* @name connectToggle
* @kind connector
* @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {string} value - Value of the refinement to apply on `attributeName`.
* @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default?
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {boolean} currentRefinement - the refinement currently applied
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaToggle',
propTypes: {
label: _propTypes2.default.string,
filter: _propTypes2.default.func,
attributeName: _propTypes2.default.string,
value: _propTypes2.default.any,
defaultRefinement: _propTypes2.default.bool
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return { currentRefinement: currentRefinement };
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName,
value = props.value,
filter = props.filter;
var checked = getCurrentRefinement(props, searchState, this.context);
if (checked) {
if (attributeName) {
searchParameters = searchParameters.addFacet(attributeName).addFacetRefinement(attributeName, value);
}
if (filter) {
searchParameters = filter(searchParameters);
}
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId(props);
var checked = getCurrentRefinement(props, searchState, this.context);
var items = [];
var index = (0, _indexUtils.getIndex)(this.context);
if (checked) {
items.push({
label: props.label,
currentRefinement: props.label,
attributeName: props.attributeName,
value: function value(nextState) {
return _refine(props, nextState, false, _this.context);
}
});
}
return { id: id, index: index, items: items };
}
});
/***/ }),
/* 344 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getId = undefined;
var _propTypes = __webpack_require__(0);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var getId = exports.getId = function getId(props) {
return props.attributes[0];
};
var namespace = 'hierarchicalMenu';
function _refine(props, searchState, nextRefinement, context) {
var id = getId(props);
var nextValue = _defineProperty({}, id, nextRefinement || '');
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage, namespace);
}
function 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 {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {string} {React.Element} [separator=' > '] - Specifies the level separator used in the data.
* @propType {string} [rootURL=null] - The root element's URL (the originating page).
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display.
*/
exports.default = (0, _createConnector2.default)({
displayName: 'AlgoliaBreadcrumb',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings');
}
return undefined;
},
rootURL: _propTypes2.default.string,
separator: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.element]),
transformItems: _propTypes2.default.func
},
defaultProps: {
rootURL: null,
separator: ' > '
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var id = getId(props);
var results = (0, _indexUtils.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);
}
});
/***/ }),
/* 345 */,
/* 346 */,
/* 347 */,
/* 348 */,
/* 349 */,
/* 350 */,
/* 351 */,
/* 352 */,
/* 353 */,
/* 354 */,
/* 355 */,
/* 356 */,
/* 357 */,
/* 358 */,
/* 359 */,
/* 360 */,
/* 361 */,
/* 362 */,
/* 363 */,
/* 364 */,
/* 365 */,
/* 366 */,
/* 367 */,
/* 368 */,
/* 369 */,
/* 370 */,
/* 371 */,
/* 372 */,
/* 373 */,
/* 374 */,
/* 375 */,
/* 376 */,
/* 377 */,
/* 378 */,
/* 379 */,
/* 380 */,
/* 381 */,
/* 382 */,
/* 383 */,
/* 384 */,
/* 385 */,
/* 386 */,
/* 387 */,
/* 388 */,
/* 389 */,
/* 390 */,
/* 391 */,
/* 392 */,
/* 393 */,
/* 394 */,
/* 395 */,
/* 396 */,
/* 397 */,
/* 398 */,
/* 399 */,
/* 400 */,
/* 401 */,
/* 402 */,
/* 403 */,
/* 404 */,
/* 405 */,
/* 406 */,
/* 407 */,
/* 408 */,
/* 409 */,
/* 410 */,
/* 411 */,
/* 412 */,
/* 413 */,
/* 414 */,
/* 415 */,
/* 416 */,
/* 417 */,
/* 418 */,
/* 419 */,
/* 420 */,
/* 421 */,
/* 422 */,
/* 423 */,
/* 424 */,
/* 425 */,
/* 426 */,
/* 427 */,
/* 428 */,
/* 429 */,
/* 430 */,
/* 431 */,
/* 432 */,
/* 433 */,
/* 434 */,
/* 435 */,
/* 436 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connectConfigure = __webpack_require__(222);
Object.defineProperty(exports, 'connectConfigure', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectConfigure).default;
}
});
var _connectCurrentRefinements = __webpack_require__(211);
Object.defineProperty(exports, 'connectCurrentRefinements', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectCurrentRefinements).default;
}
});
var _connectHierarchicalMenu = __webpack_require__(248);
Object.defineProperty(exports, 'connectHierarchicalMenu', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectHierarchicalMenu).default;
}
});
var _connectHighlight = __webpack_require__(218);
Object.defineProperty(exports, 'connectHighlight', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectHighlight).default;
}
});
var _connectHits = __webpack_require__(331);
Object.defineProperty(exports, 'connectHits', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectHits).default;
}
});
var _connectAutoComplete = __webpack_require__(437);
Object.defineProperty(exports, 'connectAutoComplete', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectAutoComplete).default;
}
});
var _connectHitsPerPage = __webpack_require__(332);
Object.defineProperty(exports, 'connectHitsPerPage', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectHitsPerPage).default;
}
});
var _connectInfiniteHits = __webpack_require__(333);
Object.defineProperty(exports, 'connectInfiniteHits', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectInfiniteHits).default;
}
});
var _connectMenu = __webpack_require__(334);
Object.defineProperty(exports, 'connectMenu', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectMenu).default;
}
});
var _connectMultiRange = __webpack_require__(335);
Object.defineProperty(exports, 'connectMultiRange', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectMultiRange).default;
}
});
var _connectPagination = __webpack_require__(336);
Object.defineProperty(exports, 'connectPagination', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectPagination).default;
}
});
var _connectPoweredBy = __webpack_require__(337);
Object.defineProperty(exports, 'connectPoweredBy', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectPoweredBy).default;
}
});
var _connectRange = __webpack_require__(209);
Object.defineProperty(exports, 'connectRange', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectRange).default;
}
});
var _connectRefinementList = __webpack_require__(338);
Object.defineProperty(exports, 'connectRefinementList', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectRefinementList).default;
}
});
var _connectScrollTo = __webpack_require__(339);
Object.defineProperty(exports, 'connectScrollTo', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectScrollTo).default;
}
});
var _connectBreadcrumb = __webpack_require__(344);
Object.defineProperty(exports, 'connectBreadcrumb', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectBreadcrumb).default;
}
});
var _connectSearchBox = __webpack_require__(340);
Object.defineProperty(exports, 'connectSearchBox', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectSearchBox).default;
}
});
var _connectSortBy = __webpack_require__(341);
Object.defineProperty(exports, 'connectSortBy', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectSortBy).default;
}
});
var _connectStats = __webpack_require__(342);
Object.defineProperty(exports, 'connectStats', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectStats).default;
}
});
var _connectToggle = __webpack_require__(343);
Object.defineProperty(exports, 'connectToggle', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_connectToggle).default;
}
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/***/ }),
/* 437 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createConnector = __webpack_require__(2);
var _createConnector2 = _interopRequireDefault(_createConnector);
var _indexUtils = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var getId = function getId() {
return 'query';
};
function getCurrentRefinement(props, searchState, context) {
var id = getId();
return (0, _indexUtils.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();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return (0, _indexUtils.refineValue)(searchState, nextValue, context, resetPage);
}
function _cleanUp(props, searchState, context) {
return (0, _indexUtils.cleanUpValue)(searchState, context, getId());
}
/**
* connectAutoComplete connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* prop to a [Configure](guide/Search_parameters.html) widget.
* @name connectAutoComplete
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state.
* @providedPropType {function} refine - a function to change the query.
* @providedPropType {string} currentRefinement - the query to search for.
*/
exports.default = (0, _createConnector2.default)({
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));
}
});
/***/ })
/******/ ]);
});
//# sourceMappingURL=Connectors.js.map |
ajax/libs/material-ui/4.9.2/esm/Typography/Typography.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
export var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: {
margin: 0
},
/* Styles applied to the root element if `variant="body2"`. */
body2: theme.typography.body2,
/* Styles applied to the root element if `variant="body1"`. */
body1: theme.typography.body1,
/* Styles applied to the root element if `variant="caption"`. */
caption: theme.typography.caption,
/* Styles applied to the root element if `variant="button"`. */
button: theme.typography.button,
/* Styles applied to the root element if `variant="h1"`. */
h1: theme.typography.h1,
/* Styles applied to the root element if `variant="h2"`. */
h2: theme.typography.h2,
/* Styles applied to the root element if `variant="h3"`. */
h3: theme.typography.h3,
/* Styles applied to the root element if `variant="h4"`. */
h4: theme.typography.h4,
/* Styles applied to the root element if `variant="h5"`. */
h5: theme.typography.h5,
/* Styles applied to the root element if `variant="h6"`. */
h6: theme.typography.h6,
/* Styles applied to the root element if `variant="subtitle1"`. */
subtitle1: theme.typography.subtitle1,
/* Styles applied to the root element if `variant="subtitle2"`. */
subtitle2: theme.typography.subtitle2,
/* Styles applied to the root element if `variant="overline"`. */
overline: theme.typography.overline,
/* Styles applied to the root element if `variant="srOnly"`. Only accessible to screen readers. */
srOnly: {
position: 'absolute',
height: 1,
width: 1,
overflow: 'hidden'
},
/* Styles applied to the root element if `align="left"`. */
alignLeft: {
textAlign: 'left'
},
/* Styles applied to the root element if `align="center"`. */
alignCenter: {
textAlign: 'center'
},
/* Styles applied to the root element if `align="right"`. */
alignRight: {
textAlign: 'right'
},
/* Styles applied to the root element if `align="justify"`. */
alignJustify: {
textAlign: 'justify'
},
/* Styles applied to the root element if `nowrap={true}`. */
noWrap: {
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
},
/* Styles applied to the root element if `gutterBottom={true}`. */
gutterBottom: {
marginBottom: '0.35em'
},
/* Styles applied to the root element if `paragraph={true}`. */
paragraph: {
marginBottom: 16
},
/* Styles applied to the root element if `color="inherit"`. */
colorInherit: {
color: 'inherit'
},
/* Styles applied to the root element if `color="primary"`. */
colorPrimary: {
color: theme.palette.primary.main
},
/* Styles applied to the root element if `color="secondary"`. */
colorSecondary: {
color: theme.palette.secondary.main
},
/* Styles applied to the root element if `color="textPrimary"`. */
colorTextPrimary: {
color: theme.palette.text.primary
},
/* Styles applied to the root element if `color="textSecondary"`. */
colorTextSecondary: {
color: theme.palette.text.secondary
},
/* Styles applied to the root element if `color="error"`. */
colorError: {
color: theme.palette.error.main
},
/* Styles applied to the root element if `display="inline"`. */
displayInline: {
display: 'inline'
},
/* Styles applied to the root element if `display="block"`. */
displayBlock: {
display: 'block'
}
};
};
var defaultVariantMapping = {
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
h5: 'h5',
h6: 'h6',
subtitle1: 'h6',
subtitle2: 'h6',
body1: 'p',
body2: 'p'
};
var Typography = React.forwardRef(function Typography(props, ref) {
var _props$align = props.align,
align = _props$align === void 0 ? 'inherit' : _props$align,
classes = props.classes,
className = props.className,
_props$color = props.color,
color = _props$color === void 0 ? 'initial' : _props$color,
component = props.component,
_props$display = props.display,
display = _props$display === void 0 ? 'initial' : _props$display,
_props$gutterBottom = props.gutterBottom,
gutterBottom = _props$gutterBottom === void 0 ? false : _props$gutterBottom,
_props$noWrap = props.noWrap,
noWrap = _props$noWrap === void 0 ? false : _props$noWrap,
_props$paragraph = props.paragraph,
paragraph = _props$paragraph === void 0 ? false : _props$paragraph,
_props$variant = props.variant,
variant = _props$variant === void 0 ? 'body1' : _props$variant,
_props$variantMapping = props.variantMapping,
variantMapping = _props$variantMapping === void 0 ? defaultVariantMapping : _props$variantMapping,
other = _objectWithoutProperties(props, ["align", "classes", "className", "color", "component", "display", "gutterBottom", "noWrap", "paragraph", "variant", "variantMapping"]);
var Component = component || (paragraph ? 'p' : variantMapping[variant] || defaultVariantMapping[variant]) || 'span';
return React.createElement(Component, _extends({
className: clsx(classes.root, className, variant !== 'inherit' && classes[variant], color !== 'initial' && classes["color".concat(capitalize(color))], noWrap && classes.noWrap, gutterBottom && classes.gutterBottom, paragraph && classes.paragraph, align !== 'inherit' && classes["align".concat(capitalize(align))], display !== 'initial' && classes["display".concat(capitalize(display))]),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? Typography.propTypes = {
/**
* Set the text-align on the component.
*/
align: PropTypes.oneOf(['inherit', 'left', 'center', 'right', 'justify']),
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['initial', 'inherit', 'primary', 'secondary', 'textPrimary', 'textSecondary', 'error']),
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
* Overrides the behavior of the `variantMapping` prop.
*/
component: PropTypes.elementType,
/**
* Controls the display type
*/
display: PropTypes.oneOf(['initial', 'block', 'inline']),
/**
* If `true`, the text will have a bottom margin.
*/
gutterBottom: PropTypes.bool,
/**
* If `true`, the text will not wrap, but instead will truncate with a text overflow ellipsis.
*
* Note that text overflow can only happen with block or inline-block level elements
* (the element needs to have a width in order to overflow).
*/
noWrap: PropTypes.bool,
/**
* If `true`, the text will have a bottom margin.
*/
paragraph: PropTypes.bool,
/**
* Applies the theme typography styles.
*/
variant: PropTypes.oneOf(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'subtitle1', 'subtitle2', 'body1', 'body2', 'caption', 'button', 'overline', 'srOnly', 'inherit']),
/**
* The component maps the variant prop to a range of different DOM element types.
* For instance, subtitle1 to `<h6>`.
* If you wish to change that mapping, you can provide your own.
* Alternatively, you can use the `component` prop.
*/
variantMapping: PropTypes.object
} : void 0;
export default withStyles(styles, {
name: 'MuiTypography'
})(Typography); |
ajax/libs/primereact/7.2.1/togglebutton/togglebutton.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames, IconUtils } from 'primereact/utils';
import { tip } from 'primereact/tooltip';
import { Ripple } from 'primereact/ripple';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var ToggleButton = /*#__PURE__*/function (_Component) {
_inherits(ToggleButton, _Component);
var _super = _createSuper(ToggleButton);
function ToggleButton(props) {
var _this;
_classCallCheck(this, ToggleButton);
_this = _super.call(this, props);
_this.toggle = _this.toggle.bind(_assertThisInitialized(_this));
_this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(ToggleButton, [{
key: "toggle",
value: function toggle(e) {
if (!this.props.disabled && this.props.onChange) {
this.props.onChange({
originalEvent: e,
value: !this.props.checked,
stopPropagation: function stopPropagation() {},
preventDefault: function preventDefault() {},
target: {
name: this.props.name,
id: this.props.id,
value: !this.props.checked
}
});
}
}
}, {
key: "onKeyDown",
value: function onKeyDown(event) {
if (event.key === 'Enter') {
this.toggle(event);
event.preventDefault();
}
}
}, {
key: "hasLabel",
value: function hasLabel() {
return this.props.onLabel && this.props.onLabel.length > 0 && this.props.offLabel && this.props.offLabel.length > 0;
}
}, {
key: "hasIcon",
value: function hasIcon() {
return this.props.onIcon && this.props.onIcon.length > 0 && this.props.offIcon && this.props.offIcon.length > 0;
}
}, {
key: "getLabel",
value: function getLabel() {
return this.hasLabel() ? this.props.checked ? this.props.onLabel : this.props.offLabel : ' ';
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.props.tooltip) {
this.renderTooltip();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) {
if (this.tooltip) this.tooltip.update(_objectSpread({
content: this.props.tooltip
}, this.props.tooltipOptions || {}));else this.renderTooltip();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.tooltip) {
this.tooltip.destroy();
this.tooltip = null;
}
}
}, {
key: "renderTooltip",
value: function renderTooltip() {
this.tooltip = tip({
target: this.container,
content: this.props.tooltip,
options: this.props.tooltipOptions
});
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var className = classNames('p-button p-togglebutton p-component', {
'p-button-icon-only': this.hasIcon() && !this.hasLabel(),
'p-highlight': this.props.checked,
'p-disabled': this.props.disabled
}, this.props.className),
iconClassName = null;
var hasIcon = this.hasIcon();
var label = this.getLabel();
var icon = this.props.checked ? this.props.onIcon : this.props.offIcon;
if (hasIcon) {
iconClassName = classNames('p-button-icon p-c', {
'p-button-icon-left': this.props.iconPos === 'left' && label,
'p-button-icon-right': this.props.iconPos === 'right' && label
});
}
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this2.container = el;
},
id: this.props.id,
className: className,
style: this.props.style,
onClick: this.toggle,
onFocus: this.props.onFocus,
onBlur: this.props.onBlur,
onKeyDown: this.onKeyDown,
tabIndex: !this.props.disabled && this.props.tabIndex,
"aria-labelledby": this.props.ariaLabelledBy
}, hasIcon && IconUtils.getJSXIcon(icon, {
className: iconClassName
}, {
props: this.props
}), /*#__PURE__*/React.createElement("span", {
className: "p-button-label"
}, label), /*#__PURE__*/React.createElement(Ripple, null));
}
}]);
return ToggleButton;
}(Component);
_defineProperty(ToggleButton, "defaultProps", {
id: null,
onIcon: null,
offIcon: null,
onLabel: 'Yes',
offLabel: 'No',
iconPos: 'left',
style: null,
className: null,
checked: false,
tabIndex: 0,
tooltip: null,
tooltipOptions: null,
ariaLabelledBy: null,
onChange: null,
onFocus: null,
onBlur: null
});
export { ToggleButton };
|
ajax/libs/react-native-web/0.13.5/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/7.0.0-rc.1/virtualscroller/virtualscroller.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 _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 VirtualScroller = /*#__PURE__*/function (_Component) {
_inherits(VirtualScroller, _Component);
var _super = _createSuper(VirtualScroller);
function VirtualScroller(props) {
var _this;
_classCallCheck(this, VirtualScroller);
_this = _super.call(this, props);
var isBoth = _this.isBoth();
_this.state = {
first: isBoth ? {
rows: 0,
cols: 0
} : 0,
last: isBoth ? {
rows: 0,
cols: 0
} : 0,
numItemsInViewport: isBoth ? {
rows: 0,
cols: 0
} : 0,
numToleratedItems: props.numToleratedItems,
loading: props.loading,
loaderArr: []
};
_this.onScroll = _this.onScroll.bind(_assertThisInitialized(_this));
_this.lastScrollPos = isBoth ? {
top: 0,
left: 0
} : 0;
return _this;
}
_createClass(VirtualScroller, [{
key: "scrollTo",
value: function scrollTo(options) {
this.el && this.el.scrollTo(options);
}
}, {
key: "scrollToIndex",
value: function scrollToIndex(index) {
var _this2 = this;
var behavior = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'auto';
var isBoth = this.isBoth();
var isHorizontal = this.isHorizontal();
var first = this.state.first;
var numToleratedItems = this.state.numToleratedItems;
var itemSize = this.props.itemSize;
var contentPos = this.getContentPosition();
var calculateFirst = function calculateFirst() {
var _index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var _numT = arguments.length > 1 ? arguments[1] : undefined;
return _index <= _numT ? 0 : _index;
};
var calculateCoord = function calculateCoord(_first, _size, _cpos) {
return _first * _size + _cpos;
};
var scrollTo = function scrollTo() {
var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var top = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return _this2.scrollTo({
left: left,
top: top,
behavior: behavior
});
};
if (isBoth) {
var newFirst = {
rows: calculateFirst(index[0], numToleratedItems[0]),
cols: calculateFirst(index[1], numToleratedItems[1])
};
if (newFirst.rows !== first.rows || newFirst.cols !== first.cols) {
scrollTo(calculateCoord(newFirst.cols, itemSize[1], contentPos.left), calculateCoord(newFirst.rows, itemSize[0], contentPos.top));
this.setState({
first: newFirst
});
}
} else {
var _newFirst = calculateFirst(index, numToleratedItems);
if (_newFirst !== first) {
isHorizontal ? scrollTo(calculateCoord(_newFirst, itemSize, contentPos.left), 0) : scrollTo(0, calculateCoord(_newFirst, itemSize, contentPos.top));
this.setState({
first: _newFirst
});
}
}
}
}, {
key: "scrollInView",
value: function scrollInView(index, to) {
var _this3 = this;
var behavior = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'auto';
if (to) {
var isBoth = this.isBoth();
var isHorizontal = this.isHorizontal();
var _this$getRenderedRang = this.getRenderedRange(),
first = _this$getRenderedRang.first,
viewport = _this$getRenderedRang.viewport;
var itemSize = this.props.itemSize;
var scrollTo = function scrollTo() {
var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var top = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return _this3.scrollTo({
left: left,
top: top,
behavior: behavior
});
};
var isToStart = to === 'to-start';
var isToEnd = to === 'to-end';
if (isToStart) {
if (isBoth) {
if (viewport.first.rows - first.rows > index[0]) {
scrollTo(viewport.first.cols * itemSize, (viewport.first.rows - 1) * itemSize);
} else if (viewport.first.cols - first.cols > index[1]) {
scrollTo((viewport.first.cols - 1) * itemSize, viewport.first.rows * itemSize);
}
} else {
if (viewport.first - first > index) {
var pos = (viewport.first - 1) * itemSize;
isHorizontal ? scrollTo(pos, 0) : scrollTo(0, pos);
}
}
} else if (isToEnd) {
if (isBoth) {
if (viewport.last.rows - first.rows <= index[0] + 1) {
scrollTo(viewport.first.cols * itemSize, (viewport.first.rows + 1) * itemSize);
} else if (viewport.last.cols - first.cols <= index[1] + 1) {
scrollTo((viewport.first.cols + 1) * itemSize, viewport.first.rows * itemSize);
}
} else {
if (viewport.last - first <= index + 1) {
var _pos2 = (viewport.first + 1) * itemSize;
isHorizontal ? scrollTo(_pos2, 0) : scrollTo(0, _pos2);
}
}
}
} else {
this.scrollToIndex(index, behavior);
}
}
}, {
key: "getRows",
value: function getRows() {
return this.state.loading ? this.props.loaderDisabled ? this.state.loaderArr : [] : this.loadedItems();
}
}, {
key: "getColumns",
value: function getColumns() {
if (this.props.columns) {
var isBoth = this.isBoth();
var isHorizontal = this.isHorizontal();
if (isBoth || isHorizontal) {
return this.state.loading && this.props.loaderDisabled ? isBoth ? this.state.loaderArr[0] : this.state.loaderArr : this.props.columns.slice(isBoth ? this.state.first.cols : this.state.first, isBoth ? this.state.last.cols : this.state.last);
}
}
return this.props.columns;
}
}, {
key: "getRenderedRange",
value: function getRenderedRange() {
var isBoth = this.isBoth();
var isHorizontal = this.isHorizontal();
var _this$state = this.state,
first = _this$state.first,
last = _this$state.last,
numItemsInViewport = _this$state.numItemsInViewport;
var itemSize = this.props.itemSize;
var calculateFirstInViewport = function calculateFirstInViewport(_pos, _size) {
return Math.floor(_pos / (_size || _pos));
};
var firstInViewport = first;
var lastInViewport = 0;
if (this.el) {
var scrollTop = this.el.scrollTop;
var scrollLeft = this.el.scrollLeft;
if (isBoth) {
firstInViewport = {
rows: calculateFirstInViewport(scrollTop, itemSize[0]),
cols: calculateFirstInViewport(scrollLeft, itemSize[1])
};
lastInViewport = {
rows: firstInViewport.rows + numItemsInViewport.rows,
cols: firstInViewport.cols + numItemsInViewport.cols
};
} else {
var scrollPos = isHorizontal ? scrollLeft : scrollTop;
firstInViewport = calculateFirstInViewport(scrollPos, itemSize);
lastInViewport = firstInViewport + numItemsInViewport;
}
}
return {
first: first,
last: last,
viewport: {
first: firstInViewport,
last: lastInViewport
}
};
}
}, {
key: "isVertical",
value: function isVertical() {
return this.props.orientation === 'vertical';
}
}, {
key: "isHorizontal",
value: function isHorizontal() {
return this.props.orientation === 'horizontal';
}
}, {
key: "isBoth",
value: function isBoth() {
return this.props.orientation === 'both';
}
}, {
key: "calculateOptions",
value: function calculateOptions() {
var _this4 = this;
var isBoth = this.isBoth();
var isHorizontal = this.isHorizontal();
var first = this.state.first;
var itemSize = this.props.itemSize;
var contentPos = this.getContentPosition();
var contentWidth = this.el ? this.el.offsetWidth - contentPos.left : 0;
var contentHeight = this.el ? this.el.offsetHeight - contentPos.top : 0;
var calculateNumItemsInViewport = function calculateNumItemsInViewport(_contentSize, _itemSize) {
return Math.ceil(_contentSize / (_itemSize || _contentSize));
};
var calculateNumToleratedItems = function calculateNumToleratedItems(_numItems) {
return Math.ceil(_numItems / 2);
};
var numItemsInViewport = isBoth ? {
rows: calculateNumItemsInViewport(contentHeight, itemSize[0]),
cols: calculateNumItemsInViewport(contentWidth, itemSize[1])
} : calculateNumItemsInViewport(isHorizontal ? contentWidth : contentHeight, itemSize);
var numToleratedItems = this.state.numToleratedItems || (isBoth ? [calculateNumToleratedItems(numItemsInViewport.rows), calculateNumToleratedItems(numItemsInViewport.cols)] : calculateNumToleratedItems(numItemsInViewport));
var calculateLast = function calculateLast(_first, _num, _numT, _isCols) {
return _this4.getLast(_first + _num + (_first < _numT ? 2 : 3) * _numT, _isCols);
};
var last = isBoth ? {
rows: calculateLast(first.rows, numItemsInViewport.rows, numToleratedItems[0]),
cols: calculateLast(first.cols, numItemsInViewport.cols, numToleratedItems[1], true)
} : calculateLast(first, numItemsInViewport, numToleratedItems);
var state = {
numItemsInViewport: numItemsInViewport,
last: last,
numToleratedItems: numToleratedItems
};
if (this.props.showLoader) {
state['loaderArr'] = isBoth ? Array.from({
length: numItemsInViewport.rows
}).map(function () {
return Array.from({
length: numItemsInViewport.cols
});
}) : Array.from({
length: numItemsInViewport
});
}
this.setState(state, function () {
if (_this4.props.lazy) {
_this4.props.onLazyLoad && _this4.props.onLazyLoad({
first: _this4.state.first,
last: _this4.state.last
});
}
});
}
}, {
key: "getLast",
value: function getLast() {
var last = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var isCols = arguments.length > 1 ? arguments[1] : undefined;
if (this.props.items) {
return Math.min(isCols ? (this.props.columns || this.props.items[0]).length : this.props.items.length, last);
}
return 0;
}
}, {
key: "getContentPosition",
value: function getContentPosition() {
if (this.content) {
var style = getComputedStyle(this.content);
var left = parseInt(style.paddingLeft, 10) + Math.max(parseInt(style.left, 10), 0);
var right = parseInt(style.paddingRight, 10) + Math.max(parseInt(style.right, 10), 0);
var top = parseInt(style.paddingTop, 10) + Math.max(parseInt(style.top, 10), 0);
var bottom = parseInt(style.paddingBottom, 10) + Math.max(parseInt(style.bottom, 10), 0);
return {
left: left,
right: right,
top: top,
bottom: bottom,
x: left + right,
y: top + bottom
};
}
return {
left: 0,
right: 0,
top: 0,
bottom: 0,
x: 0,
y: 0
};
}
}, {
key: "setSize",
value: function setSize() {
var _this5 = this;
if (this.el) {
var isBoth = this.isBoth();
var isHorizontal = this.isHorizontal();
var parentElement = this.el.parentElement;
var width = this.props.scrollWidth || "".concat(this.el.offsetWidth || parentElement.offsetWidth, "px");
var height = this.props.scrollHeight || "".concat(this.el.offsetHeight || parentElement.offsetHeight, "px");
var setProp = function setProp(_name, _value) {
return _this5.el.style[_name] = _value;
};
if (isBoth || isHorizontal) {
setProp('height', height);
setProp('width', width);
} else {
setProp('height', height);
}
}
}
}, {
key: "setSpacerSize",
value: function setSpacerSize() {
var _this6 = this;
var items = this.props.items;
if (this.spacer && items) {
var isBoth = this.isBoth();
var isHorizontal = this.isHorizontal();
var itemSize = this.props.itemSize;
var contentPos = this.getContentPosition();
var setProp = function setProp(_name, _value, _size) {
var _cpos = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
return _this6.spacer.style[_name] = (_value || []).length * _size + _cpos + 'px';
};
if (isBoth) {
setProp('height', items, itemSize[0], contentPos.y);
setProp('width', this.props.columns || items[1], itemSize[1], contentPos.x);
} else {
isHorizontal ? setProp('width', this.props.columns || items, itemSize, contentPos.x) : setProp('height', items, itemSize, contentPos.y);
}
}
}
}, {
key: "setContentPosition",
value: function setContentPosition(pos) {
var _this7 = this;
if (this.content) {
var isBoth = this.isBoth();
var isHorizontal = this.isHorizontal();
var first = pos ? pos.first : this.state.first;
var itemSize = this.props.itemSize;
var calculateTranslateVal = function calculateTranslateVal(_first, _size) {
return _first * _size;
};
var setTransform = function setTransform() {
var _x = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var _y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
_this7.content.style.transform = "translate3d(".concat(_x, "px, ").concat(_y, "px, 0)");
_this7.sticky && (_this7.sticky.style.top = "".concat(_y, "px"));
};
if (isBoth) {
setTransform(calculateTranslateVal(first.cols, itemSize[1]), calculateTranslateVal(first.rows, itemSize[0]));
} else {
var translateVal = calculateTranslateVal(first, itemSize);
isHorizontal ? setTransform(translateVal, 0) : setTransform(0, translateVal);
}
}
}
}, {
key: "onScrollPositionChange",
value: function onScrollPositionChange(event) {
var _this8 = this;
var target = event.target;
var isBoth = this.isBoth();
var isHorizontal = this.isHorizontal();
var _this$state2 = this.state,
first = _this$state2.first,
last = _this$state2.last,
numItemsInViewport = _this$state2.numItemsInViewport,
numToleratedItems = _this$state2.numToleratedItems;
var itemSize = this.props.itemSize;
var contentPos = this.getContentPosition();
var calculateScrollPos = function calculateScrollPos(_pos, _cpos) {
return _pos ? _pos > _cpos ? _pos - _cpos : _pos : 0;
};
var calculateCurrentIndex = function calculateCurrentIndex(_pos, _size) {
return Math.floor(_pos / (_size || _pos));
};
var calculateTriggerIndex = function calculateTriggerIndex(_currentIndex, _first, _last, _num, _numT, _isScrollDownOrRight) {
return _currentIndex <= _numT ? _numT : _isScrollDownOrRight ? _last - _num - _numT : _first + _numT - 1;
};
var calculateFirst = function calculateFirst(_currentIndex, _triggerIndex, _first, _last, _num, _numT, _isScrollDownOrRight) {
if (_currentIndex <= _numT) return 0;else return _isScrollDownOrRight ? _currentIndex < _triggerIndex ? _first : _currentIndex - _numT : _currentIndex > _triggerIndex ? _first : _currentIndex - 2 * _numT;
};
var calculateLast = function calculateLast(_currentIndex, _first, _last, _num, _numT, _isCols) {
var lastValue = _first + _num + 2 * _numT;
if (_currentIndex >= _numT) {
lastValue += _numT + 1;
}
return _this8.getLast(lastValue, _isCols);
};
var scrollTop = calculateScrollPos(target.scrollTop, contentPos.top);
var scrollLeft = calculateScrollPos(target.scrollLeft, contentPos.left);
var newFirst = 0;
var newLast = last;
var isRangeChanged = false;
if (isBoth) {
var isScrollDown = this.lastScrollPos.top <= scrollTop;
var isScrollRight = this.lastScrollPos.left <= scrollLeft;
var currentIndex = {
rows: calculateCurrentIndex(scrollTop, itemSize[0]),
cols: calculateCurrentIndex(scrollLeft, itemSize[1])
};
var triggerIndex = {
rows: calculateTriggerIndex(currentIndex.rows, first.rows, last.rows, numItemsInViewport.rows, numToleratedItems[0], isScrollDown),
cols: calculateTriggerIndex(currentIndex.cols, first.cols, last.cols, numItemsInViewport.cols, numToleratedItems[1], isScrollRight)
};
newFirst = {
rows: calculateFirst(currentIndex.rows, triggerIndex.rows, first.rows, last.rows, numItemsInViewport.rows, numToleratedItems[0], isScrollDown),
cols: calculateFirst(currentIndex.cols, triggerIndex.cols, first.cols, last.cols, numItemsInViewport.cols, numToleratedItems[1], isScrollRight)
};
newLast = {
rows: calculateLast(currentIndex.rows, newFirst.rows, last.rows, numItemsInViewport.rows, numToleratedItems[0]),
cols: calculateLast(currentIndex.cols, newFirst.cols, last.cols, numItemsInViewport.cols, numToleratedItems[1], true)
};
isRangeChanged = newFirst.rows !== first.rows && newLast.rows !== last.rows || newFirst.cols !== first.cols && newLast.cols !== last.cols;
this.lastScrollPos = {
top: scrollTop,
left: scrollLeft
};
} else {
var scrollPos = isHorizontal ? scrollLeft : scrollTop;
var isScrollDownOrRight = this.lastScrollPos <= scrollPos;
var _currentIndex2 = calculateCurrentIndex(scrollPos, itemSize);
var _triggerIndex2 = calculateTriggerIndex(_currentIndex2, first, last, numItemsInViewport, numToleratedItems, isScrollDownOrRight);
newFirst = calculateFirst(_currentIndex2, _triggerIndex2, first, last, numItemsInViewport, numToleratedItems, isScrollDownOrRight);
newLast = calculateLast(_currentIndex2, newFirst, last, numItemsInViewport, numToleratedItems);
isRangeChanged = newFirst !== first && newLast !== last;
this.lastScrollPos = scrollPos;
}
return {
first: newFirst,
last: newLast,
isRangeChanged: isRangeChanged
};
}
}, {
key: "onScrollChange",
value: function onScrollChange(event) {
var _this9 = this;
var _this$onScrollPositio = this.onScrollPositionChange(event),
first = _this$onScrollPositio.first,
last = _this$onScrollPositio.last,
isRangeChanged = _this$onScrollPositio.isRangeChanged;
if (isRangeChanged) {
var newState = {
first: first,
last: last
};
this.setContentPosition(newState);
this.setState(newState, function () {
_this9.props.onScrollIndexChange && _this9.props.onScrollIndexChange(newState);
if (_this9.props.lazy) {
_this9.props.onLazyLoad && _this9.props.onLazyLoad(newState);
}
});
}
}
}, {
key: "onScroll",
value: function onScroll(event) {
var _this10 = this;
this.props.onScroll && this.props.onScroll(event);
if (this.props.delay) {
if (this.scrollTimeout) {
clearTimeout(this.scrollTimeout);
}
if (!this.state.loading && this.props.showLoader) {
var _this$onScrollPositio2 = this.onScrollPositionChange(event),
changed = _this$onScrollPositio2.isRangeChanged;
changed && this.setState({
loading: true
});
}
this.scrollTimeout = setTimeout(function () {
_this10.onScrollChange(event);
if (_this10.state.loading && _this10.props.showLoader && !_this10.props.lazy) {
_this10.setState({
loading: false
});
}
}, this.props.delay);
} else {
this.onScrollChange(event);
}
}
}, {
key: "getOptions",
value: function getOptions(renderedIndex) {
var first = this.state.first;
var count = (this.props.items || []).length;
var index = this.isBoth() ? first.rows + renderedIndex : first + renderedIndex;
return {
index: index,
count: count,
first: index === 0,
last: index === count - 1,
even: index % 2 === 0,
odd: index % 2 !== 0,
props: this.props
};
}
}, {
key: "loaderOptions",
value: function loaderOptions(index, extOptions) {
var count = this.state.loaderArr.length;
return _objectSpread({
index: index,
count: count,
first: index === 0,
last: index === count - 1,
even: index % 2 === 0,
odd: index % 2 !== 0,
props: this.props
}, extOptions);
}
}, {
key: "loadedItems",
value: function loadedItems() {
var _this11 = this;
var items = this.props.items;
if (items && !this.state.loading) {
var isBoth = this.isBoth();
var isHorizontal = this.isHorizontal();
var _this$state3 = this.state,
first = _this$state3.first,
last = _this$state3.last;
if (isBoth) return items.slice(first.rows, last.rows).map(function (item) {
return _this11.props.columns ? item : item.slice(first.cols, last.cols);
});else if (isHorizontal && this.props.columns) return items;else return items.slice(first, last);
}
return [];
}
}, {
key: "init",
value: function init() {
this.setSize();
this.calculateOptions();
this.setSpacerSize();
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
this.init();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
if (!ObjectUtils.equals(prevProps.itemSize, this.props.itemSize) || !prevProps.items || prevProps.items.length !== (this.props.items || []).length) {
this.init();
}
if (this.props.lazy && prevProps.loading !== this.props.loading && this.state.loading !== this.props.loading) {
this.setState({
loading: this.props.loading
});
}
if (prevProps.orientation !== this.props.orientation) {
this.lastScrollPos = this.isBoth() ? {
top: 0,
left: 0
} : 0;
}
}
}, {
key: "renderLoaderItem",
value: function renderLoaderItem(index) {
var extOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var options = this.loaderOptions(index, extOptions);
var content = ObjectUtils.getJSXElement(this.props.loadingTemplate, options);
return /*#__PURE__*/React.createElement(React.Fragment, {
key: index
}, content);
}
}, {
key: "renderLoader",
value: function renderLoader() {
var _this12 = this;
if (!this.props.loaderDisabled && this.props.showLoader && this.state.loading) {
var className = classNames('p-virtualscroller-loader', {
'p-component-overlay': !this.props.loadingTemplate
});
var content = /*#__PURE__*/React.createElement("i", {
className: "p-virtualscroller-loading-icon pi pi-spinner pi-spin"
});
if (this.props.loadingTemplate) {
var isBoth = this.isBoth();
var numItemsInViewport = this.state.numItemsInViewport;
content = this.state.loaderArr.map(function (_, index) {
return _this12.renderLoaderItem(index, isBoth && {
numCols: numItemsInViewport.cols
});
});
}
return /*#__PURE__*/React.createElement("div", {
className: className
}, content);
}
return null;
}
}, {
key: "renderSpacer",
value: function renderSpacer() {
var _this13 = this;
if (this.props.showSpacer) {
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this13.spacer = el;
},
className: "p-virtualscroller-spacer"
});
}
return null;
}
}, {
key: "renderItem",
value: function renderItem(item, index) {
var options = this.getOptions(index);
var content = ObjectUtils.getJSXElement(this.props.itemTemplate, item, options);
return /*#__PURE__*/React.createElement(React.Fragment, {
key: options.index
}, content);
}
}, {
key: "renderItems",
value: function renderItems(loadedItems) {
var _this14 = this;
return loadedItems.map(function (item, index) {
return _this14.renderItem(item, index);
});
}
}, {
key: "renderContent",
value: function renderContent() {
var _this15 = this;
var loadedItems = this.loadedItems();
var items = this.renderItems(loadedItems);
var className = classNames('p-virtualscroller-content', {
'p-virtualscroller-loading': this.state.loading
});
var content = /*#__PURE__*/React.createElement("div", {
className: className,
ref: function ref(el) {
return _this15.content = el;
}
}, items);
if (this.props.contentTemplate) {
var defaultOptions = {
className: className,
contentRef: function contentRef(el) {
return _this15.content = el;
},
spacerRef: function spacerRef(el) {
return _this15.spacer = el;
},
stickyRef: function stickyRef(el) {
return _this15.sticky = el;
},
items: loadedItems,
getItemOptions: function getItemOptions(index) {
return _this15.getOptions(index);
},
children: items,
element: content,
props: this.props,
loading: this.state.loading,
getLoaderOptions: function getLoaderOptions(index, ext) {
return _this15.loaderOptions(index, ext);
},
loadingTemplate: this.props.loadingTemplate,
itemSize: this.props.itemSize,
rows: this.getRows(),
columns: this.getColumns(),
vertical: this.isVertical(),
horizontal: this.isHorizontal(),
both: this.isBoth()
};
return ObjectUtils.getJSXElement(this.props.contentTemplate, defaultOptions);
}
return content;
}
}, {
key: "render",
value: function render() {
var _this16 = this;
if (this.props.disabled) {
var content = ObjectUtils.getJSXElement(this.props.contentTemplate, {
items: this.props.items,
rows: this.props.items,
columns: this.props.columns
});
return /*#__PURE__*/React.createElement(React.Fragment, null, this.props.children, content);
} else {
var isBoth = this.isBoth();
var isHorizontal = this.isHorizontal();
var className = classNames('p-virtualscroller', {
'p-both-scroll': isBoth,
'p-horizontal-scroll': isHorizontal
}, this.props.className);
var loader = this.renderLoader();
var _content = this.renderContent();
var spacer = this.renderSpacer();
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this16.el = el;
},
className: className,
tabIndex: 0,
style: this.props.style,
onScroll: this.onScroll
}, _content, spacer, loader);
}
}
}]);
return VirtualScroller;
}(Component);
_defineProperty(VirtualScroller, "defaultProps", {
id: null,
style: null,
className: null,
items: null,
itemSize: 0,
scrollHeight: null,
scrollWidth: null,
orientation: 'vertical',
numToleratedItems: null,
delay: 0,
lazy: false,
disabled: false,
loaderDisabled: false,
columns: null,
loading: false,
showSpacer: true,
showLoader: false,
loadingTemplate: null,
itemTemplate: null,
contentTemplate: null,
onScroll: null,
onScrollIndexChange: null,
onLazyLoad: null
});
export { VirtualScroller };
|
ajax/libs/primereact/7.2.0/editor/editor.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, classNames } from 'primereact/utils';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function 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 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"] && DomHandler.isExist(_this.editorElement)) {
_this.quill = new module["default"](_this.editorElement, {
modules: _objectSpread({
toolbar: _this.props.showHeader ? _this.toolbarElement : false
}, _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.showHeader === false) {
toolbarHeader = '';
this.toolbarElement = undefined;
} else 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',
showHeader: true,
headerTemplate: null,
onTextChange: null,
onSelectionChange: null,
onLoad: null
});
export { Editor };
|
ajax/libs/react-redux/8.0.0-alpha.1/react-redux.js | cdnjs/cdnjs | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('react-dom')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'react-dom'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRedux = {}, global.React, global.ReactDOM));
}(this, (function (exports, React, reactDom) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
const ReactReduxContext = /*#__PURE__*/React__default['default'].createContext(null);
{
ReactReduxContext.displayName = 'ReactRedux';
}
// Default to a dummy "batch" implementation that just runs the callback
function defaultNoopBatch(callback) {
callback();
}
let batch = defaultNoopBatch; // Allow injecting another batching function later
const setBatch = newBatch => batch = newBatch; // Supply a getter just to skip dealing with ESM bindings
const getBatch = () => batch;
// well as nesting subscriptions of descendant components, so that we can ensure the
// ancestor components re-render before descendants
function createListenerCollection() {
const batch = getBatch();
let first = null;
let last = null;
return {
clear() {
first = null;
last = null;
},
notify() {
batch(() => {
let listener = first;
while (listener) {
listener.callback();
listener = listener.next;
}
});
},
get() {
let listeners = [];
let listener = first;
while (listener) {
listeners.push(listener);
listener = listener.next;
}
return listeners;
},
subscribe(callback) {
let isSubscribed = true;
let listener = last = {
callback,
next: null,
prev: last
};
if (listener.prev) {
listener.prev.next = listener;
} else {
first = listener;
}
return function unsubscribe() {
if (!isSubscribed || first === null) return;
isSubscribed = false;
if (listener.next) {
listener.next.prev = listener.prev;
} else {
last = listener.prev;
}
if (listener.prev) {
listener.prev.next = listener.next;
} else {
first = listener.next;
}
};
}
};
}
const nullListeners = {
notify() {},
get: () => []
};
function createSubscription(store, parentSub) {
let unsubscribe;
let listeners = nullListeners;
function addNestedSub(listener) {
trySubscribe();
return listeners.subscribe(listener);
}
function notifyNestedSubs() {
listeners.notify();
}
function handleChangeWrapper() {
if (subscription.onStateChange) {
subscription.onStateChange();
}
}
function isSubscribed() {
return Boolean(unsubscribe);
}
function trySubscribe() {
if (!unsubscribe) {
unsubscribe = parentSub ? parentSub.addNestedSub(handleChangeWrapper) : store.subscribe(handleChangeWrapper);
listeners = createListenerCollection();
}
}
function tryUnsubscribe() {
if (unsubscribe) {
unsubscribe();
unsubscribe = undefined;
listeners.clear();
listeners = nullListeners;
}
}
const subscription = {
addNestedSub,
notifyNestedSubs,
handleChangeWrapper,
isSubscribed,
trySubscribe,
tryUnsubscribe,
getListeners: () => listeners
};
return subscription;
}
// To get around it, we can conditionally useEffect on the server (no-op) and
// useLayoutEffect in the browser. We need useLayoutEffect to ensure the store
// subscription callback always has the selector from the latest render commit
// available, otherwise a store update may happen between render and the effect,
// which may cause missed updates; we also must ensure the store subscription
// is created synchronously, otherwise a store update may occur before the
// subscription is created and an inconsistent state may be observed
const useIsomorphicLayoutEffect = typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined' ? React.useLayoutEffect : React.useEffect;
function Provider({
store,
context,
children
}) {
const contextValue = React.useMemo(() => {
const subscription = createSubscription(store);
return {
store,
subscription
};
}, [store]);
const previousState = React.useMemo(() => store.getState(), [store]);
useIsomorphicLayoutEffect(() => {
const {
subscription
} = contextValue;
subscription.onStateChange = subscription.notifyNestedSubs;
subscription.trySubscribe();
if (previousState !== store.getState()) {
subscription.notifyNestedSubs();
}
return () => {
subscription.tryUnsubscribe();
subscription.onStateChange = undefined;
};
}, [contextValue, previousState]);
const Context = context || ReactReduxContext;
return /*#__PURE__*/React__default['default'].createElement(Context.Provider, {
value: contextValue
}, children);
}
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 createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var reactIs_development = createCommonjsModule(function (module, exports) {
{
(function() {
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
// (unstable) APIs that have been removed. Can we remove the symbols?
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
function isValidElementType(type) {
return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
}
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
} // AsyncMode is deprecated along with isAsyncMode
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint
console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode;
exports.Suspense = Suspense;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isLazy = isLazy;
exports.isMemo = isMemo;
exports.isPortal = isPortal;
exports.isProfiler = isProfiler;
exports.isStrictMode = isStrictMode;
exports.isSuspense = isSuspense;
exports.isValidElementType = isValidElementType;
exports.typeOf = typeOf;
})();
}
});
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_development;
}
});
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var FORWARD_REF_STATICS = {
'$$typeof': true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true
};
var MEMO_STATICS = {
'$$typeof': true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs.Memo] = MEMO_STATICS;
function getStatics(component) {
// React v16.11 and below
if (reactIs.isMemo(component)) {
return MEMO_STATICS;
} // React v16.12 and above
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols) {
keys = keys.concat(getOwnPropertySymbols(sourceComponent));
}
var targetStatics = getStatics(targetComponent);
var sourceStatics = getStatics(sourceComponent);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
}
return targetComponent;
}
var hoistNonReactStatics_cjs = hoistNonReactStatics;
/**
* Prints a warning in the console if it exists.
*
* @param {String} message The warning message.
* @returns {void}
*/
function warning(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that if you enable
// "break on all exceptions" in your console,
// it would pause the execution at this line.
throw new Error(message);
/* eslint-disable no-empty */
} catch (e) {}
/* eslint-enable no-empty */
}
function verify(selector, methodName) {
if (!selector) {
throw new Error(`Unexpected value for ${methodName} in connect.`);
} else if (methodName === 'mapStateToProps' || methodName === 'mapDispatchToProps') {
if (!Object.prototype.hasOwnProperty.call(selector, 'dependsOnOwnProps')) {
warning(`The selector for ${methodName} of connect did not specify a value for dependsOnOwnProps.`);
}
}
}
function verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps) {
verify(mapStateToProps, 'mapStateToProps');
verify(mapDispatchToProps, 'mapDispatchToProps');
verify(mergeProps, 'mergeProps');
}
const _excluded$1 = ["initMapStateToProps", "initMapDispatchToProps", "initMergeProps"];
function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, {
areStatesEqual,
areOwnPropsEqual,
areStatePropsEqual
}) {
let hasRunAtLeastOnce = false;
let state;
let ownProps;
let stateProps;
let dispatchProps;
let mergedProps;
function handleFirstCall(firstState, firstOwnProps) {
state = firstState;
ownProps = firstOwnProps; // @ts-ignore
stateProps = mapStateToProps(state, ownProps); // @ts-ignore
dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
hasRunAtLeastOnce = true;
return mergedProps;
}
function handleNewPropsAndNewState() {
// @ts-ignore
stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps.dependsOnOwnProps) // @ts-ignore
dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewProps() {
if (mapStateToProps.dependsOnOwnProps) // @ts-ignore
stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps.dependsOnOwnProps) // @ts-ignore
dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewState() {
const nextStateProps = mapStateToProps(state, ownProps);
const statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps); // @ts-ignore
stateProps = nextStateProps;
if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleSubsequentCalls(nextState, nextOwnProps) {
const propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps);
const stateChanged = !areStatesEqual(nextState, state);
state = nextState;
ownProps = nextOwnProps;
if (propsChanged && stateChanged) return handleNewPropsAndNewState();
if (propsChanged) return handleNewProps();
if (stateChanged) return handleNewState();
return mergedProps;
}
return function pureFinalPropsSelector(nextState, nextOwnProps) {
return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps);
};
}
// TODO: Add more comments
// The selector returned by selectorFactory will memoize its results,
// allowing connect's shouldComponentUpdate to return false if final
// props have not changed.
function finalPropsSelectorFactory(dispatch, _ref) {
let {
initMapStateToProps,
initMapDispatchToProps,
initMergeProps
} = _ref,
options = _objectWithoutPropertiesLoose(_ref, _excluded$1);
const mapStateToProps = initMapStateToProps(dispatch, options);
const mapDispatchToProps = initMapDispatchToProps(dispatch, options);
const mergeProps = initMergeProps(dispatch, options);
{
verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps);
}
const selectorFactory = pureFinalPropsSelectorFactory;
return selectorFactory( // @ts-ignore
mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options);
}
function bindActionCreators(actionCreators, dispatch) {
const boundActionCreators = {};
for (const key in actionCreators) {
const actionCreator = actionCreators[key];
if (typeof actionCreator === 'function') {
boundActionCreators[key] = (...args) => dispatch(actionCreator(...args));
}
}
return boundActionCreators;
}
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
function isPlainObject(obj) {
if (typeof obj !== 'object' || obj === null) return false;
let proto = Object.getPrototypeOf(obj);
if (proto === null) return true;
let baseProto = proto;
while (Object.getPrototypeOf(baseProto) !== null) {
baseProto = Object.getPrototypeOf(baseProto);
}
return proto === baseProto;
}
function verifyPlainObject(value, displayName, methodName) {
if (!isPlainObject(value)) {
warning(`${methodName}() in ${displayName} must return a plain object. Instead received ${value}.`);
}
}
function wrapMapToPropsConstant( // * Note:
// It seems that the dispatch argument
// could be a dispatch function in some cases (ex: whenMapDispatchToPropsIsMissing)
// and a state object in some others (ex: whenMapStateToPropsIsMissing)
// eslint-disable-next-line no-unused-vars
getConstant) {
return function initConstantSelector(dispatch) {
const constant = getConstant(dispatch);
function constantSelector() {
return constant;
}
constantSelector.dependsOnOwnProps = false;
return constantSelector;
};
} // dependsOnOwnProps is used by createMapToPropsProxy to determine whether to pass props as args
// to the mapToProps function being wrapped. It is also used by makePurePropsSelector to determine
// whether mapToProps needs to be invoked when props have changed.
//
// A length of one signals that mapToProps does not depend on props from the parent component.
// A length of zero is assumed to mean mapToProps is getting args via arguments or ...args and
// therefore not reporting its length accurately..
// TODO Can this get pulled out so that we can subscribe directly to the store if we don't need ownProps?
function getDependsOnOwnProps(mapToProps) {
return mapToProps.dependsOnOwnProps ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;
} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,
// this function wraps mapToProps in a proxy function which does several things:
//
// * Detects whether the mapToProps function being called depends on props, which
// is used by selectorFactory to decide if it should reinvoke on props changes.
//
// * On first call, handles mapToProps if returns another function, and treats that
// new function as the true mapToProps for subsequent calls.
//
// * On first call, verifies the first result is a plain object, in order to warn
// the developer that their mapToProps function is not returning a valid result.
//
function wrapMapToPropsFunc(mapToProps, methodName) {
return function initProxySelector(dispatch, {
displayName
}) {
const proxy = function mapToPropsProxy(stateOrDispatch, ownProps) {
return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch, undefined);
}; // allow detectFactoryAndVerify to get ownProps
proxy.dependsOnOwnProps = true;
proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) {
proxy.mapToProps = mapToProps;
proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps);
let props = proxy(stateOrDispatch, ownProps);
if (typeof props === 'function') {
proxy.mapToProps = props;
proxy.dependsOnOwnProps = getDependsOnOwnProps(props);
props = proxy(stateOrDispatch, ownProps);
}
verifyPlainObject(props, displayName, methodName);
return props;
};
return proxy;
};
}
function whenMapDispatchToPropsIsFunction(mapDispatchToProps) {
return typeof mapDispatchToProps === 'function' ? wrapMapToPropsFunc(mapDispatchToProps, 'mapDispatchToProps') : undefined;
}
function whenMapDispatchToPropsIsMissing(mapDispatchToProps) {
return !mapDispatchToProps ? wrapMapToPropsConstant(dispatch => ({
dispatch
})) : undefined;
}
function whenMapDispatchToPropsIsObject(mapDispatchToProps) {
return mapDispatchToProps && typeof mapDispatchToProps === 'object' ? wrapMapToPropsConstant(dispatch => bindActionCreators(mapDispatchToProps, dispatch)) : undefined;
}
var defaultMapDispatchToPropsFactories = [whenMapDispatchToPropsIsFunction, whenMapDispatchToPropsIsMissing, whenMapDispatchToPropsIsObject];
function whenMapStateToPropsIsFunction(mapStateToProps) {
return typeof mapStateToProps === 'function' ? wrapMapToPropsFunc(mapStateToProps, 'mapStateToProps') : undefined;
}
function whenMapStateToPropsIsMissing(mapStateToProps) {
return !mapStateToProps ? wrapMapToPropsConstant(() => ({})) : undefined;
}
var defaultMapStateToPropsFactories = [whenMapStateToPropsIsFunction, whenMapStateToPropsIsMissing];
function defaultMergeProps(stateProps, dispatchProps, ownProps) {
return _extends({}, ownProps, stateProps, dispatchProps);
}
function wrapMergePropsFunc(mergeProps) {
return function initMergePropsProxy(dispatch, {
displayName,
areMergedPropsEqual
}) {
let hasRunOnce = false;
let mergedProps;
return function mergePropsProxy(stateProps, dispatchProps, ownProps) {
const nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps);
if (hasRunOnce) {
if (!areMergedPropsEqual(nextMergedProps, mergedProps)) mergedProps = nextMergedProps;
} else {
hasRunOnce = true;
mergedProps = nextMergedProps;
verifyPlainObject(mergedProps, displayName, 'mergeProps');
}
return mergedProps;
};
};
}
function whenMergePropsIsFunction(mergeProps) {
return typeof mergeProps === 'function' ? wrapMergePropsFunc(mergeProps) : undefined;
}
function whenMergePropsIsOmitted(mergeProps) {
return !mergeProps ? () => defaultMergeProps : undefined;
}
var defaultMergePropsFactories = [whenMergePropsIsFunction, whenMergePropsIsOmitted];
function is(x, y) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function shallowEqual(objA, objB) {
if (is(objA, objB)) return true;
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return false;
for (let i = 0; i < keysA.length; i++) {
if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
const _excluded = ["reactReduxForwardedRef"];
const NO_SUBSCRIPTION_ARRAY = [null, null]; // Attempts to stringify whatever not-really-a-component value we were given
// for logging in an error message
const stringifyComponent = Comp => {
try {
return JSON.stringify(Comp);
} catch (err) {
return String(Comp);
}
};
// This is "just" a `useLayoutEffect`, but with two modifications:
// - we need to fall back to `useEffect` in SSR to avoid annoying warnings
// - we extract this to a separate function to avoid closing over values
// and causing memory leaks
function useIsomorphicLayoutEffectWithArgs(effectFunc, effectArgs, dependencies) {
useIsomorphicLayoutEffect(() => effectFunc(...effectArgs), dependencies);
} // Effect callback, extracted: assign the latest props values to refs for later usage
function captureWrapperProps(lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps, // actualChildProps: unknown,
childPropsFromStoreUpdate, notifyNestedSubs) {
// We want to capture the wrapper props and child props we used for later comparisons
lastWrapperProps.current = wrapperProps;
renderIsScheduled.current = false; // If the render was from a store update, clear out that reference and cascade the subscriber update
if (childPropsFromStoreUpdate.current) {
childPropsFromStoreUpdate.current = null;
notifyNestedSubs();
}
} // Effect callback, extracted: subscribe to the Redux store or nearest connected ancestor,
// check for updates after dispatched actions, and trigger re-renders.
function subscribeUpdates(shouldHandleStateChanges, store, subscription, childPropsSelector, lastWrapperProps, lastChildProps, renderIsScheduled, isMounted, childPropsFromStoreUpdate, notifyNestedSubs, // forceComponentUpdateDispatch: React.Dispatch<any>,
additionalSubscribeListener) {
// If we're not subscribed to the store, nothing to do here
if (!shouldHandleStateChanges) return () => {}; // Capture values for checking if and when this component unmounts
let didUnsubscribe = false;
let lastThrownError = null; // We'll run this callback every time a store subscription update propagates to this component
const checkForUpdates = () => {
if (didUnsubscribe || !isMounted.current) {
// Don't run stale listeners.
// Redux doesn't guarantee unsubscriptions happen until next dispatch.
return;
}
const latestStoreState = store.getState();
let newChildProps, error;
try {
// Actually run the selector with the most recent store state and wrapper props
// to determine what the child props should be
newChildProps = childPropsSelector(latestStoreState, lastWrapperProps.current);
} catch (e) {
error = e;
lastThrownError = e;
}
if (!error) {
lastThrownError = null;
} // If the child props haven't changed, nothing to do here - cascade the subscription update
if (newChildProps === lastChildProps.current) {
if (!renderIsScheduled.current) {
notifyNestedSubs();
}
} else {
// Save references to the new child props. Note that we track the "child props from store update"
// as a ref instead of a useState/useReducer because we need a way to determine if that value has
// been processed. If this went into useState/useReducer, we couldn't clear out the value without
// forcing another re-render, which we don't want.
lastChildProps.current = newChildProps;
childPropsFromStoreUpdate.current = newChildProps;
renderIsScheduled.current = true; // Trigger the React `useSyncExternalStore` subscriber
additionalSubscribeListener();
}
}; // Actually subscribe to the nearest connected ancestor (or store)
subscription.onStateChange = checkForUpdates;
subscription.trySubscribe(); // Pull data from the store after first render in case the store has
// changed since we began.
checkForUpdates();
const unsubscribeWrapper = () => {
didUnsubscribe = true;
subscription.tryUnsubscribe();
subscription.onStateChange = null;
if (lastThrownError) {
// It's possible that we caught an error due to a bad mapState function, but the
// parent re-rendered without this component and we're about to unmount.
// This shouldn't happen as long as we do top-down subscriptions correctly, but
// if we ever do those wrong, this throw will surface the error in our tests.
// In that case, throw the error from here so it doesn't get lost.
throw lastThrownError;
}
};
return unsubscribeWrapper;
} // Reducer initial state creation for our update reducer
function match(arg, factories, name) {
for (let i = factories.length - 1; i >= 0; i--) {
const result = factories[i](arg);
if (result) return result;
}
return (dispatch, options) => {
throw new Error(`Invalid value of type ${typeof arg} for ${name} argument when connecting component ${options.wrappedComponentName}.`);
};
}
function strictEqual(a, b) {
return a === b;
}
/**
* Infers the type of props that a connector will inject into a component.
*/
/**
* Connects a React component to a Redux store.
*
* - Without arguments, just wraps the component, without changing the behavior / props
*
* - If 2 params are passed (3rd param, mergeProps, is skipped), default behavior
* is to override ownProps (as stated in the docs), so what remains is everything that's
* not a state or dispatch prop
*
* - When 3rd param is passed, we don't know if ownProps propagate and whether they
* should be valid component props, because it depends on mergeProps implementation.
* As such, it is the user's responsibility to extend ownProps interface from state or
* dispatch props or both when applicable
*
* @param mapStateToProps A function that extracts values from state
* @param mapDispatchToProps Setup for dispatching actions
* @param mergeProps Optional callback to merge state and dispatch props together
* @param options Options for configuring the connection
*
*/
function connect(mapStateToProps, mapDispatchToProps, mergeProps, {
// The `pure` option has been removed, so TS doesn't like us destructuring this to check its existence.
// @ts-ignore
pure,
areStatesEqual = strictEqual,
areOwnPropsEqual = shallowEqual,
areStatePropsEqual = shallowEqual,
areMergedPropsEqual = shallowEqual,
// use React's forwardRef to expose a ref of the wrapped component
forwardRef = false,
// the context consumer to use
context = ReactReduxContext
} = {}) {
{
if (pure !== undefined) {
throw new Error('The `pure` option has been removed. `connect` is now always a "pure/memoized" component');
}
}
const Context = context;
const initMapStateToProps = match(mapStateToProps, // @ts-ignore
defaultMapStateToPropsFactories, 'mapStateToProps');
const initMapDispatchToProps = match(mapDispatchToProps, // @ts-ignore
defaultMapDispatchToPropsFactories, 'mapDispatchToProps');
const initMergeProps = match(mergeProps, // @ts-ignore
defaultMergePropsFactories, 'mergeProps');
const shouldHandleStateChanges = Boolean(mapStateToProps);
const wrapWithConnect = WrappedComponent => {
if (!reactIs.isValidElementType(WrappedComponent)) {
throw new Error(`You must pass a component to the function returned by connect. Instead received ${stringifyComponent(WrappedComponent)}`);
}
const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
const displayName = `Connect(${wrappedComponentName})`;
const selectorFactoryOptions = {
pure,
shouldHandleStateChanges,
displayName,
wrappedComponentName,
WrappedComponent,
initMapStateToProps,
initMapDispatchToProps,
// @ts-ignore
initMergeProps,
areStatesEqual,
areStatePropsEqual,
areOwnPropsEqual,
areMergedPropsEqual
}; // If we aren't running in "pure" mode, we don't want to memoize values.
// To avoid conditionally calling hooks, we fall back to a tiny wrapper
// that just executes the given callback immediately.
const usePureOnlyMemo = pure ? React.useMemo : callback => callback();
function ConnectFunction(props) {
const [propsContext, reactReduxForwardedRef, wrapperProps] = React.useMemo(() => {
// Distinguish between actual "data" props that were passed to the wrapper component,
// and values needed to control behavior (forwarded refs, alternate context instances).
// To maintain the wrapperProps object reference, memoize this destructuring.
const {
reactReduxForwardedRef
} = props,
wrapperProps = _objectWithoutPropertiesLoose(props, _excluded);
return [props.context, reactReduxForwardedRef, wrapperProps];
}, [props]);
const ContextToUse = React.useMemo(() => {
// Users may optionally pass in a custom context instance to use instead of our ReactReduxContext.
// Memoize the check that determines which context instance we should use.
return propsContext && propsContext.Consumer && // @ts-ignore
reactIs.isContextConsumer( /*#__PURE__*/React__default['default'].createElement(propsContext.Consumer, null)) ? propsContext : Context;
}, [propsContext, Context]); // Retrieve the store and ancestor subscription via context, if available
const contextValue = React.useContext(ContextToUse); // The store _must_ exist as either a prop or in context.
// We'll check to see if it _looks_ like a Redux store first.
// This allows us to pass through a `store` prop that is just a plain value.
const didStoreComeFromProps = Boolean(props.store) && Boolean(props.store.getState) && Boolean(props.store.dispatch);
const didStoreComeFromContext = Boolean(contextValue) && Boolean(contextValue.store);
if (!didStoreComeFromProps && !didStoreComeFromContext) {
throw new Error(`Could not find "store" in the context of ` + `"${displayName}". Either wrap the root component in a <Provider>, ` + `or pass a custom React context provider to <Provider> and the corresponding ` + `React context consumer to ${displayName} in connect options.`);
} // Based on the previous check, one of these must be true
const store = didStoreComeFromProps ? props.store : contextValue.store;
const childPropsSelector = React.useMemo(() => {
// The child props selector needs the store reference as an input.
// Re-create this selector whenever the store changes.
return finalPropsSelectorFactory(store.dispatch, selectorFactoryOptions);
}, [store]);
const [subscription, notifyNestedSubs] = React.useMemo(() => {
if (!shouldHandleStateChanges) return NO_SUBSCRIPTION_ARRAY; // This Subscription's source should match where store came from: props vs. context. A component
// connected to the store via props shouldn't use subscription from context, or vice versa.
const subscription = createSubscription(store, didStoreComeFromProps ? undefined : contextValue.subscription); // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in
// the middle of the notification loop, where `subscription` will then be null. This can
// probably be avoided if Subscription's listeners logic is changed to not call listeners
// that have been unsubscribed in the middle of the notification loop.
const notifyNestedSubs = subscription.notifyNestedSubs.bind(subscription);
return [subscription, notifyNestedSubs];
}, [store, didStoreComeFromProps, contextValue]); // Determine what {store, subscription} value should be put into nested context, if necessary,
// and memoize that value to avoid unnecessary context updates.
const overriddenContextValue = React.useMemo(() => {
if (didStoreComeFromProps) {
// This component is directly subscribed to a store from props.
// We don't want descendants reading from this store - pass down whatever
// the existing context value is from the nearest connected ancestor.
return contextValue;
} // Otherwise, put this component's subscription instance into context, so that
// connected descendants won't update until after this component is done
return _extends({}, contextValue, {
subscription
});
}, [didStoreComeFromProps, contextValue, subscription]); // Set up refs to coordinate values between the subscription effect and the render logic
const lastChildProps = React.useRef();
const lastWrapperProps = React.useRef(wrapperProps);
const childPropsFromStoreUpdate = React.useRef();
const renderIsScheduled = React.useRef(false);
React.useRef(false);
const isMounted = React.useRef(false);
const latestSubscriptionCallbackError = React.useRef();
useIsomorphicLayoutEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
};
}, []);
const actualChildPropsSelector = usePureOnlyMemo(() => {
const selector = () => {
// Tricky logic here:
// - This render may have been triggered by a Redux store update that produced new child props
// - However, we may have gotten new wrapper props after that
// If we have new child props, and the same wrapper props, we know we should use the new child props as-is.
// But, if we have new wrapper props, those might change the child props, so we have to recalculate things.
// So, we'll use the child props from store update only if the wrapper props are the same as last time.
if (childPropsFromStoreUpdate.current && wrapperProps === lastWrapperProps.current) {
return childPropsFromStoreUpdate.current;
} // TODO We're reading the store directly in render() here. Bad idea?
// This will likely cause Bad Things (TM) to happen in Concurrent Mode.
// Note that we do this because on renders _not_ caused by store updates, we need the latest store state
// to determine what the child props should be.
return childPropsSelector(store.getState(), wrapperProps);
};
return selector;
}, [store, wrapperProps]); // We need this to execute synchronously every time we re-render. However, React warns
// about useLayoutEffect in SSR, so we try to detect environment and fall back to
// just useEffect instead to avoid the warning, since neither will run anyway.
const subscribeForReact = React.useMemo(() => {
const subscribe = reactListener => {
if (!subscription) {
return () => {};
}
return subscribeUpdates(shouldHandleStateChanges, store, subscription, // @ts-ignore
childPropsSelector, lastWrapperProps, lastChildProps, renderIsScheduled, isMounted, childPropsFromStoreUpdate, notifyNestedSubs, reactListener);
};
return subscribe;
}, [subscription]);
useIsomorphicLayoutEffectWithArgs(captureWrapperProps, [lastWrapperProps, lastChildProps, renderIsScheduled, wrapperProps, childPropsFromStoreUpdate, notifyNestedSubs]);
let actualChildProps;
try {
actualChildProps = React.useSyncExternalStore(subscribeForReact, actualChildPropsSelector, // TODO Need a real getServerSnapshot here
actualChildPropsSelector);
} catch (err) {
if (latestSubscriptionCallbackError.current) {
err.message += `\nThe error may be correlated with this previous error:\n${latestSubscriptionCallbackError.current.stack}\n\n`;
}
throw err;
}
useIsomorphicLayoutEffect(() => {
latestSubscriptionCallbackError.current = undefined;
childPropsFromStoreUpdate.current = undefined;
lastChildProps.current = actualChildProps;
}); // Now that all that's done, we can finally try to actually render the child component.
// We memoize the elements for the rendered child component as an optimization.
const renderedWrappedComponent = React.useMemo(() => {
return (
/*#__PURE__*/
// @ts-ignore
React__default['default'].createElement(WrappedComponent, _extends({}, actualChildProps, {
ref: reactReduxForwardedRef
}))
);
}, [reactReduxForwardedRef, WrappedComponent, actualChildProps]); // If React sees the exact same element reference as last time, it bails out of re-rendering
// that child, same as if it was wrapped in React.memo() or returned false from shouldComponentUpdate.
const renderedChild = React.useMemo(() => {
if (shouldHandleStateChanges) {
// If this component is subscribed to store updates, we need to pass its own
// subscription instance down to our descendants. That means rendering the same
// Context instance, and putting a different value into the context.
return /*#__PURE__*/React__default['default'].createElement(ContextToUse.Provider, {
value: overriddenContextValue
}, renderedWrappedComponent);
}
return renderedWrappedComponent;
}, [ContextToUse, renderedWrappedComponent, overriddenContextValue]);
return renderedChild;
} // If we're in "pure" mode, ensure our wrapper component only re-renders when incoming props have changed.
const _Connect = React__default['default'].memo(ConnectFunction);
// Add a hacky cast to get the right output type
const Connect = _Connect;
Connect.WrappedComponent = WrappedComponent;
Connect.displayName = ConnectFunction.displayName = displayName;
if (forwardRef) {
const _forwarded = React__default['default'].forwardRef(function forwardConnectRef(props, ref) {
// @ts-ignore
return /*#__PURE__*/React__default['default'].createElement(Connect, _extends({}, props, {
reactReduxForwardedRef: ref
}));
});
const forwarded = _forwarded;
forwarded.displayName = displayName;
forwarded.WrappedComponent = WrappedComponent;
return hoistNonReactStatics_cjs(forwarded, WrappedComponent);
}
return hoistNonReactStatics_cjs(Connect, WrappedComponent);
};
return wrapWithConnect;
}
/**
* A hook to access the value of the `ReactReduxContext`. This is a low-level
* hook that you should usually not need to call directly.
*
* @returns {any} the value of the `ReactReduxContext`
*
* @example
*
* import React from 'react'
* import { useReduxContext } from 'react-redux'
*
* export const CounterComponent = ({ value }) => {
* const { store } = useReduxContext()
* return <div>{store.getState()}</div>
* }
*/
function useReduxContext() {
const contextValue = React.useContext(ReactReduxContext);
if (!contextValue) {
throw new Error('could not find react-redux context value; please ensure the component is wrapped in a <Provider>');
}
return contextValue;
}
/**
* Hook factory, which creates a `useStore` hook bound to a given context.
*
* @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
* @returns {Function} A `useStore` hook bound to the specified context.
*/
function createStoreHook(context = ReactReduxContext) {
const useReduxContext$1 = context === ReactReduxContext ? useReduxContext : () => React.useContext(context);
return function useStore() {
const {
store
} = useReduxContext$1();
return store;
};
}
/**
* A hook to access the redux store.
*
* @returns {any} the redux store
*
* @example
*
* import React from 'react'
* import { useStore } from 'react-redux'
*
* export const ExampleComponent = () => {
* const store = useStore()
* return <div>{store.getState()}</div>
* }
*/
const useStore = /*#__PURE__*/createStoreHook();
/**
* Hook factory, which creates a `useDispatch` hook bound to a given context.
*
* @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
* @returns {Function} A `useDispatch` hook bound to the specified context.
*/
function createDispatchHook(context = ReactReduxContext) {
const useStore$1 = // @ts-ignore
context === ReactReduxContext ? useStore : createStoreHook(context);
return function useDispatch() {
const store = useStore$1(); // @ts-ignore
return store.dispatch;
};
}
/**
* A hook to access the redux `dispatch` function.
*
* @returns {any|function} redux store's `dispatch` function
*
* @example
*
* import React, { useCallback } from 'react'
* import { useDispatch } from 'react-redux'
*
* export const CounterComponent = ({ value }) => {
* const dispatch = useDispatch()
* const increaseCounter = useCallback(() => dispatch({ type: 'increase-counter' }), [])
* return (
* <div>
* <span>{value}</span>
* <button onClick={increaseCounter}>Increase counter</button>
* </div>
* )
* }
*/
const useDispatch = /*#__PURE__*/createDispatchHook();
var useSyncExternalStoreWithSelector_development = createCommonjsModule(function (module, exports) {
{
(function() {
/**
* 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.
*/
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
// Don't require this file directly; it's embedded by Rollup during build.
if (
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
'function'
) {
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
}
var React = React__default['default'];
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x, y) {
return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
;
}
var objectIs = typeof Object.is === 'function' ? Object.is : is;
var useSyncExternalStore = React.useSyncExternalStore;
// for CommonJS interop.
var useRef = React.useRef,
useEffect = React.useEffect,
useMemo = React.useMemo,
useDebugValue = React.useDebugValue; // Same as useSyncExternalStore, but supports selector and isEqual arguments.
function useSyncExternalStoreWithSelector(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) {
// Use this to track the rendered snapshot.
var instRef = useRef(null);
var inst;
if (instRef.current === null) {
inst = {
hasValue: false,
value: null
};
instRef.current = inst;
} else {
inst = instRef.current;
}
var _useMemo = useMemo(function () {
// Track the memoized state using closure variables that are local to this
// memoized instance of a getSnapshot function. Intentionally not using a
// useRef hook, because that state would be shared across all concurrent
// copies of the hook/component.
var hasMemo = false;
var memoizedSnapshot;
var memoizedSelection;
var memoizedSelector = function (nextSnapshot) {
if (!hasMemo) {
// The first time the hook is called, there is no memoized result.
hasMemo = true;
memoizedSnapshot = nextSnapshot;
var _nextSelection = selector(nextSnapshot);
if (isEqual !== undefined) {
// Even if the selector has changed, the currently rendered selection
// may be equal to the new selection. We should attempt to reuse the
// current value if possible, to preserve downstream memoizations.
if (inst.hasValue) {
var currentSelection = inst.value;
if (isEqual(currentSelection, _nextSelection)) {
memoizedSelection = currentSelection;
return currentSelection;
}
}
}
memoizedSelection = _nextSelection;
return _nextSelection;
} // We may be able to reuse the previous invocation's result.
// We may be able to reuse the previous invocation's result.
var prevSnapshot = memoizedSnapshot;
var prevSelection = memoizedSelection;
if (objectIs(prevSnapshot, nextSnapshot)) {
// The snapshot is the same as last time. Reuse the previous selection.
return prevSelection;
} // The snapshot has changed, so we need to compute a new selection.
// The snapshot has changed, so we need to compute a new selection.
var nextSelection = selector(nextSnapshot); // If a custom isEqual function is provided, use that to check if the data
// has changed. If it hasn't, return the previous selection. That signals
// to React that the selections are conceptually equal, and we can bail
// out of rendering.
// If a custom isEqual function is provided, use that to check if the data
// has changed. If it hasn't, return the previous selection. That signals
// to React that the selections are conceptually equal, and we can bail
// out of rendering.
if (isEqual !== undefined && isEqual(prevSelection, nextSelection)) {
return prevSelection;
}
memoizedSnapshot = nextSnapshot;
memoizedSelection = nextSelection;
return nextSelection;
}; // Assigning this to a constant so that Flow knows it can't change.
// Assigning this to a constant so that Flow knows it can't change.
var maybeGetServerSnapshot = getServerSnapshot === undefined ? null : getServerSnapshot;
var getSnapshotWithSelector = function () {
return memoizedSelector(getSnapshot());
};
var getServerSnapshotWithSelector = maybeGetServerSnapshot === null ? undefined : function () {
return memoizedSelector(maybeGetServerSnapshot());
};
return [getSnapshotWithSelector, getServerSnapshotWithSelector];
}, [getSnapshot, getServerSnapshot, selector, isEqual]),
getSelection = _useMemo[0],
getServerSelection = _useMemo[1];
var value = useSyncExternalStore(subscribe, getSelection, getServerSelection);
useEffect(function () {
inst.hasValue = true;
inst.value = value;
}, [value]);
useDebugValue(value);
return value;
}
exports.useSyncExternalStoreWithSelector = useSyncExternalStoreWithSelector;
/**
* 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.
*/
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
// Don't require this file directly; it's embedded by Rollup during build.
if (
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
'function'
) {
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
}
})();
}
});
var withSelector = createCommonjsModule(function (module) {
{
module.exports = useSyncExternalStoreWithSelector_development;
}
});
const refEquality = (a, b) => a === b;
/**
* Hook factory, which creates a `useSelector` hook bound to a given context.
*
* @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
* @returns {Function} A `useSelector` hook bound to the specified context.
*/
function createSelectorHook(context = ReactReduxContext) {
const useReduxContext$1 = context === ReactReduxContext ? useReduxContext : () => React.useContext(context);
return function useSelector(selector, equalityFn = refEquality) {
{
if (!selector) {
throw new Error(`You must pass a selector to useSelector`);
}
if (typeof selector !== 'function') {
throw new Error(`You must pass a function as a selector to useSelector`);
}
if (typeof equalityFn !== 'function') {
throw new Error(`You must pass a function as an equality function to useSelector`);
}
}
const {
store
} = useReduxContext$1();
const selectedState = withSelector.useSyncExternalStoreWithSelector(store.subscribe, store.getState, // TODO Need a server-side snapshot here
store.getState, selector, equalityFn);
React.useDebugValue(selectedState);
return selectedState;
};
}
/**
* A hook to access the redux store's state. This hook takes a selector function
* as an argument. The selector is called with the store state.
*
* This hook takes an optional equality comparison function as the second parameter
* that allows you to customize the way the selected state is compared to determine
* whether the component needs to be re-rendered.
*
* @param {Function} selector the selector function
* @param {Function=} equalityFn the function that will be used to determine equality
*
* @returns {any} the selected state
*
* @example
*
* import React from 'react'
* import { useSelector } from 'react-redux'
*
* export const CounterComponent = () => {
* const counter = useSelector(state => state.counter)
* return <div>{counter}</div>
* }
*/
const useSelector = /*#__PURE__*/createSelectorHook();
// with standard React renderers (ReactDOM, React Native)
setBatch(reactDom.unstable_batchedUpdates);
Object.defineProperty(exports, 'batch', {
enumerable: true,
get: function () {
return reactDom.unstable_batchedUpdates;
}
});
exports.Provider = Provider;
exports.ReactReduxContext = ReactReduxContext;
exports.connect = connect;
exports.createDispatchHook = createDispatchHook;
exports.createSelectorHook = createSelectorHook;
exports.createStoreHook = createStoreHook;
exports.shallowEqual = shallowEqual;
exports.useDispatch = useDispatch;
exports.useSelector = useSelector;
exports.useStore = useStore;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
ajax/libs/react-native-web/0.0.0-4fd133e73/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.9.4/es/internal/svg-icons/Close.js | cdnjs/cdnjs | import React from 'react';
import createSvgIcon from './createSvgIcon';
/**
* @ignore - internal component.
*/
export default createSvgIcon(React.createElement("path", {
d: "M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
}), 'Close'); |
ajax/libs/material-ui/4.9.3/esm/GridListTile/GridListTile.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
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 var 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%'
}
};
var fit = function fit(imgEl, classes) {
if (!imgEl || !imgEl.complete) {
return;
}
if (imgEl.width / imgEl.height > imgEl.parentElement.offsetWidth / imgEl.parentElement.offsetHeight) {
var _imgEl$classList, _imgEl$classList2;
(_imgEl$classList = imgEl.classList).remove.apply(_imgEl$classList, _toConsumableArray(classes.imgFullWidth.split(' ')));
(_imgEl$classList2 = imgEl.classList).add.apply(_imgEl$classList2, _toConsumableArray(classes.imgFullHeight.split(' ')));
} else {
var _imgEl$classList3, _imgEl$classList4;
(_imgEl$classList3 = imgEl.classList).remove.apply(_imgEl$classList3, _toConsumableArray(classes.imgFullHeight.split(' ')));
(_imgEl$classList4 = imgEl.classList).add.apply(_imgEl$classList4, _toConsumableArray(classes.imgFullWidth.split(' ')));
}
};
function ensureImageCover(imgEl, classes) {
if (!imgEl) {
return;
}
if (imgEl.complete) {
fit(imgEl, classes);
} else {
imgEl.addEventListener('load', function () {
fit(imgEl, classes);
});
}
}
var GridListTile = React.forwardRef(function GridListTile(props, ref) {
// cols rows default values are for docs only
var children = props.children,
classes = props.classes,
className = props.className,
_props$cols = props.cols,
cols = _props$cols === void 0 ? 1 : _props$cols,
_props$component = props.component,
Component = _props$component === void 0 ? 'li' : _props$component,
_props$rows = props.rows,
rows = _props$rows === void 0 ? 1 : _props$rows,
other = _objectWithoutProperties(props, ["children", "classes", "className", "cols", "component", "rows"]);
var imgRef = React.useRef(null);
React.useEffect(function () {
ensureImageCover(imgRef.current, classes);
});
React.useEffect(function () {
var handleResize = debounce(function () {
fit(imgRef.current, classes);
});
window.addEventListener('resize', handleResize);
return function () {
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, function (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/boardgame-io/0.39.6/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 (type !== 'number') {
error(`invalid value returned by turn.order.next — expected number 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.4/esm/Modal/Modal.js | cdnjs/cdnjs | import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { getThemeProps, useTheme } from '@material-ui/styles';
import { elementAcceptingRef } from '@material-ui/utils';
import ownerDocument from '../utils/ownerDocument';
import Portal from '../Portal';
import createChainedFunction from '../utils/createChainedFunction';
import useForkRef from '../utils/useForkRef';
import useEventCallback from '../utils/useEventCallback';
import zIndex from '../styles/zIndex';
import ModalManager, { ariaHidden } from './ModalManager';
import TrapFocus from './TrapFocus';
import SimpleBackdrop from './SimpleBackdrop';
function getContainer(container) {
container = typeof container === 'function' ? container() : container;
return ReactDOM.findDOMNode(container);
}
function getHasTransition(props) {
return props.children ? props.children.props.hasOwnProperty('in') : false;
} // A modal manager used to track and manage the state of open Modals.
// Modals don't open on the server so this won't conflict with concurrent requests.
var defaultManager = new ModalManager();
export var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: {
position: 'fixed',
zIndex: theme.zIndex.modal,
right: 0,
bottom: 0,
top: 0,
left: 0
},
/* Styles applied to the root element if the `Modal` has exited. */
hidden: {
visibility: 'hidden'
}
};
};
/**
* Modal is a lower-level construct that is leveraged by the following components:
*
* - [Dialog](/api/dialog/)
* - [Drawer](/api/drawer/)
* - [Menu](/api/menu/)
* - [Popover](/api/popover/)
*
* If you are creating a modal dialog, you probably want to use the [Dialog](/api/dialog/) component
* rather than directly using Modal.
*
* This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
*/
var Modal = React.forwardRef(function Modal(inProps, ref) {
var theme = useTheme();
var props = getThemeProps({
name: 'MuiModal',
props: _extends({}, inProps),
theme: theme
});
var _props$BackdropCompon = props.BackdropComponent,
BackdropComponent = _props$BackdropCompon === void 0 ? SimpleBackdrop : _props$BackdropCompon,
BackdropProps = props.BackdropProps,
children = props.children,
_props$closeAfterTran = props.closeAfterTransition,
closeAfterTransition = _props$closeAfterTran === void 0 ? false : _props$closeAfterTran,
container = props.container,
_props$disableAutoFoc = props.disableAutoFocus,
disableAutoFocus = _props$disableAutoFoc === void 0 ? false : _props$disableAutoFoc,
_props$disableBackdro = props.disableBackdropClick,
disableBackdropClick = _props$disableBackdro === void 0 ? false : _props$disableBackdro,
_props$disableEnforce = props.disableEnforceFocus,
disableEnforceFocus = _props$disableEnforce === void 0 ? false : _props$disableEnforce,
_props$disableEscapeK = props.disableEscapeKeyDown,
disableEscapeKeyDown = _props$disableEscapeK === void 0 ? false : _props$disableEscapeK,
_props$disablePortal = props.disablePortal,
disablePortal = _props$disablePortal === void 0 ? false : _props$disablePortal,
_props$disableRestore = props.disableRestoreFocus,
disableRestoreFocus = _props$disableRestore === void 0 ? false : _props$disableRestore,
_props$disableScrollL = props.disableScrollLock,
disableScrollLock = _props$disableScrollL === void 0 ? false : _props$disableScrollL,
_props$hideBackdrop = props.hideBackdrop,
hideBackdrop = _props$hideBackdrop === void 0 ? false : _props$hideBackdrop,
_props$keepMounted = props.keepMounted,
keepMounted = _props$keepMounted === void 0 ? false : _props$keepMounted,
_props$manager = props.manager,
manager = _props$manager === void 0 ? defaultManager : _props$manager,
onBackdropClick = props.onBackdropClick,
onClose = props.onClose,
onEscapeKeyDown = props.onEscapeKeyDown,
onRendered = props.onRendered,
open = props.open,
other = _objectWithoutProperties(props, ["BackdropComponent", "BackdropProps", "children", "closeAfterTransition", "container", "disableAutoFocus", "disableBackdropClick", "disableEnforceFocus", "disableEscapeKeyDown", "disablePortal", "disableRestoreFocus", "disableScrollLock", "hideBackdrop", "keepMounted", "manager", "onBackdropClick", "onClose", "onEscapeKeyDown", "onRendered", "open"]);
var _React$useState = React.useState(true),
exited = _React$useState[0],
setExited = _React$useState[1];
var modal = React.useRef({});
var mountNodeRef = React.useRef(null);
var modalRef = React.useRef(null);
var handleRef = useForkRef(modalRef, ref);
var hasTransition = getHasTransition(props);
var getDoc = function getDoc() {
return ownerDocument(mountNodeRef.current);
};
var getModal = function getModal() {
modal.current.modalRef = modalRef.current;
modal.current.mountNode = mountNodeRef.current;
return modal.current;
};
var handleMounted = function handleMounted() {
manager.mount(getModal(), {
disableScrollLock: disableScrollLock
}); // Fix a bug on Chrome where the scroll isn't initially 0.
modalRef.current.scrollTop = 0;
};
var handleOpen = useEventCallback(function () {
var resolvedContainer = getContainer(container) || getDoc().body;
manager.add(getModal(), resolvedContainer); // The element was already mounted.
if (modalRef.current) {
handleMounted();
}
});
var isTopModal = React.useCallback(function () {
return manager.isTopModal(getModal());
}, [manager]);
var handlePortalRef = useEventCallback(function (node) {
mountNodeRef.current = node;
if (!node) {
return;
}
if (onRendered) {
onRendered();
}
if (open && isTopModal()) {
handleMounted();
} else {
ariaHidden(modalRef.current, true);
}
});
var handleClose = React.useCallback(function () {
manager.remove(getModal());
}, [manager]);
React.useEffect(function () {
return function () {
handleClose();
};
}, [handleClose]);
React.useEffect(function () {
if (open) {
handleOpen();
} else if (!hasTransition || !closeAfterTransition) {
handleClose();
}
}, [open, handleClose, hasTransition, closeAfterTransition, handleOpen]);
if (!keepMounted && !open && (!hasTransition || exited)) {
return null;
}
var handleEnter = function handleEnter() {
setExited(false);
};
var handleExited = function handleExited() {
setExited(true);
if (closeAfterTransition) {
handleClose();
}
};
var handleBackdropClick = function handleBackdropClick(event) {
if (event.target !== event.currentTarget) {
return;
}
if (onBackdropClick) {
onBackdropClick(event);
}
if (!disableBackdropClick && onClose) {
onClose(event, 'backdropClick');
}
};
var handleKeyDown = function handleKeyDown(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.
if (event.key !== 'Escape' || !isTopModal()) {
return;
} // Swallow the event, in case someone is listening for the escape key on the body.
event.stopPropagation();
if (onEscapeKeyDown) {
onEscapeKeyDown(event);
}
if (!disableEscapeKeyDown && onClose) {
onClose(event, 'escapeKeyDown');
}
};
var inlineStyle = styles(theme || {
zIndex: zIndex
});
var childProps = {};
if (children.props.tabIndex === undefined) {
childProps.tabIndex = children.props.tabIndex || '-1';
} // It's a Transition like component
if (hasTransition) {
childProps.onEnter = createChainedFunction(handleEnter, children.props.onEnter);
childProps.onExited = createChainedFunction(handleExited, children.props.onExited);
}
return React.createElement(Portal, {
ref: handlePortalRef,
container: container,
disablePortal: disablePortal
}, React.createElement("div", _extends({
ref: handleRef,
onKeyDown: handleKeyDown,
role: "presentation"
}, other, {
style: _extends({}, inlineStyle.root, {}, !open && exited ? inlineStyle.hidden : {}, {}, other.style)
}), hideBackdrop ? null : React.createElement(BackdropComponent, _extends({
open: open,
onClick: handleBackdropClick
}, BackdropProps)), React.createElement(TrapFocus, {
disableEnforceFocus: disableEnforceFocus,
disableAutoFocus: disableAutoFocus,
disableRestoreFocus: disableRestoreFocus,
getDoc: getDoc,
isEnabled: isTopModal,
open: open
}, React.cloneElement(children, childProps))));
});
process.env.NODE_ENV !== "production" ? Modal.propTypes = {
/**
* A backdrop component. This prop enables custom backdrop rendering.
*/
BackdropComponent: PropTypes.elementType,
/**
* Props applied to the [`Backdrop`](/api/backdrop/) element.
*/
BackdropProps: PropTypes.object,
/**
* A single child content element.
*/
children: elementAcceptingRef.isRequired,
/**
* When set to true the Modal waits until a nested Transition is completed before closing.
*/
closeAfterTransition: PropTypes.bool,
/**
* A node, component instance, or function that returns either.
* The `container` will have the portal children appended to it.
*/
container: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
/**
* If `true`, the modal will not automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes.
* This also works correctly with any modal children that have the `disableAutoFocus` prop.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
*/
disableAutoFocus: PropTypes.bool,
/**
* If `true`, clicking the backdrop will not fire any callback.
*/
disableBackdropClick: PropTypes.bool,
/**
* If `true`, the modal will not prevent focus from leaving the modal while open.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
*/
disableEnforceFocus: PropTypes.bool,
/**
* If `true`, hitting escape will not fire any callback.
*/
disableEscapeKeyDown: PropTypes.bool,
/**
* Disable the portal behavior.
* The children stay within it's parent DOM hierarchy.
*/
disablePortal: PropTypes.bool,
/**
* If `true`, the modal will not restore focus to previously focused element once
* modal is hidden.
*/
disableRestoreFocus: PropTypes.bool,
/**
* Disable the scroll lock behavior.
*/
disableScrollLock: PropTypes.bool,
/**
* If `true`, the backdrop is not rendered.
*/
hideBackdrop: PropTypes.bool,
/**
* Always keep the children in the DOM.
* This prop can be useful in SEO situation or
* when you want to maximize the responsiveness of the Modal.
*/
keepMounted: PropTypes.bool,
/**
* @ignore
*/
manager: PropTypes.object,
/**
* Callback fired when the backdrop is clicked.
*/
onBackdropClick: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
* The `reason` parameter can optionally be used to control the response to `onClose`.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
*/
onClose: PropTypes.func,
/**
* Callback fired when the escape key is pressed,
* `disableEscapeKeyDown` is false and the modal is in focus.
*/
onEscapeKeyDown: PropTypes.func,
/**
* Callback fired once the children has been mounted into the `container`.
* It signals that the `open={true}` prop took effect.
*
* This prop will be deprecated and removed in v5, the ref can be used instead.
*/
onRendered: PropTypes.func,
/**
* If `true`, the modal is open.
*/
open: PropTypes.bool.isRequired
} : void 0;
export default Modal; |
ajax/libs/material-ui/5.0.0-alpha.22/modern/styles/ThemeProvider.js | cdnjs/cdnjs | import React from 'react';
import PropTypes from 'prop-types';
import { ThemeProvider as MuiThemeProvider } from '@material-ui/styles';
import { exactProp } from '@material-ui/utils';
import { ThemeContext as StyledEngineThemeContext } from '@material-ui/styled-engine';
import useTheme from './useTheme';
function InnerThemeProvider(props) {
const theme = useTheme();
return /*#__PURE__*/React.createElement(StyledEngineThemeContext.Provider, {
value: typeof theme === 'object' ? theme : {}
}, props.children);
}
process.env.NODE_ENV !== "production" ? InnerThemeProvider.propTypes = {
/**
* Your component tree.
*/
children: PropTypes.node
} : void 0;
/**
* This component makes the `theme` available down the React tree.
* It should preferably be used at **the root of your component tree**.
*/
function ThemeProvider(props) {
const {
children,
theme: localTheme
} = props;
return /*#__PURE__*/React.createElement(MuiThemeProvider, {
theme: localTheme
}, /*#__PURE__*/React.createElement(InnerThemeProvider, null, children));
}
process.env.NODE_ENV !== "production" ? ThemeProvider.propTypes = {
/**
* Your component tree.
*/
children: PropTypes.node,
/**
* A theme object. You can provide a function to extend the outer theme.
*/
theme: PropTypes.oneOfType([PropTypes.object, PropTypes.func]).isRequired
} : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== "production" ? ThemeProvider.propTypes = exactProp(ThemeProvider.propTypes) : void 0;
}
export default ThemeProvider; |
ajax/libs/react-native-web/0.0.0-bd62af4f4/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.9.3/esm/internal/svg-icons/IndeterminateCheckBox.js | cdnjs/cdnjs | import React from 'react';
import createSvgIcon from './createSvgIcon';
/**
* @ignore - internal component.
*/
export default createSvgIcon(React.createElement("path", {
d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10H7v-2h10v2z"
}), 'IndeterminateCheckBox'); |
ajax/libs/react-native-web/0.15.0/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);
},
/**
* 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/primereact/6.6.0/accordion/accordion.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { UniqueComponentId, classNames, ObjectUtils, CSSTransition } 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 _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var AccordionTab = /*#__PURE__*/function (_Component) {
_inherits(AccordionTab, _Component);
var _super = _createSuper(AccordionTab);
function AccordionTab() {
_classCallCheck(this, AccordionTab);
return _super.apply(this, arguments);
}
return AccordionTab;
}(Component);
_defineProperty(AccordionTab, "defaultProps", {
header: null,
disabled: false,
headerStyle: null,
headerClassName: null,
headerTemplate: null,
contentStyle: null,
contentClassName: null
});
var Accordion = /*#__PURE__*/function (_Component2) {
_inherits(Accordion, _Component2);
var _super2 = _createSuper(Accordion);
function Accordion(props) {
var _this;
_classCallCheck(this, Accordion);
_this = _super2.call(this, props);
var state = {
id: _this.props.id
};
if (!_this.props.onTabChange) {
state = _objectSpread(_objectSpread({}, state), {}, {
activeIndex: props.activeIndex
});
}
_this.state = state;
_this.contentWrappers = [];
return _this;
}
_createClass(Accordion, [{
key: "onTabHeaderClick",
value: function onTabHeaderClick(event, tab, index) {
if (!tab.props.disabled) {
var selected = this.isSelected(index);
var newActiveIndex = null;
if (this.props.multiple) {
var indexes = (this.props.onTabChange ? this.props.activeIndex : this.state.activeIndex) || [];
if (selected) indexes = indexes.filter(function (i) {
return i !== index;
});else indexes = [].concat(_toConsumableArray(indexes), [index]);
newActiveIndex = indexes;
} else {
newActiveIndex = selected ? null : index;
}
var callback = selected ? this.props.onTabClose : this.props.onTabOpen;
if (callback) {
callback({
originalEvent: event,
index: index
});
}
if (this.props.onTabChange) {
this.props.onTabChange({
originalEvent: event,
index: newActiveIndex
});
} else {
this.setState({
activeIndex: newActiveIndex
});
}
}
event.preventDefault();
}
}, {
key: "isSelected",
value: function isSelected(index) {
var activeIndex = this.props.onTabChange ? this.props.activeIndex : this.state.activeIndex;
return this.props.multiple ? activeIndex && activeIndex.indexOf(index) >= 0 : activeIndex === index;
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (!this.state.id) {
this.setState({
id: UniqueComponentId()
});
}
}
}, {
key: "renderTabHeader",
value: function renderTabHeader(tab, selected, index) {
var _classNames,
_this2 = this;
var tabHeaderClass = classNames('p-accordion-header', {
'p-highlight': selected,
'p-disabled': tab.props.disabled
}, tab.props.headerClassName);
var iconClassName = classNames('p-accordion-toggle-icon', (_classNames = {}, _defineProperty(_classNames, "".concat(this.props.expandIcon), !selected), _defineProperty(_classNames, "".concat(this.props.collapseIcon), selected), _classNames));
var id = this.state.id + '_header_' + index;
var ariaControls = this.state.id + '_content_' + index;
var tabIndex = tab.props.disabled ? -1 : null;
var header = tab.props.headerTemplate ? ObjectUtils.getJSXElement(tab.props.headerTemplate, tab.props) : /*#__PURE__*/React.createElement("span", {
className: "p-accordion-header-text"
}, tab.props.header);
return /*#__PURE__*/React.createElement("div", {
className: tabHeaderClass,
style: tab.props.headerStyle
}, /*#__PURE__*/React.createElement("a", {
href: '#' + ariaControls,
id: id,
className: "p-accordion-header-link",
"aria-controls": ariaControls,
role: "tab",
"aria-expanded": selected,
onClick: function onClick(event) {
return _this2.onTabHeaderClick(event, tab, index);
},
tabIndex: tabIndex
}, /*#__PURE__*/React.createElement("span", {
className: iconClassName
}), header));
}
}, {
key: "renderTabContent",
value: function renderTabContent(tab, selected, index) {
var className = classNames('p-toggleable-content', tab.props.contentClassName);
var id = this.state.id + '_content_' + index;
var toggleableContentRef = /*#__PURE__*/React.createRef();
return /*#__PURE__*/React.createElement(CSSTransition, {
nodeRef: toggleableContentRef,
classNames: "p-toggleable-content",
timeout: {
enter: 1000,
exit: 450
},
in: selected,
unmountOnExit: true,
options: this.props.transitionOptions
}, /*#__PURE__*/React.createElement("div", {
ref: toggleableContentRef,
id: id,
className: className,
style: tab.props.contentStyle,
role: "region",
"aria-labelledby": this.state.id + '_header_' + index
}, /*#__PURE__*/React.createElement("div", {
className: "p-accordion-content"
}, tab.props.children)));
}
}, {
key: "renderTab",
value: function renderTab(tab, index) {
var selected = this.isSelected(index);
var tabHeader = this.renderTabHeader(tab, selected, index);
var tabContent = this.renderTabContent(tab, selected, index);
var tabClassName = classNames('p-accordion-tab', {
'p-accordion-tab-active': selected
});
return /*#__PURE__*/React.createElement("div", {
key: tab.props.header,
className: tabClassName
}, tabHeader, tabContent);
}
}, {
key: "renderTabs",
value: function renderTabs() {
var _this3 = this;
return React.Children.map(this.props.children, function (tab, index) {
if (tab && tab.type === AccordionTab) {
return _this3.renderTab(tab, index);
}
});
}
}, {
key: "render",
value: function render() {
var _this4 = this;
var className = classNames('p-accordion p-component', this.props.className);
var tabs = this.renderTabs();
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this4.container = el;
},
id: this.state.id,
className: className,
style: this.props.style
}, tabs);
}
}]);
return Accordion;
}(Component);
_defineProperty(Accordion, "defaultProps", {
id: null,
activeIndex: null,
className: null,
style: null,
multiple: false,
expandIcon: 'pi pi-chevron-right',
collapseIcon: 'pi pi-chevron-down',
transitionOptions: null,
onTabOpen: null,
onTabClose: null,
onTabChange: null
});
export { Accordion, AccordionTab };
|
ajax/libs/primereact/6.5.1/terminal/terminal.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { TerminalService } from 'primereact/terminalservice';
import { classNames } from 'primereact/core';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Terminal = /*#__PURE__*/function (_Component) {
_inherits(Terminal, _Component);
var _super = _createSuper(Terminal);
function Terminal(props) {
var _this;
_classCallCheck(this, Terminal);
_this = _super.call(this, props);
_this.state = {
commandText: '',
commands: [],
index: 0
};
_this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
_this.onInputChange = _this.onInputChange.bind(_assertThisInitialized(_this));
_this.onInputKeyDown = _this.onInputKeyDown.bind(_assertThisInitialized(_this));
_this.response = _this.response.bind(_assertThisInitialized(_this));
_this.clear = _this.clear.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(Terminal, [{
key: "onClick",
value: function onClick() {
this.input.focus();
}
}, {
key: "onInputChange",
value: function onInputChange(e) {
this.setState({
commandText: e.target.value
});
}
}, {
key: "onInputKeyDown",
value: function onInputKeyDown(e) {
var code = e.which || e.keyCode;
var commands = this.state.commands;
switch (code) {
//up
case 38:
if (commands && commands.length) {
var prevIndex = this.state.index - 1 < 0 ? commands.length - 1 : this.state.index - 1;
var command = commands[prevIndex];
this.setState({
index: prevIndex,
commandText: command.text
});
}
break;
//enter
case 13:
if (!!this.state.commandText) {
var newCommands = _toConsumableArray(commands);
var text = this.state.commandText;
newCommands.push({
text: text
});
this.setState(function (prevState) {
return {
index: prevState.index + 1,
commandText: '',
commands: newCommands
};
}, function () {
TerminalService.emit('command', text);
});
}
break;
}
}
}, {
key: "response",
value: function response(res) {
var commands = this.state.commands;
if (commands && commands.length > 0) {
var _commands = _toConsumableArray(commands);
_commands[_commands.length - 1].response = res;
this.setState({
commands: _commands
});
}
}
}, {
key: "clear",
value: function clear() {
this.setState({
commands: [],
index: 0
});
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
TerminalService.on('response', this.response);
TerminalService.on('clear', this.clear);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
this.container.scrollTop = this.container.scrollHeight;
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
TerminalService.off('response', this.response);
TerminalService.off('clear', this.clear);
}
}, {
key: "renderWelcomeMessage",
value: function renderWelcomeMessage() {
if (this.props.welcomeMessage) {
return /*#__PURE__*/React.createElement("div", null, this.props.welcomeMessage);
}
return null;
}
}, {
key: "renderCommand",
value: function renderCommand(command, index) {
var text = command.text,
response = command.response;
return /*#__PURE__*/React.createElement("div", {
key: "".concat(text).concat(index)
}, /*#__PURE__*/React.createElement("span", {
className: "p-terminal-prompt"
}, this.props.prompt, "\xA0"), /*#__PURE__*/React.createElement("span", {
className: "p-terminal-command"
}, text), /*#__PURE__*/React.createElement("div", {
className: "p-terminal-response"
}, response));
}
}, {
key: "renderContent",
value: function renderContent() {
var _this2 = this;
var commands = this.state.commands.map(function (c, i) {
return _this2.renderCommand(c, i);
});
return /*#__PURE__*/React.createElement("div", {
className: "p-terminal-content"
}, commands);
}
}, {
key: "renderPromptContainer",
value: function renderPromptContainer() {
var _this3 = this;
return /*#__PURE__*/React.createElement("div", {
className: "p-terminal-prompt-container"
}, /*#__PURE__*/React.createElement("span", {
className: "p-terminal-prompt"
}, this.props.prompt, "\xA0"), /*#__PURE__*/React.createElement("input", {
ref: function ref(el) {
return _this3.input = el;
},
type: "text",
value: this.state.commandText,
className: "p-terminal-input",
autoComplete: "off",
onChange: this.onInputChange,
onKeyDown: this.onInputKeyDown
}));
}
}, {
key: "render",
value: function render() {
var _this4 = this;
var className = classNames('p-terminal p-component', this.props.className);
var welcomeMessage = this.renderWelcomeMessage();
var content = this.renderContent();
var prompt = this.renderPromptContainer();
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this4.container = el;
},
id: this.props.id,
className: className,
style: this.props.style,
onClick: this.onClick
}, welcomeMessage, content, prompt);
}
}]);
return Terminal;
}(Component);
_defineProperty(Terminal, "defaultProps", {
id: null,
style: null,
className: null,
welcomeMessage: null,
prompt: null
});
export { Terminal };
|
ajax/libs/boardgame-io/0.46.0/esm/react.js | cdnjs/cdnjs | import 'nanoid';
import './Debug-2442efb1.js';
import 'redux';
import './turn-order-21b8f302.js';
import 'immer';
import 'lodash.isplainobject';
import './reducer-f5240269.js';
import 'rfc6902';
import './initialize-c886df92.js';
import './transport-0079de87.js';
import { C as Client$1 } from './client-cb18d220.js';
import 'flatted';
import { M as MCTSBot } from './ai-6a82d805.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-fbc37e56.js';
import './master-cf421046.js';
import 'socket.io-client';
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Client
*
* boardgame.io React client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} debug - Enables the Debug UI.
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET,
* UNDO and REDO.
*/
function Client(opts) {
var _a;
let { game, numPlayers, loading, board, multiplayer, enhancer, debug } = opts;
// Component that is displayed before the client has synced
// with the game master.
if (loading === undefined) {
const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting...");
loading = Loading;
}
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _a = class WrappedBoard extends React.Component {
constructor(props) {
super(props);
if (debug === undefined) {
debug = props.debug;
}
this.client = Client$1({
game,
debug,
numPlayers,
multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
enhancer,
});
}
componentDidMount() {
this.unsubscribe = this.client.subscribe(() => this.forceUpdate());
this.client.start();
}
componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
componentDidUpdate(prevProps) {
if (this.props.matchID != prevProps.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (this.props.playerID != prevProps.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (this.props.credentials != prevProps.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
render() {
const state = this.client.getState();
if (state === null) {
return React.createElement(loading);
}
let _board = null;
if (board) {
_board = React.createElement(board, {
...state,
...this.props,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
matchID: this.client.matchID,
playerID: this.client.playerID,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
log: this.client.log,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages,
});
}
return React.createElement("div", { className: "bgio-client" }, _board);
}
},
_a.propTypes = {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string,
// Enable / disable the Debug UI.
debug: PropTypes.any,
},
_a.defaultProps = {
matchID: 'default',
playerID: null,
credentials: null,
debug: true,
},
_a;
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
class _LobbyConnectionImpl {
constructor({ server, gameComponents, playerName, playerCredentials, }) {
this.client = new LobbyClient({ server });
this.gameComponents = gameComponents;
this.playerName = playerName || 'Visitor';
this.playerCredentials = playerCredentials;
this.matches = [];
}
async refresh() {
try {
this.matches = [];
const games = await this.client.listGames();
for (const game of games) {
if (!this._getGameComponents(game))
continue;
const { matches } = await this.client.listMatches(game);
this.matches.push(...matches);
}
}
catch (error) {
throw new Error('failed to retrieve list of matches (' + error + ')');
}
}
_getMatchInstance(matchID) {
for (const inst of this.matches) {
if (inst['matchID'] === matchID)
return inst;
}
}
_getGameComponents(gameName) {
for (const comp of this.gameComponents) {
if (comp.game.name === gameName)
return comp;
}
}
_findPlayer(playerName) {
for (const inst of this.matches) {
if (inst.players.some((player) => player.name === playerName))
return inst;
}
}
async join(gameName, matchID, playerID) {
try {
let inst = this._findPlayer(this.playerName);
if (inst) {
throw new Error('player has already joined ' + inst.matchID);
}
inst = this._getMatchInstance(matchID);
if (!inst) {
throw new Error('game instance ' + matchID + ' not found');
}
const json = await this.client.joinMatch(gameName, matchID, {
playerID,
playerName: this.playerName,
});
inst.players[Number.parseInt(playerID)].name = this.playerName;
this.playerCredentials = json.playerCredentials;
}
catch (error) {
throw new Error('failed to join match ' + matchID + ' (' + error + ')');
}
}
async leave(gameName, matchID) {
try {
const inst = this._getMatchInstance(matchID);
if (!inst)
throw new Error('match instance not found');
for (const player of inst.players) {
if (player.name === this.playerName) {
await this.client.leaveMatch(gameName, matchID, {
playerID: player.id.toString(),
credentials: this.playerCredentials,
});
delete player.name;
delete this.playerCredentials;
return;
}
}
throw new Error('player not found in match');
}
catch (error) {
throw new Error('failed to leave match ' + matchID + ' (' + error + ')');
}
}
async disconnect() {
const inst = this._findPlayer(this.playerName);
if (inst) {
await this.leave(inst.gameName, inst.matchID);
}
this.matches = [];
this.playerName = 'Visitor';
}
async create(gameName, numPlayers) {
try {
const comp = this._getGameComponents(gameName);
if (!comp)
throw new Error('game not found');
if (numPlayers < comp.game.minPlayers ||
numPlayers > comp.game.maxPlayers)
throw new Error('invalid number of players ' + numPlayers);
await this.client.createMatch(gameName, { numPlayers });
}
catch (error) {
throw new Error('failed to create match for ' + gameName + ' (' + error + ')');
}
}
}
/**
* LobbyConnection
*
* Lobby model.
*
* @param {string} server - '<host>:<port>' of the server.
* @param {Array} gameComponents - A map of Board and Game objects for the supported games.
* @param {string} playerName - The name of the player.
* @param {string} playerCredentials - The credentials currently used by the player, if any.
*
* Returns:
* A JS object that synchronizes the list of running game instances with the server and provides an API to create/join/start instances.
*/
function LobbyConnection(opts) {
return new _LobbyConnectionImpl(opts);
}
/*
* Copyright 2018 The boardgame.io Authors.
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
class LobbyLoginForm extends React.Component {
constructor() {
super(...arguments);
this.state = {
playerName: this.props.playerName,
nameErrorMsg: '',
};
this.onClickEnter = () => {
if (this.state.playerName === '')
return;
this.props.onEnter(this.state.playerName);
};
this.onKeyPress = (event) => {
if (event.key === 'Enter') {
this.onClickEnter();
}
};
this.onChangePlayerName = (event) => {
const name = event.target.value.trim();
this.setState({
playerName: name,
nameErrorMsg: name.length > 0 ? '' : 'empty player name',
});
};
}
render() {
return (React.createElement("div", null,
React.createElement("p", { className: "phase-title" }, "Choose a player name:"),
React.createElement("input", { type: "text", value: this.state.playerName, onChange: this.onChangePlayerName, onKeyPress: this.onKeyPress }),
React.createElement("span", { className: "buttons" },
React.createElement("button", { className: "buttons", onClick: this.onClickEnter }, "Enter")),
React.createElement("br", null),
React.createElement("span", { className: "error-msg" },
this.state.nameErrorMsg,
React.createElement("br", null))));
}
}
LobbyLoginForm.defaultProps = {
playerName: '',
};
/*
* Copyright 2018 The boardgame.io Authors.
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
class LobbyMatchInstance extends React.Component {
constructor() {
super(...arguments);
this._createSeat = (player) => {
return player.name || '[free]';
};
this._createButtonJoin = (inst, seatId) => (React.createElement("button", { key: 'button-join-' + inst.matchID, onClick: () => this.props.onClickJoin(inst.gameName, inst.matchID, '' + seatId) }, "Join"));
this._createButtonLeave = (inst) => (React.createElement("button", { key: 'button-leave-' + inst.matchID, onClick: () => this.props.onClickLeave(inst.gameName, inst.matchID) }, "Leave"));
this._createButtonPlay = (inst, seatId) => (React.createElement("button", { key: 'button-play-' + inst.matchID, onClick: () => this.props.onClickPlay(inst.gameName, {
matchID: inst.matchID,
playerID: '' + seatId,
numPlayers: inst.players.length,
}) }, "Play"));
this._createButtonSpectate = (inst) => (React.createElement("button", { key: 'button-spectate-' + inst.matchID, onClick: () => this.props.onClickPlay(inst.gameName, {
matchID: inst.matchID,
numPlayers: inst.players.length,
}) }, "Spectate"));
this._createInstanceButtons = (inst) => {
const playerSeat = inst.players.find((player) => player.name === this.props.playerName);
const freeSeat = inst.players.find((player) => !player.name);
if (playerSeat && freeSeat) {
// already seated: waiting for match to start
return this._createButtonLeave(inst);
}
if (freeSeat) {
// at least 1 seat is available
return this._createButtonJoin(inst, freeSeat.id);
}
// match is full
if (playerSeat) {
return (React.createElement("div", null, [
this._createButtonPlay(inst, playerSeat.id),
this._createButtonLeave(inst),
]));
}
// allow spectating
return this._createButtonSpectate(inst);
};
}
render() {
const match = this.props.match;
let status = 'OPEN';
if (!match.players.some((player) => !player.name)) {
status = 'RUNNING';
}
return (React.createElement("tr", { key: 'line-' + match.matchID },
React.createElement("td", { key: 'cell-name-' + match.matchID }, match.gameName),
React.createElement("td", { key: 'cell-status-' + match.matchID }, status),
React.createElement("td", { key: 'cell-seats-' + match.matchID }, match.players.map((player) => this._createSeat(player)).join(', ')),
React.createElement("td", { key: 'cell-buttons-' + match.matchID }, this._createInstanceButtons(match))));
}
}
/*
* Copyright 2018 The boardgame.io Authors.
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
class LobbyCreateMatchForm extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedGame: 0,
numPlayers: 2,
};
this._createGameNameOption = (game, idx) => {
return (React.createElement("option", { key: 'name-option-' + idx, value: idx }, game.game.name));
};
this._createNumPlayersOption = (idx) => {
return (React.createElement("option", { key: 'num-option-' + idx, value: idx }, idx));
};
this._createNumPlayersRange = (game) => {
return Array.from({ length: game.maxPlayers + 1 })
.map((_, i) => i)
.slice(game.minPlayers);
};
this.onChangeNumPlayers = (event) => {
this.setState({
numPlayers: Number.parseInt(event.target.value),
});
};
this.onChangeSelectedGame = (event) => {
const idx = Number.parseInt(event.target.value);
this.setState({
selectedGame: idx,
numPlayers: this.props.games[idx].game.minPlayers,
});
};
this.onClickCreate = () => {
this.props.createMatch(this.props.games[this.state.selectedGame].game.name, this.state.numPlayers);
};
/* fix min and max number of players */
for (const game of props.games) {
const matchDetails = game.game;
if (!matchDetails.minPlayers) {
matchDetails.minPlayers = 1;
}
if (!matchDetails.maxPlayers) {
matchDetails.maxPlayers = 4;
}
console.assert(matchDetails.maxPlayers >= matchDetails.minPlayers);
}
this.state = {
selectedGame: 0,
numPlayers: props.games[0].game.minPlayers,
};
}
render() {
return (React.createElement("div", null,
React.createElement("select", { value: this.state.selectedGame, onChange: (evt) => this.onChangeSelectedGame(evt) }, this.props.games.map((game, index) => this._createGameNameOption(game, index))),
React.createElement("span", null, "Players:"),
React.createElement("select", { value: this.state.numPlayers, onChange: this.onChangeNumPlayers }, this._createNumPlayersRange(this.props.games[this.state.selectedGame].game).map((number) => this._createNumPlayersOption(number))),
React.createElement("span", { className: "buttons" },
React.createElement("button", { onClick: this.onClickCreate }, "Create"))));
}
}
/*
* Copyright 2018 The boardgame.io Authors.
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
var LobbyPhases;
(function (LobbyPhases) {
LobbyPhases["ENTER"] = "enter";
LobbyPhases["PLAY"] = "play";
LobbyPhases["LIST"] = "list";
})(LobbyPhases || (LobbyPhases = {}));
/**
* Lobby
*
* React lobby component.
*
* @param {Array} gameComponents - An array of Board and Game objects for the supported games.
* @param {string} lobbyServer - Address of the lobby server (for example 'localhost:8000').
* If not set, defaults to the server that served the page.
* @param {string} gameServer - Address of the game server (for example 'localhost:8001').
* If not set, defaults to the server that served the page.
* @param {function} clientFactory - Function that is used to create the game clients.
* @param {number} refreshInterval - Interval between server updates (default: 2000ms).
* @param {bool} debug - Enable debug information (default: false).
*
* Returns:
* A React component that provides a UI to create, list, join, leave, play or
* spectate matches (game instances).
*/
class Lobby extends React.Component {
constructor(props) {
super(props);
this.state = {
phase: LobbyPhases.ENTER,
playerName: 'Visitor',
runningMatch: null,
errorMsg: '',
credentialStore: {},
};
this._createConnection = (props) => {
const name = this.state.playerName;
this.connection = LobbyConnection({
server: props.lobbyServer,
gameComponents: props.gameComponents,
playerName: name,
playerCredentials: this.state.credentialStore[name],
});
};
this._updateCredentials = (playerName, credentials) => {
this.setState((prevState) => {
// clone store or componentDidUpdate will not be triggered
const store = Object.assign({}, prevState.credentialStore);
store[playerName] = credentials;
return { credentialStore: store };
});
};
this._updateConnection = async () => {
await this.connection.refresh();
this.forceUpdate();
};
this._enterLobby = (playerName) => {
this.setState({ playerName, phase: LobbyPhases.LIST });
};
this._exitLobby = async () => {
await this.connection.disconnect();
this.setState({ phase: LobbyPhases.ENTER, errorMsg: '' });
};
this._createMatch = async (gameName, numPlayers) => {
try {
await this.connection.create(gameName, numPlayers);
await this.connection.refresh();
// rerender
this.setState({});
}
catch (error) {
this.setState({ errorMsg: error.message });
}
};
this._joinMatch = async (gameName, matchID, playerID) => {
try {
await this.connection.join(gameName, matchID, playerID);
await this.connection.refresh();
this._updateCredentials(this.connection.playerName, this.connection.playerCredentials);
}
catch (error) {
this.setState({ errorMsg: error.message });
}
};
this._leaveMatch = async (gameName, matchID) => {
try {
await this.connection.leave(gameName, matchID);
await this.connection.refresh();
this._updateCredentials(this.connection.playerName, this.connection.playerCredentials);
}
catch (error) {
this.setState({ errorMsg: error.message });
}
};
this._startMatch = (gameName, matchOpts) => {
const gameCode = this.connection._getGameComponents(gameName);
if (!gameCode) {
this.setState({
errorMsg: 'game ' + gameName + ' not supported',
});
return;
}
let multiplayer = undefined;
if (matchOpts.numPlayers > 1) {
multiplayer = this.props.gameServer
? SocketIO({ server: this.props.gameServer })
: SocketIO();
}
if (matchOpts.numPlayers == 1) {
const maxPlayers = gameCode.game.maxPlayers;
const bots = {};
for (let i = 1; i < maxPlayers; i++) {
bots[i + ''] = MCTSBot;
}
multiplayer = Local({ bots });
}
const app = this.props.clientFactory({
game: gameCode.game,
board: gameCode.board,
debug: this.props.debug,
multiplayer,
});
const match = {
app: app,
matchID: matchOpts.matchID,
playerID: matchOpts.numPlayers > 1 ? matchOpts.playerID : '0',
credentials: this.connection.playerCredentials,
};
this.setState({ phase: LobbyPhases.PLAY, runningMatch: match });
};
this._exitMatch = () => {
this.setState({ phase: LobbyPhases.LIST, runningMatch: null });
};
this._getPhaseVisibility = (phase) => {
return this.state.phase !== phase ? 'hidden' : 'phase';
};
this.renderMatches = (matches, playerName) => {
return matches.map((match) => {
const { matchID, gameName, players } = match;
return (React.createElement(LobbyMatchInstance, { key: 'instance-' + matchID, match: { matchID, gameName, players: Object.values(players) }, playerName: playerName, onClickJoin: this._joinMatch, onClickLeave: this._leaveMatch, onClickPlay: this._startMatch }));
});
};
this._createConnection(this.props);
setInterval(this._updateConnection, this.props.refreshInterval);
}
componentDidMount() {
const cookie = Cookies.load('lobbyState') || {};
if (cookie.phase && cookie.phase === LobbyPhases.PLAY) {
cookie.phase = LobbyPhases.LIST;
}
this.setState({
phase: cookie.phase || LobbyPhases.ENTER,
playerName: cookie.playerName || 'Visitor',
credentialStore: cookie.credentialStore || {},
});
}
componentDidUpdate(prevProps, prevState) {
const name = this.state.playerName;
const creds = this.state.credentialStore[name];
if (prevState.phase !== this.state.phase ||
prevState.credentialStore[name] !== creds ||
prevState.playerName !== name) {
this._createConnection(this.props);
this._updateConnection();
const cookie = {
phase: this.state.phase,
playerName: name,
credentialStore: this.state.credentialStore,
};
Cookies.save('lobbyState', cookie, { path: '/' });
}
}
render() {
const { gameComponents, renderer } = this.props;
const { errorMsg, playerName, phase, runningMatch } = this.state;
if (renderer) {
return renderer({
errorMsg,
gameComponents,
matches: this.connection.matches,
phase,
playerName,
runningMatch,
handleEnterLobby: this._enterLobby,
handleExitLobby: this._exitLobby,
handleCreateMatch: this._createMatch,
handleJoinMatch: this._joinMatch,
handleLeaveMatch: this._leaveMatch,
handleExitMatch: this._exitMatch,
handleRefreshMatches: this._updateConnection,
handleStartMatch: this._startMatch,
});
}
return (React.createElement("div", { id: "lobby-view", style: { padding: 50 } },
React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.ENTER) },
React.createElement(LobbyLoginForm, { key: playerName, playerName: playerName, onEnter: this._enterLobby })),
React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.LIST) },
React.createElement("p", null,
"Welcome, ",
playerName),
React.createElement("div", { className: "phase-title", id: "match-creation" },
React.createElement("span", null, "Create a match:"),
React.createElement(LobbyCreateMatchForm, { games: gameComponents, createMatch: this._createMatch })),
React.createElement("p", { className: "phase-title" }, "Join a match:"),
React.createElement("div", { id: "instances" },
React.createElement("table", null,
React.createElement("tbody", null, this.renderMatches(this.connection.matches, playerName))),
React.createElement("span", { className: "error-msg" },
errorMsg,
React.createElement("br", null))),
React.createElement("p", { className: "phase-title" }, "Matches that become empty are automatically deleted.")),
React.createElement("div", { className: this._getPhaseVisibility(LobbyPhases.PLAY) },
runningMatch && (React.createElement(runningMatch.app, { matchID: runningMatch.matchID, playerID: runningMatch.playerID, credentials: runningMatch.credentials })),
React.createElement("div", { className: "buttons", id: "match-exit" },
React.createElement("button", { onClick: this._exitMatch }, "Exit match"))),
React.createElement("div", { className: "buttons", id: "lobby-exit" },
React.createElement("button", { onClick: this._exitLobby }, "Exit lobby"))));
}
}
Lobby.propTypes = {
gameComponents: PropTypes.array.isRequired,
lobbyServer: PropTypes.string,
gameServer: PropTypes.string,
debug: PropTypes.bool,
clientFactory: PropTypes.func,
refreshInterval: PropTypes.number,
};
Lobby.defaultProps = {
debug: false,
clientFactory: Client,
refreshInterval: 2000,
};
export { Client, Lobby };
|
ajax/libs/boardgame-io/0.39.13/esm/react-native.js | cdnjs/cdnjs | import { z as _inherits, _ as _createClass, B as _defineProperty, t as _classCallCheck, C as _possibleConstructorReturn, D as _getPrototypeOf, K as _objectWithoutProperties, r as _objectSpread2 } from './turn-order-b89c94e7.js';
import 'redux';
import 'immer';
import './reducer-f8e7aa66.js';
import './Debug-2d6f2f47.js';
import 'flatted';
import './ai-3a30115d.js';
import './initialize-d650b559.js';
import { C as Client$1 } from './client-46dff2fb.js';
import React from 'react';
import PropTypes from 'prop-types';
/**
* 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);
function WrappedBoard(props) {
var _this;
_classCallCheck(this, WrappedBoard);
_this = _possibleConstructorReturn(this, _getPrototypeOf(WrappedBoard).call(this, props));
_this.client = Client$1({
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;
}
export { Client };
|
ajax/libs/primereact/7.2.0/confirmdialog/confirmdialog.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { DomHandler, classNames, ObjectUtils, IconUtils } from 'primereact/utils';
import { Dialog } from 'primereact/dialog';
import { Button } from 'primereact/button';
import { localeOption } from 'primereact/api';
import { Portal } from 'primereact/portal';
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function confirmDialog(props) {
var appendTo = props.appendTo || document.body;
var confirmDialogWrapper = document.createDocumentFragment();
DomHandler.appendChild(confirmDialogWrapper, appendTo);
props = _objectSpread(_objectSpread({}, props), {
visible: props.visible === undefined ? true : props.visible
});
var confirmDialogEl = /*#__PURE__*/React.createElement(ConfirmDialog, props);
ReactDOM.render(confirmDialogEl, confirmDialogWrapper);
var updateConfirmDialog = function updateConfirmDialog(newProps) {
props = _objectSpread(_objectSpread({}, props), newProps);
ReactDOM.render( /*#__PURE__*/React.cloneElement(confirmDialogEl, props), confirmDialogWrapper);
};
return {
_destroy: function _destroy() {
ReactDOM.unmountComponentAtNode(confirmDialogWrapper);
},
show: function show() {
updateConfirmDialog({
visible: true,
onHide: function onHide() {
updateConfirmDialog({
visible: false
}); // reset
}
});
},
hide: function hide() {
updateConfirmDialog({
visible: false
});
},
update: function update(newProps) {
updateConfirmDialog(newProps);
}
};
}
var ConfirmDialog = /*#__PURE__*/function (_Component) {
_inherits(ConfirmDialog, _Component);
var _super = _createSuper(ConfirmDialog);
function ConfirmDialog(props) {
var _this;
_classCallCheck(this, ConfirmDialog);
_this = _super.call(this, props);
_this.state = {
visible: props.visible
};
_this.reject = _this.reject.bind(_assertThisInitialized(_this));
_this.accept = _this.accept.bind(_assertThisInitialized(_this));
_this.hide = _this.hide.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(ConfirmDialog, [{
key: "acceptLabel",
value: function acceptLabel() {
return this.props.acceptLabel || localeOption('accept');
}
}, {
key: "rejectLabel",
value: function rejectLabel() {
return this.props.rejectLabel || localeOption('reject');
}
}, {
key: "accept",
value: function accept() {
if (this.props.accept) {
this.props.accept();
}
this.hide('accept');
}
}, {
key: "reject",
value: function reject() {
if (this.props.reject) {
this.props.reject();
}
this.hide('reject');
}
}, {
key: "show",
value: function show() {
this.setState({
visible: true
});
}
}, {
key: "hide",
value: function hide(result) {
var _this2 = this;
this.setState({
visible: false
}, function () {
if (_this2.props.onHide) {
_this2.props.onHide(result);
}
});
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.visible !== this.props.visible) {
this.setState({
visible: this.props.visible
});
}
}
}, {
key: "renderFooter",
value: function renderFooter() {
var acceptClassName = classNames('p-confirm-dialog-accept', this.props.acceptClassName);
var rejectClassName = classNames('p-confirm-dialog-reject', {
'p-button-text': !this.props.rejectClassName
}, this.props.rejectClassName);
var content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, {
label: this.rejectLabel(),
icon: this.props.rejectIcon,
className: rejectClassName,
onClick: this.reject
}), /*#__PURE__*/React.createElement(Button, {
label: this.acceptLabel(),
icon: this.props.acceptIcon,
className: acceptClassName,
onClick: this.accept,
autoFocus: true
}));
if (this.props.footer) {
var defaultContentOptions = {
accept: this.accept,
reject: this.reject,
acceptClassName: acceptClassName,
rejectClassName: rejectClassName,
acceptLabel: this.acceptLabel(),
rejectLabel: this.rejectLabel(),
element: content,
props: this.props
};
return ObjectUtils.getJSXElement(this.props.footer, defaultContentOptions);
}
return content;
}
}, {
key: "renderElement",
value: function renderElement() {
var className = classNames('p-confirm-dialog', this.props.className);
var dialogProps = ObjectUtils.findDiffKeys(this.props, ConfirmDialog.defaultProps);
var message = ObjectUtils.getJSXElement(this.props.message, this.props);
var footer = this.renderFooter();
return /*#__PURE__*/React.createElement(Dialog, _extends({
visible: this.state.visible
}, dialogProps, {
className: className,
footer: footer,
onHide: this.hide,
breakpoints: this.props.breakpoints
}), IconUtils.getJSXIcon(this.props.icon, {
className: 'p-confirm-dialog-icon'
}, {
props: this.props
}), /*#__PURE__*/React.createElement("span", {
className: "p-confirm-dialog-message"
}, message));
}
}, {
key: "render",
value: function render() {
var element = this.renderElement();
return /*#__PURE__*/React.createElement(Portal, {
element: element,
appendTo: this.props.appendTo
});
}
}]);
return ConfirmDialog;
}(Component);
_defineProperty(ConfirmDialog, "defaultProps", {
visible: false,
message: null,
rejectLabel: null,
acceptLabel: null,
icon: null,
rejectIcon: null,
acceptIcon: null,
rejectClassName: null,
acceptClassName: null,
className: null,
appendTo: null,
footer: null,
breakpoints: null,
onHide: null,
accept: null,
reject: null
});
export { ConfirmDialog, confirmDialog };
|
ajax/libs/react-native-web/0.11.4/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/material-ui/4.9.2/es/utils/isMuiElement.js | cdnjs/cdnjs | import React from 'react';
export default function isMuiElement(element, muiNames) {
return React.isValidElement(element) && muiNames.indexOf(element.type.muiName) !== -1;
} |
ajax/libs/react-native-web/0.0.0-376ccc31b/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.0.0-bd62af4f4/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; |
pages/layout/grid.js | Kagami/material-ui | import 'docs/src/modules/components/bootstrap';
// --- Post bootstrap -----
import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
const req = require.context('docs/src/pages/layout/grid', false, /\.md|\.js$/);
const reqSource = require.context('!raw-loader!../../docs/src/pages/layout/grid', false, /\.js$/);
const reqPrefix = 'pages/layout/grid';
function Page() {
return <MarkdownDocs req={req} reqSource={reqSource} reqPrefix={reqPrefix} />;
}
export default Page;
|
packages/material-ui-icons/src/KeyboardBackspaceTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M21 11H6.83l3.58-3.59L9 6l-6 6 6 6 1.41-1.41L6.83 13H21v-2z" /></g></React.Fragment>
, 'KeyboardBackspaceTwoTone');
|
pages/index.js | Kagami/material-ui | import 'docs/src/modules/components/bootstrap';
// --- Post bootstrap -----
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import HomeSteps from 'docs/src/modules/components/HomeSteps';
import Tidelift from 'docs/src/modules/components/Tidelift';
import HomeBackers from 'docs/src/modules/components/HomeBackers';
import HomeFooter from 'docs/src/modules/components/HomeFooter';
import AppFrame from 'docs/src/modules/components/AppFrame';
import Link from 'docs/src/modules/components/Link';
import Head from 'docs/src/modules/components/Head';
const styles = theme => ({
root: {
flex: '1 0 100%',
},
hero: {
minHeight: '80vh',
flex: '0 0 auto',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: theme.palette.background.paper,
color: theme.palette.type === 'light' ? theme.palette.primary.dark : theme.palette.primary.main,
},
text: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
},
title: {
letterSpacing: '.7rem',
textIndent: '.7rem',
fontWeight: theme.typography.fontWeightLight,
[theme.breakpoints.only('xs')]: {
fontSize: 28,
},
whiteSpace: 'nowrap',
},
headline: {
paddingLeft: theme.spacing.unit * 4,
paddingRight: theme.spacing.unit * 4,
marginTop: theme.spacing.unit,
maxWidth: 500,
textAlign: 'center',
},
content: {
paddingBottom: theme.spacing.unit * 8,
paddingTop: theme.spacing.unit * 8,
[theme.breakpoints.up('sm')]: {
paddingTop: theme.spacing.unit * 12,
},
},
button: {
marginTop: theme.spacing.unit * 3,
},
logo: {
margin: `${theme.spacing.unit * 3}px 0 ${theme.spacing.unit * 4}px`,
width: '100%',
height: '35vw',
maxHeight: 200,
},
steps: {
maxWidth: theme.spacing.unit * 130,
margin: 'auto',
},
step: {
padding: `${theme.spacing.unit * 3}px ${theme.spacing.unit * 2}px`,
},
stepIcon: {
marginBottom: theme.spacing.unit,
},
markdownElement: {},
});
class HomePage extends React.Component {
componentDidMount() {
if (window.location.hash !== '') {
window.location.replace(`https://v0.material-ui.com/${window.location.hash}`);
}
}
render() {
const classes = this.props.classes;
return (
<AppFrame>
<div className={classes.root}>
<Head />
<Tidelift />
<div className={classes.hero}>
<div className={classes.content}>
<img
src="/static/images/material-ui-logo.svg"
alt="Material-UI Logo"
className={classes.logo}
/>
<div className={classes.text}>
<Typography
variant="h3"
align="center"
component="h1"
color="inherit"
gutterBottom
className={classes.title}
>
{'MATERIAL-UI'}
</Typography>
<Typography
variant="h5"
component="h2"
color="inherit"
gutterBottom
className={classes.headline}
>
{"React components that implement Google's Material Design."}
</Typography>
<Button
component={buttonProps => (
<Link naked prefetch href="/getting-started/installation" {...buttonProps} />
)}
className={classes.button}
variant="outlined"
color="primary"
>
{'Get Started'}
</Button>
</div>
</div>
</div>
<HomeSteps />
<HomeBackers />
<HomeFooter />
</div>
<script
type="application/ld+json"
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: `
{
"@context": "http://schema.org",
"@type": "Organization",
"name": "Material-UI",
"url": "https://material-ui.com/",
"logo": "https://material-ui.com/static/brand.png",
"sameAs": [
"https://twitter.com/materialUI",
"https://github.com/mui-org/material-ui",
"https://opencollective.com/material-ui"
]
}
`,
}}
/>
</AppFrame>
);
}
}
HomePage.propTypes = {
classes: PropTypes.object.isRequired,
};
const Page = withStyles(styles)(HomePage);
// Hack for https://github.com/zeit/next.js/pull/5857
export default () => <Page />;
|
packages/material-ui-icons/src/PregnantWomanSharp.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M9 4c0-1.11.89-2 2-2s2 .89 2 2-.89 2-2 2-2-.89-2-2zm7 9c-.01-1.34-.83-2.51-2-3 0-1.66-1.34-3-3-3s-3 1.34-3 3v7h2v5h3v-5h3v-4z" /></React.Fragment>
, 'PregnantWomanSharp');
|
docs/src/pages/demos/autocomplete/IntegrationAutosuggest.js | Kagami/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import deburr from 'lodash/deburr';
import Autosuggest from 'react-autosuggest';
import match from 'autosuggest-highlight/match';
import parse from 'autosuggest-highlight/parse';
import TextField from '@material-ui/core/TextField';
import Paper from '@material-ui/core/Paper';
import MenuItem from '@material-ui/core/MenuItem';
import Popper from '@material-ui/core/Popper';
import { withStyles } from '@material-ui/core/styles';
const suggestions = [
{ label: 'Afghanistan' },
{ label: 'Aland Islands' },
{ label: 'Albania' },
{ label: 'Algeria' },
{ label: 'American Samoa' },
{ label: 'Andorra' },
{ label: 'Angola' },
{ label: 'Anguilla' },
{ label: 'Antarctica' },
{ label: 'Antigua and Barbuda' },
{ label: 'Argentina' },
{ label: 'Armenia' },
{ label: 'Aruba' },
{ label: 'Australia' },
{ label: 'Austria' },
{ label: 'Azerbaijan' },
{ label: 'Bahamas' },
{ label: 'Bahrain' },
{ label: 'Bangladesh' },
{ label: 'Barbados' },
{ label: 'Belarus' },
{ label: 'Belgium' },
{ label: 'Belize' },
{ label: 'Benin' },
{ label: 'Bermuda' },
{ label: 'Bhutan' },
{ label: 'Bolivia, Plurinational State of' },
{ label: 'Bonaire, Sint Eustatius and Saba' },
{ label: 'Bosnia and Herzegovina' },
{ label: 'Botswana' },
{ label: 'Bouvet Island' },
{ label: 'Brazil' },
{ label: 'British Indian Ocean Territory' },
{ label: 'Brunei Darussalam' },
];
function renderInputComponent(inputProps) {
const { classes, inputRef = () => {}, ref, ...other } = inputProps;
return (
<TextField
fullWidth
InputProps={{
inputRef: node => {
ref(node);
inputRef(node);
},
classes: {
input: classes.input,
},
}}
{...other}
/>
);
}
function renderSuggestion(suggestion, { query, isHighlighted }) {
const matches = match(suggestion.label, query);
const parts = parse(suggestion.label, matches);
return (
<MenuItem selected={isHighlighted} component="div">
<div>
{parts.map((part, index) => {
return part.highlight ? (
<span key={String(index)} style={{ fontWeight: 500 }}>
{part.text}
</span>
) : (
<strong key={String(index)} style={{ fontWeight: 300 }}>
{part.text}
</strong>
);
})}
</div>
</MenuItem>
);
}
function getSuggestions(value) {
const inputValue = deburr(value.trim()).toLowerCase();
const inputLength = inputValue.length;
let count = 0;
return inputLength === 0
? []
: suggestions.filter(suggestion => {
const keep =
count < 5 && suggestion.label.slice(0, inputLength).toLowerCase() === inputValue;
if (keep) {
count += 1;
}
return keep;
});
}
function getSuggestionValue(suggestion) {
return suggestion.label;
}
const styles = theme => ({
root: {
height: 250,
flexGrow: 1,
},
container: {
position: 'relative',
},
suggestionsContainerOpen: {
position: 'absolute',
zIndex: 1,
marginTop: theme.spacing.unit,
left: 0,
right: 0,
},
suggestion: {
display: 'block',
},
suggestionsList: {
margin: 0,
padding: 0,
listStyleType: 'none',
},
divider: {
height: theme.spacing.unit * 2,
},
});
class IntegrationAutosuggest extends React.Component {
state = {
single: '',
popper: '',
suggestions: [],
};
handleSuggestionsFetchRequested = ({ value }) => {
this.setState({
suggestions: getSuggestions(value),
});
};
handleSuggestionsClearRequested = () => {
this.setState({
suggestions: [],
});
};
handleChange = name => (event, { newValue }) => {
this.setState({
[name]: newValue,
});
};
render() {
const { classes } = this.props;
const autosuggestProps = {
renderInputComponent,
suggestions: this.state.suggestions,
onSuggestionsFetchRequested: this.handleSuggestionsFetchRequested,
onSuggestionsClearRequested: this.handleSuggestionsClearRequested,
getSuggestionValue,
renderSuggestion,
};
return (
<div className={classes.root}>
<Autosuggest
{...autosuggestProps}
inputProps={{
classes,
placeholder: 'Search a country (start with a)',
value: this.state.single,
onChange: this.handleChange('single'),
}}
theme={{
container: classes.container,
suggestionsContainerOpen: classes.suggestionsContainerOpen,
suggestionsList: classes.suggestionsList,
suggestion: classes.suggestion,
}}
renderSuggestionsContainer={options => (
<Paper {...options.containerProps} square>
{options.children}
</Paper>
)}
/>
<div className={classes.divider} />
<Autosuggest
{...autosuggestProps}
inputProps={{
classes,
label: 'Label',
placeholder: 'With Popper',
value: this.state.popper,
onChange: this.handleChange('popper'),
inputRef: node => {
this.popperNode = node;
},
InputLabelProps: {
shrink: true,
},
}}
theme={{
suggestionsList: classes.suggestionsList,
suggestion: classes.suggestion,
}}
renderSuggestionsContainer={options => (
<Popper anchorEl={this.popperNode} open={Boolean(options.children)}>
<Paper
square
{...options.containerProps}
style={{ width: this.popperNode ? this.popperNode.clientWidth : null }}
>
{options.children}
</Paper>
</Popper>
)}
/>
</div>
);
}
}
IntegrationAutosuggest.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(IntegrationAutosuggest);
|
packages/material-ui-icons/src/FormatAlignJustifyOutlined.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M3 21h18v-2H3v2zm0-4h18v-2H3v2zm0-4h18v-2H3v2zm0-4h18V7H3v2zm0-6v2h18V3H3z" /></g></React.Fragment>
, 'FormatAlignJustifyOutlined');
|
packages/material-ui-icons/src/RoomServiceTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M12 9.58c-2.95 0-5.47 1.83-6.5 4.41h13c-1.03-2.58-3.55-4.41-6.5-4.41z" opacity=".3" /><path d="M2 17h20v2H2zM13.84 7.79c.1-.24.16-.51.16-.79 0-1.1-.9-2-2-2s-2 .9-2 2c0 .28.06.55.16.79C6.25 8.6 3.27 11.93 3 16h18c-.27-4.07-3.25-7.4-7.16-8.21zM12 9.58c2.95 0 5.47 1.83 6.5 4.41h-13c1.03-2.58 3.55-4.41 6.5-4.41z" /></React.Fragment>
, 'RoomServiceTwoTone');
|
packages/material-ui-icons/src/FlashOffRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M16.12 11.5c.39-.67-.09-1.5-.86-1.5h-1.87l2.28 2.28.45-.78zM16.28 3.45c.33-.67-.15-1.45-.9-1.45H8c-.55 0-1 .45-1 1v.61l6.13 6.13 3.15-6.29zM18.44 17.88L4.12 3.56a.9959.9959 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41L7 9.27V12c0 .55.45 1 1 1h2v7.15c0 .51.67.69.93.25l2.65-4.55 3.44 3.44c.39.39 1.02.39 1.41 0 .4-.39.4-1.02.01-1.41z" /></g></React.Fragment>
, 'FlashOffRounded');
|
packages/material-ui-icons/src/Forward30TwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M18 13c0 3.31-2.69 6-6 6s-6-2.69-6-6 2.69-6 6-6v4l5-5-5-5v4c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8h-2z" /><path d="M10.54 15.22c-.06.05-.12.09-.2.12s-.17.04-.27.04c-.09 0-.17-.01-.25-.04s-.14-.06-.2-.11-.1-.1-.13-.17-.05-.14-.05-.22h-.85c0 .21.04.39.12.55s.19.28.33.38.29.18.46.23.35.07.53.07c.21 0 .41-.03.6-.08s.34-.14.48-.24.24-.24.32-.39.12-.33.12-.53c0-.23-.06-.44-.18-.61s-.3-.3-.54-.39c.1-.05.2-.1.28-.17s.15-.14.2-.22.1-.16.13-.25.04-.18.04-.27c0-.2-.04-.37-.11-.53s-.17-.28-.3-.38-.28-.18-.46-.23-.37-.08-.59-.08c-.19 0-.38.03-.54.08s-.32.13-.44.23-.23.22-.3.37-.11.3-.11.48h.85c0-.07.02-.14.05-.2s.07-.11.12-.15.11-.07.18-.1.14-.03.22-.03c.1 0 .18.01.25.04s.13.06.18.11.08.11.11.17.04.14.04.22c0 .18-.05.32-.16.43s-.26.16-.48.16h-.43v.66h.45c.11 0 .2.01.29.04s.16.06.22.11.11.12.14.2.05.18.05.29c0 .09-.01.17-.04.24s-.08.11-.13.17zM14.44 11.78c-.18-.07-.37-.1-.59-.1s-.41.03-.59.1-.33.18-.45.33-.23.34-.29.57-.1.5-.1.82v.74c0 .32.04.6.11.82s.17.42.3.57.28.26.46.33.37.1.59.1.41-.03.59-.1.33-.18.45-.33.22-.34.29-.57.1-.5.1-.82v-.74c0-.32-.04-.6-.11-.82s-.17-.42-.3-.57-.28-.26-.46-.33zm.01 2.57c0 .19-.01.35-.04.48s-.06.24-.11.32-.11.14-.19.17-.16.05-.25.05-.18-.02-.25-.05-.14-.09-.19-.17-.09-.19-.12-.32-.04-.29-.04-.48v-.97c0-.19.01-.35.04-.48s.06-.23.12-.31.11-.14.19-.17.16-.05.25-.05.18.02.25.05.14.09.19.17.09.18.12.31.04.29.04.48v.97z" /></React.Fragment>
, 'Forward30TwoTone');
|
packages/material-ui-icons/src/LocalCarWash.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M17 5c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zm-5 0c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zM7 5c.83 0 1.5-.67 1.5-1.5C8.5 2.5 7 .8 7 .8S5.5 2.5 5.5 3.5C5.5 4.33 6.17 5 7 5zm11.92 3.01C18.72 7.42 18.16 7 17.5 7h-11c-.66 0-1.21.42-1.42 1.01L3 14v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 18c-.83 0-1.5-.67-1.5-1.5S5.67 15 6.5 15s1.5.67 1.5 1.5S7.33 18 6.5 18zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 13l1.5-4.5h11L19 13H5z" /></React.Fragment>
, 'LocalCarWash');
|
packages/material-ui-icons/src/FormatAlignRight.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M3 21h18v-2H3v2zm6-4h12v-2H9v2zm-6-4h18v-2H3v2zm6-4h12V7H9v2zM3 3v2h18V3H3z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment>
, 'FormatAlignRight');
|
packages/material-ui-icons/src/SignalCellularConnectedNoInternet3BarOutlined.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path fillOpacity=".3" d="M22 8V2L2 22h16V8h4z" /><path d="M18 22V6L2 22h16zm2-12v8h2v-8h-2zm0 12h2v-2h-2v2z" /></g></React.Fragment>
, 'SignalCellularConnectedNoInternet3BarOutlined');
|
packages/material-ui-icons/src/StayPrimaryPortraitSharp.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M5.01 1v22H19V1H5.01zM17 19H7V5h10v14z" /></g></React.Fragment>
, 'StayPrimaryPortraitSharp');
|
packages/material-ui-icons/src/ArrowDownwardOutlined.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z" /></React.Fragment>
, 'ArrowDownwardOutlined');
|
docs/src/pages/demos/cards/SimpleCard.js | Kagami/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
const styles = {
card: {
minWidth: 275,
},
bullet: {
display: 'inline-block',
margin: '0 2px',
transform: 'scale(0.8)',
},
title: {
fontSize: 14,
},
pos: {
marginBottom: 12,
},
};
function SimpleCard(props) {
const { classes } = props;
const bull = <span className={classes.bullet}>•</span>;
return (
<Card className={classes.card}>
<CardContent>
<Typography className={classes.title} color="textSecondary" gutterBottom>
Word of the Day
</Typography>
<Typography variant="h5" component="h2">
be
{bull}
nev
{bull}o{bull}
lent
</Typography>
<Typography className={classes.pos} color="textSecondary">
adjective
</Typography>
<Typography component="p">
well meaning and kindly.
<br />
{'"a benevolent smile"'}
</Typography>
</CardContent>
<CardActions>
<Button size="small">Learn More</Button>
</CardActions>
</Card>
);
}
SimpleCard.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(SimpleCard);
|
packages/material-ui-icons/src/RestaurantSharp.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M16 6v8h3v8h2V2c-2.76 0-5 2.24-5 4zM11 9H9V2H7v7H5V2H3v7c0 2.21 1.79 4 4 4v9h2v-9c2.21 0 4-1.79 4-4V2h-2v7z" /></React.Fragment>
, 'RestaurantSharp');
|
packages/material-ui-icons/src/UnarchiveTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M5 19h14V8H5v11zm7-9l4 4h-2.55v3h-2.91v-3H8l4-4z" opacity=".3" /><path d="M20.54 5.23l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27zM6.24 5h11.52l.83 1H5.42l.82-1zM19 19H5V8h14v11z" /><path d="M10.55 17h2.9v-3H16l-4-4-4 4h2.55z" /></React.Fragment>
, 'UnarchiveTwoTone');
|
packages/material-ui-icons/src/PhoneLockedSharp.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M13.21 17.37c-2.83-1.44-5.15-3.75-6.59-6.59l2.53-2.53L8.54 3H3.03C2.45 13.18 10.82 21.55 21 20.97v-5.51l-5.27-.61-2.52 2.52z" /><path d="M20 4v-.36c0-1.31-.94-2.5-2.24-2.63C16.26.86 15 2.03 15 3.5V4h-1v6h7V4h-1zm-1 0h-3v-.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5V4z" /></g></React.Fragment>
, 'PhoneLockedSharp');
|
packages/material-ui-icons/src/LocalAirportRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M21 14.58c0-.36-.19-.69-.49-.89L13 9V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-7.51 4.69c-.3.19-.49.53-.49.89 0 .7.68 1.21 1.36 1L10 13.5V19l-1.8 1.35c-.13.09-.2.24-.2.4v.59c0 .33.32.57.64.48L11.5 21l2.86.82c.32.09.64-.15.64-.48v-.59c0-.16-.07-.31-.2-.4L13 19v-5.5l6.64 2.08c.68.21 1.36-.3 1.36-1z" /></React.Fragment>
, 'LocalAirportRounded');
|
packages/material-ui-icons/src/EventRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M16 13h-3c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1h3c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1zm0-10v1H8V3c0-.55-.45-1-1-1s-1 .45-1 1v1H5c-1.11 0-1.99.9-1.99 2L3 20c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-1V3c0-.55-.45-1-1-1s-1 .45-1 1zm2 17H6c-.55 0-1-.45-1-1V9h14v10c0 .55-.45 1-1 1z" /></g></React.Fragment>
, 'EventRounded');
|
packages/material-ui-icons/src/ChildCareOutlined.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><circle cx="14.5" cy="10.5" r="1.25" /><circle cx="9.5" cy="10.5" r="1.25" /><path d="M22.94 11.34c-.25-1.51-1.36-2.74-2.81-3.17-.53-1.12-1.28-2.1-2.19-2.91C16.36 3.85 14.28 3 12 3s-4.36.85-5.94 2.26c-.92.81-1.67 1.8-2.19 2.91-1.45.43-2.56 1.65-2.81 3.17-.04.21-.06.43-.06.66 0 .23.02.45.06.66.25 1.51 1.36 2.74 2.81 3.17.52 1.11 1.27 2.09 2.17 2.89C7.62 20.14 9.71 21 12 21s4.38-.86 5.97-2.28c.9-.8 1.65-1.79 2.17-2.89 1.44-.43 2.55-1.65 2.8-3.17.04-.21.06-.43.06-.66 0-.23-.02-.45-.06-.66zM19 14c-.1 0-.19-.02-.29-.03-.2.67-.49 1.29-.86 1.86C16.6 17.74 14.45 19 12 19s-4.6-1.26-5.85-3.17c-.37-.57-.66-1.19-.86-1.86-.1.01-.19.03-.29.03-1.1 0-2-.9-2-2s.9-2 2-2c.1 0 .19.02.29.03.2-.67.49-1.29.86-1.86C7.4 6.26 9.55 5 12 5s4.6 1.26 5.85 3.17c.37.57.66 1.19.86 1.86.1-.01.19-.03.29-.03 1.1 0 2 .9 2 2s-.9 2-2 2z" /><path d="M12 17c2.01 0 3.74-1.23 4.5-3h-9c.76 1.77 2.49 3 4.5 3z" /></React.Fragment>
, 'ChildCareOutlined');
|
packages/material-ui-icons/src/PagesTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M7 7l4 1V5H5v6h3zM8 13H5v6h6v-3l-4 1zM17 17l-4-1v3h6v-6h-3zM13 8l4-1-1 4h3V5h-6z" opacity=".3" /><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5 5h6v3L7 7l1 4H5V5zm6 14H5v-6h3l-1 4 4-1v3zm-1.63-4.37l.91-2.63-.91-2.63 2.63.91 2.63-.91-.91 2.63.91 2.63-2.63-.91-2.63.91zM19 19h-6v-3l4 1-1-4h3v6zm0-8h-3l1-4-4 1V5h6v6z" /></g></React.Fragment>
, 'PagesTwoTone');
|
packages/material-ui-icons/src/EuroSymbolOutlined.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M15 18.5c-2.51 0-4.68-1.42-5.76-3.5H15v-2H8.58c-.05-.33-.08-.66-.08-1s.03-.67.08-1H15V9H9.24C10.32 6.92 12.5 5.5 15 5.5c1.61 0 3.09.59 4.23 1.57L21 5.3C19.41 3.87 17.3 3 15 3c-3.92 0-7.24 2.51-8.48 6H3v2h3.06c-.04.33-.06.66-.06 1s.02.67.06 1H3v2h3.52c1.24 3.49 4.56 6 8.48 6 2.31 0 4.41-.87 6-2.3l-1.78-1.77c-1.13.98-2.6 1.57-4.22 1.57z" /></g></React.Fragment>
, 'EuroSymbolOutlined');
|
packages/material-ui-icons/src/NewReleasesSharp.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M23 12l-2.44-2.78.34-3.68-3.61-.82-1.89-3.18L12 3 8.6 1.54 6.71 4.72l-3.61.81.34 3.68L1 12l2.44 2.78-.34 3.69 3.61.82 1.89 3.18L12 21l3.4 1.46 1.89-3.18 3.61-.82-.34-3.68L23 12zm-10 5h-2v-2h2v2zm0-4h-2V7h2v6z" /></React.Fragment>
, 'NewReleasesSharp');
|
docs/src/pages/demos/dialogs/FullScreenDialog.js | Kagami/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import ListItemText from '@material-ui/core/ListItemText';
import ListItem from '@material-ui/core/ListItem';
import List from '@material-ui/core/List';
import Divider from '@material-ui/core/Divider';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import CloseIcon from '@material-ui/icons/Close';
import Slide from '@material-ui/core/Slide';
const styles = {
appBar: {
position: 'relative',
},
flex: {
flex: 1,
},
};
function Transition(props) {
return <Slide direction="up" {...props} />;
}
class FullScreenDialog extends React.Component {
state = {
open: false,
};
handleClickOpen = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
render() {
const { classes } = this.props;
return (
<div>
<Button variant="outlined" color="primary" onClick={this.handleClickOpen}>
Open full-screen dialog
</Button>
<Dialog
fullScreen
open={this.state.open}
onClose={this.handleClose}
TransitionComponent={Transition}
>
<AppBar className={classes.appBar}>
<Toolbar>
<IconButton color="inherit" onClick={this.handleClose} aria-label="Close">
<CloseIcon />
</IconButton>
<Typography variant="h6" color="inherit" className={classes.flex}>
Sound
</Typography>
<Button color="inherit" onClick={this.handleClose}>
save
</Button>
</Toolbar>
</AppBar>
<List>
<ListItem button>
<ListItemText primary="Phone ringtone" secondary="Titania" />
</ListItem>
<Divider />
<ListItem button>
<ListItemText primary="Default notification ringtone" secondary="Tethys" />
</ListItem>
</List>
</Dialog>
</div>
);
}
}
FullScreenDialog.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(FullScreenDialog);
|
packages/material-ui-icons/src/LiveTvRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M10.5 17.15l3.98-2.28c.67-.38.67-1.35 0-1.74l-3.98-2.28c-.67-.38-1.5.11-1.5.87v4.55c0 .77.83 1.26 1.5.88z" /><path d="M21 6h-7.59l2.94-2.94c.2-.2.2-.51 0-.71s-.51-.2-.71 0L12 5.99 8.36 2.35c-.2-.2-.51-.2-.71 0s-.2.51 0 .71L10.59 6H3c-1.1 0-2 .89-2 2v12c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.11-.9-2-2-2zm-1 14H4c-.55 0-1-.45-1-1V9c0-.55.45-1 1-1h16c.55 0 1 .45 1 1v10c0 .55-.45 1-1 1z" /></g></React.Fragment>
, 'LiveTvRounded');
|
packages/material-ui-icons/src/LeakRemove.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M10 3H8c0 .37-.04.72-.12 1.06l1.59 1.59C9.81 4.84 10 3.94 10 3zM3 4.27l2.84 2.84C5.03 7.67 4.06 8 3 8v2c1.61 0 3.09-.55 4.27-1.46L8.7 9.97C7.14 11.24 5.16 12 3 12v2c2.71 0 5.19-.99 7.11-2.62l2.5 2.5C10.99 15.81 10 18.29 10 21h2c0-2.16.76-4.14 2.03-5.69l1.43 1.43C14.55 17.91 14 19.39 14 21h2c0-1.06.33-2.03.89-2.84L19.73 21 21 19.73 4.27 3 3 4.27zM14 3h-2c0 1.5-.37 2.91-1.02 4.16l1.46 1.46C13.42 6.98 14 5.06 14 3zm5.94 13.12c.34-.08.69-.12 1.06-.12v-2c-.94 0-1.84.19-2.66.52l1.6 1.6zm-4.56-4.56l1.46 1.46C18.09 12.37 19.5 12 21 12v-2c-2.06 0-3.98.58-5.62 1.56z" /></React.Fragment>
, 'LeakRemove');
|
packages/material-ui-icons/src/UnfoldLessOutlined.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M24 0v24H0V0h24z" opacity=".87" /><path d="M7.41 18.59L8.83 20 12 16.83 15.17 20l1.41-1.41L12 14l-4.59 4.59zm9.18-13.18L15.17 4 12 7.17 8.83 4 7.41 5.41 12 10l4.59-4.59z" /></React.Fragment>
, 'UnfoldLessOutlined');
|
packages/material-ui-icons/src/PaletteOutlined.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 22C6.49 22 2 17.51 2 12S6.49 2 12 2s10 4.04 10 9c0 3.31-2.69 6-6 6h-1.77c-.28 0-.5.22-.5.5 0 .12.05.23.13.33.41.47.64 1.06.64 1.67 0 1.38-1.12 2.5-2.5 2.5zm0-18c-4.41 0-8 3.59-8 8s3.59 8 8 8c.28 0 .5-.22.5-.5 0-.16-.08-.28-.14-.35-.41-.46-.63-1.05-.63-1.65 0-1.38 1.12-2.5 2.5-2.5H16c2.21 0 4-1.79 4-4 0-3.86-3.59-7-8-7z" /><circle cx="6.5" cy="11.5" r="1.5" /><circle cx="9.5" cy="7.5" r="1.5" /><circle cx="14.5" cy="7.5" r="1.5" /><circle cx="17.5" cy="11.5" r="1.5" /></g></React.Fragment>
, 'PaletteOutlined');
|
docs/src/pages/utils/popper/PositionedPopper.js | Kagami/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Popper from '@material-ui/core/Popper';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import Button from '@material-ui/core/Button';
import Fade from '@material-ui/core/Fade';
import Paper from '@material-ui/core/Paper';
const styles = theme => ({
root: {
width: 500,
},
typography: {
padding: theme.spacing.unit * 2,
},
});
class PositionedPopper extends React.Component {
state = {
anchorEl: null,
open: false,
placement: null,
};
handleClick = placement => event => {
const { currentTarget } = event;
this.setState(state => ({
anchorEl: currentTarget,
open: state.placement !== placement || !state.open,
placement,
}));
};
render() {
const { classes } = this.props;
const { anchorEl, open, placement } = this.state;
return (
<div className={classes.root}>
<Popper open={open} anchorEl={anchorEl} placement={placement} transition>
{({ TransitionProps }) => (
<Fade {...TransitionProps} timeout={350}>
<Paper>
<Typography className={classes.typography}>The content of the Popper.</Typography>
</Paper>
</Fade>
)}
</Popper>
<Grid container justify="center">
<Grid item>
<Button onClick={this.handleClick('top-start')}>top-start</Button>
<Button onClick={this.handleClick('top')}>top</Button>
<Button onClick={this.handleClick('top-end')}>top-end</Button>
</Grid>
</Grid>
<Grid container justify="center">
<Grid item xs={6}>
<Button onClick={this.handleClick('left-start')}>left-start</Button>
<br />
<Button onClick={this.handleClick('left')}>left</Button>
<br />
<Button onClick={this.handleClick('left-end')}>left-end</Button>
</Grid>
<Grid item container xs={6} alignItems="flex-end" direction="column" spacing={0}>
<Grid item>
<Button onClick={this.handleClick('right-start')}>right-start</Button>
</Grid>
<Grid item>
<Button onClick={this.handleClick('right')}>right</Button>
</Grid>
<Grid item>
<Button onClick={this.handleClick('right-end')}>right-end</Button>
</Grid>
</Grid>
</Grid>
<Grid container justify="center">
<Grid item>
<Button onClick={this.handleClick('bottom-start')}>bottom-start</Button>
<Button onClick={this.handleClick('bottom')}>bottom</Button>
<Button onClick={this.handleClick('bottom-end')}>bottom-end</Button>
</Grid>
</Grid>
</div>
);
}
}
PositionedPopper.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(PositionedPopper);
|
packages/material-ui-icons/src/CommuteRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 4H5C3.34 4 2 5.34 2 7v8c0 1.66 1.34 3 3 3l-.77.77c-.28.28-.28.72 0 1s.72.28 1 0L7 18h2v-5H4.5c-.28 0-.5-.22-.5-.5v-6c0-.28.22-.5.5-.5h8c.28 0 .5.22.5.5V8h2V7c0-1.66-1.34-3-3-3zM5 14c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm15.57-4.34c-.14-.4-.52-.66-.97-.66h-7.19c-.46 0-.83.26-.98.66l-1.42 4.11v5.24c0 .55.45.99 1 .99s1-.45 1-1v-1h8v1c0 .55.45 1 1 1s.99-.44 1-.99L22 13.77l-1.43-4.11zm-7.8.34h6.48c.21 0 .4.14.47.34l.69 2c.11.32-.13.66-.47.66h-7.85c-.34 0-.58-.34-.47-.66l.69-2c.05-.2.24-.34.46-.34zM12 16c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm8 0c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" /></g></React.Fragment>
, 'CommuteRounded');
|
packages/material-ui-icons/src/SignalCellular4BarTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M2 22h20V2L2 22z" /></g></React.Fragment>
, 'SignalCellular4BarTwoTone');
|
packages/material-ui-icons/src/WorkOutlineOutlined.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M14 6V4h-4v2h4zM4 8v11h16V8H4zm16-2c1.11 0 2 .89 2 2v11c0 1.11-.89 2-2 2H4c-1.11 0-2-.89-2-2l.01-11c0-1.11.88-2 1.99-2h4V4c0-1.11.89-2 2-2h4c1.11 0 2 .89 2 2v2h4z" /></g></React.Fragment>
, 'WorkOutlineOutlined');
|
packages/material-ui-icons/src/RestoreFromTrashTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M16 14h-2v4h-4v-4H8v5h8zM16 14V9H8v5l4-4z" opacity=".3" /><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zm2-5V9h8v10H8v-5zM15.5 4l-1-1h-5l-1 1H5v2h14V4z" /><path d="M10 18h4v-4h2l-4-4-4 4h2z" /></React.Fragment>
, 'RestoreFromTrashTwoTone');
|
packages/material-ui-icons/src/DirectionsBoatTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M6.49 15.68L8 13.96l1.51 1.72c.34.4 1.28 1.32 2.49 1.32 1.21 0 2.15-.92 2.49-1.32L16 13.96l1.51 1.72c.2.23.6.64 1.14.94l1.12-3.97-2.39-.78L12 10.11l-5.38 1.77-2.4.79 1.13 3.96c.55-.31.94-.72 1.14-.95zM11 3h2v1h-2z" opacity=".3" /><path d="M3.95 19H4c1.6 0 3.02-.88 4-2 .98 1.12 2.4 2 4 2s3.02-.88 4-2c.98 1.12 2.4 2 4 2h.05l1.89-6.68c.08-.26.06-.54-.06-.78s-.34-.42-.6-.5L20 10.62V6c0-1.1-.9-2-2-2h-3V1H9v3H6c-1.1 0-2 .9-2 2v4.62l-1.29.42c-.26.08-.48.26-.6.5s-.15.52-.06.78L3.95 19zM11 3h2v1h-2V3zM6 6h12v3.97L12 8 6 9.97V6zm.62 5.87L12 10.11l5.38 1.77 2.39.78-1.12 3.97c-.54-.3-.94-.71-1.14-.94L16 13.96l-1.51 1.72c-.34.4-1.28 1.32-2.49 1.32-1.21 0-2.15-.92-2.49-1.32L8 13.96l-1.51 1.72c-.2.23-.6.63-1.14.93l-1.13-3.96 2.4-.78zM8 22.01c1.26.64 2.63.97 4 .97s2.74-.32 4-.97c1.26.65 2.62.99 4 .99h2v-2h-2c-1.39 0-2.78-.47-4-1.32-1.22.85-2.61 1.28-4 1.28s-2.78-.43-4-1.28C6.78 20.53 5.39 21 4 21H2v2h2c1.38 0 2.74-.35 4-.99z" /></React.Fragment>
, 'DirectionsBoatTwoTone');
|
docs/src/pages/demos/lists/PinnedSubheaderList.js | Kagami/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListSubheader from '@material-ui/core/ListSubheader';
const styles = theme => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
position: 'relative',
overflow: 'auto',
maxHeight: 300,
},
listSection: {
backgroundColor: 'inherit',
},
ul: {
backgroundColor: 'inherit',
padding: 0,
},
});
function PinnedSubheaderList(props) {
const { classes } = props;
return (
<List className={classes.root} subheader={<li />}>
{[0, 1, 2, 3, 4].map(sectionId => (
<li key={`section-${sectionId}`} className={classes.listSection}>
<ul className={classes.ul}>
<ListSubheader>{`I'm sticky ${sectionId}`}</ListSubheader>
{[0, 1, 2].map(item => (
<ListItem key={`item-${sectionId}-${item}`}>
<ListItemText primary={`Item ${item}`} />
</ListItem>
))}
</ul>
</li>
))}
</List>
);
}
PinnedSubheaderList.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(PinnedSubheaderList);
|
docs/src/pages/premium-themes/tweeper/components/atoms/IconButton.js | Kagami/material-ui | import React from 'react';
import cx from 'classnames';
import MuiIconButton from '@material-ui/core/IconButton';
import { ICON_BUTTON } from '../../theme/core';
const IconButton = ({
className,
shaded,
noPad,
narrowPad,
separated,
linkInverted,
danger,
success,
...props
}) => (
<MuiIconButton
className={cx(
ICON_BUTTON.root,
className,
shaded && ICON_BUTTON.shaded,
noPad && ICON_BUTTON.noPad,
narrowPad && ICON_BUTTON.narrowPad,
separated && ICON_BUTTON.separated,
linkInverted && ICON_BUTTON.linkInverted,
danger && ICON_BUTTON.danger,
success && ICON_BUTTON.success,
)}
{...props}
/>
);
export default IconButton;
|
packages/material-ui-icons/src/SignalWifi3BarSharp.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path fillOpacity=".3" d="M23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5 23.64 7z" /><path d="M3.53 10.95L12 21.5l8.47-10.55C20.04 10.62 16.81 8 12 8s-8.04 2.62-8.47 2.95z" /></g></React.Fragment>
, 'SignalWifi3BarSharp');
|
docs/src/pages/customization/themes/CustomStyles.js | Kagami/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import Checkbox from '@material-ui/core/Checkbox';
import { createMuiTheme, MuiThemeProvider, withStyles } from '@material-ui/core/styles';
import orange from '@material-ui/core/colors/orange';
const styles = theme => ({
root: {
color: theme.status.danger,
'&$checked': {
color: theme.status.danger,
},
},
checked: {},
});
let CustomCheckbox = props => (
<Checkbox
defaultChecked
classes={{
root: props.classes.root,
checked: props.classes.checked,
}}
/>
);
CustomCheckbox.propTypes = {
classes: PropTypes.object.isRequired,
};
CustomCheckbox = withStyles(styles)(CustomCheckbox);
const theme = createMuiTheme({
status: {
// My business variables
danger: orange[500],
},
typography: { useNextVariants: true },
});
function CustomStyles() {
return (
<MuiThemeProvider theme={theme}>
<CustomCheckbox />
</MuiThemeProvider>
);
}
export default CustomStyles;
|
packages/material-ui-icons/src/SettingsInputHdmiTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M8 9H7v3.53l2.79 5.58.21.42V20h4v-1.47l.21-.42L17 12.53V9h-1z" opacity=".3" /><path d="M18 7V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v3H5v6l3 6v3h8v-3l3-6V7h-1zM8 4h8v3h-2.01V5h-1v2H11V5h-1v2H8V4zm9 8.53l-3 6V20h-4v-1.47l-3-6V9h10v3.53z" /></React.Fragment>
, 'SettingsInputHdmiTwoTone');
|
packages/material-ui-icons/src/BackspaceTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M7.06 5L2.4 12l4.67 7H22V5H7.06c.01 0 .01 0 0 0zM9 8.41L10.41 7 14 10.59 17.59 7 19 8.41 15.41 12 19 15.59 17.59 17 14 13.41 10.41 17 9 15.59 12.59 12 9 8.41z" opacity=".3" /><path d="M22 3H7c-.69 0-1.23.35-1.59.88L0 12l5.41 8.11c.36.53.9.89 1.59.89h15c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H7.07L2.4 12l4.66-7H22v14z" /><path d="M10.41 17L14 13.41 17.59 17 19 15.59 15.41 12 19 8.41 17.59 7 14 10.59 10.41 7 9 8.41 12.59 12 9 15.59z" /></React.Fragment>
, 'BackspaceTwoTone');
|
packages/material-ui-icons/src/RemoveFromQueueSharp.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M23 3H1v16h7v2h8v-2h7V3zm-2 14H3V5h18v12zm-5-7v2H8v-2h8z" /></React.Fragment>
, 'RemoveFromQueueSharp');
|
packages/material-ui-icons/src/BluetoothAudioTwoTone.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M14.24 12.01l2.32 2.32c.28-.72.44-1.51.44-2.33s-.16-1.59-.43-2.31l-2.33 2.32zm5.29-5.3l-1.26 1.26c.63 1.21.98 2.57.98 4.02s-.36 2.82-.98 4.02l1.2 1.2c.97-1.54 1.54-3.36 1.54-5.31-.01-1.89-.55-3.67-1.48-5.19zm-3.82 1L10 2H9v7.59L4.41 5 3 6.41 8.59 12 3 17.59 4.41 19 9 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM11 5.83l1.88 1.88L11 9.59V5.83zm1.88 10.46L11 18.17v-3.76l1.88 1.88z" /></g></React.Fragment>
, 'BluetoothAudioTwoTone');
|
packages/material-ui-icons/src/FlipRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h3c.55 0 1-.45 1-1s-.45-1-1-1H6c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h2c.55 0 1-.45 1-1s-.45-1-1-1H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-7 20c.55 0 1-.45 1-1V2c0-.55-.45-1-1-1s-1 .45-1 1v20c0 .55.45 1 1 1zm7-6h2v-2h-2v2zM15 5h2V3h-2v2zm4 8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2z" /></g></React.Fragment>
, 'FlipRounded');
|
packages/material-ui-icons/src/FormatColorFillOutlined.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M16.56 8.94L7.62 0 6.21 1.41l2.38 2.38-5.15 5.15c-.59.59-.59 1.54 0 2.12l5.5 5.5c.29.29.68.44 1.06.44s.77-.15 1.06-.44l5.5-5.5c.59-.58.59-1.53 0-2.12zM5.21 10L10 5.21 14.79 10H5.21zM19 11.5s-2 2.17-2 3.5c0 1.1.9 2 2 2s2-.9 2-2c0-1.33-2-3.5-2-3.5z" /><path fillOpacity=".36" d="M0 20h24v4H0v-4z" /></g></React.Fragment>
, 'FormatColorFillOutlined');
|
packages/material-ui-icons/src/PhoneInTalkRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12.88 5.05c3.18.4 5.67 2.89 6.07 6.07.06.51.49.88.99.88.04 0 .08 0 .12-.01.55-.07.94-.57.87-1.12-.51-4.09-3.72-7.3-7.81-7.81-.55-.06-1.05.33-1.11.88-.07.55.32 1.05.87 1.11zM13.26 7.16c-.53-.14-1.08.18-1.22.72s.18 1.08.72 1.22c1.05.27 1.87 1.09 2.15 2.15.12.45.52.75.97.75.08 0 .17-.01.25-.03.53-.14.85-.69.72-1.22-.47-1.77-1.84-3.14-3.59-3.59z" /><path d="M19.23 15.26l-2.54-.29c-.61-.07-1.21.14-1.64.57l-1.84 1.84c-2.83-1.44-5.15-3.75-6.59-6.59l1.85-1.85c.43-.43.64-1.03.57-1.64l-.29-2.52c-.12-1.01-.97-1.77-1.99-1.77H5.03c-1.13 0-2.07.94-2 2.07.53 8.54 7.36 15.36 15.89 15.89 1.13.07 2.07-.87 2.07-2v-1.73c.01-1.01-.75-1.86-1.76-1.98z" /></g></React.Fragment>
, 'PhoneInTalkRounded');
|
packages/material-ui-icons/src/ShopTwoOutlined.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M3 9H1v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2H3V9z" /><path d="M18 5V3c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H5v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2V5h-5zm-6-2h4v2h-4V3zm9 13H7V7h14v9z" /><path d="M12 15l5.5-4L12 8z" /></React.Fragment>
, 'ShopTwoOutlined');
|
packages/material-ui-icons/src/RedeemRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M20 6h-2.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm10 15H5c-.55 0-1-.45-1-1v-1h16v1c0 .55-.45 1-1 1zm1-5H4V9c0-.55.45-1 1-1h4.08L7.6 10.02c-.33.45-.23 1.08.22 1.4.44.32 1.07.22 1.39-.22L12 7.4l2.79 3.8c.32.44.95.54 1.39.22.45-.32.55-.95.22-1.4L14.92 8H19c.55 0 1 .45 1 1v5z" /></React.Fragment>
, 'RedeemRounded');
|
packages/material-ui-icons/src/TableChartRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M10 10.02h5V21h-5V10.02zM17 21h3c1.1 0 2-.9 2-2v-9h-5v11zm3-18H5c-1.1 0-2 .9-2 2v3h19V5c0-1.1-.9-2-2-2zM3 19c0 1.1.9 2 2 2h3V10H3v9z" /></g></React.Fragment>
, 'TableChartRounded');
|
packages/material-ui-icons/src/SmokeFreeRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M20.5 13H22v3h-1.5zM18 13h1.5v3H18zM17 14.5c0-.83-.67-1.5-1.5-1.5h-.84l2.18 2.18c.1-.21.16-.44.16-.68zM18.96 2.35H19h-.04zM18.85 4.73c.38-.38.67-.84.84-1.35.16-.5-.19-1.01-.71-1.02-.34.01-.61.25-.72.58-.18.55-.62.99-1.17 1.17-.34.11-.59.39-.59.74V5c0 .37.27.69.64.75 1.93.31 3.36 2 3.36 4.02v1.48c0 .41.34.75.75.75s.75-.34.75-.75V9.76c0-2.22-1.28-4.14-3.15-5.03z" /><path d="M14.61 8.65h1.42c1.05 0 1.97.74 1.97 2.05v.55c0 .41.33.75.75.75h.01c.41 0 .75-.33.75-.75v-.89c0-1.81-1.6-3.16-3.47-3.16h-1.3c-1.02 0-1.94-.73-2.07-1.75-.12-.95.46-1.7 1.3-1.93.32-.09.54-.38.54-.72 0-.49-.46-.86-.93-.72-1.42.41-2.45 1.73-2.42 3.28.02 1.85 1.61 3.29 3.45 3.29zM4.12 5.29a.9959.9959 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41L9 13H3.5c-.83 0-1.5.67-1.5 1.5S2.67 16 3.5 16H12l6.29 6.29c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L4.12 5.29z" /></React.Fragment>
, 'SmokeFreeRounded');
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.