path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
ajax/libs/react-native-web/0.0.0-dfb716c98/exports/createElement/index.js | cdnjs/cdnjs | /**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import AccessibilityUtil from '../../modules/AccessibilityUtil';
import createDOMProps from '../../modules/createDOMProps';
import React from 'react';
var createElement = function createElement(component, props) {
// Use equivalent platform elements where possible.
var accessibilityComponent;
if (component && component.constructor === String) {
accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props);
}
var Component = accessibilityComponent || component;
var domProps = createDOMProps(Component, props);
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
children[_key - 2] = arguments[_key];
}
return React.createElement.apply(React, [Component, domProps].concat(children));
};
export default createElement; |
ajax/libs/primereact/6.5.0/avatar/avatar.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames, ObjectUtils } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Avatar = /*#__PURE__*/function (_Component) {
_inherits(Avatar, _Component);
var _super = _createSuper(Avatar);
function Avatar() {
_classCallCheck(this, Avatar);
return _super.apply(this, arguments);
}
_createClass(Avatar, [{
key: "renderContent",
value: function renderContent() {
var _this = this;
if (this.props.label) {
return /*#__PURE__*/React.createElement("span", {
className: "p-avatar-text"
}, this.props.label);
} else if (this.props.icon) {
var iconClassName = classNames('p-avatar-icon', this.props.icon);
return /*#__PURE__*/React.createElement("span", {
className: iconClassName
});
} else if (this.props.image) {
var onError = function onError(e) {
if (_this.props.onImageError) {
_this.props.onImageError(e);
}
};
return /*#__PURE__*/React.createElement("img", {
src: this.props.image,
alt: this.props.imageAlt,
onError: onError
});
}
return null;
}
}, {
key: "render",
value: function render() {
var containerClassName = classNames('p-avatar p-component', {
'p-avatar-image': this.props.image != null,
'p-avatar-circle': this.props.shape === 'circle',
'p-avatar-lg': this.props.size === 'large',
'p-avatar-xl': this.props.size === 'xlarge',
'p-avatar-clickable': !!this.props.onClick
}, this.props.className);
var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props) : this.renderContent();
return /*#__PURE__*/React.createElement("div", {
className: containerClassName,
style: this.props.style,
onClick: this.props.onClick
}, content, this.props.children);
}
}]);
return Avatar;
}(Component);
_defineProperty(Avatar, "defaultProps", {
label: null,
icon: null,
image: null,
size: 'normal',
shape: 'square',
style: null,
className: null,
template: null,
imageAlt: 'avatar',
onImageError: null,
onClick: null
});
export { Avatar };
|
ajax/libs/material-ui/4.9.4/es/Toolbar/Toolbar.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
position: 'relative',
display: 'flex',
alignItems: 'center'
},
/* Styles applied to the root element if `disableGutters={false}`. */
gutters: {
paddingLeft: theme.spacing(2),
paddingRight: theme.spacing(2),
[theme.breakpoints.up('sm')]: {
paddingLeft: theme.spacing(3),
paddingRight: theme.spacing(3)
}
},
/* Styles applied to the root element if `variant="regular"`. */
regular: theme.mixins.toolbar,
/* Styles applied to the root element if `variant="dense"`. */
dense: {
minHeight: 48
}
});
const Toolbar = React.forwardRef(function Toolbar(props, ref) {
const {
classes,
className,
component: Component = 'div',
disableGutters = false,
variant = 'regular'
} = props,
other = _objectWithoutPropertiesLoose(props, ["classes", "className", "component", "disableGutters", "variant"]);
return React.createElement(Component, _extends({
className: clsx(classes.root, classes[variant], className, !disableGutters && classes.gutters),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? Toolbar.propTypes = {
/**
* Toolbar children, usually a mixture of `IconButton`, `Button` and `Typography`.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: PropTypes.elementType,
/**
* If `true`, disables gutter padding.
*/
disableGutters: PropTypes.bool,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['regular', 'dense'])
} : void 0;
export default withStyles(styles, {
name: 'MuiToolbar'
})(Toolbar); |
ajax/libs/material-ui/4.9.2/esm/NoSsr/NoSsr.js | cdnjs/cdnjs | import React from 'react';
import PropTypes from 'prop-types';
import { exactProp } from '@material-ui/utils';
var useEnhancedEffect = typeof window !== 'undefined' && process.env.NODE_ENV !== 'test' ? React.useLayoutEffect : React.useEffect;
/**
* NoSsr purposely removes components from the subject of Server Side Rendering (SSR).
*
* This component can be useful in a variety of situations:
* - Escape hatch for broken dependencies not supporting SSR.
* - Improve the time-to-first paint on the client by only rendering above the fold.
* - Reduce the rendering time on the server.
* - Under too heavy server load, you can turn on service degradation.
*/
function NoSsr(props) {
var children = props.children,
_props$defer = props.defer,
defer = _props$defer === void 0 ? false : _props$defer,
_props$fallback = props.fallback,
fallback = _props$fallback === void 0 ? null : _props$fallback;
var _React$useState = React.useState(false),
mountedState = _React$useState[0],
setMountedState = _React$useState[1];
useEnhancedEffect(function () {
if (!defer) {
setMountedState(true);
}
}, [defer]);
React.useEffect(function () {
if (defer) {
setMountedState(true);
}
}, [defer]); // We need the Fragment here to force react-docgen to recognise NoSsr as a component.
return React.createElement(React.Fragment, null, mountedState ? children : fallback);
}
process.env.NODE_ENV !== "production" ? NoSsr.propTypes = {
/**
* You can wrap a node.
*/
children: PropTypes.node.isRequired,
/**
* If `true`, the component will not only prevent server-side rendering.
* It will also defer the rendering of the children into a different screen frame.
*/
defer: PropTypes.bool,
/**
* The fallback content to display.
*/
fallback: PropTypes.node
} : void 0;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line
NoSsr['propTypes' + ''] = exactProp(NoSsr.propTypes);
}
export default NoSsr; |
ajax/libs/primereact/6.5.0-rc.2/skeleton/skeleton.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames } from 'primereact/utils';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var propTypes = {exports: {}};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = ReactPropTypesSecret_1;
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} shim.isRequired = shim;
function getShim() {
return shim;
} // Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
propTypes.exports = factoryWithThrowingShims();
}
var PropTypes = propTypes.exports;
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Skeleton = /*#__PURE__*/function (_Component) {
_inherits(Skeleton, _Component);
var _super = _createSuper(Skeleton);
function Skeleton() {
_classCallCheck(this, Skeleton);
return _super.apply(this, arguments);
}
_createClass(Skeleton, [{
key: "skeletonStyle",
value: function skeletonStyle() {
if (this.props.size) return {
width: this.props.size,
height: this.props.size,
borderRadius: this.props.borderRadius
};else return {
width: this.props.width,
height: this.props.height,
borderRadius: this.props.borderRadius
};
}
}, {
key: "render",
value: function render() {
var skeletonClassName = classNames('p-skeleton p-component', {
'p-skeleton-circle': this.props.shape === 'circle',
'p-skeleton-none': this.props.animation === 'none'
}, this.props.className);
var style = this.skeletonStyle();
return /*#__PURE__*/React.createElement("div", {
style: style,
className: skeletonClassName
});
}
}]);
return Skeleton;
}(Component);
_defineProperty(Skeleton, "defaultProps", {
shape: 'rectangle',
size: null,
width: '100%',
height: '1rem',
borderRadius: null,
animation: 'wave',
style: null,
className: null
});
_defineProperty(Skeleton, "propTypes", {
shape: PropTypes.string,
size: PropTypes.string,
width: PropTypes.string,
height: PropTypes.string,
borderRadius: PropTypes.string,
animation: PropTypes.string,
style: PropTypes.object,
className: PropTypes.string
});
export { Skeleton };
|
ajax/libs/boardgame-io/0.43.0/boardgameio.es.js | cdnjs/cdnjs | import { nanoid } from 'nanoid';
import { applyMiddleware, compose, createStore } from 'redux';
import produce from 'immer';
import { stringify, parse } from 'flatted';
import React from 'react';
import PropTypes from 'prop-types';
import ioNamespace__default from 'socket.io-client';
function noop() { }
const identity = x => x;
function assign(tar, src) {
// @ts-ignore
for (const k in src)
tar[k] = src[k];
return tar;
}
function run(fn) {
return fn();
}
function blank_object() {
return Object.create(null);
}
function run_all(fns) {
fns.forEach(run);
}
function is_function(thing) {
return typeof thing === 'function';
}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}
function subscribe(store, ...callbacks) {
if (store == null) {
return noop;
}
const unsub = store.subscribe(...callbacks);
return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
function component_subscribe(component, store, callback) {
component.$$.on_destroy.push(subscribe(store, callback));
}
function create_slot(definition, ctx, $$scope, fn) {
if (definition) {
const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
return definition[0](slot_ctx);
}
}
function get_slot_context(definition, ctx, $$scope, fn) {
return definition[1] && fn
? assign($$scope.ctx.slice(), definition[1](fn(ctx)))
: $$scope.ctx;
}
function get_slot_changes(definition, $$scope, dirty, fn) {
if (definition[2] && fn) {
const lets = definition[2](fn(dirty));
if ($$scope.dirty === undefined) {
return lets;
}
if (typeof lets === 'object') {
const merged = [];
const len = Math.max($$scope.dirty.length, lets.length);
for (let i = 0; i < len; i += 1) {
merged[i] = $$scope.dirty[i] | lets[i];
}
return merged;
}
return $$scope.dirty | lets;
}
return $$scope.dirty;
}
function update_slot(slot, slot_definition, ctx, $$scope, dirty, get_slot_changes_fn, get_slot_context_fn) {
const slot_changes = get_slot_changes(slot_definition, $$scope, dirty, get_slot_changes_fn);
if (slot_changes) {
const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
slot.p(slot_context, slot_changes);
}
}
function exclude_internal_props(props) {
const result = {};
for (const k in props)
if (k[0] !== '$')
result[k] = props[k];
return result;
}
function null_to_empty(value) {
return value == null ? '' : value;
}
const is_client = typeof window !== 'undefined';
let now = is_client
? () => window.performance.now()
: () => Date.now();
let raf = is_client ? cb => requestAnimationFrame(cb) : noop;
const tasks = new Set();
function run_tasks(now) {
tasks.forEach(task => {
if (!task.c(now)) {
tasks.delete(task);
task.f();
}
});
if (tasks.size !== 0)
raf(run_tasks);
}
/**
* Creates a new task that runs on each raf frame
* until it returns a falsy value or is aborted
*/
function loop(callback) {
let task;
if (tasks.size === 0)
raf(run_tasks);
return {
promise: new Promise(fulfill => {
tasks.add(task = { c: callback, f: fulfill });
}),
abort() {
tasks.delete(task);
}
};
}
function append(target, node) {
target.appendChild(node);
}
function insert(target, node, anchor) {
target.insertBefore(node, anchor || null);
}
function detach(node) {
node.parentNode.removeChild(node);
}
function destroy_each(iterations, detaching) {
for (let i = 0; i < iterations.length; i += 1) {
if (iterations[i])
iterations[i].d(detaching);
}
}
function element(name) {
return document.createElement(name);
}
function svg_element(name) {
return document.createElementNS('http://www.w3.org/2000/svg', name);
}
function text(data) {
return document.createTextNode(data);
}
function space() {
return text(' ');
}
function empty() {
return text('');
}
function listen(node, event, handler, options) {
node.addEventListener(event, handler, options);
return () => node.removeEventListener(event, handler, options);
}
function stop_propagation(fn) {
return function (event) {
event.stopPropagation();
// @ts-ignore
return fn.call(this, event);
};
}
function attr(node, attribute, value) {
if (value == null)
node.removeAttribute(attribute);
else if (node.getAttribute(attribute) !== value)
node.setAttribute(attribute, value);
}
function to_number(value) {
return value === '' ? undefined : +value;
}
function children(element) {
return Array.from(element.childNodes);
}
function set_data(text, data) {
data = '' + data;
if (text.wholeText !== data)
text.data = data;
}
function set_input_value(input, value) {
input.value = value == null ? '' : value;
}
function select_option(select, value) {
for (let i = 0; i < select.options.length; i += 1) {
const option = select.options[i];
if (option.__value === value) {
option.selected = true;
return;
}
}
}
function select_value(select) {
const selected_option = select.querySelector(':checked') || select.options[0];
return selected_option && selected_option.__value;
}
function toggle_class(element, name, toggle) {
element.classList[toggle ? 'add' : 'remove'](name);
}
function custom_event(type, detail) {
const e = document.createEvent('CustomEvent');
e.initCustomEvent(type, false, false, detail);
return e;
}
const active_docs = new Set();
let active = 0;
// https://github.com/darkskyapp/string-hash/blob/master/index.js
function hash(str) {
let hash = 5381;
let i = str.length;
while (i--)
hash = ((hash << 5) - hash) ^ str.charCodeAt(i);
return hash >>> 0;
}
function create_rule(node, a, b, duration, delay, ease, fn, uid = 0) {
const step = 16.666 / duration;
let keyframes = '{\n';
for (let p = 0; p <= 1; p += step) {
const t = a + (b - a) * ease(p);
keyframes += p * 100 + `%{${fn(t, 1 - t)}}\n`;
}
const rule = keyframes + `100% {${fn(b, 1 - b)}}\n}`;
const name = `__svelte_${hash(rule)}_${uid}`;
const doc = node.ownerDocument;
active_docs.add(doc);
const stylesheet = doc.__svelte_stylesheet || (doc.__svelte_stylesheet = doc.head.appendChild(element('style')).sheet);
const current_rules = doc.__svelte_rules || (doc.__svelte_rules = {});
if (!current_rules[name]) {
current_rules[name] = true;
stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length);
}
const animation = node.style.animation || '';
node.style.animation = `${animation ? `${animation}, ` : ``}${name} ${duration}ms linear ${delay}ms 1 both`;
active += 1;
return name;
}
function delete_rule(node, name) {
const previous = (node.style.animation || '').split(', ');
const next = previous.filter(name
? anim => anim.indexOf(name) < 0 // remove specific animation
: anim => anim.indexOf('__svelte') === -1 // remove all Svelte animations
);
const deleted = previous.length - next.length;
if (deleted) {
node.style.animation = next.join(', ');
active -= deleted;
if (!active)
clear_rules();
}
}
function clear_rules() {
raf(() => {
if (active)
return;
active_docs.forEach(doc => {
const stylesheet = doc.__svelte_stylesheet;
let i = stylesheet.cssRules.length;
while (i--)
stylesheet.deleteRule(i);
doc.__svelte_rules = {};
});
active_docs.clear();
});
}
let current_component;
function set_current_component(component) {
current_component = component;
}
function get_current_component() {
if (!current_component)
throw new Error(`Function called outside component initialization`);
return current_component;
}
function afterUpdate(fn) {
get_current_component().$$.after_update.push(fn);
}
function onDestroy(fn) {
get_current_component().$$.on_destroy.push(fn);
}
function createEventDispatcher() {
const component = get_current_component();
return (type, detail) => {
const callbacks = component.$$.callbacks[type];
if (callbacks) {
// TODO are there situations where events could be dispatched
// in a server (non-DOM) environment?
const event = custom_event(type, detail);
callbacks.slice().forEach(fn => {
fn.call(component, event);
});
}
};
}
function setContext(key, context) {
get_current_component().$$.context.set(key, context);
}
function getContext(key) {
return get_current_component().$$.context.get(key);
}
// TODO figure out if we still want to support
// shorthand events, or if we want to implement
// a real bubbling mechanism
function bubble(component, event) {
const callbacks = component.$$.callbacks[event.type];
if (callbacks) {
callbacks.slice().forEach(fn => fn(event));
}
}
const dirty_components = [];
const binding_callbacks = [];
const render_callbacks = [];
const flush_callbacks = [];
const resolved_promise = Promise.resolve();
let update_scheduled = false;
function schedule_update() {
if (!update_scheduled) {
update_scheduled = true;
resolved_promise.then(flush);
}
}
function add_render_callback(fn) {
render_callbacks.push(fn);
}
let flushing = false;
const seen_callbacks = new Set();
function flush() {
if (flushing)
return;
flushing = true;
do {
// first, call beforeUpdate functions
// and update components
for (let i = 0; i < dirty_components.length; i += 1) {
const component = dirty_components[i];
set_current_component(component);
update(component.$$);
}
dirty_components.length = 0;
while (binding_callbacks.length)
binding_callbacks.pop()();
// then, once components are updated, call
// afterUpdate functions. This may cause
// subsequent updates...
for (let i = 0; i < render_callbacks.length; i += 1) {
const callback = render_callbacks[i];
if (!seen_callbacks.has(callback)) {
// ...so guard against infinite loops
seen_callbacks.add(callback);
callback();
}
}
render_callbacks.length = 0;
} while (dirty_components.length);
while (flush_callbacks.length) {
flush_callbacks.pop()();
}
update_scheduled = false;
flushing = false;
seen_callbacks.clear();
}
function update($$) {
if ($$.fragment !== null) {
$$.update();
run_all($$.before_update);
const dirty = $$.dirty;
$$.dirty = [-1];
$$.fragment && $$.fragment.p($$.ctx, dirty);
$$.after_update.forEach(add_render_callback);
}
}
let promise;
function wait() {
if (!promise) {
promise = Promise.resolve();
promise.then(() => {
promise = null;
});
}
return promise;
}
function dispatch(node, direction, kind) {
node.dispatchEvent(custom_event(`${direction ? 'intro' : 'outro'}${kind}`));
}
const outroing = new Set();
let outros;
function group_outros() {
outros = {
r: 0,
c: [],
p: outros // parent group
};
}
function check_outros() {
if (!outros.r) {
run_all(outros.c);
}
outros = outros.p;
}
function transition_in(block, local) {
if (block && block.i) {
outroing.delete(block);
block.i(local);
}
}
function transition_out(block, local, detach, callback) {
if (block && block.o) {
if (outroing.has(block))
return;
outroing.add(block);
outros.c.push(() => {
outroing.delete(block);
if (callback) {
if (detach)
block.d(1);
callback();
}
});
block.o(local);
}
}
const null_transition = { duration: 0 };
function create_bidirectional_transition(node, fn, params, intro) {
let config = fn(node, params);
let t = intro ? 0 : 1;
let running_program = null;
let pending_program = null;
let animation_name = null;
function clear_animation() {
if (animation_name)
delete_rule(node, animation_name);
}
function init(program, duration) {
const d = program.b - t;
duration *= Math.abs(d);
return {
a: t,
b: program.b,
d,
duration,
start: program.start,
end: program.start + duration,
group: program.group
};
}
function go(b) {
const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;
const program = {
start: now() + delay,
b
};
if (!b) {
// @ts-ignore todo: improve typings
program.group = outros;
outros.r += 1;
}
if (running_program) {
pending_program = program;
}
else {
// if this is an intro, and there's a delay, we need to do
// an initial tick and/or apply CSS animation immediately
if (css) {
clear_animation();
animation_name = create_rule(node, t, b, duration, delay, easing, css);
}
if (b)
tick(0, 1);
running_program = init(program, duration);
add_render_callback(() => dispatch(node, b, 'start'));
loop(now => {
if (pending_program && now > pending_program.start) {
running_program = init(pending_program, duration);
pending_program = null;
dispatch(node, running_program.b, 'start');
if (css) {
clear_animation();
animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css);
}
}
if (running_program) {
if (now >= running_program.end) {
tick(t = running_program.b, 1 - t);
dispatch(node, running_program.b, 'end');
if (!pending_program) {
// we're done
if (running_program.b) {
// intro — we can tidy up immediately
clear_animation();
}
else {
// outro — needs to be coordinated
if (!--running_program.group.r)
run_all(running_program.group.c);
}
}
running_program = null;
}
else if (now >= running_program.start) {
const p = now - running_program.start;
t = running_program.a + running_program.d * easing(p / running_program.duration);
tick(t, 1 - t);
}
}
return !!(running_program || pending_program);
});
}
}
return {
run(b) {
if (is_function(config)) {
wait().then(() => {
// @ts-ignore
config = config();
go(b);
});
}
else {
go(b);
}
},
end() {
clear_animation();
running_program = pending_program = null;
}
};
}
const globals = (typeof window !== 'undefined'
? window
: typeof globalThis !== 'undefined'
? globalThis
: global);
function get_spread_update(levels, updates) {
const update = {};
const to_null_out = {};
const accounted_for = { $$scope: 1 };
let i = levels.length;
while (i--) {
const o = levels[i];
const n = updates[i];
if (n) {
for (const key in o) {
if (!(key in n))
to_null_out[key] = 1;
}
for (const key in n) {
if (!accounted_for[key]) {
update[key] = n[key];
accounted_for[key] = 1;
}
}
levels[i] = n;
}
else {
for (const key in o) {
accounted_for[key] = 1;
}
}
}
for (const key in to_null_out) {
if (!(key in update))
update[key] = undefined;
}
return update;
}
function get_spread_object(spread_props) {
return typeof spread_props === 'object' && spread_props !== null ? spread_props : {};
}
function create_component(block) {
block && block.c();
}
function mount_component(component, target, anchor) {
const { fragment, on_mount, on_destroy, after_update } = component.$$;
fragment && fragment.m(target, anchor);
// onMount happens before the initial afterUpdate
add_render_callback(() => {
const new_on_destroy = on_mount.map(run).filter(is_function);
if (on_destroy) {
on_destroy.push(...new_on_destroy);
}
else {
// Edge case - component was destroyed immediately,
// most likely as a result of a binding initialising
run_all(new_on_destroy);
}
component.$$.on_mount = [];
});
after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
const $$ = component.$$;
if ($$.fragment !== null) {
run_all($$.on_destroy);
$$.fragment && $$.fragment.d(detaching);
// TODO null out other refs, including component.$$ (but need to
// preserve final state?)
$$.on_destroy = $$.fragment = null;
$$.ctx = [];
}
}
function make_dirty(component, i) {
if (component.$$.dirty[0] === -1) {
dirty_components.push(component);
schedule_update();
component.$$.dirty.fill(0);
}
component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
}
function init(component, options, instance, create_fragment, not_equal, props, dirty = [-1]) {
const parent_component = current_component;
set_current_component(component);
const prop_values = options.props || {};
const $$ = component.$$ = {
fragment: null,
ctx: null,
// state
props,
update: noop,
not_equal,
bound: blank_object(),
// lifecycle
on_mount: [],
on_destroy: [],
before_update: [],
after_update: [],
context: new Map(parent_component ? parent_component.$$.context : []),
// everything else
callbacks: blank_object(),
dirty
};
let ready = false;
$$.ctx = instance
? instance(component, prop_values, (i, ret, ...rest) => {
const value = rest.length ? rest[0] : ret;
if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
if ($$.bound[i])
$$.bound[i](value);
if (ready)
make_dirty(component, i);
}
return ret;
})
: [];
$$.update();
ready = true;
run_all($$.before_update);
// `false` as a special case of no DOM component
$$.fragment = create_fragment ? create_fragment($$.ctx) : false;
if (options.target) {
if (options.hydrate) {
const nodes = children(options.target);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.l(nodes);
nodes.forEach(detach);
}
else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.c();
}
if (options.intro)
transition_in(component.$$.fragment);
mount_component(component, options.target, options.anchor);
flush();
}
set_current_component(parent_component);
}
class SvelteComponent {
$destroy() {
destroy_component(this, 1);
this.$destroy = noop;
}
$on(type, callback) {
const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index !== -1)
callbacks.splice(index, 1);
};
}
$set() {
// overridden by instance, if it has props
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const MAKE_MOVE = 'MAKE_MOVE';
const GAME_EVENT = 'GAME_EVENT';
const REDO = 'REDO';
const RESET = 'RESET';
const SYNC = 'SYNC';
const UNDO = 'UNDO';
const UPDATE = 'UPDATE';
const PLUGIN = 'PLUGIN';
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Generate a move to be dispatched to the game move reducer.
*
* @param {string} type - The move type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const makeMove = (type, args, playerID, credentials) => ({
type: MAKE_MOVE,
payload: { type, args, playerID, credentials },
});
/**
* Generate a game event to be dispatched to the flow reducer.
*
* @param {string} type - The event type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const gameEvent = (type, args, playerID, credentials) => ({
type: GAME_EVENT,
payload: { type, args, playerID, credentials },
});
/**
* Generate an automatic game event that is a side-effect of a move.
* @param {string} type - The event type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const automaticGameEvent = (type, args, playerID, credentials) => ({
type: GAME_EVENT,
payload: { type, args, playerID, credentials },
automatic: true,
});
const sync = (info) => ({
type: SYNC,
state: info.state,
log: info.log,
initialState: info.initialState,
clientOnly: true,
});
/**
* Used to update the Redux store's state in response to
* an action coming from another player.
* @param {object} state - The state to restore.
* @param {Array} deltalog - A log delta.
*/
const update$1 = (state, deltalog) => ({
type: UPDATE,
state,
deltalog,
clientOnly: true,
});
/**
* Used to reset the game state.
* @param {object} state - The initial state.
*/
const reset = (state) => ({
type: RESET,
state,
clientOnly: true,
});
/**
* Used to undo the last move.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const undo = (playerID, credentials) => ({
type: UNDO,
payload: { type: null, args: null, playerID, credentials },
});
/**
* Used to redo the last undone move.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const redo = (playerID, credentials) => ({
type: REDO,
payload: { type: null, args: null, playerID, credentials },
});
/**
* Allows plugins to define their own actions and intercept them.
*/
const plugin = (type, args, playerID, credentials) => ({
type: PLUGIN,
payload: { type, args, playerID, credentials },
});
var ActionCreators = /*#__PURE__*/Object.freeze({
makeMove: makeMove,
gameEvent: gameEvent,
automaticGameEvent: automaticGameEvent,
sync: sync,
update: update$1,
reset: reset,
undo: undo,
redo: redo,
plugin: plugin
});
/**
* Moves can return this when they want to indicate
* that the combination of arguments is illegal and
* the move ought to be discarded.
*/
const INVALID_MOVE = 'INVALID_MOVE';
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Plugin that allows using Immer to make immutable changes
* to G by just mutating it.
*/
const ImmerPlugin = {
name: 'plugin-immer',
fnWrap: (move) => (G, ctx, ...args) => {
let isInvalid = false;
const newG = produce(G, (G) => {
const result = move(G, ctx, ...args);
if (result === INVALID_MOVE) {
isInvalid = true;
return;
}
return result;
});
if (isInvalid)
return INVALID_MOVE;
return newG;
},
};
// Inlined version of Alea from https://github.com/davidbau/seedrandom.
// Converted to Typescript October 2020.
class Alea {
constructor(seed) {
const mash = Mash();
// Apply the seeding algorithm from Baagoe.
this.c = 1;
this.s0 = mash(' ');
this.s1 = mash(' ');
this.s2 = mash(' ');
this.s0 -= mash(seed);
if (this.s0 < 0) {
this.s0 += 1;
}
this.s1 -= mash(seed);
if (this.s1 < 0) {
this.s1 += 1;
}
this.s2 -= mash(seed);
if (this.s2 < 0) {
this.s2 += 1;
}
}
next() {
const t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
this.s0 = this.s1;
this.s1 = this.s2;
return (this.s2 = t - (this.c = Math.trunc(t)));
}
}
function Mash() {
let n = 0xefc8249d;
const mash = function (data) {
const str = data.toString();
for (let i = 0; i < str.length; i++) {
n += str.charCodeAt(i);
let h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
return mash;
}
function copy(f, t) {
t.c = f.c;
t.s0 = f.s0;
t.s1 = f.s1;
t.s2 = f.s2;
return t;
}
function alea(seed, state) {
const xg = new Alea(seed);
const prng = xg.next.bind(xg);
if (state)
copy(state, xg);
prng.state = () => copy(xg, {});
return prng;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Random
*
* Calls that require a pseudorandom number generator.
* Uses a seed from ctx, and also persists the PRNG
* state in ctx so that moves can stay pure.
*/
class Random {
/**
* constructor
* @param {object} ctx - The ctx object to initialize from.
*/
constructor(state) {
// If we are on the client, the seed is not present.
// Just use a temporary seed to execute the move without
// crashing it. The move state itself is discarded,
// so the actual value doesn't matter.
this.state = state || { seed: '0' };
this.used = false;
}
/**
* Generates a new seed from the current date / time.
*/
static seed() {
return Date.now().toString(36).slice(-10);
}
isUsed() {
return this.used;
}
getState() {
return this.state;
}
/**
* Generate a random number.
*/
_random() {
this.used = true;
const R = this.state;
const seed = R.prngstate ? '' : R.seed;
const rand = alea(seed, R.prngstate);
const number = rand();
this.state = {
...R,
prngstate: rand.state(),
};
return number;
}
api() {
const random = this._random.bind(this);
const SpotValue = {
D4: 4,
D6: 6,
D8: 8,
D10: 10,
D12: 12,
D20: 20,
};
// Generate functions for predefined dice values D4 - D20.
const predefined = {};
for (const key in SpotValue) {
const spotvalue = SpotValue[key];
predefined[key] = (diceCount) => {
return diceCount === undefined
? Math.floor(random() * spotvalue) + 1
: [...new Array(diceCount).keys()].map(() => Math.floor(random() * spotvalue) + 1);
};
}
function Die(spotvalue = 6, diceCount) {
return diceCount === undefined
? Math.floor(random() * spotvalue) + 1
: [...new Array(diceCount).keys()].map(() => Math.floor(random() * spotvalue) + 1);
}
return {
/**
* Similar to Die below, but with fixed spot values.
* Supports passing a diceCount
* if not defined, defaults to 1 and returns the value directly.
* if defined, returns an array containing the random dice values.
*
* D4: (diceCount) => value
* D6: (diceCount) => value
* D8: (diceCount) => value
* D10: (diceCount) => value
* D12: (diceCount) => value
* D20: (diceCount) => value
*/
...predefined,
/**
* Roll a die of specified spot value.
*
* @param {number} spotvalue - The die dimension (default: 6).
* @param {number} diceCount - number of dice to throw.
* if not defined, defaults to 1 and returns the value directly.
* if defined, returns an array containing the random dice values.
*/
Die,
/**
* Generate a random number between 0 and 1.
*/
Number: () => {
return random();
},
/**
* Shuffle an array.
*
* @param {Array} deck - The array to shuffle. Does not mutate
* the input, but returns the shuffled array.
*/
Shuffle: (deck) => {
const clone = deck.slice(0);
let srcIndex = deck.length;
let dstIndex = 0;
const shuffled = new Array(srcIndex);
while (srcIndex) {
const randIndex = Math.trunc(srcIndex * random());
shuffled[dstIndex++] = clone[randIndex];
clone[randIndex] = clone[--srcIndex];
}
return shuffled;
},
_obj: this,
};
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const RandomPlugin = {
name: 'random',
noClient: ({ api }) => {
return api._obj.isUsed();
},
flush: ({ api }) => {
return api._obj.getState();
},
api: ({ data }) => {
const random = new Random(data);
return random.api();
},
setup: ({ game }) => {
let { seed } = game;
if (seed === undefined) {
seed = Random.seed();
}
return { seed };
},
playerView: () => undefined,
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Events
*/
class Events {
constructor(flow, playerID) {
this.flow = flow;
this.playerID = playerID;
this.dispatch = [];
}
/**
* Attaches the Events API to ctx.
* @param {object} ctx - The ctx object to attach to.
*/
api(ctx) {
const events = {
_obj: this,
};
const { phase, turn } = ctx;
for (const key of this.flow.eventNames) {
events[key] = (...args) => {
this.dispatch.push({ key, args, phase, turn });
};
}
return events;
}
isUsed() {
return this.dispatch.length > 0;
}
/**
* Updates ctx with the triggered events.
* @param {object} state - The state object { G, ctx }.
*/
update(state) {
for (let i = 0; i < this.dispatch.length; i++) {
const item = this.dispatch[i];
// If the turn already ended some other way,
// don't try to end the turn again.
if (item.key === 'endTurn' && item.turn !== state.ctx.turn) {
continue;
}
// If the phase already ended some other way,
// don't try to end the phase again.
if ((item.key === 'endPhase' || item.key === 'setPhase') &&
item.phase !== state.ctx.phase) {
continue;
}
const action = automaticGameEvent(item.key, item.args, this.playerID);
state = {
...state,
...this.flow.processEvent(state, action),
};
}
return state;
}
}
/*
* Copyright 2020 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const EventsPlugin = {
name: 'events',
noClient: ({ api }) => {
return api._obj.isUsed();
},
dangerouslyFlushRawState: ({ state, api }) => {
return api._obj.update(state);
},
api: ({ game, playerID, ctx }) => {
return new Events(game.flow, playerID).api(ctx);
},
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Plugin that makes it possible to add metadata to log entries.
* During a move, you can set metadata using ctx.log.setMetadata and it will be
* available on the log entry for that move.
*/
const LogPlugin = {
name: 'log',
flush: () => ({}),
api: ({ data }) => {
return {
setMetadata: (metadata) => {
data.metadata = metadata;
},
};
},
setup: () => ({}),
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* List of plugins that are always added.
*/
const DEFAULT_PLUGINS = [ImmerPlugin, RandomPlugin, EventsPlugin, LogPlugin];
/**
* Allow plugins to intercept actions and process them.
*/
const ProcessAction = (state, action, opts) => {
opts.game.plugins
.filter((plugin) => plugin.action !== undefined)
.filter((plugin) => plugin.name === action.payload.type)
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
const data = plugin.action(pluginState.data, action.payload);
state = {
...state,
plugins: {
...state.plugins,
[name]: { ...pluginState, data },
},
};
});
return state;
};
/**
* The API's created by various plugins are stored in the plugins
* section of the state object:
*
* {
* G: {},
* ctx: {},
* plugins: {
* plugin-a: {
* data: {}, // this is generated by the plugin at Setup / Flush.
* api: {}, // this is ephemeral and generated by Enhance.
* }
* }
* }
*
* This function takes these API's and stuffs them back into
* ctx for consumption inside a move function or hook.
*/
const EnhanceCtx = (state) => {
const ctx = { ...state.ctx };
const plugins = state.plugins || {};
Object.entries(plugins).forEach(([name, { api }]) => {
ctx[name] = api;
});
return ctx;
};
/**
* Applies the provided plugins to the given move / flow function.
*
* @param {function} fn - The move function or trigger to apply the plugins to.
* @param {object} plugins - The list of plugins.
*/
const FnWrap = (fn, plugins) => {
const reducer = (acc, { fnWrap }) => fnWrap(acc);
return [...DEFAULT_PLUGINS, ...plugins]
.filter((plugin) => plugin.fnWrap !== undefined)
.reduce(reducer, fn);
};
/**
* Allows the plugin to generate its initial state.
*/
const Setup = (state, opts) => {
[...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.setup !== undefined)
.forEach((plugin) => {
const name = plugin.name;
const data = plugin.setup({
G: state.G,
ctx: state.ctx,
game: opts.game,
});
state = {
...state,
plugins: {
...state.plugins,
[name]: { data },
},
};
});
return state;
};
/**
* Invokes the plugin before a move or event.
* The API that the plugin generates is stored inside
* the `plugins` section of the state (which is subsequently
* merged into ctx).
*/
const Enhance = (state, opts) => {
[...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.api !== undefined)
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
const api = plugin.api({
G: state.G,
ctx: state.ctx,
data: pluginState.data,
game: opts.game,
playerID: opts.playerID,
});
state = {
...state,
plugins: {
...state.plugins,
[name]: { ...pluginState, api },
},
};
});
return state;
};
/**
* Allows plugins to update their state after a move / event.
*/
const Flush = (state, opts) => {
// Note that we flush plugins in reverse order, to make sure that plugins
// that come before in the chain are still available.
[...DEFAULT_PLUGINS, ...opts.game.plugins].reverse().forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
if (plugin.flush) {
const newData = plugin.flush({
G: state.G,
ctx: state.ctx,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
state = {
...state,
plugins: {
...state.plugins,
[plugin.name]: { data: newData },
},
};
}
else if (plugin.dangerouslyFlushRawState) {
state = plugin.dangerouslyFlushRawState({
state,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
// Remove everything other than data.
const data = state.plugins[name].data;
state = {
...state,
plugins: {
...state.plugins,
[plugin.name]: { data },
},
};
}
});
return state;
};
/**
* Allows plugins to indicate if they should not be materialized on the client.
* This will cause the client to discard the state update and wait for the
* master instead.
*/
const NoClient = (state, opts) => {
return [...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.noClient !== undefined)
.map((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name];
if (pluginState) {
return plugin.noClient({
G: state.G,
ctx: state.ctx,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
}
return false;
})
.some((value) => value === true);
};
/**
* Allows plugins to customize their data for specific players.
* For example, a plugin may want to share no data with the client, or
* want to keep some player data secret from opponents.
*/
const PlayerView = ({ G, ctx, plugins = {} }, { game, playerID }) => {
[...DEFAULT_PLUGINS, ...game.plugins].forEach(({ name, playerView }) => {
if (!playerView)
return;
const { data } = plugins[name] || { data: {} };
const newData = playerView({ G, ctx, game, data, playerID });
plugins = {
...plugins,
[name]: { data: newData },
};
});
return plugins;
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const production = process.env.NODE_ENV === 'production';
const logfn = production ? () => { } : console.log;
const errorfn = console.error;
function info(msg) {
logfn(`INFO: ${msg}`);
}
function error(error) {
errorfn('ERROR:', error);
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Event to change the active players (and their stages) in the current turn.
*/
function SetActivePlayersEvent(state, _playerID, arg) {
return { ...state, ctx: SetActivePlayers(state.ctx, arg) };
}
function SetActivePlayers(ctx, arg) {
let { _prevActivePlayers } = ctx;
let activePlayers = {};
let _nextActivePlayers = null;
let _activePlayersMoveLimit = {};
if (Array.isArray(arg)) {
// support a simple array of player IDs as active players
const value = {};
arg.forEach((v) => (value[v] = Stage.NULL));
activePlayers = value;
}
else {
// process active players argument object
if (arg.next) {
_nextActivePlayers = arg.next;
}
_prevActivePlayers = arg.revert
? _prevActivePlayers.concat({
activePlayers: ctx.activePlayers,
_activePlayersMoveLimit: ctx._activePlayersMoveLimit,
_activePlayersNumMoves: ctx._activePlayersNumMoves,
})
: [];
if (arg.currentPlayer !== undefined) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, ctx.currentPlayer, arg.currentPlayer);
}
if (arg.others !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
if (id !== ctx.currentPlayer) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.others);
}
}
}
if (arg.all !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.all);
}
}
if (arg.value) {
for (const id in arg.value) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.value[id]);
}
}
if (arg.moveLimit) {
for (const id in activePlayers) {
if (_activePlayersMoveLimit[id] === undefined) {
_activePlayersMoveLimit[id] = arg.moveLimit;
}
}
}
}
if (Object.keys(activePlayers).length == 0) {
activePlayers = null;
}
if (Object.keys(_activePlayersMoveLimit).length == 0) {
_activePlayersMoveLimit = null;
}
const _activePlayersNumMoves = {};
for (const id in activePlayers) {
_activePlayersNumMoves[id] = 0;
}
return {
...ctx,
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
_prevActivePlayers,
_nextActivePlayers,
};
}
/**
* Update activePlayers, setting it to previous, next or null values
* when it becomes empty.
* @param ctx
*/
function UpdateActivePlayersOnceEmpty(ctx) {
let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, } = ctx;
if (activePlayers && Object.keys(activePlayers).length == 0) {
if (ctx._nextActivePlayers) {
ctx = SetActivePlayers(ctx, ctx._nextActivePlayers);
({
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
_prevActivePlayers,
} = ctx);
}
else if (_prevActivePlayers.length > 0) {
const lastIndex = _prevActivePlayers.length - 1;
({
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
} = _prevActivePlayers[lastIndex]);
_prevActivePlayers = _prevActivePlayers.slice(0, lastIndex);
}
else {
activePlayers = null;
_activePlayersMoveLimit = null;
}
}
return {
...ctx,
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
_prevActivePlayers,
};
}
/**
* Apply an active player argument to the given player ID
* @param {Object} activePlayers
* @param {Object} _activePlayersMoveLimit
* @param {String} playerID The player to apply the parameter to
* @param {(String|Object)} arg An active player argument
*/
function ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, playerID, arg) {
if (typeof arg !== 'object' || arg === Stage.NULL) {
arg = { stage: arg };
}
if (arg.stage !== undefined) {
activePlayers[playerID] = arg.stage;
if (arg.moveLimit)
_activePlayersMoveLimit[playerID] = arg.moveLimit;
}
}
/**
* Converts a playOrderPos index into its value in playOrder.
* @param {Array} playOrder - An array of player ID's.
* @param {number} playOrderPos - An index into the above.
*/
function getCurrentPlayer(playOrder, playOrderPos) {
// convert to string in case playOrder is set to number[]
return playOrder[playOrderPos] + '';
}
/**
* Called at the start of a turn to initialize turn order state.
*
* TODO: This is called inside StartTurn, which is called from
* both UpdateTurn and StartPhase (so it's called at the beginning
* of a new phase as well as between turns). We should probably
* split it into two.
*/
function InitTurnOrderState(state, turn) {
let { G, ctx } = state;
const ctxWithAPI = EnhanceCtx(state);
const order = turn.order;
let playOrder = [...new Array(ctx.numPlayers)].map((_, i) => i + '');
if (order.playOrder !== undefined) {
playOrder = order.playOrder(G, ctxWithAPI);
}
const playOrderPos = order.first(G, ctxWithAPI);
const posType = typeof playOrderPos;
if (posType !== 'number') {
error(`invalid value returned by turn.order.first — expected number got ${posType} “${playOrderPos}”.`);
}
const currentPlayer = getCurrentPlayer(playOrder, playOrderPos);
ctx = { ...ctx, currentPlayer, playOrderPos, playOrder };
ctx = SetActivePlayers(ctx, turn.activePlayers || {});
return ctx;
}
/**
* Called at the end of each turn to update the turn order state.
* @param {object} G - The game object G.
* @param {object} ctx - The game object ctx.
* @param {object} turn - A turn object for this phase.
* @param {string} endTurnArg - An optional argument to endTurn that
may specify the next player.
*/
function UpdateTurnOrderState(state, currentPlayer, turn, endTurnArg) {
const order = turn.order;
let { G, ctx } = state;
let playOrderPos = ctx.playOrderPos;
let endPhase = false;
if (endTurnArg && endTurnArg !== true) {
if (typeof endTurnArg !== 'object') {
error(`invalid argument to endTurn: ${endTurnArg}`);
}
Object.keys(endTurnArg).forEach((arg) => {
switch (arg) {
case 'remove':
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
break;
case 'next':
playOrderPos = ctx.playOrder.indexOf(endTurnArg.next);
currentPlayer = endTurnArg.next;
break;
default:
error(`invalid argument to endTurn: ${arg}`);
}
});
}
else {
const ctxWithAPI = EnhanceCtx(state);
const t = order.next(G, ctxWithAPI);
const type = typeof t;
if (t !== undefined && type !== 'number') {
error(`invalid value returned by turn.order.next — expected number or undefined got ${type} “${t}”.`);
}
if (t === undefined) {
endPhase = true;
}
else {
playOrderPos = t;
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
}
}
ctx = {
...ctx,
playOrderPos,
currentPlayer,
};
return { endPhase, ctx };
}
/**
* Set of different turn orders possible in a phase.
* These are meant to be passed to the `turn` setting
* in the flow objects.
*
* Each object defines the first player when the phase / game
* begins, and also a function `next` to determine who the
* next player is when the turn ends.
*
* The phase ends if next() returns undefined.
*/
const TurnOrder = {
/**
* DEFAULT
*
* The default round-robin turn order.
*/
DEFAULT: {
first: (G, ctx) => ctx.turn === 0
? ctx.playOrderPos
: (ctx.playOrderPos + 1) % ctx.playOrder.length,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* RESET
*
* Similar to DEFAULT, but starts from 0 each time.
*/
RESET: {
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* CONTINUE
*
* Similar to DEFAULT, but starts with the player who ended the last phase.
*/
CONTINUE: {
first: (G, ctx) => ctx.playOrderPos,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* ONCE
*
* Another round-robin turn order, but goes around just once.
* The phase ends after all players have played.
*/
ONCE: {
first: () => 0,
next: (G, ctx) => {
if (ctx.playOrderPos < ctx.playOrder.length - 1) {
return ctx.playOrderPos + 1;
}
},
},
/**
* CUSTOM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase.
*
* @param {Array} playOrder - The play order.
*/
CUSTOM: (playOrder) => ({
playOrder: () => playOrder,
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
/**
* CUSTOM_FROM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase to a value specified by a field
* in G.
*
* @param {string} playOrderField - Field in G.
*/
CUSTOM_FROM: (playOrderField) => ({
playOrder: (G) => G[playOrderField],
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
};
const Stage = {
NULL: null,
};
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Flow
*
* Creates a reducer that updates ctx (analogous to how moves update G).
*/
function Flow({ moves, phases, endIf, onEnd, turn, events, plugins, }) {
// Attach defaults.
if (moves === undefined) {
moves = {};
}
if (events === undefined) {
events = {};
}
if (plugins === undefined) {
plugins = [];
}
if (phases === undefined) {
phases = {};
}
if (!endIf)
endIf = () => undefined;
if (!onEnd)
onEnd = (G) => G;
if (!turn)
turn = {};
const phaseMap = { ...phases };
if ('' in phaseMap) {
error('cannot specify phase with empty name');
}
phaseMap[''] = {};
const moveMap = {};
const moveNames = new Set();
let startingPhase = null;
Object.keys(moves).forEach((name) => moveNames.add(name));
const HookWrapper = (fn) => {
const withPlugins = FnWrap(fn, plugins);
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return withPlugins(state.G, ctxWithAPI);
};
};
const TriggerWrapper = (endIf) => {
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return endIf(state.G, ctxWithAPI);
};
};
const wrapped = {
onEnd: HookWrapper(onEnd),
endIf: TriggerWrapper(endIf),
};
for (const phase in phaseMap) {
const conf = phaseMap[phase];
if (conf.start === true) {
startingPhase = phase;
}
if (conf.moves !== undefined) {
for (const move of Object.keys(conf.moves)) {
moveMap[phase + '.' + move] = conf.moves[move];
moveNames.add(move);
}
}
if (conf.endIf === undefined) {
conf.endIf = () => undefined;
}
if (conf.onBegin === undefined) {
conf.onBegin = (G) => G;
}
if (conf.onEnd === undefined) {
conf.onEnd = (G) => G;
}
if (conf.turn === undefined) {
conf.turn = turn;
}
if (conf.turn.order === undefined) {
conf.turn.order = TurnOrder.DEFAULT;
}
if (conf.turn.onBegin === undefined) {
conf.turn.onBegin = (G) => G;
}
if (conf.turn.onEnd === undefined) {
conf.turn.onEnd = (G) => G;
}
if (conf.turn.endIf === undefined) {
conf.turn.endIf = () => false;
}
if (conf.turn.onMove === undefined) {
conf.turn.onMove = (G) => G;
}
if (conf.turn.stages === undefined) {
conf.turn.stages = {};
}
for (const stage in conf.turn.stages) {
const stageConfig = conf.turn.stages[stage];
const moves = stageConfig.moves || {};
for (const move of Object.keys(moves)) {
const key = phase + '.' + stage + '.' + move;
moveMap[key] = moves[move];
moveNames.add(move);
}
}
conf.wrapped = {
onBegin: HookWrapper(conf.onBegin),
onEnd: HookWrapper(conf.onEnd),
endIf: TriggerWrapper(conf.endIf),
};
conf.turn.wrapped = {
onMove: HookWrapper(conf.turn.onMove),
onBegin: HookWrapper(conf.turn.onBegin),
onEnd: HookWrapper(conf.turn.onEnd),
endIf: TriggerWrapper(conf.turn.endIf),
};
}
function GetPhase(ctx) {
return ctx.phase ? phaseMap[ctx.phase] : phaseMap[''];
}
function OnMove(s) {
return s;
}
function Process(state, events) {
const phasesEnded = new Set();
const turnsEnded = new Set();
for (let i = 0; i < events.length; i++) {
const { fn, arg, ...rest } = events[i];
// Detect a loop of EndPhase calls.
// This could potentially even be an infinite loop
// if the endIf condition of each phase blindly
// returns true. The moment we detect a single
// loop, we just bail out of all phases.
if (fn === EndPhase) {
turnsEnded.clear();
const phase = state.ctx.phase;
if (phasesEnded.has(phase)) {
const ctx = { ...state.ctx, phase: null };
return { ...state, ctx };
}
phasesEnded.add(phase);
}
// Process event.
const next = [];
state = fn(state, {
...rest,
arg,
next,
});
if (fn === EndGame) {
break;
}
// Check if we should end the game.
const shouldEndGame = ShouldEndGame(state);
if (shouldEndGame) {
events.push({
fn: EndGame,
arg: shouldEndGame,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the phase.
const shouldEndPhase = ShouldEndPhase(state);
if (shouldEndPhase) {
events.push({
fn: EndPhase,
arg: shouldEndPhase,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the turn.
if (fn === OnMove) {
const shouldEndTurn = ShouldEndTurn(state);
if (shouldEndTurn) {
events.push({
fn: EndTurn,
arg: shouldEndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
}
events.push(...next);
}
return state;
}
///////////
// Start //
///////////
function StartGame(state, { next }) {
next.push({ fn: StartPhase });
return state;
}
function StartPhase(state, { next }) {
let { G, ctx } = state;
const conf = GetPhase(ctx);
// Run any phase setup code provided by the user.
G = conf.wrapped.onBegin(state);
next.push({ fn: StartTurn });
return { ...state, G, ctx };
}
function StartTurn(state, { currentPlayer }) {
let { G, ctx } = state;
const conf = GetPhase(ctx);
// Initialize the turn order state.
if (currentPlayer) {
ctx = { ...ctx, currentPlayer };
if (conf.turn.activePlayers) {
ctx = SetActivePlayers(ctx, conf.turn.activePlayers);
}
}
else {
// This is only called at the beginning of the phase
// when there is no currentPlayer yet.
ctx = InitTurnOrderState(state, conf.turn);
}
const turn = ctx.turn + 1;
ctx = { ...ctx, turn, numMoves: 0, _prevActivePlayers: [] };
G = conf.turn.wrapped.onBegin({ ...state, G, ctx });
return { ...state, G, ctx, _undo: [], _redo: [] };
}
////////////
// Update //
////////////
function UpdatePhase(state, { arg, next, phase }) {
const conf = GetPhase({ phase });
let { ctx } = state;
if (arg && arg.next) {
if (arg.next in phaseMap) {
ctx = { ...ctx, phase: arg.next };
}
else {
error('invalid phase: ' + arg.next);
return state;
}
}
else if (conf.next !== undefined) {
ctx = { ...ctx, phase: conf.next };
}
else {
ctx = { ...ctx, phase: null };
}
state = { ...state, ctx };
// Start the new phase.
next.push({ fn: StartPhase });
return state;
}
function UpdateTurn(state, { arg, currentPlayer, next }) {
let { G, ctx } = state;
const conf = GetPhase(ctx);
// Update turn order state.
const { endPhase, ctx: newCtx } = UpdateTurnOrderState(state, currentPlayer, conf.turn, arg);
ctx = newCtx;
state = { ...state, G, ctx };
if (endPhase) {
next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase });
}
else {
next.push({ fn: StartTurn, currentPlayer: ctx.currentPlayer });
}
return state;
}
function UpdateStage(state, { arg, playerID }) {
if (typeof arg === 'string' || arg === Stage.NULL) {
arg = { stage: arg };
}
let { ctx } = state;
let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, } = ctx;
// Checking if stage is valid, even Stage.NULL
if (arg.stage !== undefined) {
if (activePlayers === null) {
activePlayers = {};
}
activePlayers[playerID] = arg.stage;
_activePlayersNumMoves[playerID] = 0;
if (arg.moveLimit) {
if (_activePlayersMoveLimit === null) {
_activePlayersMoveLimit = {};
}
_activePlayersMoveLimit[playerID] = arg.moveLimit;
}
}
ctx = {
...ctx,
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
};
return { ...state, ctx };
}
///////////////
// ShouldEnd //
///////////////
function ShouldEndGame(state) {
return wrapped.endIf(state);
}
function ShouldEndPhase(state) {
const conf = GetPhase(state.ctx);
return conf.wrapped.endIf(state);
}
function ShouldEndTurn(state) {
const conf = GetPhase(state.ctx);
// End the turn if the required number of moves has been made.
const currentPlayerMoves = state.ctx.numMoves || 0;
if (conf.turn.moveLimit && currentPlayerMoves >= conf.turn.moveLimit) {
return true;
}
return conf.turn.wrapped.endIf(state);
}
/////////
// End //
/////////
function EndGame(state, { arg, phase }) {
state = EndPhase(state, { phase });
if (arg === undefined) {
arg = true;
}
state = { ...state, ctx: { ...state.ctx, gameover: arg } };
// Run game end hook.
const G = wrapped.onEnd(state);
return { ...state, G };
}
function EndPhase(state, { arg, next, turn, automatic }) {
// End the turn first.
state = EndTurn(state, { turn, force: true, automatic: true });
let G = state.G;
let ctx = state.ctx;
if (next) {
next.push({ fn: UpdatePhase, arg, phase: ctx.phase });
}
// If we aren't in a phase, there is nothing else to do.
if (ctx.phase === null) {
return state;
}
// Run any cleanup code for the phase that is about to end.
const conf = GetPhase(ctx);
G = conf.wrapped.onEnd(state);
// Reset the phase.
ctx = { ...ctx, phase: null };
// Add log entry.
const action = gameEvent('endPhase', arg);
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
if (automatic) {
logEntry.automatic = true;
}
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog };
}
function EndTurn(state, { arg, next, turn, force, automatic, playerID }) {
// This is not the turn that EndTurn was originally
// called for. The turn was probably ended some other way.
if (turn !== state.ctx.turn) {
return state;
}
let { G, ctx } = state;
const conf = GetPhase(ctx);
// Prevent ending the turn if moveLimit hasn't been reached.
const currentPlayerMoves = ctx.numMoves || 0;
if (!force &&
conf.turn.moveLimit &&
currentPlayerMoves < conf.turn.moveLimit) {
info(`cannot end turn before making ${conf.turn.moveLimit} moves`);
return state;
}
// Run turn-end triggers.
G = conf.turn.wrapped.onEnd(state);
if (next) {
next.push({ fn: UpdateTurn, arg, currentPlayer: ctx.currentPlayer });
}
// Reset activePlayers.
ctx = { ...ctx, activePlayers: null };
// Remove player from playerOrder
if (arg && arg.remove) {
playerID = playerID || ctx.currentPlayer;
const playOrder = ctx.playOrder.filter((i) => i != playerID);
const playOrderPos = ctx.playOrderPos > playOrder.length - 1 ? 0 : ctx.playOrderPos;
ctx = { ...ctx, playOrder, playOrderPos };
if (playOrder.length === 0) {
next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase });
return state;
}
}
// Add log entry.
const action = gameEvent('endTurn', arg);
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
if (automatic) {
logEntry.automatic = true;
}
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog, _undo: [], _redo: [] };
}
function EndStage(state, { arg, next, automatic, playerID }) {
playerID = playerID || state.ctx.currentPlayer;
let { ctx } = state;
let { activePlayers, _activePlayersMoveLimit } = ctx;
const playerInStage = activePlayers !== null && playerID in activePlayers;
if (!arg && playerInStage) {
const conf = GetPhase(ctx);
const stage = conf.turn.stages[activePlayers[playerID]];
if (stage && stage.next)
arg = stage.next;
}
// Checking if arg is a valid stage, even Stage.NULL
if (next && arg !== undefined) {
next.push({ fn: UpdateStage, arg, playerID });
}
// If player isn’t in a stage, there is nothing else to do.
if (!playerInStage)
return state;
// Remove player from activePlayers.
activePlayers = Object.keys(activePlayers)
.filter((id) => id !== playerID)
.reduce((obj, key) => {
obj[key] = activePlayers[key];
return obj;
}, {});
if (_activePlayersMoveLimit) {
// Remove player from _activePlayersMoveLimit.
_activePlayersMoveLimit = Object.keys(_activePlayersMoveLimit)
.filter((id) => id !== playerID)
.reduce((obj, key) => {
obj[key] = _activePlayersMoveLimit[key];
return obj;
}, {});
}
ctx = UpdateActivePlayersOnceEmpty({
...ctx,
activePlayers,
_activePlayersMoveLimit,
});
// Add log entry.
const action = gameEvent('endStage', arg);
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
if (automatic) {
logEntry.automatic = true;
}
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, ctx, deltalog };
}
/**
* Retrieves the relevant move that can be played by playerID.
*
* If ctx.activePlayers is set (i.e. one or more players are in some stage),
* then it attempts to find the move inside the stages config for
* that turn. If the stage for a player is '', then the player is
* allowed to make a move (as determined by the phase config), but
* isn't restricted to a particular set as defined in the stage config.
*
* If not, it then looks for the move inside the phase.
*
* If it doesn't find the move there, it looks at the global move definition.
*
* @param {object} ctx
* @param {string} name
* @param {string} playerID
*/
function GetMove(ctx, name, playerID) {
const conf = GetPhase(ctx);
const stages = conf.turn.stages;
const { activePlayers } = ctx;
if (activePlayers &&
activePlayers[playerID] !== undefined &&
activePlayers[playerID] !== Stage.NULL &&
stages[activePlayers[playerID]] !== undefined &&
stages[activePlayers[playerID]].moves !== undefined) {
// Check if moves are defined for the player's stage.
const stage = stages[activePlayers[playerID]];
const moves = stage.moves;
if (name in moves) {
return moves[name];
}
}
else if (conf.moves) {
// Check if moves are defined for the current phase.
if (name in conf.moves) {
return conf.moves[name];
}
}
else if (name in moves) {
// Check for the move globally.
return moves[name];
}
return null;
}
function ProcessMove(state, action) {
const conf = GetPhase(state.ctx);
const move = GetMove(state.ctx, action.type, action.playerID);
const shouldCount = !move || typeof move === 'function' || move.noLimit !== true;
const { ctx } = state;
const { _activePlayersNumMoves } = ctx;
const { playerID } = action;
let numMoves = state.ctx.numMoves;
if (shouldCount) {
if (playerID == state.ctx.currentPlayer) {
numMoves++;
}
if (ctx.activePlayers)
_activePlayersNumMoves[playerID]++;
}
state = {
...state,
ctx: {
...ctx,
numMoves,
_activePlayersNumMoves,
},
};
if (ctx._activePlayersMoveLimit &&
_activePlayersNumMoves[playerID] >= ctx._activePlayersMoveLimit[playerID]) {
state = EndStage(state, { playerID, automatic: true });
}
const G = conf.turn.wrapped.onMove(state);
state = { ...state, G };
const events = [{ fn: OnMove }];
return Process(state, events);
}
function SetStageEvent(state, playerID, arg) {
return Process(state, [{ fn: EndStage, arg, playerID }]);
}
function EndStageEvent(state, playerID) {
return Process(state, [{ fn: EndStage, playerID }]);
}
function SetPhaseEvent(state, _playerID, newPhase) {
return Process(state, [
{
fn: EndPhase,
phase: state.ctx.phase,
turn: state.ctx.turn,
arg: { next: newPhase },
},
]);
}
function EndPhaseEvent(state) {
return Process(state, [
{ fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn },
]);
}
function EndTurnEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
function PassEvent(state, _playerID, arg) {
return Process(state, [
{
fn: EndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
force: true,
arg,
},
]);
}
function EndGameEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndGame, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
const eventHandlers = {
endStage: EndStageEvent,
setStage: SetStageEvent,
endTurn: EndTurnEvent,
pass: PassEvent,
endPhase: EndPhaseEvent,
setPhase: SetPhaseEvent,
endGame: EndGameEvent,
setActivePlayers: SetActivePlayersEvent,
};
const enabledEventNames = [];
if (events.endTurn !== false) {
enabledEventNames.push('endTurn');
}
if (events.pass !== false) {
enabledEventNames.push('pass');
}
if (events.endPhase !== false) {
enabledEventNames.push('endPhase');
}
if (events.setPhase !== false) {
enabledEventNames.push('setPhase');
}
if (events.endGame !== false) {
enabledEventNames.push('endGame');
}
if (events.setActivePlayers !== false) {
enabledEventNames.push('setActivePlayers');
}
if (events.endStage !== false) {
enabledEventNames.push('endStage');
}
if (events.setStage !== false) {
enabledEventNames.push('setStage');
}
function ProcessEvent(state, action) {
const { type, playerID, args } = action.payload;
if (Object.prototype.hasOwnProperty.call(eventHandlers, type)) {
const eventArgs = [state, playerID].concat(args);
return eventHandlers[type].apply({}, eventArgs);
}
return state;
}
function IsPlayerActive(_G, ctx, playerID) {
if (ctx.activePlayers) {
return playerID in ctx.activePlayers;
}
return ctx.currentPlayer === playerID;
}
return {
ctx: (numPlayers) => ({
numPlayers,
turn: 0,
currentPlayer: '0',
playOrder: [...new Array(numPlayers)].map((_d, i) => i + ''),
playOrderPos: 0,
phase: startingPhase,
activePlayers: null,
}),
init: (state) => {
return Process(state, [{ fn: StartGame }]);
},
isPlayerActive: IsPlayerActive,
eventHandlers,
eventNames: Object.keys(eventHandlers),
enabledEventNames,
moveMap,
moveNames: [...moveNames.values()],
processMove: ProcessMove,
processEvent: ProcessEvent,
getMove: GetMove,
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function IsProcessed(game) {
return game.processMove !== undefined;
}
/**
* Helper to generate the game move reducer. The returned
* reducer has the following signature:
*
* (G, action, ctx) => {}
*
* You can roll your own if you like, or use any Redux
* addon to generate such a reducer.
*
* The convention used in this framework is to
* have action.type contain the name of the move, and
* action.args contain any additional arguments as an
* Array.
*/
function ProcessGameConfig(game) {
// The Game() function has already been called on this
// config object, so just pass it through.
if (IsProcessed(game)) {
return game;
}
if (game.name === undefined)
game.name = 'default';
if (game.disableUndo === undefined)
game.disableUndo = false;
if (game.setup === undefined)
game.setup = () => ({});
if (game.moves === undefined)
game.moves = {};
if (game.playerView === undefined)
game.playerView = (G) => G;
if (game.plugins === undefined)
game.plugins = [];
game.plugins.forEach((plugin) => {
if (plugin.name === undefined) {
throw new Error('Plugin missing name attribute');
}
if (plugin.name.includes(' ')) {
throw new Error(plugin.name + ': Plugin name must not include spaces');
}
});
if (game.name.includes(' ')) {
throw new Error(game.name + ': Game name must not include spaces');
}
const flow = Flow(game);
return {
...game,
flow,
moveNames: flow.moveNames,
pluginNames: game.plugins.map((p) => p.name),
processMove: (state, action) => {
let moveFn = flow.getMove(state.ctx, action.type, action.playerID);
if (IsLongFormMove(moveFn)) {
moveFn = moveFn.move;
}
if (moveFn instanceof Function) {
const fn = FnWrap(moveFn, game.plugins);
const ctxWithAPI = {
...EnhanceCtx(state),
playerID: action.playerID,
};
let args = [];
if (action.args !== undefined) {
args = args.concat(action.args);
}
return fn(state.G, ctxWithAPI, ...args);
}
error(`invalid move object: ${action.type}`);
return state.G;
},
};
}
function IsLongFormMove(move) {
return move instanceof Object && move.move !== undefined;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Check if the payload for the passed action contains a playerID.
*/
const actionHasPlayerID = (action) => action.payload.playerID !== null && action.payload.playerID !== undefined;
/**
* Returns true if a move can be undone.
*/
const CanUndoMove = (G, ctx, move) => {
function HasUndoable(move) {
return move.undoable !== undefined;
}
function IsFunction(undoable) {
return undoable instanceof Function;
}
if (!HasUndoable(move)) {
return true;
}
if (IsFunction(move.undoable)) {
return move.undoable(G, ctx);
}
return move.undoable;
};
/**
* Update the undo and redo stacks for a move or event.
*/
function updateUndoRedoState(state, opts) {
if (opts.game.disableUndo)
return state;
const undoEntry = {
G: state.G,
ctx: state.ctx,
plugins: state.plugins,
playerID: opts.action.payload.playerID || state.ctx.currentPlayer,
};
if (opts.action.type === 'MAKE_MOVE') {
undoEntry.moveType = opts.action.payload.type;
}
return {
...state,
_undo: [...state._undo, undoEntry],
// Always reset redo stack when making a move or event
_redo: [],
};
}
/**
* Process state, adding the initial deltalog for this action.
*/
function initializeDeltalog(state, action, move) {
// Create a log entry for this action.
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
const pluginLogMetadata = state.plugins.log.data.metadata;
if (pluginLogMetadata !== undefined) {
logEntry.metadata = pluginLogMetadata;
}
if (typeof move === 'object' && move.redact === true) {
logEntry.redact = true;
}
return {
...state,
deltalog: [logEntry],
};
}
/**
* CreateGameReducer
*
* Creates the main game state reducer.
*/
function CreateGameReducer({ game, isClient, }) {
game = ProcessGameConfig(game);
/**
* GameReducer
*
* Redux reducer that maintains the overall game state.
* @param {object} state - The state before the action.
* @param {object} action - A Redux action.
*/
return (state = null, action) => {
switch (action.type) {
case GAME_EVENT: {
state = { ...state, deltalog: [] };
// Process game events only on the server.
// These events like `endTurn` typically
// contain code that may rely on secret state
// and cannot be computed on the client.
if (isClient) {
return state;
}
// Disallow events once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot call event after game end`);
return state;
}
// Ignore the event if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed event: ${action.payload.type}`);
return state;
}
// Execute plugins.
state = Enhance(state, {
game,
isClient: false,
playerID: action.payload.playerID,
});
// Process event.
let newState = game.flow.processEvent(state, action);
// Execute plugins.
newState = Flush(newState, { game, isClient: false });
// Update undo / redo state.
newState = updateUndoRedoState(newState, { game, action });
return { ...newState, _stateID: state._stateID + 1 };
}
case MAKE_MOVE: {
state = { ...state, deltalog: [] };
// Check whether the move is allowed at this time.
const move = game.flow.getMove(state.ctx, action.payload.type, action.payload.playerID || state.ctx.currentPlayer);
if (move === null) {
error(`disallowed move: ${action.payload.type}`);
return state;
}
// Don't run move on client if move says so.
if (isClient && move.client === false) {
return state;
}
// Disallow moves once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot make move after game end`);
return state;
}
// Ignore the move if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed move: ${action.payload.type}`);
return state;
}
// Execute plugins.
state = Enhance(state, {
game,
isClient,
playerID: action.payload.playerID,
});
// Process the move.
const G = game.processMove(state, action.payload);
// The game declared the move as invalid.
if (G === INVALID_MOVE) {
error(`invalid move: ${action.payload.type} args: ${action.payload.args}`);
return state;
}
const newState = { ...state, G };
// Some plugin indicated that it is not suitable to be
// materialized on the client (and must wait for the server
// response instead).
if (isClient && NoClient(newState, { game })) {
return state;
}
state = newState;
// If we're on the client, just process the move
// and no triggers in multiplayer mode.
// These will be processed on the server, which
// will send back a state update.
if (isClient) {
state = Flush(state, {
game,
isClient: true,
});
return {
...state,
_stateID: state._stateID + 1,
};
}
// On the server, construct the deltalog.
state = initializeDeltalog(state, action, move);
// Allow the flow reducer to process any triggers that happen after moves.
state = game.flow.processMove(state, action.payload);
state = Flush(state, { game });
// Update undo / redo state.
state = updateUndoRedoState(state, { game, action });
return {
...state,
_stateID: state._stateID + 1,
};
}
case RESET:
case UPDATE:
case SYNC: {
return action.state;
}
case UNDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Undo is not enabled');
return state;
}
const { _undo, _redo } = state;
if (_undo.length < 2) {
return state;
}
const last = _undo[_undo.length - 1];
const restore = _undo[_undo.length - 2];
// Only allow players to undo their own moves.
if (actionHasPlayerID(action) &&
action.payload.playerID !== last.playerID) {
return state;
}
// Only allow undoable moves to be undone.
const lastMove = game.flow.getMove(restore.ctx, last.moveType, last.playerID);
if (!CanUndoMove(state.G, state.ctx, lastMove)) {
return state;
}
state = initializeDeltalog(state, action);
return {
...state,
G: restore.G,
ctx: restore.ctx,
plugins: restore.plugins,
_stateID: state._stateID + 1,
_undo: _undo.slice(0, -1),
_redo: [last, ..._redo],
};
}
case REDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Redo is not enabled');
return state;
}
const { _undo, _redo } = state;
if (_redo.length == 0) {
return state;
}
const first = _redo[0];
// Only allow players to redo their own undos.
if (actionHasPlayerID(action) &&
action.payload.playerID !== first.playerID) {
return state;
}
state = initializeDeltalog(state, action);
return {
...state,
G: first.G,
ctx: first.ctx,
plugins: first.plugins,
_stateID: state._stateID + 1,
_undo: [..._undo, first],
_redo: _redo.slice(1),
};
}
case PLUGIN: {
return ProcessAction(state, action, { game });
}
default: {
return state;
}
}
};
}
/*
* Copyright 2020 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Creates the initial game state.
*/
function InitializeGame({ game, numPlayers, setupData, }) {
game = ProcessGameConfig(game);
if (!numPlayers) {
numPlayers = 2;
}
const ctx = game.flow.ctx(numPlayers);
let state = {
// User managed state.
G: {},
// Framework managed state.
ctx,
// Plugin related state.
plugins: {},
};
// Run plugins over initial state.
state = Setup(state, { game });
state = Enhance(state, { game, playerID: undefined });
const enhancedCtx = EnhanceCtx(state);
state.G = game.setup(enhancedCtx, setupData);
let initial = {
...state,
// List of {G, ctx} pairs that can be undone.
_undo: [],
// List of {G, ctx} pairs that can be redone.
_redo: [],
// A monotonically non-decreasing ID to ensure that
// state updates are only allowed from clients that
// are at the same version that the server.
_stateID: 0,
};
initial = game.flow.init(initial);
initial = Flush(initial, { game });
// Initialize undo stack.
if (!game.disableUndo) {
initial._undo = [
{
G: initial.G,
ctx: initial.ctx,
plugins: initial.plugins,
},
];
}
return initial;
}
const subscriber_queue = [];
/**
* Create a `Writable` store that allows both updating and reading by subscription.
* @param {*=}value initial value
* @param {StartStopNotifier=}start start and stop notifications for subscriptions
*/
function writable(value, start = noop) {
let stop;
const subscribers = [];
function set(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
if (stop) { // store is ready
const run_queue = !subscriber_queue.length;
for (let i = 0; i < subscribers.length; i += 1) {
const s = subscribers[i];
s[1]();
subscriber_queue.push(s, value);
}
if (run_queue) {
for (let i = 0; i < subscriber_queue.length; i += 2) {
subscriber_queue[i][0](subscriber_queue[i + 1]);
}
subscriber_queue.length = 0;
}
}
}
}
function update(fn) {
set(fn(value));
}
function subscribe(run, invalidate = noop) {
const subscriber = [run, invalidate];
subscribers.push(subscriber);
if (subscribers.length === 1) {
stop = start(set) || noop;
}
run(value);
return () => {
const index = subscribers.indexOf(subscriber);
if (index !== -1) {
subscribers.splice(index, 1);
}
if (subscribers.length === 0) {
stop();
stop = null;
}
};
}
return { set, update, subscribe };
}
function cubicOut(t) {
const f = t - 1.0;
return f * f * f + 1.0;
}
function fly(node, { delay = 0, duration = 400, easing = cubicOut, x = 0, y = 0, opacity = 0 }) {
const style = getComputedStyle(node);
const target_opacity = +style.opacity;
const transform = style.transform === 'none' ? '' : style.transform;
const od = target_opacity * (1 - opacity);
return {
delay,
duration,
easing,
css: (t, u) => `
transform: ${transform} translate(${(1 - t) * x}px, ${(1 - t) * y}px);
opacity: ${target_opacity - (od * u)}`
};
}
/* src/client/debug/Menu.svelte generated by Svelte v3.24.0 */
function add_css() {
var style = element("style");
style.id = "svelte-14p9tpy-style";
style.textContent = ".menu.svelte-14p9tpy{display:flex;margin-top:-10px;flex-direction:row-reverse;border:1px solid #ccc;border-radius:5px 5px 0 0;height:25px;line-height:25px;margin-right:-500px;transform-origin:bottom right;transform:rotate(-90deg) translate(0, -500px)}.menu-item.svelte-14p9tpy{line-height:25px;cursor:pointer;border:0;background:#fefefe;color:#555;padding-left:15px;padding-right:15px;text-align:center}.menu-item.svelte-14p9tpy:first-child{border-radius:0 5px 0 0}.menu-item.svelte-14p9tpy:last-child{border-radius:5px 0 0 0}.menu-item.active.svelte-14p9tpy{cursor:default;font-weight:bold;background:#ddd;color:#555}.menu-item.svelte-14p9tpy:hover,.menu-item.svelte-14p9tpy:focus{background:#eee;color:#555}";
append(document.head, style);
}
function get_each_context(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[4] = list[i][0];
child_ctx[5] = list[i][1].label;
return child_ctx;
}
// (57:2) {#each Object.entries(panes) as [key, {label}
function create_each_block(ctx) {
let button;
let t0_value = /*label*/ ctx[5] + "";
let t0;
let t1;
let mounted;
let dispose;
function click_handler(...args) {
return /*click_handler*/ ctx[3](/*key*/ ctx[4], ...args);
}
return {
c() {
button = element("button");
t0 = text(t0_value);
t1 = space();
attr(button, "class", "menu-item svelte-14p9tpy");
toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, t0);
append(button, t1);
if (!mounted) {
dispose = listen(button, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*panes*/ 2 && t0_value !== (t0_value = /*label*/ ctx[5] + "")) set_data(t0, t0_value);
if (dirty & /*pane, Object, panes*/ 3) {
toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]);
}
},
d(detaching) {
if (detaching) detach(button);
mounted = false;
dispose();
}
};
}
function create_fragment(ctx) {
let nav;
let each_value = Object.entries(/*panes*/ ctx[1]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
}
return {
c() {
nav = element("nav");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(nav, "class", "menu svelte-14p9tpy");
},
m(target, anchor) {
insert(target, nav, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(nav, null);
}
},
p(ctx, [dirty]) {
if (dirty & /*pane, Object, panes, dispatch*/ 7) {
each_value = Object.entries(/*panes*/ ctx[1]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block(child_ctx);
each_blocks[i].c();
each_blocks[i].m(nav, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(nav);
destroy_each(each_blocks, detaching);
}
};
}
function instance($$self, $$props, $$invalidate) {
let { pane } = $$props;
let { panes } = $$props;
const dispatch = createEventDispatcher();
const click_handler = key => dispatch("change", key);
$$self.$set = $$props => {
if ("pane" in $$props) $$invalidate(0, pane = $$props.pane);
if ("panes" in $$props) $$invalidate(1, panes = $$props.panes);
};
return [pane, panes, dispatch, click_handler];
}
class Menu extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-14p9tpy-style")) add_css();
init(this, options, instance, create_fragment, safe_not_equal, { pane: 0, panes: 1 });
}
}
var contextKey = {};
/* node_modules/svelte-json-tree-auto/src/JSONArrow.svelte generated by Svelte v3.24.0 */
function add_css$1() {
var style = element("style");
style.id = "svelte-1vyml86-style";
style.textContent = ".container.svelte-1vyml86{display:inline-block;cursor:pointer;transform:translate(calc(0px - var(--li-identation)), -50%);position:absolute;top:50%;padding-right:100%}.arrow.svelte-1vyml86{transform-origin:25% 50%;position:relative;line-height:1.1em;font-size:0.75em;margin-left:0;transition:150ms;color:var(--arrow-sign);user-select:none;font-family:'Courier New', Courier, monospace}.expanded.svelte-1vyml86{transform:rotateZ(90deg) translateX(-3px)}";
append(document.head, style);
}
function create_fragment$1(ctx) {
let div1;
let div0;
let mounted;
let dispose;
return {
c() {
div1 = element("div");
div0 = element("div");
div0.textContent = `${"▶"}`;
attr(div0, "class", "arrow svelte-1vyml86");
toggle_class(div0, "expanded", /*expanded*/ ctx[0]);
attr(div1, "class", "container svelte-1vyml86");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, div0);
if (!mounted) {
dispose = listen(div1, "click", /*click_handler*/ ctx[1]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*expanded*/ 1) {
toggle_class(div0, "expanded", /*expanded*/ ctx[0]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div1);
mounted = false;
dispose();
}
};
}
function instance$1($$self, $$props, $$invalidate) {
let { expanded } = $$props;
function click_handler(event) {
bubble($$self, event);
}
$$self.$set = $$props => {
if ("expanded" in $$props) $$invalidate(0, expanded = $$props.expanded);
};
return [expanded, click_handler];
}
class JSONArrow extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1vyml86-style")) add_css$1();
init(this, options, instance$1, create_fragment$1, safe_not_equal, { expanded: 0 });
}
}
/* node_modules/svelte-json-tree-auto/src/JSONKey.svelte generated by Svelte v3.24.0 */
function add_css$2() {
var style = element("style");
style.id = "svelte-1vlbacg-style";
style.textContent = "label.svelte-1vlbacg{display:inline-block;color:var(--label-color);padding:0}.spaced.svelte-1vlbacg{padding-right:var(--li-colon-space)}";
append(document.head, style);
}
// (16:0) {#if showKey && key}
function create_if_block(ctx) {
let label;
let span;
let t0;
let t1;
let mounted;
let dispose;
return {
c() {
label = element("label");
span = element("span");
t0 = text(/*key*/ ctx[0]);
t1 = text(/*colon*/ ctx[2]);
attr(label, "class", "svelte-1vlbacg");
toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]);
},
m(target, anchor) {
insert(target, label, anchor);
append(label, span);
append(span, t0);
append(span, t1);
if (!mounted) {
dispose = listen(label, "click", /*click_handler*/ ctx[5]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*key*/ 1) set_data(t0, /*key*/ ctx[0]);
if (dirty & /*colon*/ 4) set_data(t1, /*colon*/ ctx[2]);
if (dirty & /*isParentExpanded*/ 2) {
toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]);
}
},
d(detaching) {
if (detaching) detach(label);
mounted = false;
dispose();
}
};
}
function create_fragment$2(ctx) {
let if_block_anchor;
let if_block = /*showKey*/ ctx[3] && /*key*/ ctx[0] && create_if_block(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*showKey*/ ctx[3] && /*key*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop,
o: noop,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function instance$2($$self, $$props, $$invalidate) {
let { key } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray = false } = $$props,
{ colon = ":" } = $$props;
function click_handler(event) {
bubble($$self, event);
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ("colon" in $$props) $$invalidate(2, colon = $$props.colon);
};
let showKey;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*isParentExpanded, isParentArray, key*/ 19) {
$: $$invalidate(3, showKey = isParentExpanded || !isParentArray || key != +key);
}
};
return [key, isParentExpanded, colon, showKey, isParentArray, click_handler];
}
class JSONKey extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1vlbacg-style")) add_css$2();
init(this, options, instance$2, create_fragment$2, safe_not_equal, {
key: 0,
isParentExpanded: 1,
isParentArray: 4,
colon: 2
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONNested.svelte generated by Svelte v3.24.0 */
function add_css$3() {
var style = element("style");
style.id = "svelte-rwxv37-style";
style.textContent = "label.svelte-rwxv37{display:inline-block}.indent.svelte-rwxv37{padding-left:var(--li-identation)}.collapse.svelte-rwxv37{--li-display:inline;display:inline;font-style:italic}.comma.svelte-rwxv37{margin-left:-0.5em;margin-right:0.5em}label.svelte-rwxv37{position:relative}";
append(document.head, style);
}
function get_each_context$1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[12] = list[i];
child_ctx[20] = i;
return child_ctx;
}
// (57:4) {#if expandable && isParentExpanded}
function create_if_block_3(ctx) {
let jsonarrow;
let current;
jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } });
jsonarrow.$on("click", /*toggleExpand*/ ctx[15]);
return {
c() {
create_component(jsonarrow.$$.fragment);
},
m(target, anchor) {
mount_component(jsonarrow, target, anchor);
current = true;
},
p(ctx, dirty) {
const jsonarrow_changes = {};
if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0];
jsonarrow.$set(jsonarrow_changes);
},
i(local) {
if (current) return;
transition_in(jsonarrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonarrow.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonarrow, detaching);
}
};
}
// (75:4) {:else}
function create_else_block(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = "…";
},
m(target, anchor) {
insert(target, span, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(span);
}
};
}
// (63:4) {#if isParentExpanded}
function create_if_block$1(ctx) {
let ul;
let t;
let current;
let mounted;
let dispose;
let each_value = /*slicedKeys*/ ctx[13];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$1(get_each_context$1(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block = /*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length && create_if_block_1();
return {
c() {
ul = element("ul");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t = space();
if (if_block) if_block.c();
attr(ul, "class", "svelte-rwxv37");
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
},
m(target, anchor) {
insert(target, ul, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(ul, null);
}
append(ul, t);
if (if_block) if_block.m(ul, null);
current = true;
if (!mounted) {
dispose = listen(ul, "click", /*expand*/ ctx[16]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*expanded, previewKeys, getKey, slicedKeys, isArray, getValue, getPreviewValue*/ 10129) {
each_value = /*slicedKeys*/ ctx[13];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$1(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$1(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(ul, t);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length) {
if (if_block) ; else {
if_block = create_if_block_1();
if_block.c();
if_block.m(ul, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*expanded*/ 1) {
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_each(each_blocks, detaching);
if (if_block) if_block.d();
mounted = false;
dispose();
}
};
}
// (67:10) {#if !expanded && index < previewKeys.length - 1}
function create_if_block_2(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = ",";
attr(span, "class", "comma svelte-rwxv37");
},
m(target, anchor) {
insert(target, span, anchor);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
// (65:8) {#each slicedKeys as key, index}
function create_each_block$1(ctx) {
let jsonnode;
let t;
let if_block_anchor;
let current;
jsonnode = new JSONNode({
props: {
key: /*getKey*/ ctx[8](/*key*/ ctx[12]),
isParentExpanded: /*expanded*/ ctx[0],
isParentArray: /*isArray*/ ctx[4],
value: /*expanded*/ ctx[0]
? /*getValue*/ ctx[9](/*key*/ ctx[12])
: /*getPreviewValue*/ ctx[10](/*key*/ ctx[12])
}
});
let if_block = !/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1 && create_if_block_2();
return {
c() {
create_component(jsonnode.$$.fragment);
t = space();
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
mount_component(jsonnode, target, anchor);
insert(target, t, anchor);
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const jsonnode_changes = {};
if (dirty & /*getKey, slicedKeys*/ 8448) jsonnode_changes.key = /*getKey*/ ctx[8](/*key*/ ctx[12]);
if (dirty & /*expanded*/ 1) jsonnode_changes.isParentExpanded = /*expanded*/ ctx[0];
if (dirty & /*isArray*/ 16) jsonnode_changes.isParentArray = /*isArray*/ ctx[4];
if (dirty & /*expanded, getValue, slicedKeys, getPreviewValue*/ 9729) jsonnode_changes.value = /*expanded*/ ctx[0]
? /*getValue*/ ctx[9](/*key*/ ctx[12])
: /*getPreviewValue*/ ctx[10](/*key*/ ctx[12]);
jsonnode.$set(jsonnode_changes);
if (!/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1) {
if (if_block) ; else {
if_block = create_if_block_2();
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnode, detaching);
if (detaching) detach(t);
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (71:8) {#if slicedKeys.length < previewKeys.length }
function create_if_block_1(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = "…";
},
m(target, anchor) {
insert(target, span, anchor);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
function create_fragment$3(ctx) {
let li;
let label_1;
let t0;
let jsonkey;
let t1;
let span1;
let span0;
let t2;
let t3;
let t4;
let current_block_type_index;
let if_block1;
let t5;
let span2;
let t6;
let current;
let mounted;
let dispose;
let if_block0 = /*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2] && create_if_block_3(ctx);
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[12],
colon: /*context*/ ctx[14].colon,
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3]
}
});
jsonkey.$on("click", /*toggleExpand*/ ctx[15]);
const if_block_creators = [create_if_block$1, create_else_block];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*isParentExpanded*/ ctx[2]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
li = element("li");
label_1 = element("label");
if (if_block0) if_block0.c();
t0 = space();
create_component(jsonkey.$$.fragment);
t1 = space();
span1 = element("span");
span0 = element("span");
t2 = text(/*label*/ ctx[1]);
t3 = text(/*bracketOpen*/ ctx[5]);
t4 = space();
if_block1.c();
t5 = space();
span2 = element("span");
t6 = text(/*bracketClose*/ ctx[6]);
attr(label_1, "class", "svelte-rwxv37");
attr(li, "class", "svelte-rwxv37");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]);
},
m(target, anchor) {
insert(target, li, anchor);
append(li, label_1);
if (if_block0) if_block0.m(label_1, null);
append(label_1, t0);
mount_component(jsonkey, label_1, null);
append(label_1, t1);
append(label_1, span1);
append(span1, span0);
append(span0, t2);
append(span1, t3);
append(li, t4);
if_blocks[current_block_type_index].m(li, null);
append(li, t5);
append(li, span2);
append(span2, t6);
current = true;
if (!mounted) {
dispose = listen(span1, "click", /*toggleExpand*/ ctx[15]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2]) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*expandable, isParentExpanded*/ 2052) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_3(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(label_1, t0);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
const jsonkey_changes = {};
if (dirty & /*key*/ 4096) jsonkey_changes.key = /*key*/ ctx[12];
if (dirty & /*isParentExpanded*/ 4) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[3];
jsonkey.$set(jsonkey_changes);
if (!current || dirty & /*label*/ 2) set_data(t2, /*label*/ ctx[1]);
if (!current || dirty & /*bracketOpen*/ 32) set_data(t3, /*bracketOpen*/ ctx[5]);
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block1 = if_blocks[current_block_type_index];
if (!if_block1) {
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block1.c();
}
transition_in(if_block1, 1);
if_block1.m(li, t5);
}
if (!current || dirty & /*bracketClose*/ 64) set_data(t6, /*bracketClose*/ ctx[6]);
if (dirty & /*isParentExpanded*/ 4) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(jsonkey.$$.fragment, local);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(jsonkey.$$.fragment, local);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (detaching) detach(li);
if (if_block0) if_block0.d();
destroy_component(jsonkey);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$3($$self, $$props, $$invalidate) {
let { key } = $$props,
{ keys } = $$props,
{ colon = ":" } = $$props,
{ label = "" } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props,
{ isArray = false } = $$props,
{ bracketOpen } = $$props,
{ bracketClose } = $$props;
let { previewKeys = keys } = $$props;
let { getKey = key => key } = $$props;
let { getValue = key => key } = $$props;
let { getPreviewValue = getValue } = $$props;
let { expanded = false } = $$props, { expandable = true } = $$props;
const context = getContext(contextKey);
setContext(contextKey, { ...context, colon });
function toggleExpand() {
$$invalidate(0, expanded = !expanded);
}
function expand() {
$$invalidate(0, expanded = true);
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(12, key = $$props.key);
if ("keys" in $$props) $$invalidate(17, keys = $$props.keys);
if ("colon" in $$props) $$invalidate(18, colon = $$props.colon);
if ("label" in $$props) $$invalidate(1, label = $$props.label);
if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ("isArray" in $$props) $$invalidate(4, isArray = $$props.isArray);
if ("bracketOpen" in $$props) $$invalidate(5, bracketOpen = $$props.bracketOpen);
if ("bracketClose" in $$props) $$invalidate(6, bracketClose = $$props.bracketClose);
if ("previewKeys" in $$props) $$invalidate(7, previewKeys = $$props.previewKeys);
if ("getKey" in $$props) $$invalidate(8, getKey = $$props.getKey);
if ("getValue" in $$props) $$invalidate(9, getValue = $$props.getValue);
if ("getPreviewValue" in $$props) $$invalidate(10, getPreviewValue = $$props.getPreviewValue);
if ("expanded" in $$props) $$invalidate(0, expanded = $$props.expanded);
if ("expandable" in $$props) $$invalidate(11, expandable = $$props.expandable);
};
let slicedKeys;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*isParentExpanded*/ 4) {
$: if (!isParentExpanded) {
$$invalidate(0, expanded = false);
}
}
if ($$self.$$.dirty & /*expanded, keys, previewKeys*/ 131201) {
$: $$invalidate(13, slicedKeys = expanded ? keys : previewKeys.slice(0, 5));
}
};
return [
expanded,
label,
isParentExpanded,
isParentArray,
isArray,
bracketOpen,
bracketClose,
previewKeys,
getKey,
getValue,
getPreviewValue,
expandable,
key,
slicedKeys,
context,
toggleExpand,
expand,
keys,
colon
];
}
class JSONNested extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-rwxv37-style")) add_css$3();
init(this, options, instance$3, create_fragment$3, safe_not_equal, {
key: 12,
keys: 17,
colon: 18,
label: 1,
isParentExpanded: 2,
isParentArray: 3,
isArray: 4,
bracketOpen: 5,
bracketClose: 6,
previewKeys: 7,
getKey: 8,
getValue: 9,
getPreviewValue: 10,
expanded: 0,
expandable: 11
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONObjectNode.svelte generated by Svelte v3.24.0 */
function create_fragment$4(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[5],
previewKeys: /*keys*/ ctx[5],
getValue: /*getValue*/ ctx[6],
label: "" + (/*nodeType*/ ctx[3] + " "),
bracketOpen: "{",
bracketClose: "}"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5];
if (dirty & /*keys*/ 32) jsonnested_changes.previewKeys = /*keys*/ ctx[5];
if (dirty & /*nodeType*/ 8) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + " ");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$4($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props,
{ nodeType } = $$props;
let { expanded = true } = $$props;
function getValue(key) {
return value[key];
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(7, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ("nodeType" in $$props) $$invalidate(3, nodeType = $$props.nodeType);
if ("expanded" in $$props) $$invalidate(4, expanded = $$props.expanded);
};
let keys;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 128) {
$: $$invalidate(5, keys = Object.getOwnPropertyNames(value));
}
};
return [
key,
isParentExpanded,
isParentArray,
nodeType,
expanded,
keys,
getValue,
value
];
}
class JSONObjectNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$4, create_fragment$4, safe_not_equal, {
key: 0,
value: 7,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONArrayNode.svelte generated by Svelte v3.24.0 */
function create_fragment$5(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
isArray: true,
keys: /*keys*/ ctx[5],
previewKeys: /*previewKeys*/ ctx[6],
getValue: /*getValue*/ ctx[7],
label: "Array(" + /*value*/ ctx[1].length + ")",
bracketOpen: "[",
bracketClose: "]"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5];
if (dirty & /*previewKeys*/ 64) jsonnested_changes.previewKeys = /*previewKeys*/ ctx[6];
if (dirty & /*value*/ 2) jsonnested_changes.label = "Array(" + /*value*/ ctx[1].length + ")";
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$5($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props;
let { expanded = JSON.stringify(value).length < 1024 } = $$props;
const filteredKey = new Set(["length"]);
function getValue(key) {
return value[key];
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ("expanded" in $$props) $$invalidate(4, expanded = $$props.expanded);
};
let keys;
let previewKeys;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 2) {
$: $$invalidate(5, keys = Object.getOwnPropertyNames(value));
}
if ($$self.$$.dirty & /*keys*/ 32) {
$: $$invalidate(6, previewKeys = keys.filter(key => !filteredKey.has(key)));
}
};
return [
key,
value,
isParentExpanded,
isParentArray,
expanded,
keys,
previewKeys,
getValue
];
}
class JSONArrayNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$5, create_fragment$5, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONIterableArrayNode.svelte generated by Svelte v3.24.0 */
function create_fragment$6(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[4],
getKey,
getValue,
isArray: true,
label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"),
bracketOpen: "{",
bracketClose: "}"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4];
if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function getKey(key) {
return String(key[0]);
}
function getValue(key) {
return key[1];
}
function instance$6($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props,
{ nodeType } = $$props;
let keys = [];
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(5, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ("nodeType" in $$props) $$invalidate(3, nodeType = $$props.nodeType);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 32) {
$: {
let result = [];
let i = 0;
for (const entry of value) {
result.push([i++, entry]);
}
$$invalidate(4, keys = result);
}
}
};
return [key, isParentExpanded, isParentArray, nodeType, keys, value];
}
class JSONIterableArrayNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$6, create_fragment$6, safe_not_equal, {
key: 0,
value: 5,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3
});
}
}
class MapEntry {
constructor(key, value) {
this.key = key;
this.value = value;
}
}
/* node_modules/svelte-json-tree-auto/src/JSONIterableMapNode.svelte generated by Svelte v3.24.0 */
function create_fragment$7(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[4],
getKey: getKey$1,
getValue: getValue$1,
label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"),
colon: "",
bracketOpen: "{",
bracketClose: "}"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4];
if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function getKey$1(entry) {
return entry[0];
}
function getValue$1(entry) {
return entry[1];
}
function instance$7($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props,
{ nodeType } = $$props;
let keys = [];
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(5, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ("nodeType" in $$props) $$invalidate(3, nodeType = $$props.nodeType);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 32) {
$: {
let result = [];
let i = 0;
for (const entry of value) {
result.push([i++, new MapEntry(entry[0], entry[1])]);
}
$$invalidate(4, keys = result);
}
}
};
return [key, isParentExpanded, isParentArray, nodeType, keys, value];
}
class JSONIterableMapNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$7, create_fragment$7, safe_not_equal, {
key: 0,
value: 5,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONMapEntryNode.svelte generated by Svelte v3.24.0 */
function create_fragment$8(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
key: /*isParentExpanded*/ ctx[2]
? String(/*key*/ ctx[0])
: /*value*/ ctx[1].key,
keys: /*keys*/ ctx[5],
getValue: /*getValue*/ ctx[6],
label: /*isParentExpanded*/ ctx[2] ? "Entry " : "=> ",
bracketOpen: "{",
bracketClose: "}"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*isParentExpanded, key, value*/ 7) jsonnested_changes.key = /*isParentExpanded*/ ctx[2]
? String(/*key*/ ctx[0])
: /*value*/ ctx[1].key;
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.label = /*isParentExpanded*/ ctx[2] ? "Entry " : "=> ";
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$8($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props;
let { expanded = false } = $$props;
const keys = ["key", "value"];
function getValue(key) {
return value[key];
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ("expanded" in $$props) $$invalidate(4, expanded = $$props.expanded);
};
return [key, value, isParentExpanded, isParentArray, expanded, keys, getValue];
}
class JSONMapEntryNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$8, create_fragment$8, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONValueNode.svelte generated by Svelte v3.24.0 */
function add_css$4() {
var style = element("style");
style.id = "svelte-3bjyvl-style";
style.textContent = "li.svelte-3bjyvl{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-3bjyvl{padding-left:var(--li-identation)}.String.svelte-3bjyvl{color:var(--string-color)}.Date.svelte-3bjyvl{color:var(--date-color)}.Number.svelte-3bjyvl{color:var(--number-color)}.Boolean.svelte-3bjyvl{color:var(--boolean-color)}.Null.svelte-3bjyvl{color:var(--null-color)}.Undefined.svelte-3bjyvl{color:var(--undefined-color)}.Function.svelte-3bjyvl{color:var(--function-color);font-style:italic}.Symbol.svelte-3bjyvl{color:var(--symbol-color)}";
append(document.head, style);
}
function create_fragment$9(ctx) {
let li;
let jsonkey;
let t0;
let span;
let t1_value = (/*valueGetter*/ ctx[2]
? /*valueGetter*/ ctx[2](/*value*/ ctx[1])
: /*value*/ ctx[1]) + "";
let t1;
let span_class_value;
let current;
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[0],
colon: /*colon*/ ctx[6],
isParentExpanded: /*isParentExpanded*/ ctx[3],
isParentArray: /*isParentArray*/ ctx[4]
}
});
return {
c() {
li = element("li");
create_component(jsonkey.$$.fragment);
t0 = space();
span = element("span");
t1 = text(t1_value);
attr(span, "class", span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl"));
attr(li, "class", "svelte-3bjyvl");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(jsonkey, li, null);
append(li, t0);
append(li, span);
append(span, t1);
current = true;
},
p(ctx, [dirty]) {
const jsonkey_changes = {};
if (dirty & /*key*/ 1) jsonkey_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4];
jsonkey.$set(jsonkey_changes);
if ((!current || dirty & /*valueGetter, value*/ 6) && t1_value !== (t1_value = (/*valueGetter*/ ctx[2]
? /*valueGetter*/ ctx[2](/*value*/ ctx[1])
: /*value*/ ctx[1]) + "")) set_data(t1, t1_value);
if (!current || dirty & /*nodeType*/ 32 && span_class_value !== (span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl"))) {
attr(span, "class", span_class_value);
}
if (dirty & /*isParentExpanded*/ 8) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
}
},
i(local) {
if (current) return;
transition_in(jsonkey.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonkey.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(jsonkey);
}
};
}
function instance$9($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ valueGetter = null } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props,
{ nodeType } = $$props;
const { colon } = getContext(contextKey);
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
if ("valueGetter" in $$props) $$invalidate(2, valueGetter = $$props.valueGetter);
if ("isParentExpanded" in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ("nodeType" in $$props) $$invalidate(5, nodeType = $$props.nodeType);
};
return [key, value, valueGetter, isParentExpanded, isParentArray, nodeType, colon];
}
class JSONValueNode extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-3bjyvl-style")) add_css$4();
init(this, options, instance$9, create_fragment$9, safe_not_equal, {
key: 0,
value: 1,
valueGetter: 2,
isParentExpanded: 3,
isParentArray: 4,
nodeType: 5
});
}
}
/* node_modules/svelte-json-tree-auto/src/ErrorNode.svelte generated by Svelte v3.24.0 */
function add_css$5() {
var style = element("style");
style.id = "svelte-1ca3gb2-style";
style.textContent = "li.svelte-1ca3gb2{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-1ca3gb2{padding-left:var(--li-identation)}.collapse.svelte-1ca3gb2{--li-display:inline;display:inline;font-style:italic}";
append(document.head, style);
}
function get_each_context$2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[8] = list[i];
child_ctx[10] = i;
return child_ctx;
}
// (40:2) {#if isParentExpanded}
function create_if_block_2$1(ctx) {
let jsonarrow;
let current;
jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } });
jsonarrow.$on("click", /*toggleExpand*/ ctx[7]);
return {
c() {
create_component(jsonarrow.$$.fragment);
},
m(target, anchor) {
mount_component(jsonarrow, target, anchor);
current = true;
},
p(ctx, dirty) {
const jsonarrow_changes = {};
if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0];
jsonarrow.$set(jsonarrow_changes);
},
i(local) {
if (current) return;
transition_in(jsonarrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonarrow.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonarrow, detaching);
}
};
}
// (45:2) {#if isParentExpanded}
function create_if_block$2(ctx) {
let ul;
let current;
let if_block = /*expanded*/ ctx[0] && create_if_block_1$1(ctx);
return {
c() {
ul = element("ul");
if (if_block) if_block.c();
attr(ul, "class", "svelte-1ca3gb2");
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
},
m(target, anchor) {
insert(target, ul, anchor);
if (if_block) if_block.m(ul, null);
current = true;
},
p(ctx, dirty) {
if (/*expanded*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*expanded*/ 1) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$1(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(ul, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
if (dirty & /*expanded*/ 1) {
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
if (if_block) if_block.d();
}
};
}
// (47:6) {#if expanded}
function create_if_block_1$1(ctx) {
let jsonnode;
let t0;
let li;
let jsonkey;
let t1;
let span;
let current;
jsonnode = new JSONNode({
props: {
key: "message",
value: /*value*/ ctx[2].message
}
});
jsonkey = new JSONKey({
props: {
key: "stack",
colon: ":",
isParentExpanded: /*isParentExpanded*/ ctx[3]
}
});
let each_value = /*stack*/ ctx[5];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$2(get_each_context$2(ctx, each_value, i));
}
return {
c() {
create_component(jsonnode.$$.fragment);
t0 = space();
li = element("li");
create_component(jsonkey.$$.fragment);
t1 = space();
span = element("span");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(li, "class", "svelte-1ca3gb2");
},
m(target, anchor) {
mount_component(jsonnode, target, anchor);
insert(target, t0, anchor);
insert(target, li, anchor);
mount_component(jsonkey, li, null);
append(li, t1);
append(li, span);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(span, null);
}
current = true;
},
p(ctx, dirty) {
const jsonnode_changes = {};
if (dirty & /*value*/ 4) jsonnode_changes.value = /*value*/ ctx[2].message;
jsonnode.$set(jsonnode_changes);
const jsonkey_changes = {};
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
jsonkey.$set(jsonkey_changes);
if (dirty & /*stack*/ 32) {
each_value = /*stack*/ ctx[5];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$2(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$2(child_ctx);
each_blocks[i].c();
each_blocks[i].m(span, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
transition_in(jsonkey.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
transition_out(jsonkey.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnode, detaching);
if (detaching) detach(t0);
if (detaching) detach(li);
destroy_component(jsonkey);
destroy_each(each_blocks, detaching);
}
};
}
// (52:12) {#each stack as line, index}
function create_each_block$2(ctx) {
let span;
let t_value = /*line*/ ctx[8] + "";
let t;
let br;
return {
c() {
span = element("span");
t = text(t_value);
br = element("br");
attr(span, "class", "svelte-1ca3gb2");
toggle_class(span, "indent", /*index*/ ctx[10] > 0);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
insert(target, br, anchor);
},
p(ctx, dirty) {
if (dirty & /*stack*/ 32 && t_value !== (t_value = /*line*/ ctx[8] + "")) set_data(t, t_value);
},
d(detaching) {
if (detaching) detach(span);
if (detaching) detach(br);
}
};
}
function create_fragment$a(ctx) {
let li;
let t0;
let jsonkey;
let t1;
let span;
let t2;
let t3_value = (/*expanded*/ ctx[0] ? "" : /*value*/ ctx[2].message) + "";
let t3;
let t4;
let current;
let mounted;
let dispose;
let if_block0 = /*isParentExpanded*/ ctx[3] && create_if_block_2$1(ctx);
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[1],
colon: /*context*/ ctx[6].colon,
isParentExpanded: /*isParentExpanded*/ ctx[3],
isParentArray: /*isParentArray*/ ctx[4]
}
});
let if_block1 = /*isParentExpanded*/ ctx[3] && create_if_block$2(ctx);
return {
c() {
li = element("li");
if (if_block0) if_block0.c();
t0 = space();
create_component(jsonkey.$$.fragment);
t1 = space();
span = element("span");
t2 = text("Error: ");
t3 = text(t3_value);
t4 = space();
if (if_block1) if_block1.c();
attr(li, "class", "svelte-1ca3gb2");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
},
m(target, anchor) {
insert(target, li, anchor);
if (if_block0) if_block0.m(li, null);
append(li, t0);
mount_component(jsonkey, li, null);
append(li, t1);
append(li, span);
append(span, t2);
append(span, t3);
append(li, t4);
if (if_block1) if_block1.m(li, null);
current = true;
if (!mounted) {
dispose = listen(span, "click", /*toggleExpand*/ ctx[7]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*isParentExpanded*/ ctx[3]) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*isParentExpanded*/ 8) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_2$1(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(li, t0);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
const jsonkey_changes = {};
if (dirty & /*key*/ 2) jsonkey_changes.key = /*key*/ ctx[1];
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4];
jsonkey.$set(jsonkey_changes);
if ((!current || dirty & /*expanded, value*/ 5) && t3_value !== (t3_value = (/*expanded*/ ctx[0] ? "" : /*value*/ ctx[2].message) + "")) set_data(t3, t3_value);
if (/*isParentExpanded*/ ctx[3]) {
if (if_block1) {
if_block1.p(ctx, dirty);
if (dirty & /*isParentExpanded*/ 8) {
transition_in(if_block1, 1);
}
} else {
if_block1 = create_if_block$2(ctx);
if_block1.c();
transition_in(if_block1, 1);
if_block1.m(li, null);
}
} else if (if_block1) {
group_outros();
transition_out(if_block1, 1, 1, () => {
if_block1 = null;
});
check_outros();
}
if (dirty & /*isParentExpanded*/ 8) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(jsonkey.$$.fragment, local);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(jsonkey.$$.fragment, local);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (detaching) detach(li);
if (if_block0) if_block0.d();
destroy_component(jsonkey);
if (if_block1) if_block1.d();
mounted = false;
dispose();
}
};
}
function instance$a($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props;
let { expanded = false } = $$props;
const context = getContext(contextKey);
setContext(contextKey, { ...context, colon: ":" });
function toggleExpand() {
$$invalidate(0, expanded = !expanded);
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(1, key = $$props.key);
if ("value" in $$props) $$invalidate(2, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ("expanded" in $$props) $$invalidate(0, expanded = $$props.expanded);
};
let stack;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 4) {
$: $$invalidate(5, stack = value.stack.split("\n"));
}
if ($$self.$$.dirty & /*isParentExpanded*/ 8) {
$: if (!isParentExpanded) {
$$invalidate(0, expanded = false);
}
}
};
return [
expanded,
key,
value,
isParentExpanded,
isParentArray,
stack,
context,
toggleExpand
];
}
class ErrorNode extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1ca3gb2-style")) add_css$5();
init(this, options, instance$a, create_fragment$a, safe_not_equal, {
key: 1,
value: 2,
isParentExpanded: 3,
isParentArray: 4,
expanded: 0
});
}
}
function objType(obj) {
const type = Object.prototype.toString.call(obj).slice(8, -1);
if (type === 'Object') {
if (typeof obj[Symbol.iterator] === 'function') {
return 'Iterable';
}
return obj.constructor.name;
}
return type;
}
/* node_modules/svelte-json-tree-auto/src/JSONNode.svelte generated by Svelte v3.24.0 */
function create_fragment$b(ctx) {
let switch_instance;
let switch_instance_anchor;
let current;
var switch_value = /*componentType*/ ctx[5];
function switch_props(ctx) {
return {
props: {
key: /*key*/ ctx[0],
value: /*value*/ ctx[1],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
nodeType: /*nodeType*/ ctx[4],
valueGetter: /*valueGetter*/ ctx[6]
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
if (switch_instance) create_component(switch_instance.$$.fragment);
switch_instance_anchor = empty();
},
m(target, anchor) {
if (switch_instance) {
mount_component(switch_instance, target, anchor);
}
insert(target, switch_instance_anchor, anchor);
current = true;
},
p(ctx, [dirty]) {
const switch_instance_changes = {};
if (dirty & /*key*/ 1) switch_instance_changes.key = /*key*/ ctx[0];
if (dirty & /*value*/ 2) switch_instance_changes.value = /*value*/ ctx[1];
if (dirty & /*isParentExpanded*/ 4) switch_instance_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) switch_instance_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*nodeType*/ 16) switch_instance_changes.nodeType = /*nodeType*/ ctx[4];
if (dirty & /*valueGetter*/ 64) switch_instance_changes.valueGetter = /*valueGetter*/ ctx[6];
if (switch_value !== (switch_value = /*componentType*/ ctx[5])) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(switch_instance_anchor);
if (switch_instance) destroy_component(switch_instance, detaching);
}
};
}
function instance$b($$self, $$props, $$invalidate) {
let { key } = $$props,
{ value } = $$props,
{ isParentExpanded } = $$props,
{ isParentArray } = $$props;
function getComponent(nodeType) {
switch (nodeType) {
case "Object":
return JSONObjectNode;
case "Error":
return ErrorNode;
case "Array":
return JSONArrayNode;
case "Iterable":
case "Map":
case "Set":
return typeof value.set === "function"
? JSONIterableMapNode
: JSONIterableArrayNode;
case "MapEntry":
return JSONMapEntryNode;
default:
return JSONValueNode;
}
}
function getValueGetter(nodeType) {
switch (nodeType) {
case "Object":
case "Error":
case "Array":
case "Iterable":
case "Map":
case "Set":
case "MapEntry":
case "Number":
return undefined;
case "String":
return raw => `"${raw}"`;
case "Boolean":
return raw => raw ? "true" : "false";
case "Date":
return raw => raw.toISOString();
case "Null":
return () => "null";
case "Undefined":
return () => "undefined";
case "Function":
case "Symbol":
return raw => raw.toString();
default:
return () => `<${nodeType}>`;
}
}
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
if ("isParentExpanded" in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ("isParentArray" in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
};
let nodeType;
let componentType;
let valueGetter;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 2) {
$: $$invalidate(4, nodeType = objType(value));
}
if ($$self.$$.dirty & /*nodeType*/ 16) {
$: $$invalidate(5, componentType = getComponent(nodeType));
}
if ($$self.$$.dirty & /*nodeType*/ 16) {
$: $$invalidate(6, valueGetter = getValueGetter(nodeType));
}
};
return [
key,
value,
isParentExpanded,
isParentArray,
nodeType,
componentType,
valueGetter
];
}
class JSONNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$b, create_fragment$b, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3
});
}
}
/* node_modules/svelte-json-tree-auto/src/Root.svelte generated by Svelte v3.24.0 */
function add_css$6() {
var style = element("style");
style.id = "svelte-773n60-style";
style.textContent = "ul.svelte-773n60{--string-color:var(--json-tree-string-color, #cb3f41);--symbol-color:var(--json-tree-symbol-color, #cb3f41);--boolean-color:var(--json-tree-boolean-color, #112aa7);--function-color:var(--json-tree-function-color, #112aa7);--number-color:var(--json-tree-number-color, #3029cf);--label-color:var(--json-tree-label-color, #871d8f);--arrow-color:var(--json-tree-arrow-color, #727272);--null-color:var(--json-tree-null-color, #8d8d8d);--undefined-color:var(--json-tree-undefined-color, #8d8d8d);--date-color:var(--json-tree-date-color, #8d8d8d);--li-identation:var(--json-tree-li-indentation, 1em);--li-line-height:var(--json-tree-li-line-height, 1.3);--li-colon-space:0.3em;font-size:var(--json-tree-font-size, 12px);font-family:var(--json-tree-font-family, 'Courier New', Courier, monospace)}ul.svelte-773n60 li{line-height:var(--li-line-height);display:var(--li-display, list-item);list-style:none}ul.svelte-773n60,ul.svelte-773n60 ul{padding:0;margin:0}";
append(document.head, style);
}
function create_fragment$c(ctx) {
let ul;
let jsonnode;
let current;
jsonnode = new JSONNode({
props: {
key: /*key*/ ctx[0],
value: /*value*/ ctx[1],
isParentExpanded: true,
isParentArray: false
}
});
return {
c() {
ul = element("ul");
create_component(jsonnode.$$.fragment);
attr(ul, "class", "svelte-773n60");
},
m(target, anchor) {
insert(target, ul, anchor);
mount_component(jsonnode, ul, null);
current = true;
},
p(ctx, [dirty]) {
const jsonnode_changes = {};
if (dirty & /*key*/ 1) jsonnode_changes.key = /*key*/ ctx[0];
if (dirty & /*value*/ 2) jsonnode_changes.value = /*value*/ ctx[1];
jsonnode.$set(jsonnode_changes);
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_component(jsonnode);
}
};
}
function instance$c($$self, $$props, $$invalidate) {
setContext(contextKey, {});
let { key = "" } = $$props, { value } = $$props;
$$self.$set = $$props => {
if ("key" in $$props) $$invalidate(0, key = $$props.key);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
};
return [key, value];
}
class Root extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-773n60-style")) add_css$6();
init(this, options, instance$c, create_fragment$c, safe_not_equal, { key: 0, value: 1 });
}
}
/* src/client/debug/main/ClientSwitcher.svelte generated by Svelte v3.24.0 */
const { document: document_1 } = globals;
function add_css$7() {
var style = element("style");
style.id = "svelte-jvfq3i-style";
style.textContent = ".svelte-jvfq3i{box-sizing:border-box}section.switcher.svelte-jvfq3i{position:sticky;bottom:0;transform:translateY(20px);margin:40px -20px 0;border-top:1px solid #999;padding:20px;background:#fff}label.svelte-jvfq3i{display:flex;align-items:baseline;gap:5px;font-weight:bold}select.svelte-jvfq3i{min-width:140px}";
append(document_1.head, style);
}
function get_each_context$3(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
child_ctx[9] = i;
return child_ctx;
}
// (42:0) {#if debuggableClients.length > 1}
function create_if_block$3(ctx) {
let section;
let label;
let t;
let select;
let mounted;
let dispose;
let each_value = /*debuggableClients*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$3(get_each_context$3(ctx, each_value, i));
}
return {
c() {
section = element("section");
label = element("label");
t = text("Client\n \n ");
select = element("select");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(select, "id", selectId);
attr(select, "class", "svelte-jvfq3i");
if (/*selected*/ ctx[2] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[4].call(select));
attr(label, "class", "svelte-jvfq3i");
attr(section, "class", "switcher svelte-jvfq3i");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, label);
append(label, t);
append(label, select);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(select, null);
}
select_option(select, /*selected*/ ctx[2]);
if (!mounted) {
dispose = [
listen(select, "change", /*handleSelection*/ ctx[3]),
listen(select, "change", /*select_change_handler*/ ctx[4])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*debuggableClients, JSON*/ 2) {
each_value = /*debuggableClients*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$3(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$3(child_ctx);
each_blocks[i].c();
each_blocks[i].m(select, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (dirty & /*selected*/ 4) {
select_option(select, /*selected*/ ctx[2]);
}
},
d(detaching) {
if (detaching) detach(section);
destroy_each(each_blocks, detaching);
mounted = false;
run_all(dispose);
}
};
}
// (48:8) {#each debuggableClients as clientOption, index}
function create_each_block$3(ctx) {
let option;
let t0;
let t1;
let t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + "";
let t2;
let t3;
let t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + "";
let t4;
let t5;
let t6_value = /*clientOption*/ ctx[7].game.name + "";
let t6;
let t7;
let option_value_value;
return {
c() {
option = element("option");
t0 = text(/*index*/ ctx[9]);
t1 = text(" —\n playerID: ");
t2 = text(t2_value);
t3 = text(",\n matchID: ");
t4 = text(t4_value);
t5 = text("\n (");
t6 = text(t6_value);
t7 = text(")\n ");
option.__value = option_value_value = /*index*/ ctx[9];
option.value = option.__value;
attr(option, "class", "svelte-jvfq3i");
},
m(target, anchor) {
insert(target, option, anchor);
append(option, t0);
append(option, t1);
append(option, t2);
append(option, t3);
append(option, t4);
append(option, t5);
append(option, t6);
append(option, t7);
},
p(ctx, dirty) {
if (dirty & /*debuggableClients*/ 2 && t2_value !== (t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + "")) set_data(t2, t2_value);
if (dirty & /*debuggableClients*/ 2 && t4_value !== (t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + "")) set_data(t4, t4_value);
if (dirty & /*debuggableClients*/ 2 && t6_value !== (t6_value = /*clientOption*/ ctx[7].game.name + "")) set_data(t6, t6_value);
},
d(detaching) {
if (detaching) detach(option);
}
};
}
function create_fragment$d(ctx) {
let if_block_anchor;
let if_block = /*debuggableClients*/ ctx[1].length > 1 && create_if_block$3(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*debuggableClients*/ ctx[1].length > 1) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$3(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop,
o: noop,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
const selectId = "bgio-debug-select-client";
function instance$d($$self, $$props, $$invalidate) {
let $clientManager,
$$unsubscribe_clientManager = noop,
$$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(6, $clientManager = $$value)), clientManager);
$$self.$$.on_destroy.push(() => $$unsubscribe_clientManager());
let { clientManager } = $$props;
$$subscribe_clientManager();
const handleSelection = e => {
// Request to switch to the selected client.
const selectedClient = debuggableClients[e.target.value];
clientManager.switchToClient(selectedClient);
// Maintain focus on the client select menu after switching clients.
// Necessary because switching clients will usually trigger a mount/unmount.
const select = document.getElementById(selectId);
if (select) select.focus();
};
function select_change_handler() {
selected = select_value(this);
((($$invalidate(2, selected), $$invalidate(1, debuggableClients)), $$invalidate(5, client)), $$invalidate(6, $clientManager));
}
$$self.$set = $$props => {
if ("clientManager" in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager));
};
let client;
let debuggableClients;
let selected;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$clientManager*/ 64) {
$: $$invalidate(5, { client, debuggableClients } = $clientManager, client, ($$invalidate(1, debuggableClients), $$invalidate(6, $clientManager)));
}
if ($$self.$$.dirty & /*debuggableClients, client*/ 34) {
$: $$invalidate(2, selected = debuggableClients.indexOf(client));
}
};
return [
clientManager,
debuggableClients,
selected,
handleSelection,
select_change_handler
];
}
class ClientSwitcher extends SvelteComponent {
constructor(options) {
super();
if (!document_1.getElementById("svelte-jvfq3i-style")) add_css$7();
init(this, options, instance$d, create_fragment$d, safe_not_equal, { clientManager: 0 });
}
}
/* src/client/debug/main/Hotkey.svelte generated by Svelte v3.24.0 */
function add_css$8() {
var style = element("style");
style.id = "svelte-1vfj1mn-style";
style.textContent = ".key.svelte-1vfj1mn.svelte-1vfj1mn{display:flex;flex-direction:row;align-items:center}button.svelte-1vfj1mn.svelte-1vfj1mn{cursor:pointer;min-width:10px;padding-left:5px;padding-right:5px;height:20px;line-height:20px;text-align:center;border:1px solid #ccc;box-shadow:1px 1px 1px #888;background:#eee;color:#444}button.svelte-1vfj1mn.svelte-1vfj1mn:hover{background:#ddd}.key.active.svelte-1vfj1mn button.svelte-1vfj1mn{background:#ddd;border:1px solid #999;box-shadow:none}label.svelte-1vfj1mn.svelte-1vfj1mn{margin-left:10px}";
append(document.head, style);
}
// (78:2) {#if label}
function create_if_block$4(ctx) {
let label_1;
let t0;
let t1;
let span;
let t2_value = `(shortcut: ${/*value*/ ctx[0]})` + "";
let t2;
return {
c() {
label_1 = element("label");
t0 = text(/*label*/ ctx[1]);
t1 = space();
span = element("span");
t2 = text(t2_value);
attr(span, "class", "screen-reader-only");
attr(label_1, "for", /*id*/ ctx[5]);
attr(label_1, "class", "svelte-1vfj1mn");
},
m(target, anchor) {
insert(target, label_1, anchor);
append(label_1, t0);
append(label_1, t1);
append(label_1, span);
append(span, t2);
},
p(ctx, dirty) {
if (dirty & /*label*/ 2) set_data(t0, /*label*/ ctx[1]);
if (dirty & /*value*/ 1 && t2_value !== (t2_value = `(shortcut: ${/*value*/ ctx[0]})` + "")) set_data(t2, t2_value);
},
d(detaching) {
if (detaching) detach(label_1);
}
};
}
function create_fragment$e(ctx) {
let div;
let button;
let t0;
let t1;
let mounted;
let dispose;
let if_block = /*label*/ ctx[1] && create_if_block$4(ctx);
return {
c() {
div = element("div");
button = element("button");
t0 = text(/*value*/ ctx[0]);
t1 = space();
if (if_block) if_block.c();
attr(button, "id", /*id*/ ctx[5]);
button.disabled = /*disable*/ ctx[2];
attr(button, "class", "svelte-1vfj1mn");
attr(div, "class", "key svelte-1vfj1mn");
toggle_class(div, "active", /*active*/ ctx[3]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, button);
append(button, t0);
append(div, t1);
if (if_block) if_block.m(div, null);
if (!mounted) {
dispose = [
listen(window, "keydown", /*Keypress*/ ctx[7]),
listen(button, "click", /*Activate*/ ctx[6])
];
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*value*/ 1) set_data(t0, /*value*/ ctx[0]);
if (dirty & /*disable*/ 4) {
button.disabled = /*disable*/ ctx[2];
}
if (/*label*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$4(ctx);
if_block.c();
if_block.m(div, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*active*/ 8) {
toggle_class(div, "active", /*active*/ ctx[3]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
if (if_block) if_block.d();
mounted = false;
run_all(dispose);
}
};
}
function instance$e($$self, $$props, $$invalidate) {
let $disableHotkeys;
let { value } = $$props;
let { onPress = null } = $$props;
let { label = null } = $$props;
let { disable = false } = $$props;
const { disableHotkeys } = getContext("hotkeys");
component_subscribe($$self, disableHotkeys, value => $$invalidate(9, $disableHotkeys = value));
let active = false;
let id = `key-${value}`;
function Deactivate() {
$$invalidate(3, active = false);
}
function Activate() {
$$invalidate(3, active = true);
setTimeout(Deactivate, 200);
if (onPress) {
setTimeout(onPress, 1);
}
}
function Keypress(e) {
if (!$disableHotkeys && !disable && !e.ctrlKey && !e.metaKey && e.key == value) {
e.preventDefault();
Activate();
}
}
$$self.$set = $$props => {
if ("value" in $$props) $$invalidate(0, value = $$props.value);
if ("onPress" in $$props) $$invalidate(8, onPress = $$props.onPress);
if ("label" in $$props) $$invalidate(1, label = $$props.label);
if ("disable" in $$props) $$invalidate(2, disable = $$props.disable);
};
return [value, label, disable, active, disableHotkeys, id, Activate, Keypress, onPress];
}
class Hotkey extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1vfj1mn-style")) add_css$8();
init(this, options, instance$e, create_fragment$e, safe_not_equal, {
value: 0,
onPress: 8,
label: 1,
disable: 2
});
}
}
/* src/client/debug/main/InteractiveFunction.svelte generated by Svelte v3.24.0 */
function add_css$9() {
var style = element("style");
style.id = "svelte-1mppqmp-style";
style.textContent = ".move.svelte-1mppqmp{display:flex;flex-direction:row;cursor:pointer;margin-left:10px;color:#666}.move.svelte-1mppqmp:hover{color:#333}.move.active.svelte-1mppqmp{color:#111;font-weight:bold}.arg-field.svelte-1mppqmp{outline:none;font-family:monospace}";
append(document.head, style);
}
function create_fragment$f(ctx) {
let div;
let span0;
let t0;
let t1;
let span1;
let t3;
let span2;
let t4;
let span3;
let mounted;
let dispose;
return {
c() {
div = element("div");
span0 = element("span");
t0 = text(/*name*/ ctx[2]);
t1 = space();
span1 = element("span");
span1.textContent = "(";
t3 = space();
span2 = element("span");
t4 = space();
span3 = element("span");
span3.textContent = ")";
attr(span2, "class", "arg-field svelte-1mppqmp");
attr(span2, "contenteditable", "");
attr(div, "class", "move svelte-1mppqmp");
toggle_class(div, "active", /*active*/ ctx[3]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, span0);
append(span0, t0);
append(div, t1);
append(div, span1);
append(div, t3);
append(div, span2);
/*span2_binding*/ ctx[6](span2);
append(div, t4);
append(div, span3);
if (!mounted) {
dispose = [
listen(span2, "focus", function () {
if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments);
}),
listen(span2, "blur", function () {
if (is_function(/*Deactivate*/ ctx[1])) /*Deactivate*/ ctx[1].apply(this, arguments);
}),
listen(span2, "keypress", stop_propagation(keypress_handler)),
listen(span2, "keydown", /*OnKeyDown*/ ctx[5]),
listen(div, "click", function () {
if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments);
})
];
mounted = true;
}
},
p(new_ctx, [dirty]) {
ctx = new_ctx;
if (dirty & /*name*/ 4) set_data(t0, /*name*/ ctx[2]);
if (dirty & /*active*/ 8) {
toggle_class(div, "active", /*active*/ ctx[3]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
/*span2_binding*/ ctx[6](null);
mounted = false;
run_all(dispose);
}
};
}
const keypress_handler = () => {
};
function instance$f($$self, $$props, $$invalidate) {
let { Activate } = $$props;
let { Deactivate } = $$props;
let { name } = $$props;
let { active } = $$props;
let span;
const dispatch = createEventDispatcher();
function Submit() {
try {
const value = span.innerText;
let argArray = new Function(`return [${value}]`)();
dispatch("submit", argArray);
} catch(error) {
dispatch("error", error);
}
$$invalidate(4, span.innerText = "", span);
}
function OnKeyDown(e) {
if (e.key == "Enter") {
e.preventDefault();
Submit();
}
if (e.key == "Escape") {
e.preventDefault();
Deactivate();
}
}
afterUpdate(() => {
if (active) {
span.focus();
} else {
span.blur();
}
});
function span2_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
span = $$value;
$$invalidate(4, span);
});
}
$$self.$set = $$props => {
if ("Activate" in $$props) $$invalidate(0, Activate = $$props.Activate);
if ("Deactivate" in $$props) $$invalidate(1, Deactivate = $$props.Deactivate);
if ("name" in $$props) $$invalidate(2, name = $$props.name);
if ("active" in $$props) $$invalidate(3, active = $$props.active);
};
return [Activate, Deactivate, name, active, span, OnKeyDown, span2_binding];
}
class InteractiveFunction extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1mppqmp-style")) add_css$9();
init(this, options, instance$f, create_fragment$f, safe_not_equal, {
Activate: 0,
Deactivate: 1,
name: 2,
active: 3
});
}
}
/* src/client/debug/main/Move.svelte generated by Svelte v3.24.0 */
function add_css$a() {
var style = element("style");
style.id = "svelte-smqssc-style";
style.textContent = ".move-error.svelte-smqssc{color:#a00;font-weight:bold}.wrapper.svelte-smqssc{display:flex;flex-direction:row;align-items:center}";
append(document.head, style);
}
// (65:2) {#if error}
function create_if_block$5(ctx) {
let span;
let t;
return {
c() {
span = element("span");
t = text(/*error*/ ctx[2]);
attr(span, "class", "move-error svelte-smqssc");
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
},
p(ctx, dirty) {
if (dirty & /*error*/ 4) set_data(t, /*error*/ ctx[2]);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
function create_fragment$g(ctx) {
let div1;
let div0;
let hotkey;
let t0;
let interactivefunction;
let t1;
let current;
hotkey = new Hotkey({
props: {
value: /*shortcut*/ ctx[0],
onPress: /*Activate*/ ctx[4]
}
});
interactivefunction = new InteractiveFunction({
props: {
Activate: /*Activate*/ ctx[4],
Deactivate: /*Deactivate*/ ctx[5],
name: /*name*/ ctx[1],
active: /*active*/ ctx[3]
}
});
interactivefunction.$on("submit", /*Submit*/ ctx[6]);
interactivefunction.$on("error", /*Error*/ ctx[7]);
let if_block = /*error*/ ctx[2] && create_if_block$5(ctx);
return {
c() {
div1 = element("div");
div0 = element("div");
create_component(hotkey.$$.fragment);
t0 = space();
create_component(interactivefunction.$$.fragment);
t1 = space();
if (if_block) if_block.c();
attr(div0, "class", "wrapper svelte-smqssc");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, div0);
mount_component(hotkey, div0, null);
append(div0, t0);
mount_component(interactivefunction, div0, null);
append(div1, t1);
if (if_block) if_block.m(div1, null);
current = true;
},
p(ctx, [dirty]) {
const hotkey_changes = {};
if (dirty & /*shortcut*/ 1) hotkey_changes.value = /*shortcut*/ ctx[0];
hotkey.$set(hotkey_changes);
const interactivefunction_changes = {};
if (dirty & /*name*/ 2) interactivefunction_changes.name = /*name*/ ctx[1];
if (dirty & /*active*/ 8) interactivefunction_changes.active = /*active*/ ctx[3];
interactivefunction.$set(interactivefunction_changes);
if (/*error*/ ctx[2]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$5(ctx);
if_block.c();
if_block.m(div1, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i(local) {
if (current) return;
transition_in(hotkey.$$.fragment, local);
transition_in(interactivefunction.$$.fragment, local);
current = true;
},
o(local) {
transition_out(hotkey.$$.fragment, local);
transition_out(interactivefunction.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div1);
destroy_component(hotkey);
destroy_component(interactivefunction);
if (if_block) if_block.d();
}
};
}
function instance$g($$self, $$props, $$invalidate) {
let { shortcut } = $$props;
let { name } = $$props;
let { fn } = $$props;
const { disableHotkeys } = getContext("hotkeys");
let error$1 = "";
let active = false;
function Activate() {
disableHotkeys.set(true);
$$invalidate(3, active = true);
}
function Deactivate() {
disableHotkeys.set(false);
$$invalidate(2, error$1 = "");
$$invalidate(3, active = false);
}
function Submit(e) {
$$invalidate(2, error$1 = "");
Deactivate();
fn.apply(this, e.detail);
}
function Error(e) {
$$invalidate(2, error$1 = e.detail);
error(e.detail);
}
$$self.$set = $$props => {
if ("shortcut" in $$props) $$invalidate(0, shortcut = $$props.shortcut);
if ("name" in $$props) $$invalidate(1, name = $$props.name);
if ("fn" in $$props) $$invalidate(8, fn = $$props.fn);
};
return [shortcut, name, error$1, active, Activate, Deactivate, Submit, Error, fn];
}
class Move extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-smqssc-style")) add_css$a();
init(this, options, instance$g, create_fragment$g, safe_not_equal, { shortcut: 0, name: 1, fn: 8 });
}
}
/* src/client/debug/main/Controls.svelte generated by Svelte v3.24.0 */
function add_css$b() {
var style = element("style");
style.id = "svelte-c3lavh-style";
style.textContent = "ul.svelte-c3lavh{padding-left:0}li.svelte-c3lavh{list-style:none;margin:none;margin-bottom:5px}";
append(document.head, style);
}
function create_fragment$h(ctx) {
let ul;
let li0;
let hotkey0;
let t0;
let li1;
let hotkey1;
let t1;
let li2;
let hotkey2;
let t2;
let li3;
let hotkey3;
let current;
hotkey0 = new Hotkey({
props: {
value: "1",
onPress: /*client*/ ctx[0].reset,
label: "reset"
}
});
hotkey1 = new Hotkey({
props: {
value: "2",
onPress: /*Save*/ ctx[1],
label: "save"
}
});
hotkey2 = new Hotkey({
props: {
value: "3",
onPress: /*Restore*/ ctx[2],
label: "restore"
}
});
hotkey3 = new Hotkey({
props: { value: ".", disable: true, label: "hide" }
});
return {
c() {
ul = element("ul");
li0 = element("li");
create_component(hotkey0.$$.fragment);
t0 = space();
li1 = element("li");
create_component(hotkey1.$$.fragment);
t1 = space();
li2 = element("li");
create_component(hotkey2.$$.fragment);
t2 = space();
li3 = element("li");
create_component(hotkey3.$$.fragment);
attr(li0, "class", "svelte-c3lavh");
attr(li1, "class", "svelte-c3lavh");
attr(li2, "class", "svelte-c3lavh");
attr(li3, "class", "svelte-c3lavh");
attr(ul, "id", "debug-controls");
attr(ul, "class", "controls svelte-c3lavh");
},
m(target, anchor) {
insert(target, ul, anchor);
append(ul, li0);
mount_component(hotkey0, li0, null);
append(ul, t0);
append(ul, li1);
mount_component(hotkey1, li1, null);
append(ul, t1);
append(ul, li2);
mount_component(hotkey2, li2, null);
append(ul, t2);
append(ul, li3);
mount_component(hotkey3, li3, null);
current = true;
},
p(ctx, [dirty]) {
const hotkey0_changes = {};
if (dirty & /*client*/ 1) hotkey0_changes.onPress = /*client*/ ctx[0].reset;
hotkey0.$set(hotkey0_changes);
},
i(local) {
if (current) return;
transition_in(hotkey0.$$.fragment, local);
transition_in(hotkey1.$$.fragment, local);
transition_in(hotkey2.$$.fragment, local);
transition_in(hotkey3.$$.fragment, local);
current = true;
},
o(local) {
transition_out(hotkey0.$$.fragment, local);
transition_out(hotkey1.$$.fragment, local);
transition_out(hotkey2.$$.fragment, local);
transition_out(hotkey3.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_component(hotkey0);
destroy_component(hotkey1);
destroy_component(hotkey2);
destroy_component(hotkey3);
}
};
}
function instance$h($$self, $$props, $$invalidate) {
let { client } = $$props;
function Save() {
// get state to persist and overwrite deltalog, _undo, and _redo
const state = client.getState();
const json = stringify({
...state,
_undo: [],
_redo: [],
deltalog: []
});
window.localStorage.setItem("gamestate", json);
window.localStorage.setItem("initialState", stringify(client.initialState));
}
function Restore() {
const gamestateJSON = window.localStorage.getItem("gamestate");
const initialStateJSON = window.localStorage.getItem("initialState");
if (gamestateJSON !== null && initialStateJSON !== null) {
const gamestate = parse(gamestateJSON);
const initialState = parse(initialStateJSON);
client.store.dispatch(sync({ state: gamestate, initialState }));
}
}
$$self.$set = $$props => {
if ("client" in $$props) $$invalidate(0, client = $$props.client);
};
return [client, Save, Restore];
}
class Controls extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-c3lavh-style")) add_css$b();
init(this, options, instance$h, create_fragment$h, safe_not_equal, { client: 0 });
}
}
/* src/client/debug/main/PlayerInfo.svelte generated by Svelte v3.24.0 */
function add_css$c() {
var style = element("style");
style.id = "svelte-19aan9p-style";
style.textContent = ".player-box.svelte-19aan9p{display:flex;flex-direction:row}.player.svelte-19aan9p{cursor:pointer;text-align:center;width:30px;height:30px;line-height:30px;background:#eee;border:3px solid #fefefe;box-sizing:content-box;padding:0}.player.current.svelte-19aan9p{background:#555;color:#eee;font-weight:bold}.player.active.svelte-19aan9p{border:3px solid #ff7f50}";
append(document.head, style);
}
function get_each_context$4(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
return child_ctx;
}
// (59:2) {#each players as player}
function create_each_block$4(ctx) {
let button;
let t0_value = /*player*/ ctx[7] + "";
let t0;
let t1;
let button_aria_label_value;
let mounted;
let dispose;
function click_handler(...args) {
return /*click_handler*/ ctx[5](/*player*/ ctx[7], ...args);
}
return {
c() {
button = element("button");
t0 = text(t0_value);
t1 = space();
attr(button, "class", "player svelte-19aan9p");
attr(button, "aria-label", button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7]));
toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer);
toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, t0);
append(button, t1);
if (!mounted) {
dispose = listen(button, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*players*/ 4 && t0_value !== (t0_value = /*player*/ ctx[7] + "")) set_data(t0, t0_value);
if (dirty & /*players*/ 4 && button_aria_label_value !== (button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7]))) {
attr(button, "aria-label", button_aria_label_value);
}
if (dirty & /*players, ctx*/ 5) {
toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer);
}
if (dirty & /*players, playerID*/ 6) {
toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]);
}
},
d(detaching) {
if (detaching) detach(button);
mounted = false;
dispose();
}
};
}
function create_fragment$i(ctx) {
let div;
let each_value = /*players*/ ctx[2];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$4(get_each_context$4(ctx, each_value, i));
}
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "player-box svelte-19aan9p");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
},
p(ctx, [dirty]) {
if (dirty & /*playerLabel, players, ctx, playerID, OnClick*/ 31) {
each_value = /*players*/ ctx[2];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$4(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$4(child_ctx);
each_blocks[i].c();
each_blocks[i].m(div, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
}
};
}
function instance$i($$self, $$props, $$invalidate) {
let { ctx } = $$props;
let { playerID } = $$props;
const dispatch = createEventDispatcher();
function OnClick(player) {
if (player == playerID) {
dispatch("change", { playerID: null });
} else {
dispatch("change", { playerID: player });
}
}
function playerLabel(player) {
const properties = [];
if (player == ctx.currentPlayer) properties.push("current");
if (player == playerID) properties.push("active");
let label = `Player ${player}`;
if (properties.length) label += ` (${properties.join(", ")})`;
return label;
}
let players;
const click_handler = player => OnClick(player);
$$self.$set = $$props => {
if ("ctx" in $$props) $$invalidate(0, ctx = $$props.ctx);
if ("playerID" in $$props) $$invalidate(1, playerID = $$props.playerID);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*ctx*/ 1) {
$: $$invalidate(2, players = ctx
? [...Array(ctx.numPlayers).keys()].map(i => i.toString())
: []);
}
};
return [ctx, playerID, players, OnClick, playerLabel, click_handler];
}
class PlayerInfo extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-19aan9p-style")) add_css$c();
init(this, options, instance$i, create_fragment$i, safe_not_equal, { ctx: 0, playerID: 1 });
}
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it;
if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = o[Symbol.iterator]();
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function AssignShortcuts(moveNames, blacklist) {
var shortcuts = {};
var taken = {};
var _iterator = _createForOfIteratorHelper(blacklist),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var c = _step.value;
taken[c] = true;
} // Try assigning the first char of each move as the shortcut.
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var t = taken;
var canUseFirstChar = true;
for (var name in moveNames) {
var shortcut = name[0];
if (t[shortcut]) {
canUseFirstChar = false;
break;
}
t[shortcut] = true;
shortcuts[name] = shortcut;
}
if (canUseFirstChar) {
return shortcuts;
} // If those aren't unique, use a-z.
t = taken;
var next = 97;
shortcuts = {};
for (var _name in moveNames) {
var _shortcut = String.fromCharCode(next);
while (t[_shortcut]) {
next++;
_shortcut = String.fromCharCode(next);
}
t[_shortcut] = true;
shortcuts[_name] = _shortcut;
}
return shortcuts;
}
/* src/client/debug/main/Main.svelte generated by Svelte v3.24.0 */
function add_css$d() {
var style = element("style");
style.id = "svelte-146sq5f-style";
style.textContent = ".tree.svelte-146sq5f{--json-tree-font-family:monospace;--json-tree-font-size:14px;--json-tree-null-color:#757575}.label.svelte-146sq5f{margin-bottom:0;text-transform:none}h3.svelte-146sq5f{text-transform:uppercase}ul.svelte-146sq5f{padding-left:0}li.svelte-146sq5f{list-style:none;margin:0;margin-bottom:5px}";
append(document.head, style);
}
function get_each_context$5(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[9] = list[i][0];
child_ctx[10] = list[i][1];
return child_ctx;
}
// (77:4) {#each Object.entries(moves) as [name, fn]}
function create_each_block$5(ctx) {
let li;
let move;
let t;
let current;
move = new Move({
props: {
shortcut: /*shortcuts*/ ctx[7][/*name*/ ctx[9]],
fn: /*fn*/ ctx[10],
name: /*name*/ ctx[9]
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
t = space();
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
append(li, t);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*moves*/ 8) move_changes.shortcut = /*shortcuts*/ ctx[7][/*name*/ ctx[9]];
if (dirty & /*moves*/ 8) move_changes.fn = /*fn*/ ctx[10];
if (dirty & /*moves*/ 8) move_changes.name = /*name*/ ctx[9];
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (89:2) {#if ctx.activePlayers && events.endStage}
function create_if_block_2$2(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endStage",
shortcut: 7,
fn: /*events*/ ctx[4].endStage
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endStage;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (94:2) {#if events.endTurn}
function create_if_block_1$2(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endTurn",
shortcut: 8,
fn: /*events*/ ctx[4].endTurn
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endTurn;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (99:2) {#if ctx.phase && events.endPhase}
function create_if_block$6(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endPhase",
shortcut: 9,
fn: /*events*/ ctx[4].endPhase
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endPhase;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
function create_fragment$j(ctx) {
let section0;
let h30;
let t1;
let controls;
let t2;
let section1;
let h31;
let t4;
let playerinfo;
let t5;
let section2;
let h32;
let t7;
let ul0;
let t8;
let section3;
let h33;
let t10;
let ul1;
let t11;
let t12;
let t13;
let section4;
let h34;
let t15;
let jsontree0;
let t16;
let section5;
let h35;
let t18;
let jsontree1;
let t19;
let clientswitcher;
let current;
controls = new Controls({ props: { client: /*client*/ ctx[0] } });
playerinfo = new PlayerInfo({
props: {
ctx: /*ctx*/ ctx[5],
playerID: /*playerID*/ ctx[2]
}
});
playerinfo.$on("change", /*change_handler*/ ctx[8]);
let each_value = Object.entries(/*moves*/ ctx[3]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$5(get_each_context$5(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block0 = /*ctx*/ ctx[5].activePlayers && /*events*/ ctx[4].endStage && create_if_block_2$2(ctx);
let if_block1 = /*events*/ ctx[4].endTurn && create_if_block_1$2(ctx);
let if_block2 = /*ctx*/ ctx[5].phase && /*events*/ ctx[4].endPhase && create_if_block$6(ctx);
jsontree0 = new Root({ props: { value: /*G*/ ctx[6] } });
jsontree1 = new Root({
props: { value: SanitizeCtx(/*ctx*/ ctx[5]) }
});
clientswitcher = new ClientSwitcher({
props: { clientManager: /*clientManager*/ ctx[1] }
});
return {
c() {
section0 = element("section");
h30 = element("h3");
h30.textContent = "Controls";
t1 = space();
create_component(controls.$$.fragment);
t2 = space();
section1 = element("section");
h31 = element("h3");
h31.textContent = "Players";
t4 = space();
create_component(playerinfo.$$.fragment);
t5 = space();
section2 = element("section");
h32 = element("h3");
h32.textContent = "Moves";
t7 = space();
ul0 = element("ul");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t8 = space();
section3 = element("section");
h33 = element("h3");
h33.textContent = "Events";
t10 = space();
ul1 = element("ul");
if (if_block0) if_block0.c();
t11 = space();
if (if_block1) if_block1.c();
t12 = space();
if (if_block2) if_block2.c();
t13 = space();
section4 = element("section");
h34 = element("h3");
h34.textContent = "G";
t15 = space();
create_component(jsontree0.$$.fragment);
t16 = space();
section5 = element("section");
h35 = element("h3");
h35.textContent = "ctx";
t18 = space();
create_component(jsontree1.$$.fragment);
t19 = space();
create_component(clientswitcher.$$.fragment);
attr(h30, "class", "svelte-146sq5f");
attr(h31, "class", "svelte-146sq5f");
attr(h32, "class", "svelte-146sq5f");
attr(ul0, "class", "svelte-146sq5f");
attr(h33, "class", "svelte-146sq5f");
attr(ul1, "class", "svelte-146sq5f");
attr(h34, "class", "label svelte-146sq5f");
attr(section4, "class", "tree svelte-146sq5f");
attr(h35, "class", "label svelte-146sq5f");
attr(section5, "class", "tree svelte-146sq5f");
},
m(target, anchor) {
insert(target, section0, anchor);
append(section0, h30);
append(section0, t1);
mount_component(controls, section0, null);
insert(target, t2, anchor);
insert(target, section1, anchor);
append(section1, h31);
append(section1, t4);
mount_component(playerinfo, section1, null);
insert(target, t5, anchor);
insert(target, section2, anchor);
append(section2, h32);
append(section2, t7);
append(section2, ul0);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(ul0, null);
}
insert(target, t8, anchor);
insert(target, section3, anchor);
append(section3, h33);
append(section3, t10);
append(section3, ul1);
if (if_block0) if_block0.m(ul1, null);
append(ul1, t11);
if (if_block1) if_block1.m(ul1, null);
append(ul1, t12);
if (if_block2) if_block2.m(ul1, null);
insert(target, t13, anchor);
insert(target, section4, anchor);
append(section4, h34);
append(section4, t15);
mount_component(jsontree0, section4, null);
insert(target, t16, anchor);
insert(target, section5, anchor);
append(section5, h35);
append(section5, t18);
mount_component(jsontree1, section5, null);
insert(target, t19, anchor);
mount_component(clientswitcher, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const controls_changes = {};
if (dirty & /*client*/ 1) controls_changes.client = /*client*/ ctx[0];
controls.$set(controls_changes);
const playerinfo_changes = {};
if (dirty & /*ctx*/ 32) playerinfo_changes.ctx = /*ctx*/ ctx[5];
if (dirty & /*playerID*/ 4) playerinfo_changes.playerID = /*playerID*/ ctx[2];
playerinfo.$set(playerinfo_changes);
if (dirty & /*shortcuts, Object, moves*/ 136) {
each_value = Object.entries(/*moves*/ ctx[3]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$5(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$5(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(ul0, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*ctx*/ ctx[5].activePlayers && /*events*/ ctx[4].endStage) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*ctx, events*/ 48) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_2$2(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(ul1, t11);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
if (/*events*/ ctx[4].endTurn) {
if (if_block1) {
if_block1.p(ctx, dirty);
if (dirty & /*events*/ 16) {
transition_in(if_block1, 1);
}
} else {
if_block1 = create_if_block_1$2(ctx);
if_block1.c();
transition_in(if_block1, 1);
if_block1.m(ul1, t12);
}
} else if (if_block1) {
group_outros();
transition_out(if_block1, 1, 1, () => {
if_block1 = null;
});
check_outros();
}
if (/*ctx*/ ctx[5].phase && /*events*/ ctx[4].endPhase) {
if (if_block2) {
if_block2.p(ctx, dirty);
if (dirty & /*ctx, events*/ 48) {
transition_in(if_block2, 1);
}
} else {
if_block2 = create_if_block$6(ctx);
if_block2.c();
transition_in(if_block2, 1);
if_block2.m(ul1, null);
}
} else if (if_block2) {
group_outros();
transition_out(if_block2, 1, 1, () => {
if_block2 = null;
});
check_outros();
}
const jsontree0_changes = {};
if (dirty & /*G*/ 64) jsontree0_changes.value = /*G*/ ctx[6];
jsontree0.$set(jsontree0_changes);
const jsontree1_changes = {};
if (dirty & /*ctx*/ 32) jsontree1_changes.value = SanitizeCtx(/*ctx*/ ctx[5]);
jsontree1.$set(jsontree1_changes);
const clientswitcher_changes = {};
if (dirty & /*clientManager*/ 2) clientswitcher_changes.clientManager = /*clientManager*/ ctx[1];
clientswitcher.$set(clientswitcher_changes);
},
i(local) {
if (current) return;
transition_in(controls.$$.fragment, local);
transition_in(playerinfo.$$.fragment, local);
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
transition_in(if_block0);
transition_in(if_block1);
transition_in(if_block2);
transition_in(jsontree0.$$.fragment, local);
transition_in(jsontree1.$$.fragment, local);
transition_in(clientswitcher.$$.fragment, local);
current = true;
},
o(local) {
transition_out(controls.$$.fragment, local);
transition_out(playerinfo.$$.fragment, local);
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
transition_out(if_block0);
transition_out(if_block1);
transition_out(if_block2);
transition_out(jsontree0.$$.fragment, local);
transition_out(jsontree1.$$.fragment, local);
transition_out(clientswitcher.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(section0);
destroy_component(controls);
if (detaching) detach(t2);
if (detaching) detach(section1);
destroy_component(playerinfo);
if (detaching) detach(t5);
if (detaching) detach(section2);
destroy_each(each_blocks, detaching);
if (detaching) detach(t8);
if (detaching) detach(section3);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
if (if_block2) if_block2.d();
if (detaching) detach(t13);
if (detaching) detach(section4);
destroy_component(jsontree0);
if (detaching) detach(t16);
if (detaching) detach(section5);
destroy_component(jsontree1);
if (detaching) detach(t19);
destroy_component(clientswitcher, detaching);
}
};
}
function SanitizeCtx(ctx) {
let r = {};
for (const key in ctx) {
if (!key.startsWith("_")) {
r[key] = ctx[key];
}
}
return r;
}
function instance$j($$self, $$props, $$invalidate) {
let { client } = $$props;
let { clientManager } = $$props;
const shortcuts = AssignShortcuts(client.moves, "mlia");
let { playerID, moves, events } = client;
let ctx = {};
let G = {};
client.subscribe(state => {
if (state) $$invalidate(6, { G, ctx } = state, G, $$invalidate(5, ctx));
$$invalidate(2, { playerID, moves, events } = client, playerID, $$invalidate(3, moves), $$invalidate(4, events));
});
const change_handler = e => clientManager.switchPlayerID(e.detail.playerID);
$$self.$set = $$props => {
if ("client" in $$props) $$invalidate(0, client = $$props.client);
if ("clientManager" in $$props) $$invalidate(1, clientManager = $$props.clientManager);
};
return [
client,
clientManager,
playerID,
moves,
events,
ctx,
G,
shortcuts,
change_handler
];
}
class Main extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-146sq5f-style")) add_css$d();
init(this, options, instance$j, create_fragment$j, safe_not_equal, { client: 0, clientManager: 1 });
}
}
/* src/client/debug/info/Item.svelte generated by Svelte v3.24.0 */
function add_css$e() {
var style = element("style");
style.id = "svelte-13qih23-style";
style.textContent = ".item.svelte-13qih23.svelte-13qih23{padding:10px}.item.svelte-13qih23.svelte-13qih23:not(:first-child){border-top:1px dashed #aaa}.item.svelte-13qih23 div.svelte-13qih23{float:right;text-align:right}";
append(document.head, style);
}
function create_fragment$k(ctx) {
let div1;
let strong;
let t0;
let t1;
let div0;
let t2_value = JSON.stringify(/*value*/ ctx[1]) + "";
let t2;
return {
c() {
div1 = element("div");
strong = element("strong");
t0 = text(/*name*/ ctx[0]);
t1 = space();
div0 = element("div");
t2 = text(t2_value);
attr(div0, "class", "svelte-13qih23");
attr(div1, "class", "item svelte-13qih23");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, strong);
append(strong, t0);
append(div1, t1);
append(div1, div0);
append(div0, t2);
},
p(ctx, [dirty]) {
if (dirty & /*name*/ 1) set_data(t0, /*name*/ ctx[0]);
if (dirty & /*value*/ 2 && t2_value !== (t2_value = JSON.stringify(/*value*/ ctx[1]) + "")) set_data(t2, t2_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div1);
}
};
}
function instance$k($$self, $$props, $$invalidate) {
let { name } = $$props;
let { value } = $$props;
$$self.$set = $$props => {
if ("name" in $$props) $$invalidate(0, name = $$props.name);
if ("value" in $$props) $$invalidate(1, value = $$props.value);
};
return [name, value];
}
class Item extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-13qih23-style")) add_css$e();
init(this, options, instance$k, create_fragment$k, safe_not_equal, { name: 0, value: 1 });
}
}
/* src/client/debug/info/Info.svelte generated by Svelte v3.24.0 */
function add_css$f() {
var style = element("style");
style.id = "svelte-1yzq5o8-style";
style.textContent = ".gameinfo.svelte-1yzq5o8{padding:10px}";
append(document.head, style);
}
// (18:2) {#if client.multiplayer}
function create_if_block$7(ctx) {
let item;
let current;
item = new Item({
props: {
name: "isConnected",
value: /*$client*/ ctx[1].isConnected
}
});
return {
c() {
create_component(item.$$.fragment);
},
m(target, anchor) {
mount_component(item, target, anchor);
current = true;
},
p(ctx, dirty) {
const item_changes = {};
if (dirty & /*$client*/ 2) item_changes.value = /*$client*/ ctx[1].isConnected;
item.$set(item_changes);
},
i(local) {
if (current) return;
transition_in(item.$$.fragment, local);
current = true;
},
o(local) {
transition_out(item.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(item, detaching);
}
};
}
function create_fragment$l(ctx) {
let section;
let item0;
let t0;
let item1;
let t1;
let item2;
let t2;
let current;
item0 = new Item({
props: {
name: "matchID",
value: /*client*/ ctx[0].matchID
}
});
item1 = new Item({
props: {
name: "playerID",
value: /*client*/ ctx[0].playerID
}
});
item2 = new Item({
props: {
name: "isActive",
value: /*$client*/ ctx[1].isActive
}
});
let if_block = /*client*/ ctx[0].multiplayer && create_if_block$7(ctx);
return {
c() {
section = element("section");
create_component(item0.$$.fragment);
t0 = space();
create_component(item1.$$.fragment);
t1 = space();
create_component(item2.$$.fragment);
t2 = space();
if (if_block) if_block.c();
attr(section, "class", "gameinfo svelte-1yzq5o8");
},
m(target, anchor) {
insert(target, section, anchor);
mount_component(item0, section, null);
append(section, t0);
mount_component(item1, section, null);
append(section, t1);
mount_component(item2, section, null);
append(section, t2);
if (if_block) if_block.m(section, null);
current = true;
},
p(ctx, [dirty]) {
const item0_changes = {};
if (dirty & /*client*/ 1) item0_changes.value = /*client*/ ctx[0].matchID;
item0.$set(item0_changes);
const item1_changes = {};
if (dirty & /*client*/ 1) item1_changes.value = /*client*/ ctx[0].playerID;
item1.$set(item1_changes);
const item2_changes = {};
if (dirty & /*$client*/ 2) item2_changes.value = /*$client*/ ctx[1].isActive;
item2.$set(item2_changes);
if (/*client*/ ctx[0].multiplayer) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*client*/ 1) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$7(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(section, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(item0.$$.fragment, local);
transition_in(item1.$$.fragment, local);
transition_in(item2.$$.fragment, local);
transition_in(if_block);
current = true;
},
o(local) {
transition_out(item0.$$.fragment, local);
transition_out(item1.$$.fragment, local);
transition_out(item2.$$.fragment, local);
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(item0);
destroy_component(item1);
destroy_component(item2);
if (if_block) if_block.d();
}
};
}
function instance$l($$self, $$props, $$invalidate) {
let $client,
$$unsubscribe_client = noop,
$$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(1, $client = $$value)), client);
$$self.$$.on_destroy.push(() => $$unsubscribe_client());
let { client } = $$props;
$$subscribe_client();
let { clientManager } = $$props;
$$self.$set = $$props => {
if ("client" in $$props) $$subscribe_client($$invalidate(0, client = $$props.client));
if ("clientManager" in $$props) $$invalidate(2, clientManager = $$props.clientManager);
};
return [client, $client, clientManager];
}
class Info extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1yzq5o8-style")) add_css$f();
init(this, options, instance$l, create_fragment$l, safe_not_equal, { client: 0, clientManager: 2 });
}
}
/* src/client/debug/log/TurnMarker.svelte generated by Svelte v3.24.0 */
function add_css$g() {
var style = element("style");
style.id = "svelte-6eza86-style";
style.textContent = ".turn-marker.svelte-6eza86{display:flex;justify-content:center;align-items:center;grid-column:1;background:#555;color:#eee;text-align:center;font-weight:bold;border:1px solid #888}";
append(document.head, style);
}
function create_fragment$m(ctx) {
let div;
let t;
return {
c() {
div = element("div");
t = text(/*turn*/ ctx[0]);
attr(div, "class", "turn-marker svelte-6eza86");
attr(div, "style", /*style*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*turn*/ 1) set_data(t, /*turn*/ ctx[0]);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$m($$self, $$props, $$invalidate) {
let { turn } = $$props;
let { numEvents } = $$props;
const style = `grid-row: span ${numEvents}`;
$$self.$set = $$props => {
if ("turn" in $$props) $$invalidate(0, turn = $$props.turn);
if ("numEvents" in $$props) $$invalidate(2, numEvents = $$props.numEvents);
};
return [turn, style, numEvents];
}
class TurnMarker extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-6eza86-style")) add_css$g();
init(this, options, instance$m, create_fragment$m, safe_not_equal, { turn: 0, numEvents: 2 });
}
}
/* src/client/debug/log/PhaseMarker.svelte generated by Svelte v3.24.0 */
function add_css$h() {
var style = element("style");
style.id = "svelte-1t4xap-style";
style.textContent = ".phase-marker.svelte-1t4xap{grid-column:3;background:#555;border:1px solid #888;color:#eee;text-align:center;font-weight:bold;padding-top:10px;padding-bottom:10px;text-orientation:sideways;writing-mode:vertical-rl;line-height:30px;width:100%}";
append(document.head, style);
}
function create_fragment$n(ctx) {
let div;
let t_value = (/*phase*/ ctx[0] || "") + "";
let t;
return {
c() {
div = element("div");
t = text(t_value);
attr(div, "class", "phase-marker svelte-1t4xap");
attr(div, "style", /*style*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*phase*/ 1 && t_value !== (t_value = (/*phase*/ ctx[0] || "") + "")) set_data(t, t_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$n($$self, $$props, $$invalidate) {
let { phase } = $$props;
let { numEvents } = $$props;
const style = `grid-row: span ${numEvents}`;
$$self.$set = $$props => {
if ("phase" in $$props) $$invalidate(0, phase = $$props.phase);
if ("numEvents" in $$props) $$invalidate(2, numEvents = $$props.numEvents);
};
return [phase, style, numEvents];
}
class PhaseMarker extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1t4xap-style")) add_css$h();
init(this, options, instance$n, create_fragment$n, safe_not_equal, { phase: 0, numEvents: 2 });
}
}
/* src/client/debug/log/LogMetadata.svelte generated by Svelte v3.24.0 */
function create_fragment$o(ctx) {
let div;
return {
c() {
div = element("div");
div.textContent = `${/*renderedMetadata*/ ctx[0]}`;
},
m(target, anchor) {
insert(target, div, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$o($$self, $$props, $$invalidate) {
let { metadata } = $$props;
const renderedMetadata = metadata !== undefined
? JSON.stringify(metadata, null, 4)
: "";
$$self.$set = $$props => {
if ("metadata" in $$props) $$invalidate(1, metadata = $$props.metadata);
};
return [renderedMetadata, metadata];
}
class LogMetadata extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$o, create_fragment$o, safe_not_equal, { metadata: 1 });
}
}
/* src/client/debug/log/LogEvent.svelte generated by Svelte v3.24.0 */
function add_css$i() {
var style = element("style");
style.id = "svelte-11hs70q-style";
style.textContent = ".log-event.svelte-11hs70q{grid-column:2;cursor:pointer;overflow:hidden;display:flex;flex-direction:column;justify-content:center;background:#fff;border:1px dotted #ccc;border-left:5px solid #ccc;padding:5px;text-align:center;color:#666;font-size:14px;min-height:25px;line-height:25px}.log-event.svelte-11hs70q:hover,.log-event.svelte-11hs70q:focus{border-style:solid;background:#eee}.log-event.pinned.svelte-11hs70q{border-style:solid;background:#eee;opacity:1}.player0.svelte-11hs70q{border-left-color:#ff851b}.player1.svelte-11hs70q{border-left-color:#7fdbff}.player2.svelte-11hs70q{border-left-color:#0074d9}.player3.svelte-11hs70q{border-left-color:#39cccc}.player4.svelte-11hs70q{border-left-color:#3d9970}.player5.svelte-11hs70q{border-left-color:#2ecc40}.player6.svelte-11hs70q{border-left-color:#01ff70}.player7.svelte-11hs70q{border-left-color:#ffdc00}.player8.svelte-11hs70q{border-left-color:#001f3f}.player9.svelte-11hs70q{border-left-color:#ff4136}.player10.svelte-11hs70q{border-left-color:#85144b}.player11.svelte-11hs70q{border-left-color:#f012be}.player12.svelte-11hs70q{border-left-color:#b10dc9}.player13.svelte-11hs70q{border-left-color:#111111}.player14.svelte-11hs70q{border-left-color:#aaaaaa}.player15.svelte-11hs70q{border-left-color:#dddddd}";
append(document.head, style);
}
// (139:2) {:else}
function create_else_block$1(ctx) {
let logmetadata;
let current;
logmetadata = new LogMetadata({ props: { metadata: /*metadata*/ ctx[2] } });
return {
c() {
create_component(logmetadata.$$.fragment);
},
m(target, anchor) {
mount_component(logmetadata, target, anchor);
current = true;
},
p(ctx, dirty) {
const logmetadata_changes = {};
if (dirty & /*metadata*/ 4) logmetadata_changes.metadata = /*metadata*/ ctx[2];
logmetadata.$set(logmetadata_changes);
},
i(local) {
if (current) return;
transition_in(logmetadata.$$.fragment, local);
current = true;
},
o(local) {
transition_out(logmetadata.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(logmetadata, detaching);
}
};
}
// (137:2) {#if metadataComponent}
function create_if_block$8(ctx) {
let switch_instance;
let switch_instance_anchor;
let current;
var switch_value = /*metadataComponent*/ ctx[3];
function switch_props(ctx) {
return { props: { metadata: /*metadata*/ ctx[2] } };
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
if (switch_instance) create_component(switch_instance.$$.fragment);
switch_instance_anchor = empty();
},
m(target, anchor) {
if (switch_instance) {
mount_component(switch_instance, target, anchor);
}
insert(target, switch_instance_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const switch_instance_changes = {};
if (dirty & /*metadata*/ 4) switch_instance_changes.metadata = /*metadata*/ ctx[2];
if (switch_value !== (switch_value = /*metadataComponent*/ ctx[3])) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(switch_instance_anchor);
if (switch_instance) destroy_component(switch_instance, detaching);
}
};
}
function create_fragment$p(ctx) {
let button;
let div;
let t0;
let t1;
let t2;
let t3;
let t4;
let current_block_type_index;
let if_block;
let button_class_value;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$8, create_else_block$1];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*metadataComponent*/ ctx[3]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
button = element("button");
div = element("div");
t0 = text(/*actionType*/ ctx[4]);
t1 = text("(");
t2 = text(/*renderedArgs*/ ctx[6]);
t3 = text(")");
t4 = space();
if_block.c();
attr(button, "class", button_class_value = "log-event player" + /*playerID*/ ctx[7] + " svelte-11hs70q");
toggle_class(button, "pinned", /*pinned*/ ctx[1]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, div);
append(div, t0);
append(div, t1);
append(div, t2);
append(div, t3);
append(button, t4);
if_blocks[current_block_type_index].m(button, null);
current = true;
if (!mounted) {
dispose = [
listen(button, "click", /*click_handler*/ ctx[9]),
listen(button, "mouseenter", /*mouseenter_handler*/ ctx[10]),
listen(button, "focus", /*focus_handler*/ ctx[11]),
listen(button, "mouseleave", /*mouseleave_handler*/ ctx[12]),
listen(button, "blur", /*blur_handler*/ ctx[13])
];
mounted = true;
}
},
p(ctx, [dirty]) {
if (!current || dirty & /*actionType*/ 16) set_data(t0, /*actionType*/ ctx[4]);
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
}
transition_in(if_block, 1);
if_block.m(button, null);
}
if (dirty & /*pinned*/ 2) {
toggle_class(button, "pinned", /*pinned*/ ctx[1]);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(button);
if_blocks[current_block_type_index].d();
mounted = false;
run_all(dispose);
}
};
}
function instance$p($$self, $$props, $$invalidate) {
let { logIndex } = $$props;
let { action } = $$props;
let { pinned } = $$props;
let { metadata } = $$props;
let { metadataComponent } = $$props;
const dispatch = createEventDispatcher();
const args = action.payload.args;
const renderedArgs = typeof args === "string" ? args : (args || []).join(",");
const playerID = action.payload.playerID;
let actionType;
switch (action.type) {
case "UNDO":
actionType = "undo";
break;
case "REDO":
actionType = "redo";
case "GAME_EVENT":
case "MAKE_MOVE":
default:
actionType = action.payload.type;
break;
}
const click_handler = () => dispatch("click", { logIndex });
const mouseenter_handler = () => dispatch("mouseenter", { logIndex });
const focus_handler = () => dispatch("mouseenter", { logIndex });
const mouseleave_handler = () => dispatch("mouseleave");
const blur_handler = () => dispatch("mouseleave");
$$self.$set = $$props => {
if ("logIndex" in $$props) $$invalidate(0, logIndex = $$props.logIndex);
if ("action" in $$props) $$invalidate(8, action = $$props.action);
if ("pinned" in $$props) $$invalidate(1, pinned = $$props.pinned);
if ("metadata" in $$props) $$invalidate(2, metadata = $$props.metadata);
if ("metadataComponent" in $$props) $$invalidate(3, metadataComponent = $$props.metadataComponent);
};
return [
logIndex,
pinned,
metadata,
metadataComponent,
actionType,
dispatch,
renderedArgs,
playerID,
action,
click_handler,
mouseenter_handler,
focus_handler,
mouseleave_handler,
blur_handler
];
}
class LogEvent extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-11hs70q-style")) add_css$i();
init(this, options, instance$p, create_fragment$p, safe_not_equal, {
logIndex: 0,
action: 8,
pinned: 1,
metadata: 2,
metadataComponent: 3
});
}
}
/* node_modules/svelte-icons/components/IconBase.svelte generated by Svelte v3.24.0 */
function add_css$j() {
var style = element("style");
style.id = "svelte-c8tyih-style";
style.textContent = "svg.svelte-c8tyih{stroke:currentColor;fill:currentColor;stroke-width:0;width:100%;height:auto;max-height:100%}";
append(document.head, style);
}
// (18:2) {#if title}
function create_if_block$9(ctx) {
let title_1;
let t;
return {
c() {
title_1 = svg_element("title");
t = text(/*title*/ ctx[0]);
},
m(target, anchor) {
insert(target, title_1, anchor);
append(title_1, t);
},
p(ctx, dirty) {
if (dirty & /*title*/ 1) set_data(t, /*title*/ ctx[0]);
},
d(detaching) {
if (detaching) detach(title_1);
}
};
}
function create_fragment$q(ctx) {
let svg;
let if_block_anchor;
let current;
let if_block = /*title*/ ctx[0] && create_if_block$9(ctx);
const default_slot_template = /*$$slots*/ ctx[3].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[2], null);
return {
c() {
svg = svg_element("svg");
if (if_block) if_block.c();
if_block_anchor = empty();
if (default_slot) default_slot.c();
attr(svg, "xmlns", "http://www.w3.org/2000/svg");
attr(svg, "viewBox", /*viewBox*/ ctx[1]);
attr(svg, "class", "svelte-c8tyih");
},
m(target, anchor) {
insert(target, svg, anchor);
if (if_block) if_block.m(svg, null);
append(svg, if_block_anchor);
if (default_slot) {
default_slot.m(svg, null);
}
current = true;
},
p(ctx, [dirty]) {
if (/*title*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$9(ctx);
if_block.c();
if_block.m(svg, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (default_slot) {
if (default_slot.p && dirty & /*$$scope*/ 4) {
update_slot(default_slot, default_slot_template, ctx, /*$$scope*/ ctx[2], dirty, null, null);
}
}
if (!current || dirty & /*viewBox*/ 2) {
attr(svg, "viewBox", /*viewBox*/ ctx[1]);
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (detaching) detach(svg);
if (if_block) if_block.d();
if (default_slot) default_slot.d(detaching);
}
};
}
function instance$q($$self, $$props, $$invalidate) {
let { title = null } = $$props;
let { viewBox } = $$props;
let { $$slots = {}, $$scope } = $$props;
$$self.$set = $$props => {
if ("title" in $$props) $$invalidate(0, title = $$props.title);
if ("viewBox" in $$props) $$invalidate(1, viewBox = $$props.viewBox);
if ("$$scope" in $$props) $$invalidate(2, $$scope = $$props.$$scope);
};
return [title, viewBox, $$scope, $$slots];
}
class IconBase extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-c8tyih-style")) add_css$j();
init(this, options, instance$q, create_fragment$q, safe_not_equal, { title: 0, viewBox: 1 });
}
}
/* node_modules/svelte-icons/fa/FaArrowAltCircleDown.svelte generated by Svelte v3.24.0 */
function create_default_slot(ctx) {
let path;
return {
c() {
path = svg_element("path");
attr(path, "d", "M504 256c0 137-111 248-248 248S8 393 8 256 119 8 256 8s248 111 248 248zM212 140v116h-70.9c-10.7 0-16.1 13-8.5 20.5l114.9 114.3c4.7 4.7 12.2 4.7 16.9 0l114.9-114.3c7.6-7.6 2.2-20.5-8.5-20.5H300V140c0-6.6-5.4-12-12-12h-64c-6.6 0-12 5.4-12 12z");
},
m(target, anchor) {
insert(target, path, anchor);
},
d(detaching) {
if (detaching) detach(path);
}
};
}
function create_fragment$r(ctx) {
let iconbase;
let current;
const iconbase_spread_levels = [{ viewBox: "0 0 512 512" }, /*$$props*/ ctx[0]];
let iconbase_props = {
$$slots: { default: [create_default_slot] },
$$scope: { ctx }
};
for (let i = 0; i < iconbase_spread_levels.length; i += 1) {
iconbase_props = assign(iconbase_props, iconbase_spread_levels[i]);
}
iconbase = new IconBase({ props: iconbase_props });
return {
c() {
create_component(iconbase.$$.fragment);
},
m(target, anchor) {
mount_component(iconbase, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const iconbase_changes = (dirty & /*$$props*/ 1)
? get_spread_update(iconbase_spread_levels, [iconbase_spread_levels[0], get_spread_object(/*$$props*/ ctx[0])])
: {};
if (dirty & /*$$scope*/ 2) {
iconbase_changes.$$scope = { dirty, ctx };
}
iconbase.$set(iconbase_changes);
},
i(local) {
if (current) return;
transition_in(iconbase.$$.fragment, local);
current = true;
},
o(local) {
transition_out(iconbase.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(iconbase, detaching);
}
};
}
function instance$r($$self, $$props, $$invalidate) {
$$self.$set = $$new_props => {
$$invalidate(0, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
};
$$props = exclude_internal_props($$props);
return [$$props];
}
class FaArrowAltCircleDown extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$r, create_fragment$r, safe_not_equal, {});
}
}
/* src/client/debug/mcts/Action.svelte generated by Svelte v3.24.0 */
function add_css$k() {
var style = element("style");
style.id = "svelte-1a7time-style";
style.textContent = "div.svelte-1a7time{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;max-width:500px}";
append(document.head, style);
}
function create_fragment$s(ctx) {
let div;
let t;
return {
c() {
div = element("div");
t = text(/*text*/ ctx[0]);
attr(div, "alt", /*text*/ ctx[0]);
attr(div, "class", "svelte-1a7time");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*text*/ 1) set_data(t, /*text*/ ctx[0]);
if (dirty & /*text*/ 1) {
attr(div, "alt", /*text*/ ctx[0]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$s($$self, $$props, $$invalidate) {
let { action } = $$props;
let text;
$$self.$set = $$props => {
if ("action" in $$props) $$invalidate(1, action = $$props.action);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*action*/ 2) {
$: {
const { type, args } = action.payload;
const argsFormatted = (args || []).join(",");
$$invalidate(0, text = `${type}(${argsFormatted})`);
}
}
};
return [text, action];
}
class Action extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1a7time-style")) add_css$k();
init(this, options, instance$s, create_fragment$s, safe_not_equal, { action: 1 });
}
}
/* src/client/debug/mcts/Table.svelte generated by Svelte v3.24.0 */
function add_css$l() {
var style = element("style");
style.id = "svelte-ztcwsu-style";
style.textContent = "table.svelte-ztcwsu.svelte-ztcwsu{font-size:12px;border-collapse:collapse;border:1px solid #ddd;padding:0}tr.svelte-ztcwsu.svelte-ztcwsu{cursor:pointer}tr.svelte-ztcwsu:hover td.svelte-ztcwsu{background:#eee}tr.selected.svelte-ztcwsu td.svelte-ztcwsu{background:#eee}td.svelte-ztcwsu.svelte-ztcwsu{padding:10px;height:10px;line-height:10px;font-size:12px;border:none}th.svelte-ztcwsu.svelte-ztcwsu{background:#888;color:#fff;padding:10px;text-align:center}";
append(document.head, style);
}
function get_each_context$6(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[10] = list[i];
child_ctx[12] = i;
return child_ctx;
}
// (86:2) {#each children as child, i}
function create_each_block$6(ctx) {
let tr;
let td0;
let t0_value = /*child*/ ctx[10].value + "";
let t0;
let t1;
let td1;
let t2_value = /*child*/ ctx[10].visits + "";
let t2;
let t3;
let td2;
let action;
let t4;
let current;
let mounted;
let dispose;
action = new Action({
props: { action: /*child*/ ctx[10].parentAction }
});
function click_handler(...args) {
return /*click_handler*/ ctx[5](/*child*/ ctx[10], /*i*/ ctx[12], ...args);
}
function mouseout_handler(...args) {
return /*mouseout_handler*/ ctx[6](/*i*/ ctx[12], ...args);
}
function mouseover_handler(...args) {
return /*mouseover_handler*/ ctx[7](/*child*/ ctx[10], /*i*/ ctx[12], ...args);
}
return {
c() {
tr = element("tr");
td0 = element("td");
t0 = text(t0_value);
t1 = space();
td1 = element("td");
t2 = text(t2_value);
t3 = space();
td2 = element("td");
create_component(action.$$.fragment);
t4 = space();
attr(td0, "class", "svelte-ztcwsu");
attr(td1, "class", "svelte-ztcwsu");
attr(td2, "class", "svelte-ztcwsu");
attr(tr, "class", "svelte-ztcwsu");
toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0);
toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]);
},
m(target, anchor) {
insert(target, tr, anchor);
append(tr, td0);
append(td0, t0);
append(tr, t1);
append(tr, td1);
append(td1, t2);
append(tr, t3);
append(tr, td2);
mount_component(action, td2, null);
append(tr, t4);
current = true;
if (!mounted) {
dispose = [
listen(tr, "click", click_handler),
listen(tr, "mouseout", mouseout_handler),
listen(tr, "mouseover", mouseover_handler)
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if ((!current || dirty & /*children*/ 2) && t0_value !== (t0_value = /*child*/ ctx[10].value + "")) set_data(t0, t0_value);
if ((!current || dirty & /*children*/ 2) && t2_value !== (t2_value = /*child*/ ctx[10].visits + "")) set_data(t2, t2_value);
const action_changes = {};
if (dirty & /*children*/ 2) action_changes.action = /*child*/ ctx[10].parentAction;
action.$set(action_changes);
if (dirty & /*children*/ 2) {
toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0);
}
if (dirty & /*selectedIndex*/ 1) {
toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]);
}
},
i(local) {
if (current) return;
transition_in(action.$$.fragment, local);
current = true;
},
o(local) {
transition_out(action.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(tr);
destroy_component(action);
mounted = false;
run_all(dispose);
}
};
}
function create_fragment$t(ctx) {
let table;
let thead;
let t5;
let tbody;
let current;
let each_value = /*children*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$6(get_each_context$6(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
table = element("table");
thead = element("thead");
thead.innerHTML = `<th class="svelte-ztcwsu">Value</th>
<th class="svelte-ztcwsu">Visits</th>
<th class="svelte-ztcwsu">Action</th>`;
t5 = space();
tbody = element("tbody");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(table, "class", "svelte-ztcwsu");
},
m(target, anchor) {
insert(target, table, anchor);
append(table, thead);
append(table, t5);
append(table, tbody);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(tbody, null);
}
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*children, selectedIndex, Select, Preview*/ 15) {
each_value = /*children*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$6(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$6(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(tbody, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(table);
destroy_each(each_blocks, detaching);
}
};
}
function instance$t($$self, $$props, $$invalidate) {
let { root } = $$props;
let { selectedIndex = null } = $$props;
const dispatch = createEventDispatcher();
let parents = [];
let children = [];
function Select(node, i) {
dispatch("select", { node, selectedIndex: i });
}
function Preview(node, i) {
if (selectedIndex === null) {
dispatch("preview", { node });
}
}
const click_handler = (child, i) => Select(child, i);
const mouseout_handler = i => Preview(null);
const mouseover_handler = (child, i) => Preview(child);
$$self.$set = $$props => {
if ("root" in $$props) $$invalidate(4, root = $$props.root);
if ("selectedIndex" in $$props) $$invalidate(0, selectedIndex = $$props.selectedIndex);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*root, parents*/ 272) {
$: {
let t = root;
$$invalidate(8, parents = []);
while (t.parent) {
const parent = t.parent;
const { type, args } = t.parentAction.payload;
const argsFormatted = (args || []).join(",");
const arrowText = `${type}(${argsFormatted})`;
parents.push({ parent, arrowText });
t = parent;
}
parents.reverse();
$$invalidate(1, children = [...root.children].sort((a, b) => a.visits < b.visits ? 1 : -1).slice(0, 50));
}
}
};
return [
selectedIndex,
children,
Select,
Preview,
root,
click_handler,
mouseout_handler,
mouseover_handler
];
}
class Table extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-ztcwsu-style")) add_css$l();
init(this, options, instance$t, create_fragment$t, safe_not_equal, { root: 4, selectedIndex: 0 });
}
}
/* src/client/debug/mcts/MCTS.svelte generated by Svelte v3.24.0 */
function add_css$m() {
var style = element("style");
style.id = "svelte-1f0amz4-style";
style.textContent = ".visualizer.svelte-1f0amz4{display:flex;flex-direction:column;align-items:center;padding:50px}.preview.svelte-1f0amz4{opacity:0.5}.icon.svelte-1f0amz4{color:#777;width:32px;height:32px;margin-bottom:20px}";
append(document.head, style);
}
function get_each_context$7(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[9] = list[i].node;
child_ctx[10] = list[i].selectedIndex;
child_ctx[12] = i;
return child_ctx;
}
// (50:4) {#if i !== 0}
function create_if_block_2$3(ctx) {
let div;
let arrow;
let current;
arrow = new FaArrowAltCircleDown({});
return {
c() {
div = element("div");
create_component(arrow.$$.fragment);
attr(div, "class", "icon svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
mount_component(arrow, div, null);
current = true;
},
i(local) {
if (current) return;
transition_in(arrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(arrow.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_component(arrow);
}
};
}
// (61:6) {:else}
function create_else_block$2(ctx) {
let table;
let current;
function select_handler_1(...args) {
return /*select_handler_1*/ ctx[7](/*i*/ ctx[12], ...args);
}
table = new Table({
props: {
root: /*node*/ ctx[9],
selectedIndex: /*selectedIndex*/ ctx[10]
}
});
table.$on("select", select_handler_1);
return {
c() {
create_component(table.$$.fragment);
},
m(target, anchor) {
mount_component(table, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const table_changes = {};
if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9];
if (dirty & /*nodes*/ 1) table_changes.selectedIndex = /*selectedIndex*/ ctx[10];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(table, detaching);
}
};
}
// (57:6) {#if i === nodes.length - 1}
function create_if_block_1$3(ctx) {
let table;
let current;
function select_handler(...args) {
return /*select_handler*/ ctx[5](/*i*/ ctx[12], ...args);
}
function preview_handler(...args) {
return /*preview_handler*/ ctx[6](/*i*/ ctx[12], ...args);
}
table = new Table({ props: { root: /*node*/ ctx[9] } });
table.$on("select", select_handler);
table.$on("preview", preview_handler);
return {
c() {
create_component(table.$$.fragment);
},
m(target, anchor) {
mount_component(table, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const table_changes = {};
if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(table, detaching);
}
};
}
// (49:2) {#each nodes as { node, selectedIndex }
function create_each_block$7(ctx) {
let t;
let section;
let current_block_type_index;
let if_block1;
let current;
let if_block0 = /*i*/ ctx[12] !== 0 && create_if_block_2$3();
const if_block_creators = [create_if_block_1$3, create_else_block$2];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*i*/ ctx[12] === /*nodes*/ ctx[0].length - 1) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
if (if_block0) if_block0.c();
t = space();
section = element("section");
if_block1.c();
},
m(target, anchor) {
if (if_block0) if_block0.m(target, anchor);
insert(target, t, anchor);
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
},
p(ctx, dirty) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block1 = if_blocks[current_block_type_index];
if (!if_block1) {
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block1.c();
}
transition_in(if_block1, 1);
if_block1.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t);
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
}
};
}
// (69:2) {#if preview}
function create_if_block$a(ctx) {
let div;
let arrow;
let t;
let section;
let table;
let current;
arrow = new FaArrowAltCircleDown({});
table = new Table({ props: { root: /*preview*/ ctx[1] } });
return {
c() {
div = element("div");
create_component(arrow.$$.fragment);
t = space();
section = element("section");
create_component(table.$$.fragment);
attr(div, "class", "icon svelte-1f0amz4");
attr(section, "class", "preview svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
mount_component(arrow, div, null);
insert(target, t, anchor);
insert(target, section, anchor);
mount_component(table, section, null);
current = true;
},
p(ctx, dirty) {
const table_changes = {};
if (dirty & /*preview*/ 2) table_changes.root = /*preview*/ ctx[1];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(arrow.$$.fragment, local);
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(arrow.$$.fragment, local);
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_component(arrow);
if (detaching) detach(t);
if (detaching) detach(section);
destroy_component(table);
}
};
}
function create_fragment$u(ctx) {
let div;
let t;
let current;
let each_value = /*nodes*/ ctx[0];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$7(get_each_context$7(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block = /*preview*/ ctx[1] && create_if_block$a(ctx);
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t = space();
if (if_block) if_block.c();
attr(div, "class", "visualizer svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
append(div, t);
if (if_block) if_block.m(div, null);
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*nodes, SelectNode, PreviewNode*/ 13) {
each_value = /*nodes*/ ctx[0];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$7(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$7(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div, t);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*preview*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*preview*/ 2) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$a(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(div, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
transition_in(if_block);
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
if (if_block) if_block.d();
}
};
}
function instance$u($$self, $$props, $$invalidate) {
let { metadata } = $$props;
let nodes = [];
let preview = null;
function SelectNode({ node, selectedIndex }, i) {
$$invalidate(1, preview = null);
$$invalidate(0, nodes[i].selectedIndex = selectedIndex, nodes);
$$invalidate(0, nodes = [...nodes.slice(0, i + 1), { node }]);
}
function PreviewNode({ node }, i) {
$$invalidate(1, preview = node);
}
const select_handler = (i, e) => SelectNode(e.detail, i);
const preview_handler = (i, e) => PreviewNode(e.detail);
const select_handler_1 = (i, e) => SelectNode(e.detail, i);
$$self.$set = $$props => {
if ("metadata" in $$props) $$invalidate(4, metadata = $$props.metadata);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*metadata*/ 16) {
$: {
$$invalidate(0, nodes = [{ node: metadata }]);
}
}
};
return [
nodes,
preview,
SelectNode,
PreviewNode,
metadata,
select_handler,
preview_handler,
select_handler_1
];
}
class MCTS extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1f0amz4-style")) add_css$m();
init(this, options, instance$u, create_fragment$u, safe_not_equal, { metadata: 4 });
}
}
/* src/client/debug/log/Log.svelte generated by Svelte v3.24.0 */
function add_css$n() {
var style = element("style");
style.id = "svelte-1pq5e4b-style";
style.textContent = ".gamelog.svelte-1pq5e4b{display:grid;grid-template-columns:30px 1fr 30px;grid-auto-rows:auto;grid-auto-flow:column}";
append(document.head, style);
}
function get_each_context$8(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[16] = list[i].phase;
child_ctx[18] = i;
return child_ctx;
}
function get_each_context_1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[19] = list[i].action;
child_ctx[20] = list[i].metadata;
child_ctx[18] = i;
return child_ctx;
}
function get_each_context_2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[22] = list[i].turn;
child_ctx[18] = i;
return child_ctx;
}
// (136:4) {#if i in turnBoundaries}
function create_if_block_1$4(ctx) {
let turnmarker;
let current;
turnmarker = new TurnMarker({
props: {
turn: /*turn*/ ctx[22],
numEvents: /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]]
}
});
return {
c() {
create_component(turnmarker.$$.fragment);
},
m(target, anchor) {
mount_component(turnmarker, target, anchor);
current = true;
},
p(ctx, dirty) {
const turnmarker_changes = {};
if (dirty & /*renderedLogEntries*/ 4) turnmarker_changes.turn = /*turn*/ ctx[22];
if (dirty & /*turnBoundaries*/ 8) turnmarker_changes.numEvents = /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]];
turnmarker.$set(turnmarker_changes);
},
i(local) {
if (current) return;
transition_in(turnmarker.$$.fragment, local);
current = true;
},
o(local) {
transition_out(turnmarker.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(turnmarker, detaching);
}
};
}
// (135:2) {#each renderedLogEntries as { turn }
function create_each_block_2(ctx) {
let if_block_anchor;
let current;
let if_block = /*i*/ ctx[18] in /*turnBoundaries*/ ctx[3] && create_if_block_1$4(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
if (/*i*/ ctx[18] in /*turnBoundaries*/ ctx[3]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*turnBoundaries*/ 8) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$4(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (141:2) {#each renderedLogEntries as { action, metadata }
function create_each_block_1(ctx) {
let logevent;
let current;
logevent = new LogEvent({
props: {
pinned: /*i*/ ctx[18] === /*pinned*/ ctx[1],
logIndex: /*i*/ ctx[18],
action: /*action*/ ctx[19],
metadata: /*metadata*/ ctx[20]
}
});
logevent.$on("click", /*OnLogClick*/ ctx[5]);
logevent.$on("mouseenter", /*OnMouseEnter*/ ctx[6]);
logevent.$on("mouseleave", /*OnMouseLeave*/ ctx[7]);
return {
c() {
create_component(logevent.$$.fragment);
},
m(target, anchor) {
mount_component(logevent, target, anchor);
current = true;
},
p(ctx, dirty) {
const logevent_changes = {};
if (dirty & /*pinned*/ 2) logevent_changes.pinned = /*i*/ ctx[18] === /*pinned*/ ctx[1];
if (dirty & /*renderedLogEntries*/ 4) logevent_changes.action = /*action*/ ctx[19];
if (dirty & /*renderedLogEntries*/ 4) logevent_changes.metadata = /*metadata*/ ctx[20];
logevent.$set(logevent_changes);
},
i(local) {
if (current) return;
transition_in(logevent.$$.fragment, local);
current = true;
},
o(local) {
transition_out(logevent.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(logevent, detaching);
}
};
}
// (153:4) {#if i in phaseBoundaries}
function create_if_block$b(ctx) {
let phasemarker;
let current;
phasemarker = new PhaseMarker({
props: {
phase: /*phase*/ ctx[16],
numEvents: /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]]
}
});
return {
c() {
create_component(phasemarker.$$.fragment);
},
m(target, anchor) {
mount_component(phasemarker, target, anchor);
current = true;
},
p(ctx, dirty) {
const phasemarker_changes = {};
if (dirty & /*renderedLogEntries*/ 4) phasemarker_changes.phase = /*phase*/ ctx[16];
if (dirty & /*phaseBoundaries*/ 16) phasemarker_changes.numEvents = /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]];
phasemarker.$set(phasemarker_changes);
},
i(local) {
if (current) return;
transition_in(phasemarker.$$.fragment, local);
current = true;
},
o(local) {
transition_out(phasemarker.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(phasemarker, detaching);
}
};
}
// (152:2) {#each renderedLogEntries as { phase }
function create_each_block$8(ctx) {
let if_block_anchor;
let current;
let if_block = /*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4] && create_if_block$b(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
if (/*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*phaseBoundaries*/ 16) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$b(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function create_fragment$v(ctx) {
let div;
let t0;
let t1;
let current;
let mounted;
let dispose;
let each_value_2 = /*renderedLogEntries*/ ctx[2];
let each_blocks_2 = [];
for (let i = 0; i < each_value_2.length; i += 1) {
each_blocks_2[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i));
}
const out = i => transition_out(each_blocks_2[i], 1, 1, () => {
each_blocks_2[i] = null;
});
let each_value_1 = /*renderedLogEntries*/ ctx[2];
let each_blocks_1 = [];
for (let i = 0; i < each_value_1.length; i += 1) {
each_blocks_1[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i));
}
const out_1 = i => transition_out(each_blocks_1[i], 1, 1, () => {
each_blocks_1[i] = null;
});
let each_value = /*renderedLogEntries*/ ctx[2];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$8(get_each_context$8(ctx, each_value, i));
}
const out_2 = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks_2.length; i += 1) {
each_blocks_2[i].c();
}
t0 = space();
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].c();
}
t1 = space();
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "gamelog svelte-1pq5e4b");
toggle_class(div, "pinned", /*pinned*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks_2.length; i += 1) {
each_blocks_2[i].m(div, null);
}
append(div, t0);
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].m(div, null);
}
append(div, t1);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
current = true;
if (!mounted) {
dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[8]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*renderedLogEntries, turnBoundaries*/ 12) {
each_value_2 = /*renderedLogEntries*/ ctx[2];
let i;
for (i = 0; i < each_value_2.length; i += 1) {
const child_ctx = get_each_context_2(ctx, each_value_2, i);
if (each_blocks_2[i]) {
each_blocks_2[i].p(child_ctx, dirty);
transition_in(each_blocks_2[i], 1);
} else {
each_blocks_2[i] = create_each_block_2(child_ctx);
each_blocks_2[i].c();
transition_in(each_blocks_2[i], 1);
each_blocks_2[i].m(div, t0);
}
}
group_outros();
for (i = each_value_2.length; i < each_blocks_2.length; i += 1) {
out(i);
}
check_outros();
}
if (dirty & /*pinned, renderedLogEntries, OnLogClick, OnMouseEnter, OnMouseLeave*/ 230) {
each_value_1 = /*renderedLogEntries*/ ctx[2];
let i;
for (i = 0; i < each_value_1.length; i += 1) {
const child_ctx = get_each_context_1(ctx, each_value_1, i);
if (each_blocks_1[i]) {
each_blocks_1[i].p(child_ctx, dirty);
transition_in(each_blocks_1[i], 1);
} else {
each_blocks_1[i] = create_each_block_1(child_ctx);
each_blocks_1[i].c();
transition_in(each_blocks_1[i], 1);
each_blocks_1[i].m(div, t1);
}
}
group_outros();
for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
out_1(i);
}
check_outros();
}
if (dirty & /*renderedLogEntries, phaseBoundaries*/ 20) {
each_value = /*renderedLogEntries*/ ctx[2];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$8(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$8(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out_2(i);
}
check_outros();
}
if (dirty & /*pinned*/ 2) {
toggle_class(div, "pinned", /*pinned*/ ctx[1]);
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value_2.length; i += 1) {
transition_in(each_blocks_2[i]);
}
for (let i = 0; i < each_value_1.length; i += 1) {
transition_in(each_blocks_1[i]);
}
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks_2 = each_blocks_2.filter(Boolean);
for (let i = 0; i < each_blocks_2.length; i += 1) {
transition_out(each_blocks_2[i]);
}
each_blocks_1 = each_blocks_1.filter(Boolean);
for (let i = 0; i < each_blocks_1.length; i += 1) {
transition_out(each_blocks_1[i]);
}
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks_2, detaching);
destroy_each(each_blocks_1, detaching);
destroy_each(each_blocks, detaching);
mounted = false;
dispose();
}
};
}
function instance$v($$self, $$props, $$invalidate) {
let $client,
$$unsubscribe_client = noop,
$$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(10, $client = $$value)), client);
$$self.$$.on_destroy.push(() => $$unsubscribe_client());
let { client } = $$props;
$$subscribe_client();
const { secondaryPane } = getContext("secondaryPane");
const reducer = CreateGameReducer({ game: client.game });
const initialState = client.getInitialState();
let { log } = $client;
let pinned = null;
function rewind(logIndex) {
let state = initialState;
for (let i = 0; i < log.length; i++) {
const { action, automatic } = log[i];
if (!automatic) {
state = reducer(state, action);
if (logIndex == 0) {
break;
}
logIndex--;
}
}
return {
G: state.G,
ctx: state.ctx,
plugins: state.plugins
};
}
function OnLogClick(e) {
const { logIndex } = e.detail;
const state = rewind(logIndex);
const renderedLogEntries = log.filter(e => !e.automatic);
client.overrideGameState(state);
if (pinned == logIndex) {
$$invalidate(1, pinned = null);
secondaryPane.set(null);
} else {
$$invalidate(1, pinned = logIndex);
const { metadata } = renderedLogEntries[logIndex].action.payload;
if (metadata) {
secondaryPane.set({ component: MCTS, metadata });
}
}
}
function OnMouseEnter(e) {
const { logIndex } = e.detail;
if (pinned === null) {
const state = rewind(logIndex);
client.overrideGameState(state);
}
}
function OnMouseLeave() {
if (pinned === null) {
client.overrideGameState(null);
}
}
function Reset() {
$$invalidate(1, pinned = null);
client.overrideGameState(null);
secondaryPane.set(null);
}
onDestroy(Reset);
function OnKeyDown(e) {
// ESC.
if (e.keyCode == 27) {
Reset();
}
}
let renderedLogEntries;
let turnBoundaries = {};
let phaseBoundaries = {};
$$self.$set = $$props => {
if ("client" in $$props) $$subscribe_client($$invalidate(0, client = $$props.client));
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$client, log, renderedLogEntries*/ 1540) {
$: {
$$invalidate(9, log = $client.log);
$$invalidate(2, renderedLogEntries = log.filter(e => !e.automatic));
let eventsInCurrentPhase = 0;
let eventsInCurrentTurn = 0;
$$invalidate(3, turnBoundaries = {});
$$invalidate(4, phaseBoundaries = {});
for (let i = 0; i < renderedLogEntries.length; i++) {
const { action, payload, turn, phase } = renderedLogEntries[i];
eventsInCurrentTurn++;
eventsInCurrentPhase++;
if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].turn != turn) {
$$invalidate(3, turnBoundaries[i] = eventsInCurrentTurn, turnBoundaries);
eventsInCurrentTurn = 0;
}
if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].phase != phase) {
$$invalidate(4, phaseBoundaries[i] = eventsInCurrentPhase, phaseBoundaries);
eventsInCurrentPhase = 0;
}
}
}
}
};
return [
client,
pinned,
renderedLogEntries,
turnBoundaries,
phaseBoundaries,
OnLogClick,
OnMouseEnter,
OnMouseLeave,
OnKeyDown
];
}
class Log extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1pq5e4b-style")) add_css$n();
init(this, options, instance$v, create_fragment$v, safe_not_equal, { client: 0 });
}
}
/* src/client/debug/ai/Options.svelte generated by Svelte v3.24.0 */
function add_css$o() {
var style = element("style");
style.id = "svelte-1fu900w-style";
style.textContent = "label.svelte-1fu900w{color:#666}.option.svelte-1fu900w{margin-bottom:20px}.value.svelte-1fu900w{font-weight:bold;color:#000}input[type='checkbox'].svelte-1fu900w{vertical-align:middle}";
append(document.head, style);
}
function get_each_context$9(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[5] = list[i][0];
child_ctx[6] = list[i][1];
return child_ctx;
}
// (39:4) {#if value.range}
function create_if_block_1$5(ctx) {
let span;
let t0_value = /*values*/ ctx[1][/*key*/ ctx[5]] + "";
let t0;
let t1;
let input;
let input_min_value;
let input_max_value;
let mounted;
let dispose;
function input_change_input_handler() {
/*input_change_input_handler*/ ctx[3].call(input, /*key*/ ctx[5]);
}
return {
c() {
span = element("span");
t0 = text(t0_value);
t1 = space();
input = element("input");
attr(span, "class", "value svelte-1fu900w");
attr(input, "type", "range");
attr(input, "min", input_min_value = /*value*/ ctx[6].range.min);
attr(input, "max", input_max_value = /*value*/ ctx[6].range.max);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t0);
insert(target, t1, anchor);
insert(target, input, anchor);
set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[5]]);
if (!mounted) {
dispose = [
listen(input, "change", input_change_input_handler),
listen(input, "input", input_change_input_handler),
listen(input, "change", /*OnChange*/ ctx[2])
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*values, bot*/ 3 && t0_value !== (t0_value = /*values*/ ctx[1][/*key*/ ctx[5]] + "")) set_data(t0, t0_value);
if (dirty & /*bot*/ 1 && input_min_value !== (input_min_value = /*value*/ ctx[6].range.min)) {
attr(input, "min", input_min_value);
}
if (dirty & /*bot*/ 1 && input_max_value !== (input_max_value = /*value*/ ctx[6].range.max)) {
attr(input, "max", input_max_value);
}
if (dirty & /*values, Object, bot*/ 3) {
set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[5]]);
}
},
d(detaching) {
if (detaching) detach(span);
if (detaching) detach(t1);
if (detaching) detach(input);
mounted = false;
run_all(dispose);
}
};
}
// (44:4) {#if typeof value.value === 'boolean'}
function create_if_block$c(ctx) {
let input;
let mounted;
let dispose;
function input_change_handler() {
/*input_change_handler*/ ctx[4].call(input, /*key*/ ctx[5]);
}
return {
c() {
input = element("input");
attr(input, "type", "checkbox");
attr(input, "class", "svelte-1fu900w");
},
m(target, anchor) {
insert(target, input, anchor);
input.checked = /*values*/ ctx[1][/*key*/ ctx[5]];
if (!mounted) {
dispose = [
listen(input, "change", input_change_handler),
listen(input, "change", /*OnChange*/ ctx[2])
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*values, Object, bot*/ 3) {
input.checked = /*values*/ ctx[1][/*key*/ ctx[5]];
}
},
d(detaching) {
if (detaching) detach(input);
mounted = false;
run_all(dispose);
}
};
}
// (35:0) {#each Object.entries(bot.opts()) as [key, value]}
function create_each_block$9(ctx) {
let div;
let label;
let t0_value = /*key*/ ctx[5] + "";
let t0;
let t1;
let t2;
let t3;
let if_block0 = /*value*/ ctx[6].range && create_if_block_1$5(ctx);
let if_block1 = typeof /*value*/ ctx[6].value === "boolean" && create_if_block$c(ctx);
return {
c() {
div = element("div");
label = element("label");
t0 = text(t0_value);
t1 = space();
if (if_block0) if_block0.c();
t2 = space();
if (if_block1) if_block1.c();
t3 = space();
attr(label, "class", "svelte-1fu900w");
attr(div, "class", "option svelte-1fu900w");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, label);
append(label, t0);
append(div, t1);
if (if_block0) if_block0.m(div, null);
append(div, t2);
if (if_block1) if_block1.m(div, null);
append(div, t3);
},
p(ctx, dirty) {
if (dirty & /*bot*/ 1 && t0_value !== (t0_value = /*key*/ ctx[5] + "")) set_data(t0, t0_value);
if (/*value*/ ctx[6].range) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_1$5(ctx);
if_block0.c();
if_block0.m(div, t2);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (typeof /*value*/ ctx[6].value === "boolean") {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block$c(ctx);
if_block1.c();
if_block1.m(div, t3);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
d(detaching) {
if (detaching) detach(div);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
}
};
}
function create_fragment$w(ctx) {
let each_1_anchor;
let each_value = Object.entries(/*bot*/ ctx[0].opts());
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$9(get_each_context$9(ctx, each_value, i));
}
return {
c() {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
each_1_anchor = empty();
},
m(target, anchor) {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(target, anchor);
}
insert(target, each_1_anchor, anchor);
},
p(ctx, [dirty]) {
if (dirty & /*values, Object, bot, OnChange*/ 7) {
each_value = Object.entries(/*bot*/ ctx[0].opts());
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$9(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$9(child_ctx);
each_blocks[i].c();
each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
destroy_each(each_blocks, detaching);
if (detaching) detach(each_1_anchor);
}
};
}
function instance$w($$self, $$props, $$invalidate) {
let { bot } = $$props;
let values = {};
for (let [key, value] of Object.entries(bot.opts())) {
values[key] = value.value;
}
function OnChange() {
for (let [key, value] of Object.entries(values)) {
bot.setOpt(key, value);
}
}
function input_change_input_handler(key) {
values[key] = to_number(this.value);
$$invalidate(1, values);
$$invalidate(0, bot);
}
function input_change_handler(key) {
values[key] = this.checked;
$$invalidate(1, values);
$$invalidate(0, bot);
}
$$self.$set = $$props => {
if ("bot" in $$props) $$invalidate(0, bot = $$props.bot);
};
return [bot, values, OnChange, input_change_input_handler, input_change_handler];
}
class Options extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1fu900w-style")) add_css$o();
init(this, options, instance$w, create_fragment$w, safe_not_equal, { bot: 0 });
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Base class that bots can extend.
*/
class Bot {
constructor({ enumerate, seed, }) {
this.enumerateFn = enumerate;
this.seed = seed;
this.iterationCounter = 0;
this._opts = {};
}
addOpt({ key, range, initial, }) {
this._opts[key] = {
range,
value: initial,
};
}
getOpt(key) {
return this._opts[key].value;
}
setOpt(key, value) {
if (key in this._opts) {
this._opts[key].value = value;
}
}
opts() {
return this._opts;
}
enumerate(G, ctx, playerID) {
const actions = this.enumerateFn(G, ctx, playerID);
return actions.map((a) => {
if ('payload' in a) {
return a;
}
if ('move' in a) {
return makeMove(a.move, a.args, playerID);
}
if ('event' in a) {
return gameEvent(a.event, a.args, playerID);
}
});
}
random(arg) {
let number;
if (this.seed !== undefined) {
const seed = this.prngstate ? '' : this.seed;
const rand = alea(seed, this.prngstate);
number = rand();
this.prngstate = rand.state();
}
else {
number = Math.random();
}
if (arg) {
if (Array.isArray(arg)) {
const id = Math.floor(number * arg.length);
return arg[id];
}
else {
return Math.floor(number * arg);
}
}
return number;
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* The number of iterations to run before yielding to
* the JS event loop (in async mode).
*/
const CHUNK_SIZE = 25;
/**
* Bot that uses Monte-Carlo Tree Search to find promising moves.
*/
class MCTSBot extends Bot {
constructor({ enumerate, seed, objectives, game, iterations, playoutDepth, iterationCallback, }) {
super({ enumerate, seed });
if (objectives === undefined) {
objectives = () => ({});
}
this.objectives = objectives;
this.iterationCallback = iterationCallback || (() => { });
this.reducer = CreateGameReducer({ game });
this.iterations = iterations;
this.playoutDepth = playoutDepth;
this.addOpt({
key: 'async',
initial: false,
});
this.addOpt({
key: 'iterations',
initial: typeof iterations === 'number' ? iterations : 1000,
range: { min: 1, max: 2000 },
});
this.addOpt({
key: 'playoutDepth',
initial: typeof playoutDepth === 'number' ? playoutDepth : 50,
range: { min: 1, max: 100 },
});
}
createNode({ state, parentAction, parent, playerID, }) {
const { G, ctx } = state;
let actions = [];
let objectives = [];
if (playerID !== undefined) {
actions = this.enumerate(G, ctx, playerID);
objectives = this.objectives(G, ctx, playerID);
}
else if (ctx.activePlayers) {
for (const playerID in ctx.activePlayers) {
actions = actions.concat(this.enumerate(G, ctx, playerID));
objectives = objectives.concat(this.objectives(G, ctx, playerID));
}
}
else {
actions = actions.concat(this.enumerate(G, ctx, ctx.currentPlayer));
objectives = objectives.concat(this.objectives(G, ctx, ctx.currentPlayer));
}
return {
state,
parent,
parentAction,
actions,
objectives,
children: [],
visits: 0,
value: 0,
};
}
select(node) {
// This node has unvisited children.
if (node.actions.length > 0) {
return node;
}
// This is a terminal node.
if (node.children.length == 0) {
return node;
}
let selectedChild = null;
let best = 0;
for (const child of node.children) {
const childVisits = child.visits + Number.EPSILON;
const uct = child.value / childVisits +
Math.sqrt((2 * Math.log(node.visits)) / childVisits);
if (selectedChild == null || uct > best) {
best = uct;
selectedChild = child;
}
}
return this.select(selectedChild);
}
expand(node) {
const actions = node.actions;
if (actions.length == 0 || node.state.ctx.gameover !== undefined) {
return node;
}
const id = this.random(actions.length);
const action = actions[id];
node.actions.splice(id, 1);
const childState = this.reducer(node.state, action);
const childNode = this.createNode({
state: childState,
parentAction: action,
parent: node,
});
node.children.push(childNode);
return childNode;
}
playout({ state }) {
let playoutDepth = this.getOpt('playoutDepth');
if (typeof this.playoutDepth === 'function') {
playoutDepth = this.playoutDepth(state.G, state.ctx);
}
for (let i = 0; i < playoutDepth && state.ctx.gameover === undefined; i++) {
const { G, ctx } = state;
let playerID = ctx.currentPlayer;
if (ctx.activePlayers) {
playerID = Object.keys(ctx.activePlayers)[0];
}
const moves = this.enumerate(G, ctx, playerID);
// Check if any objectives are met.
const objectives = this.objectives(G, ctx, playerID);
const score = Object.keys(objectives).reduce((score, key) => {
const objective = objectives[key];
if (objective.checker(G, ctx)) {
return score + objective.weight;
}
return score;
}, 0);
// If so, stop and return the score.
if (score > 0) {
return { score };
}
if (!moves || moves.length == 0) {
return undefined;
}
const id = this.random(moves.length);
const childState = this.reducer(state, moves[id]);
state = childState;
}
return state.ctx.gameover;
}
backpropagate(node, result = {}) {
node.visits++;
if (result.score !== undefined) {
node.value += result.score;
}
if (result.draw === true) {
node.value += 0.5;
}
if (node.parentAction &&
result.winner === node.parentAction.payload.playerID) {
node.value++;
}
if (node.parent) {
this.backpropagate(node.parent, result);
}
}
play(state, playerID) {
const root = this.createNode({ state, playerID });
let numIterations = this.getOpt('iterations');
if (typeof this.iterations === 'function') {
numIterations = this.iterations(state.G, state.ctx);
}
const getResult = () => {
let selectedChild = null;
for (const child of root.children) {
if (selectedChild == null || child.visits > selectedChild.visits) {
selectedChild = child;
}
}
const action = selectedChild && selectedChild.parentAction;
const metadata = root;
return { action, metadata };
};
return new Promise((resolve) => {
const iteration = () => {
for (let i = 0; i < CHUNK_SIZE && this.iterationCounter < numIterations; i++) {
const leaf = this.select(root);
const child = this.expand(leaf);
const result = this.playout(child);
this.backpropagate(child, result);
this.iterationCounter++;
}
this.iterationCallback({
iterationCounter: this.iterationCounter,
numIterations,
metadata: root,
});
};
this.iterationCounter = 0;
if (this.getOpt('async')) {
const asyncIteration = () => {
if (this.iterationCounter < numIterations) {
iteration();
setTimeout(asyncIteration, 0);
}
else {
resolve(getResult());
}
};
asyncIteration();
}
else {
while (this.iterationCounter < numIterations) {
iteration();
}
resolve(getResult());
}
});
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Bot that picks a move at random.
*/
class RandomBot extends Bot {
play({ G, ctx }, playerID) {
const moves = this.enumerate(G, ctx, playerID);
return Promise.resolve({ action: this.random(moves) });
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Make a single move on the client with a bot.
*
* @param {...object} client - The game client.
* @param {...object} bot - The bot.
*/
async function Step(client, bot) {
const state = client.store.getState();
let playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
const { action, metadata } = await bot.play(state, playerID);
if (action) {
const a = {
...action,
payload: {
...action.payload,
metadata,
},
};
client.store.dispatch(a);
return a;
}
}
/**
* Simulates the game till the end or a max depth.
*
* @param {...object} game - The game object.
* @param {...object} bots - An array of bots.
* @param {...object} state - The game state to start from.
*/
async function Simulate({ game, bots, state, depth, }) {
if (depth === undefined)
depth = 10000;
const reducer = CreateGameReducer({ game });
let metadata = null;
let iter = 0;
while (state.ctx.gameover === undefined && iter < depth) {
let playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
const bot = bots instanceof Bot ? bots : bots[playerID];
const t = await bot.play(state, playerID);
if (!t.action) {
break;
}
metadata = t.metadata;
state = reducer(state, t.action);
iter++;
}
return { state, metadata };
}
/* src/client/debug/ai/AI.svelte generated by Svelte v3.24.0 */
function add_css$p() {
var style = element("style");
style.id = "svelte-lifdi8-style";
style.textContent = "ul.svelte-lifdi8{padding-left:0}li.svelte-lifdi8{list-style:none;margin:none;margin-bottom:5px}h3.svelte-lifdi8{text-transform:uppercase}label.svelte-lifdi8{color:#666}input[type='checkbox'].svelte-lifdi8{vertical-align:middle}";
append(document.head, style);
}
function get_each_context$a(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
return child_ctx;
}
// (201:4) {:else}
function create_else_block$3(ctx) {
let p0;
let t1;
let p1;
return {
c() {
p0 = element("p");
p0.textContent = "No bots available.";
t1 = space();
p1 = element("p");
p1.innerHTML = `Follow the instructions
<a href="https://boardgame.io/documentation/#/tutorial?id=bots" target="_blank">here</a>
to set up bots.`;
},
m(target, anchor) {
insert(target, p0, anchor);
insert(target, t1, anchor);
insert(target, p1, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(p0);
if (detaching) detach(t1);
if (detaching) detach(p1);
}
};
}
// (199:4) {#if client.multiplayer}
function create_if_block_5(ctx) {
let p;
return {
c() {
p = element("p");
p.textContent = "The bot debugger is only available in singleplayer mode.";
},
m(target, anchor) {
insert(target, p, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(p);
}
};
}
// (149:2) {#if client.game.ai && !client.multiplayer}
function create_if_block$d(ctx) {
let section0;
let h30;
let t1;
let ul;
let li0;
let hotkey0;
let t2;
let li1;
let hotkey1;
let t3;
let li2;
let hotkey2;
let t4;
let section1;
let h31;
let t6;
let select;
let t7;
let show_if = Object.keys(/*bot*/ ctx[7].opts()).length;
let t8;
let if_block1_anchor;
let current;
let mounted;
let dispose;
hotkey0 = new Hotkey({
props: {
value: "1",
onPress: /*Reset*/ ctx[13],
label: "reset"
}
});
hotkey1 = new Hotkey({
props: {
value: "2",
onPress: /*Step*/ ctx[11],
label: "play"
}
});
hotkey2 = new Hotkey({
props: {
value: "3",
onPress: /*Simulate*/ ctx[12],
label: "simulate"
}
});
let each_value = Object.keys(/*bots*/ ctx[8]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$a(get_each_context$a(ctx, each_value, i));
}
let if_block0 = show_if && create_if_block_4(ctx);
let if_block1 = (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) && create_if_block_1$6(ctx);
return {
c() {
section0 = element("section");
h30 = element("h3");
h30.textContent = "Controls";
t1 = space();
ul = element("ul");
li0 = element("li");
create_component(hotkey0.$$.fragment);
t2 = space();
li1 = element("li");
create_component(hotkey1.$$.fragment);
t3 = space();
li2 = element("li");
create_component(hotkey2.$$.fragment);
t4 = space();
section1 = element("section");
h31 = element("h3");
h31.textContent = "Bot";
t6 = space();
select = element("select");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t7 = space();
if (if_block0) if_block0.c();
t8 = space();
if (if_block1) if_block1.c();
if_block1_anchor = empty();
attr(h30, "class", "svelte-lifdi8");
attr(li0, "class", "svelte-lifdi8");
attr(li1, "class", "svelte-lifdi8");
attr(li2, "class", "svelte-lifdi8");
attr(ul, "class", "svelte-lifdi8");
attr(h31, "class", "svelte-lifdi8");
if (/*selectedBot*/ ctx[4] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[16].call(select));
},
m(target, anchor) {
insert(target, section0, anchor);
append(section0, h30);
append(section0, t1);
append(section0, ul);
append(ul, li0);
mount_component(hotkey0, li0, null);
append(ul, t2);
append(ul, li1);
mount_component(hotkey1, li1, null);
append(ul, t3);
append(ul, li2);
mount_component(hotkey2, li2, null);
insert(target, t4, anchor);
insert(target, section1, anchor);
append(section1, h31);
append(section1, t6);
append(section1, select);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(select, null);
}
select_option(select, /*selectedBot*/ ctx[4]);
insert(target, t7, anchor);
if (if_block0) if_block0.m(target, anchor);
insert(target, t8, anchor);
if (if_block1) if_block1.m(target, anchor);
insert(target, if_block1_anchor, anchor);
current = true;
if (!mounted) {
dispose = [
listen(select, "change", /*select_change_handler*/ ctx[16]),
listen(select, "change", /*ChangeBot*/ ctx[10])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*Object, bots*/ 256) {
each_value = Object.keys(/*bots*/ ctx[8]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$a(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$a(child_ctx);
each_blocks[i].c();
each_blocks[i].m(select, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (dirty & /*selectedBot, Object, bots*/ 272) {
select_option(select, /*selectedBot*/ ctx[4]);
}
if (dirty & /*bot*/ 128) show_if = Object.keys(/*bot*/ ctx[7].opts()).length;
if (show_if) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*bot*/ 128) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_4(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(t8.parentNode, t8);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
if (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_1$6(ctx);
if_block1.c();
if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
i(local) {
if (current) return;
transition_in(hotkey0.$$.fragment, local);
transition_in(hotkey1.$$.fragment, local);
transition_in(hotkey2.$$.fragment, local);
transition_in(if_block0);
current = true;
},
o(local) {
transition_out(hotkey0.$$.fragment, local);
transition_out(hotkey1.$$.fragment, local);
transition_out(hotkey2.$$.fragment, local);
transition_out(if_block0);
current = false;
},
d(detaching) {
if (detaching) detach(section0);
destroy_component(hotkey0);
destroy_component(hotkey1);
destroy_component(hotkey2);
if (detaching) detach(t4);
if (detaching) detach(section1);
destroy_each(each_blocks, detaching);
if (detaching) detach(t7);
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t8);
if (if_block1) if_block1.d(detaching);
if (detaching) detach(if_block1_anchor);
mounted = false;
run_all(dispose);
}
};
}
// (168:8) {#each Object.keys(bots) as bot}
function create_each_block$a(ctx) {
let option;
let t_value = /*bot*/ ctx[7] + "";
let t;
let option_value_value;
return {
c() {
option = element("option");
t = text(t_value);
option.__value = option_value_value = /*bot*/ ctx[7];
option.value = option.__value;
},
m(target, anchor) {
insert(target, option, anchor);
append(option, t);
},
p: noop,
d(detaching) {
if (detaching) detach(option);
}
};
}
// (174:4) {#if Object.keys(bot.opts()).length}
function create_if_block_4(ctx) {
let section;
let h3;
let t1;
let label;
let t3;
let input;
let t4;
let options;
let current;
let mounted;
let dispose;
options = new Options({ props: { bot: /*bot*/ ctx[7] } });
return {
c() {
section = element("section");
h3 = element("h3");
h3.textContent = "Options";
t1 = space();
label = element("label");
label.textContent = "debug";
t3 = space();
input = element("input");
t4 = space();
create_component(options.$$.fragment);
attr(h3, "class", "svelte-lifdi8");
attr(label, "class", "svelte-lifdi8");
attr(input, "type", "checkbox");
attr(input, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, h3);
append(section, t1);
append(section, label);
append(section, t3);
append(section, input);
input.checked = /*debug*/ ctx[1];
append(section, t4);
mount_component(options, section, null);
current = true;
if (!mounted) {
dispose = [
listen(input, "change", /*input_change_handler*/ ctx[17]),
listen(input, "change", /*OnDebug*/ ctx[9])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*debug*/ 2) {
input.checked = /*debug*/ ctx[1];
}
const options_changes = {};
if (dirty & /*bot*/ 128) options_changes.bot = /*bot*/ ctx[7];
options.$set(options_changes);
},
i(local) {
if (current) return;
transition_in(options.$$.fragment, local);
current = true;
},
o(local) {
transition_out(options.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(options);
mounted = false;
run_all(dispose);
}
};
}
// (183:4) {#if botAction || iterationCounter}
function create_if_block_1$6(ctx) {
let section;
let h3;
let t1;
let t2;
let if_block0 = /*progress*/ ctx[2] && /*progress*/ ctx[2] < 1 && create_if_block_3$1(ctx);
let if_block1 = /*botAction*/ ctx[5] && create_if_block_2$4(ctx);
return {
c() {
section = element("section");
h3 = element("h3");
h3.textContent = "Result";
t1 = space();
if (if_block0) if_block0.c();
t2 = space();
if (if_block1) if_block1.c();
attr(h3, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, h3);
append(section, t1);
if (if_block0) if_block0.m(section, null);
append(section, t2);
if (if_block1) if_block1.m(section, null);
},
p(ctx, dirty) {
if (/*progress*/ ctx[2] && /*progress*/ ctx[2] < 1) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_3$1(ctx);
if_block0.c();
if_block0.m(section, t2);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (/*botAction*/ ctx[5]) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_2$4(ctx);
if_block1.c();
if_block1.m(section, null);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
d(detaching) {
if (detaching) detach(section);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
}
};
}
// (186:6) {#if progress && progress < 1.0}
function create_if_block_3$1(ctx) {
let progress_1;
return {
c() {
progress_1 = element("progress");
progress_1.value = /*progress*/ ctx[2];
},
m(target, anchor) {
insert(target, progress_1, anchor);
},
p(ctx, dirty) {
if (dirty & /*progress*/ 4) {
progress_1.value = /*progress*/ ctx[2];
}
},
d(detaching) {
if (detaching) detach(progress_1);
}
};
}
// (190:6) {#if botAction}
function create_if_block_2$4(ctx) {
let ul;
let li0;
let t0;
let t1;
let t2;
let li1;
let t3;
let t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + "";
let t4;
return {
c() {
ul = element("ul");
li0 = element("li");
t0 = text("Action: ");
t1 = text(/*botAction*/ ctx[5]);
t2 = space();
li1 = element("li");
t3 = text("Args: ");
t4 = text(t4_value);
attr(li0, "class", "svelte-lifdi8");
attr(li1, "class", "svelte-lifdi8");
attr(ul, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, ul, anchor);
append(ul, li0);
append(li0, t0);
append(li0, t1);
append(ul, t2);
append(ul, li1);
append(li1, t3);
append(li1, t4);
},
p(ctx, dirty) {
if (dirty & /*botAction*/ 32) set_data(t1, /*botAction*/ ctx[5]);
if (dirty & /*botActionArgs*/ 64 && t4_value !== (t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + "")) set_data(t4, t4_value);
},
d(detaching) {
if (detaching) detach(ul);
}
};
}
function create_fragment$x(ctx) {
let section;
let current_block_type_index;
let if_block;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$d, create_if_block_5, create_else_block$3];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*client*/ ctx[0].game.ai && !/*client*/ ctx[0].multiplayer) return 0;
if (/*client*/ ctx[0].multiplayer) return 1;
return 2;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
section = element("section");
if_block.c();
},
m(target, anchor) {
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
if (!mounted) {
dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[14]);
mounted = true;
}
},
p(ctx, [dirty]) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
}
transition_in(if_block, 1);
if_block.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$x($$self, $$props, $$invalidate) {
let { client } = $$props;
let { clientManager } = $$props;
const { secondaryPane } = getContext("secondaryPane");
const bots = { "MCTS": MCTSBot, "Random": RandomBot };
let debug = false;
let progress = null;
let iterationCounter = 0;
let metadata = null;
const iterationCallback = ({ iterationCounter: c, numIterations, metadata: m }) => {
$$invalidate(3, iterationCounter = c);
$$invalidate(2, progress = c / numIterations);
metadata = m;
if (debug && metadata) {
secondaryPane.set({ component: MCTS, metadata });
}
};
function OnDebug() {
if (debug && metadata) {
secondaryPane.set({ component: MCTS, metadata });
} else {
secondaryPane.set(null);
}
}
let bot;
if (client.game.ai) {
bot = new MCTSBot({
game: client.game,
enumerate: client.game.ai.enumerate,
iterationCallback
});
bot.setOpt("async", true);
}
let selectedBot;
let botAction;
let botActionArgs;
function ChangeBot() {
const botConstructor = bots[selectedBot];
$$invalidate(7, bot = new botConstructor({
game: client.game,
enumerate: client.game.ai.enumerate,
iterationCallback
}));
bot.setOpt("async", true);
$$invalidate(5, botAction = null);
metadata = null;
secondaryPane.set(null);
$$invalidate(3, iterationCounter = 0);
}
async function Step$1() {
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
const t = await Step(client, bot);
if (t) {
$$invalidate(5, botAction = t.payload.type);
$$invalidate(6, botActionArgs = t.payload.args);
}
}
function Simulate(iterations = 10000, sleepTimeout = 100) {
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
const step = async () => {
for (let i = 0; i < iterations; i++) {
const action = await Step(client, bot);
if (!action) break;
await new Promise(resolve => setTimeout(resolve, sleepTimeout));
}
};
return step();
}
function Exit() {
client.overrideGameState(null);
secondaryPane.set(null);
$$invalidate(1, debug = false);
}
function Reset() {
client.reset();
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
Exit();
}
function OnKeyDown(e) {
// ESC.
if (e.keyCode == 27) {
Exit();
}
}
onDestroy(Exit);
function select_change_handler() {
selectedBot = select_value(this);
$$invalidate(4, selectedBot);
$$invalidate(8, bots);
}
function input_change_handler() {
debug = this.checked;
$$invalidate(1, debug);
}
$$self.$set = $$props => {
if ("client" in $$props) $$invalidate(0, client = $$props.client);
if ("clientManager" in $$props) $$invalidate(15, clientManager = $$props.clientManager);
};
return [
client,
debug,
progress,
iterationCounter,
selectedBot,
botAction,
botActionArgs,
bot,
bots,
OnDebug,
ChangeBot,
Step$1,
Simulate,
Reset,
OnKeyDown,
clientManager,
select_change_handler,
input_change_handler
];
}
class AI extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-lifdi8-style")) add_css$p();
init(this, options, instance$x, create_fragment$x, safe_not_equal, { client: 0, clientManager: 15 });
}
}
/* src/client/debug/Debug.svelte generated by Svelte v3.24.0 */
function add_css$q() {
var style = element("style");
style.id = "svelte-1dhkl71-style";
style.textContent = ".debug-panel.svelte-1dhkl71{position:fixed;color:#555;font-family:monospace;display:flex;flex-direction:row;text-align:left;right:0;top:0;height:100%;font-size:14px;box-sizing:border-box;opacity:0.9;z-index:99999}.pane.svelte-1dhkl71{flex-grow:2;overflow-x:hidden;overflow-y:scroll;background:#fefefe;padding:20px;border-left:1px solid #ccc;box-shadow:-1px 0 5px rgba(0, 0, 0, 0.2);box-sizing:border-box;width:280px}.secondary-pane.svelte-1dhkl71{background:#fefefe;overflow-y:scroll}.debug-panel.svelte-1dhkl71 button,.debug-panel.svelte-1dhkl71 select{cursor:pointer;font-size:14px;font-family:monospace}.debug-panel.svelte-1dhkl71 select{background:#eee;border:1px solid #bbb;color:#555;padding:3px;border-radius:3px}.debug-panel.svelte-1dhkl71 section{margin-bottom:20px}.debug-panel.svelte-1dhkl71 .screen-reader-only{clip:rect(0 0 0 0);clip-path:inset(50%);height:1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px}";
append(document.head, style);
}
// (118:0) {#if visible}
function create_if_block$e(ctx) {
let section;
let menu;
let t0;
let div;
let switch_instance;
let t1;
let section_transition;
let current;
menu = new Menu({
props: {
panes: /*panes*/ ctx[6],
pane: /*pane*/ ctx[2]
}
});
menu.$on("change", /*MenuChange*/ ctx[8]);
var switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component;
function switch_props(ctx) {
return {
props: {
client: /*client*/ ctx[4],
clientManager: /*clientManager*/ ctx[0]
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
let if_block = /*$secondaryPane*/ ctx[5] && create_if_block_1$7(ctx);
return {
c() {
section = element("section");
create_component(menu.$$.fragment);
t0 = space();
div = element("div");
if (switch_instance) create_component(switch_instance.$$.fragment);
t1 = space();
if (if_block) if_block.c();
attr(div, "class", "pane svelte-1dhkl71");
attr(div, "role", "region");
attr(div, "aria-label", /*pane*/ ctx[2]);
attr(div, "tabindex", "-1");
attr(section, "aria-label", "boardgame.io Debug Panel");
attr(section, "class", "debug-panel svelte-1dhkl71");
},
m(target, anchor) {
insert(target, section, anchor);
mount_component(menu, section, null);
append(section, t0);
append(section, div);
if (switch_instance) {
mount_component(switch_instance, div, null);
}
/*div_binding*/ ctx[10](div);
append(section, t1);
if (if_block) if_block.m(section, null);
current = true;
},
p(ctx, dirty) {
const menu_changes = {};
if (dirty & /*pane*/ 4) menu_changes.pane = /*pane*/ ctx[2];
menu.$set(menu_changes);
const switch_instance_changes = {};
if (dirty & /*client*/ 16) switch_instance_changes.client = /*client*/ ctx[4];
if (dirty & /*clientManager*/ 1) switch_instance_changes.clientManager = /*clientManager*/ ctx[0];
if (switch_value !== (switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component)) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, div, null);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
if (!current || dirty & /*pane*/ 4) {
attr(div, "aria-label", /*pane*/ ctx[2]);
}
if (/*$secondaryPane*/ ctx[5]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*$secondaryPane*/ 32) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$7(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(section, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(menu.$$.fragment, local);
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
transition_in(if_block);
add_render_callback(() => {
if (!section_transition) section_transition = create_bidirectional_transition(section, fly, { x: 400 }, true);
section_transition.run(1);
});
current = true;
},
o(local) {
transition_out(menu.$$.fragment, local);
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
transition_out(if_block);
if (!section_transition) section_transition = create_bidirectional_transition(section, fly, { x: 400 }, false);
section_transition.run(0);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(menu);
if (switch_instance) destroy_component(switch_instance);
/*div_binding*/ ctx[10](null);
if (if_block) if_block.d();
if (detaching && section_transition) section_transition.end();
}
};
}
// (130:4) {#if $secondaryPane}
function create_if_block_1$7(ctx) {
let div;
let switch_instance;
let current;
var switch_value = /*$secondaryPane*/ ctx[5].component;
function switch_props(ctx) {
return {
props: {
metadata: /*$secondaryPane*/ ctx[5].metadata
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
div = element("div");
if (switch_instance) create_component(switch_instance.$$.fragment);
attr(div, "class", "secondary-pane svelte-1dhkl71");
},
m(target, anchor) {
insert(target, div, anchor);
if (switch_instance) {
mount_component(switch_instance, div, null);
}
current = true;
},
p(ctx, dirty) {
const switch_instance_changes = {};
if (dirty & /*$secondaryPane*/ 32) switch_instance_changes.metadata = /*$secondaryPane*/ ctx[5].metadata;
if (switch_value !== (switch_value = /*$secondaryPane*/ ctx[5].component)) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, div, null);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
if (switch_instance) destroy_component(switch_instance);
}
};
}
function create_fragment$y(ctx) {
let if_block_anchor;
let current;
let mounted;
let dispose;
let if_block = /*visible*/ ctx[3] && create_if_block$e(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
if (!mounted) {
dispose = listen(window, "keypress", /*Keypress*/ ctx[9]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*visible*/ ctx[3]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*visible*/ 8) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$e(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
mounted = false;
dispose();
}
};
}
function instance$y($$self, $$props, $$invalidate) {
let $clientManager,
$$unsubscribe_clientManager = noop,
$$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(11, $clientManager = $$value)), clientManager);
let $secondaryPane;
$$self.$$.on_destroy.push(() => $$unsubscribe_clientManager());
let { clientManager } = $$props;
$$subscribe_clientManager();
const panes = {
main: {
label: "Main",
shortcut: "m",
component: Main
},
log: {
label: "Log",
shortcut: "l",
component: Log
},
info: {
label: "Info",
shortcut: "i",
component: Info
},
ai: {
label: "AI",
shortcut: "a",
component: AI
}
};
const disableHotkeys = writable(false);
const secondaryPane = writable(null);
component_subscribe($$self, secondaryPane, value => $$invalidate(5, $secondaryPane = value));
setContext("hotkeys", { disableHotkeys });
setContext("secondaryPane", { secondaryPane });
let paneDiv;
let pane = "main";
function MenuChange(e) {
$$invalidate(2, pane = e.detail);
paneDiv.focus();
}
let visible = true;
function Keypress(e) {
// Toggle debugger visibilty
if (e.key == ".") {
$$invalidate(3, visible = !visible);
return;
}
// Set displayed pane
if (!visible) return;
Object.entries(panes).forEach(([key, { shortcut }]) => {
if (e.key == shortcut) {
$$invalidate(2, pane = key);
}
});
}
function div_binding($$value) {
binding_callbacks[$$value ? "unshift" : "push"](() => {
paneDiv = $$value;
$$invalidate(1, paneDiv);
});
}
$$self.$set = $$props => {
if ("clientManager" in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager));
};
let client;
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$clientManager*/ 2048) {
$: $$invalidate(4, client = $clientManager.client);
}
};
return [
clientManager,
paneDiv,
pane,
visible,
client,
$secondaryPane,
panes,
secondaryPane,
MenuChange,
Keypress,
div_binding
];
}
class Debug extends SvelteComponent {
constructor(options) {
super();
if (!document.getElementById("svelte-1dhkl71-style")) add_css$q();
init(this, options, instance$y, create_fragment$y, safe_not_equal, { clientManager: 0 });
}
}
/**
* Class to manage boardgame.io clients and limit debug panel rendering.
*/
class ClientManager {
constructor() {
this.debugPanel = null;
this.currentClient = null;
this.clients = new Map();
this.subscribers = new Map();
}
/**
* Register a client with the client manager.
*/
register(client) {
// Add client to clients map.
this.clients.set(client, client);
// Mount debug for this client (no-op if another debug is already mounted).
this.mountDebug(client);
this.notifySubscribers();
}
/**
* Unregister a client from the client manager.
*/
unregister(client) {
// Remove client from clients map.
this.clients.delete(client);
if (this.currentClient === client) {
// If the removed client owned the debug panel, unmount it.
this.unmountDebug();
// Mount debug panel for next available client.
for (const [client] of this.clients) {
if (this.debugPanel)
break;
this.mountDebug(client);
}
}
this.notifySubscribers();
}
/**
* Subscribe to the client manager state.
* Calls the passed callback each time the current client changes or a client
* registers/unregisters.
* Returns a function to unsubscribe from the state updates.
*/
subscribe(callback) {
const id = Symbol();
this.subscribers.set(id, callback);
callback(this.getState());
return () => {
this.subscribers.delete(id);
};
}
/**
* Switch to a client with a matching playerID.
*/
switchPlayerID(playerID) {
// For multiplayer clients, try switching control to a different client
// that is using the same transport layer.
if (this.currentClient.multiplayer) {
for (const [client] of this.clients) {
if (client.playerID === playerID &&
client.debugOpt !== false &&
client.multiplayer === this.currentClient.multiplayer) {
this.switchToClient(client);
return;
}
}
}
// If no client matches, update the playerID for the current client.
this.currentClient.updatePlayerID(playerID);
this.notifySubscribers();
}
/**
* Set the passed client as the active client for debugging.
*/
switchToClient(client) {
if (client === this.currentClient)
return;
this.unmountDebug();
this.mountDebug(client);
this.notifySubscribers();
}
/**
* Notify all subscribers of changes to the client manager state.
*/
notifySubscribers() {
const arg = this.getState();
this.subscribers.forEach((cb) => {
cb(arg);
});
}
/**
* Get the client manager state.
*/
getState() {
return {
client: this.currentClient,
debuggableClients: this.getDebuggableClients(),
};
}
/**
* Get an array of the registered clients that haven’t disabled the debug panel.
*/
getDebuggableClients() {
return [...this.clients.values()].filter((client) => client.debugOpt !== false);
}
/**
* Mount the debug panel using the passed client.
*/
mountDebug(client) {
if (client.debugOpt === false ||
this.debugPanel !== null ||
typeof document === 'undefined') {
return;
}
let DebugImpl;
let target = document.body;
if (process.env.NODE_ENV !== 'production') {
DebugImpl = Debug;
}
if (client.debugOpt && client.debugOpt !== true) {
DebugImpl = client.debugOpt.impl || DebugImpl;
target = client.debugOpt.target || target;
}
if (DebugImpl) {
this.currentClient = client;
this.debugPanel = new DebugImpl({
target,
props: { clientManager: this },
});
}
}
/**
* Unmount the debug panel.
*/
unmountDebug() {
this.debugPanel.$destroy();
this.debugPanel = null;
this.currentClient = null;
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Global client manager instance that all clients register with.
*/
const GlobalClientManager = new ClientManager();
/**
* Standardise the passed playerID, using currentPlayer if appropriate.
*/
function assumedPlayerID(playerID, store, multiplayer) {
// In singleplayer mode, if the client does not have a playerID
// associated with it, we attach the currentPlayer as playerID.
if (!multiplayer && (playerID === null || playerID === undefined)) {
const state = store.getState();
playerID = state.ctx.currentPlayer;
}
return playerID;
}
/**
* createDispatchers
*
* Create action dispatcher wrappers with bound playerID and credentials
*/
function createDispatchers(storeActionType, innerActionNames, store, playerID, credentials, multiplayer) {
return innerActionNames.reduce((dispatchers, name) => {
dispatchers[name] = function (...args) {
store.dispatch(ActionCreators[storeActionType](name, args, assumedPlayerID(playerID, store, multiplayer), credentials));
};
return dispatchers;
}, {});
}
// Creates a set of dispatchers to make moves.
const createMoveDispatchers = createDispatchers.bind(null, 'makeMove');
// Creates a set of dispatchers to dispatch game flow events.
const createEventDispatchers = createDispatchers.bind(null, 'gameEvent');
// Creates a set of dispatchers to dispatch actions to plugins.
const createPluginDispatchers = createDispatchers.bind(null, 'plugin');
/**
* Implementation of Client (see below).
*/
class _ClientImpl {
constructor({ game, debug, numPlayers, multiplayer, matchID: matchID, playerID, credentials, enhancer, }) {
this.game = ProcessGameConfig(game);
this.playerID = playerID;
this.matchID = matchID;
this.credentials = credentials;
this.multiplayer = multiplayer;
this.debugOpt = debug;
this.manager = GlobalClientManager;
this.gameStateOverride = null;
this.subscribers = {};
this._running = false;
this.reducer = CreateGameReducer({
game: this.game,
isClient: multiplayer !== undefined,
});
this.initialState = null;
if (!multiplayer) {
this.initialState = InitializeGame({ game: this.game, numPlayers });
}
this.reset = () => {
this.store.dispatch(reset(this.initialState));
};
this.undo = () => {
const undo$1 = undo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials);
this.store.dispatch(undo$1);
};
this.redo = () => {
const redo$1 = redo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials);
this.store.dispatch(redo$1);
};
this.log = [];
/**
* Middleware that manages the log object.
* Reducers generate deltalogs, which are log events
* that are the result of application of a single action.
* The master may also send back a deltalog or the entire
* log depending on the type of request.
* The middleware below takes care of all these cases while
* managing the log object.
*/
const LogMiddleware = (store) => (next) => (action) => {
const result = next(action);
const state = store.getState();
switch (action.type) {
case MAKE_MOVE:
case GAME_EVENT:
case UNDO:
case REDO: {
const deltalog = state.deltalog;
this.log = [...this.log, ...deltalog];
break;
}
case RESET: {
this.log = [];
break;
}
case UPDATE: {
let id = -1;
if (this.log.length > 0) {
id = this.log[this.log.length - 1]._stateID;
}
let deltalog = action.deltalog || [];
// Filter out actions that are already present
// in the current log. This may occur when the
// client adds an entry to the log followed by
// the update from the master here.
deltalog = deltalog.filter((l) => l._stateID > id);
this.log = [...this.log, ...deltalog];
break;
}
case SYNC: {
this.initialState = action.initialState;
this.log = action.log || [];
break;
}
}
return result;
};
/**
* Middleware that intercepts actions and sends them to the master,
* which keeps the authoritative version of the state.
*/
const TransportMiddleware = (store) => (next) => (action) => {
const baseState = store.getState();
const result = next(action);
if (!('clientOnly' in action)) {
this.transport.onAction(baseState, action);
}
return result;
};
/**
* Middleware that intercepts actions and invokes the subscription callback.
*/
const SubscriptionMiddleware = () => (next) => (action) => {
const result = next(action);
this.notifySubscribers();
return result;
};
const middleware = applyMiddleware(SubscriptionMiddleware, TransportMiddleware, LogMiddleware);
enhancer =
enhancer !== undefined ? compose(middleware, enhancer) : middleware;
this.store = createStore(this.reducer, this.initialState, enhancer);
this.transport = {
isConnected: true,
onAction: () => { },
subscribe: () => { },
subscribeMatchData: () => { },
subscribeChatMessage: () => { },
connect: () => { },
disconnect: () => { },
updateMatchID: () => { },
updatePlayerID: () => { },
};
if (multiplayer) {
// typeof multiplayer is 'function'
this.transport = multiplayer({
gameKey: game,
game: this.game,
store: this.store,
matchID,
playerID,
credentials,
gameName: this.game.name,
numPlayers,
});
}
this.createDispatchers();
this.transport.subscribeMatchData((metadata) => {
this.matchData = metadata;
this.notifySubscribers();
});
if (this.transport.onChatMessage) {
this.chatMessages = [];
this.sendChatMessage = (payload) => {
this.transport.onChatMessage(this.matchID, {
id: nanoid(7),
sender: this.playerID,
payload: payload,
});
};
this.transport.subscribeChatMessage((message) => {
this.chatMessages = [...this.chatMessages, message];
this.notifySubscribers();
});
}
}
notifySubscribers() {
Object.values(this.subscribers).forEach((fn) => fn(this.getState()));
}
overrideGameState(state) {
this.gameStateOverride = state;
this.notifySubscribers();
}
start() {
this.transport.connect();
this._running = true;
this.manager.register(this);
}
stop() {
this.transport.disconnect();
this._running = false;
this.manager.unregister(this);
}
subscribe(fn) {
const id = Object.keys(this.subscribers).length;
this.subscribers[id] = fn;
this.transport.subscribe(() => this.notifySubscribers());
if (this._running || !this.multiplayer) {
fn(this.getState());
}
// Return a handle that allows the caller to unsubscribe.
return () => {
delete this.subscribers[id];
};
}
getInitialState() {
return this.initialState;
}
getState() {
let state = this.store.getState();
if (this.gameStateOverride !== null) {
state = this.gameStateOverride;
}
// This is the state before a sync with the game master.
if (state === null) {
return state;
}
// isActive.
let isActive = true;
const isPlayerActive = this.game.flow.isPlayerActive(state.G, state.ctx, this.playerID);
if (this.multiplayer && !isPlayerActive) {
isActive = false;
}
if (!this.multiplayer &&
this.playerID !== null &&
this.playerID !== undefined &&
!isPlayerActive) {
isActive = false;
}
if (state.ctx.gameover !== undefined) {
isActive = false;
}
// Secrets are normally stripped on the server,
// but we also strip them here so that game developers
// can see their effects while prototyping.
// Do not strip again if this is a multiplayer game
// since the server has already stripped secret info. (issue #818)
if (!this.multiplayer) {
state = {
...state,
G: this.game.playerView(state.G, state.ctx, this.playerID),
plugins: PlayerView(state, this),
};
}
// Combine into return value.
return {
...state,
log: this.log,
isActive,
isConnected: this.transport.isConnected,
};
}
createDispatchers() {
this.moves = createMoveDispatchers(this.game.moveNames, this.store, this.playerID, this.credentials, this.multiplayer);
this.events = createEventDispatchers(this.game.flow.enabledEventNames, this.store, this.playerID, this.credentials, this.multiplayer);
this.plugins = createPluginDispatchers(this.game.pluginNames, this.store, this.playerID, this.credentials, this.multiplayer);
}
updatePlayerID(playerID) {
this.playerID = playerID;
this.createDispatchers();
this.transport.updatePlayerID(playerID);
this.notifySubscribers();
}
updateMatchID(matchID) {
this.matchID = matchID;
this.createDispatchers();
this.transport.updateMatchID(matchID);
this.notifySubscribers();
}
updateCredentials(credentials) {
this.credentials = credentials;
this.createDispatchers();
this.transport.updateCredentials(credentials);
this.notifySubscribers();
}
}
/**
* Client
*
* boardgame.io JS client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} matchID - The matchID that you want to connect to.
* @param {...object} playerID - The playerID associated with this client.
* @param {...string} credentials - The authentication credentials associated with this client.
*
* Returns:
* A JS object that provides an API to interact with the
* game by dispatching moves and events.
*/
function Client(opts) {
return new _ClientImpl(opts);
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Client
*
* boardgame.io React client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} debug - Enables the Debug UI.
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET,
* UNDO and REDO.
*/
function Client$1(opts) {
var _a;
let { game, numPlayers, loading, board, multiplayer, enhancer, debug } = opts;
// Component that is displayed before the client has synced
// with the game master.
if (loading === undefined) {
const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting...");
loading = Loading;
}
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _a = class WrappedBoard extends React.Component {
constructor(props) {
super(props);
if (debug === undefined) {
debug = props.debug;
}
this.client = Client({
game,
debug,
numPlayers,
multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
enhancer,
});
}
componentDidMount() {
this.unsubscribe = this.client.subscribe(() => this.forceUpdate());
this.client.start();
}
componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
componentDidUpdate(prevProps) {
if (this.props.matchID != prevProps.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (this.props.playerID != prevProps.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (this.props.credentials != prevProps.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
render() {
const state = this.client.getState();
if (state === null) {
return React.createElement(loading);
}
let _board = null;
if (board) {
_board = React.createElement(board, {
...state,
...this.props,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
matchID: this.client.matchID,
playerID: this.client.playerID,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
log: this.client.log,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages,
});
}
return React.createElement("div", { className: "bgio-client" }, _board);
}
},
_a.propTypes = {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string,
// Enable / disable the Debug UI.
debug: PropTypes.any,
},
_a.defaultProps = {
matchID: 'default',
playerID: null,
credentials: null,
debug: true,
},
_a;
}
/**
* Client
*
* boardgame.io React Native client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React Native component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE.
*/
function Client$2(opts) {
var _class, _temp;
var game = opts.game,
numPlayers = opts.numPlayers,
board = opts.board,
multiplayer = opts.multiplayer,
enhancer = opts.enhancer;
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _temp = _class = /*#__PURE__*/function (_React$Component) {
_inherits(WrappedBoard, _React$Component);
var _super = _createSuper(WrappedBoard);
function WrappedBoard(props) {
var _this;
_classCallCheck(this, WrappedBoard);
_this = _super.call(this, props);
_this.client = Client({
game: game,
numPlayers: numPlayers,
multiplayer: multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
debug: false,
enhancer: enhancer
});
return _this;
}
_createClass(WrappedBoard, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
this.unsubscribe = this.client.subscribe(function () {
return _this2.forceUpdate();
});
this.client.start();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.matchID != this.props.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (prevProps.playerID != this.props.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (prevProps.credentials != this.props.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
}, {
key: "render",
value: function render() {
var _board = null;
var state = this.client.getState();
var _this$props = this.props,
matchID = _this$props.matchID,
playerID = _this$props.playerID,
rest = _objectWithoutProperties(_this$props, ["matchID", "playerID"]);
if (board) {
_board = /*#__PURE__*/React.createElement(board, _objectSpread2(_objectSpread2(_objectSpread2({}, state), rest), {}, {
matchID: matchID,
playerID: playerID,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
step: this.client.step,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages
}));
}
return _board;
}
}]);
return WrappedBoard;
}(React.Component), _defineProperty(_class, "propTypes", {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string
}), _defineProperty(_class, "defaultProps", {
matchID: 'default',
playerID: null,
credentials: null
}), _temp;
}
var Type;
(function (Type) {
Type[Type["SYNC"] = 0] = "SYNC";
Type[Type["ASYNC"] = 1] = "ASYNC";
})(Type || (Type = {}));
/**
* Type guard that checks if a storage implementation is synchronous.
*/
function isSynchronous(storageAPI) {
return storageAPI.type() === Type.SYNC;
}
class Sync {
type() {
return Type.SYNC;
}
/**
* Connect.
*/
connect() {
return;
}
/**
* Create a new match.
*
* This might just need to call setState and setMetadata in
* most implementations.
*
* However, it exists as a separate call so that the
* implementation can provision things differently when
* a match is created. For example, it might stow away the
* initial match state in a separate field for easier retrieval.
*/
/* istanbul ignore next */
createMatch(matchID, opts) {
if (this.createGame) {
console.warn('The database connector does not implement a createMatch method.', '\nUsing the deprecated createGame method instead.');
return this.createGame(matchID, opts);
}
else {
console.error('The database connector does not implement a createMatch method.');
}
}
/**
* Return all matches.
*/
/* istanbul ignore next */
listMatches(opts) {
if (this.listGames) {
console.warn('The database connector does not implement a listMatches method.', '\nUsing the deprecated listGames method instead.');
return this.listGames(opts);
}
else {
console.error('The database connector does not implement a listMatches method.');
}
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* InMemory data storage.
*/
class InMemory extends Sync {
/**
* Creates a new InMemory storage.
*/
constructor() {
super();
this.state = new Map();
this.initial = new Map();
this.metadata = new Map();
this.log = new Map();
}
/**
* Create a new match.
*
* @override
*/
createMatch(matchID, opts) {
this.initial.set(matchID, opts.initialState);
this.setState(matchID, opts.initialState);
this.setMetadata(matchID, opts.metadata);
}
/**
* Write the match metadata to the in-memory object.
*/
setMetadata(matchID, metadata) {
this.metadata.set(matchID, metadata);
}
/**
* Write the match state to the in-memory object.
*/
setState(matchID, state, deltalog) {
if (deltalog && deltalog.length > 0) {
const log = this.log.get(matchID) || [];
this.log.set(matchID, log.concat(deltalog));
}
this.state.set(matchID, state);
}
/**
* Fetches state for a particular matchID.
*/
fetch(matchID, opts) {
const result = {};
if (opts.state) {
result.state = this.state.get(matchID);
}
if (opts.metadata) {
result.metadata = this.metadata.get(matchID);
}
if (opts.log) {
result.log = this.log.get(matchID) || [];
}
if (opts.initialState) {
result.initialState = this.initial.get(matchID);
}
return result;
}
/**
* Remove the match state from the in-memory object.
*/
wipe(matchID) {
this.state.delete(matchID);
this.metadata.delete(matchID);
}
/**
* Return all keys.
*
* @override
*/
listMatches(opts) {
return [...this.metadata.entries()]
.filter(([, metadata]) => {
if (!opts) {
return true;
}
if (opts.gameName !== undefined &&
metadata.gameName !== opts.gameName) {
return false;
}
if (opts.where !== undefined) {
if (opts.where.isGameover !== undefined) {
const isGameover = metadata.gameover !== undefined;
if (isGameover !== opts.where.isGameover) {
return false;
}
}
if (opts.where.updatedBefore !== undefined &&
metadata.updatedAt >= opts.where.updatedBefore) {
return false;
}
if (opts.where.updatedAfter !== undefined &&
metadata.updatedAt <= opts.where.updatedAfter) {
return false;
}
}
return true;
})
.map(([key]) => key);
}
}
class WithLocalStorageMap extends Map {
constructor(key) {
super();
this.key = key;
const cache = JSON.parse(localStorage.getItem(this.key)) || [];
cache.forEach((entry) => this.set(...entry));
}
sync() {
const entries = [...this.entries()];
localStorage.setItem(this.key, JSON.stringify(entries));
}
set(key, value) {
super.set(key, value);
this.sync();
return this;
}
delete(key) {
const result = super.delete(key);
this.sync();
return result;
}
}
/**
* locaStorage data storage.
*/
class LocalStorage extends InMemory {
constructor(storagePrefix = 'bgio') {
super();
const StorageMap = (stateKey) => new WithLocalStorageMap(`${storagePrefix}_${stateKey}`);
this.state = StorageMap('state');
this.initial = StorageMap('initial');
this.metadata = StorageMap('metadata');
this.log = StorageMap('log');
}
}
/**
* Creates a new match metadata object.
*/
const createMetadata = ({ game, unlisted, setupData, numPlayers, }) => {
const metadata = {
gameName: game.name,
unlisted: !!unlisted,
players: {},
createdAt: Date.now(),
updatedAt: Date.now(),
};
if (setupData !== undefined)
metadata.setupData = setupData;
for (let playerIndex = 0; playerIndex < numPlayers; playerIndex++) {
metadata.players[playerIndex] = { id: playerIndex };
}
return metadata;
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Filter match data to get a player metadata object with credentials stripped.
*/
const filterMatchData = (matchData) => Object.values(matchData.players).map((player) => {
const { credentials, ...filteredData } = player;
return filteredData;
});
/**
* Redact the log.
*
* @param {Array} log - The game log (or deltalog).
* @param {String} playerID - The playerID that this log is
* to be sent to.
*/
function redactLog(log, playerID) {
if (log === undefined) {
return log;
}
return log.map((logEvent) => {
// filter for all other players and spectators.
if (playerID !== null && +playerID === +logEvent.action.payload.playerID) {
return logEvent;
}
if (logEvent.redact !== true) {
return logEvent;
}
const payload = {
...logEvent.action.payload,
args: null,
};
const filteredEvent = {
...logEvent,
action: { ...logEvent.action, payload },
};
const { redact, ...remaining } = filteredEvent;
return remaining;
});
}
/**
* Remove player credentials from action payload
*/
const stripCredentialsFromAction = (action) => {
const { credentials, ...payload } = action.payload;
return { ...action, payload };
};
/**
* Master
*
* Class that runs the game and maintains the authoritative state.
* It uses the transportAPI to communicate with clients and the
* storageAPI to communicate with the database.
*/
class Master {
constructor(game, storageAPI, transportAPI, auth) {
this.game = ProcessGameConfig(game);
this.storageAPI = storageAPI;
this.transportAPI = transportAPI;
this.subscribeCallback = () => { };
this.auth = auth;
}
subscribe(fn) {
this.subscribeCallback = fn;
}
/**
* Called on each move / event made by the client.
* Computes the new value of the game state and returns it
* along with a deltalog.
*/
async onUpdate(credAction, stateID, matchID, playerID) {
let metadata;
if (isSynchronous(this.storageAPI)) {
({ metadata } = this.storageAPI.fetch(matchID, { metadata: true }));
}
else {
({ metadata } = await this.storageAPI.fetch(matchID, { metadata: true }));
}
if (this.auth) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials: credAction.payload.credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized action' };
}
}
const action = stripCredentialsFromAction(credAction);
const key = matchID;
let state;
if (isSynchronous(this.storageAPI)) {
({ state } = this.storageAPI.fetch(key, { state: true }));
}
else {
({ state } = await this.storageAPI.fetch(key, { state: true }));
}
if (state === undefined) {
error(`game not found, matchID=[${key}]`);
return { error: 'game not found' };
}
if (state.ctx.gameover !== undefined) {
error(`game over - matchID=[${key}] - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
const reducer = CreateGameReducer({
game: this.game,
});
const store = createStore(reducer, state);
// Only allow UNDO / REDO if there is exactly one player
// that can make moves right now and the person doing the
// action is that player.
if (action.type == UNDO || action.type == REDO) {
const hasActivePlayers = state.ctx.activePlayers !== null;
const isCurrentPlayer = state.ctx.currentPlayer === playerID;
if (
// If activePlayers is empty, non-current players can’t undo.
(!hasActivePlayers && !isCurrentPlayer) ||
// If player is not active or multiple players are active, can’t undo.
(hasActivePlayers &&
(state.ctx.activePlayers[playerID] === undefined ||
Object.keys(state.ctx.activePlayers).length > 1))) {
error(`playerID=[${playerID}] cannot undo / redo right now`);
return;
}
}
// Check whether the player is active.
if (!this.game.flow.isPlayerActive(state.G, state.ctx, playerID)) {
error(`player not active - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
// Get move for further checkings
const move = action.type == MAKE_MOVE
? this.game.flow.getMove(state.ctx, action.payload.type, playerID)
: null;
// Check whether the player is allowed to make the move.
if (action.type == MAKE_MOVE && !move) {
error(`move not processed - canPlayerMakeMove=false - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
// Check if action's stateID is different than store's stateID
// and if move does not have ignoreStaleStateID truthy.
if (state._stateID !== stateID &&
!(move && IsLongFormMove(move) && move.ignoreStaleStateID)) {
error(`invalid stateID, was=[${stateID}], expected=[${state._stateID}]` +
` - playerID=[${playerID}] - action[${action.payload.type}]`);
return;
}
// Update server's version of the store.
store.dispatch(action);
state = store.getState();
this.subscribeCallback({
state,
action,
matchID,
});
this.transportAPI.sendAll((playerID) => {
const filteredState = {
...state,
G: this.game.playerView(state.G, state.ctx, playerID),
plugins: PlayerView(state, { playerID, game: this.game }),
deltalog: undefined,
_undo: [],
_redo: [],
};
const log = redactLog(state.deltalog, playerID);
return {
type: 'update',
args: [matchID, filteredState, log],
};
});
const { deltalog, ...stateWithoutDeltalog } = state;
let newMetadata;
if (metadata && !('gameover' in metadata)) {
newMetadata = {
...metadata,
updatedAt: Date.now(),
};
if (state.ctx.gameover !== undefined) {
newMetadata.gameover = state.ctx.gameover;
}
}
if (isSynchronous(this.storageAPI)) {
this.storageAPI.setState(key, stateWithoutDeltalog, deltalog);
if (newMetadata)
this.storageAPI.setMetadata(key, newMetadata);
}
else {
const writes = [
this.storageAPI.setState(key, stateWithoutDeltalog, deltalog),
];
if (newMetadata) {
writes.push(this.storageAPI.setMetadata(key, newMetadata));
}
await Promise.all(writes);
}
}
/**
* Called when the client connects / reconnects.
* Returns the latest game state and the entire log.
*/
async onSync(matchID, playerID, credentials, numPlayers = 2) {
const key = matchID;
const fetchOpts = {
state: true,
metadata: true,
log: true,
initialState: true,
};
const fetchResult = isSynchronous(this.storageAPI)
? this.storageAPI.fetch(key, fetchOpts)
: await this.storageAPI.fetch(key, fetchOpts);
let { state, initialState, log, metadata } = fetchResult;
if (this.auth && playerID !== undefined && playerID !== null) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
// If the game doesn't exist, then create one on demand.
// TODO: Move this out of the sync call.
if (state === undefined) {
initialState = state = InitializeGame({ game: this.game, numPlayers });
metadata = createMetadata({
game: this.game,
unlisted: true,
numPlayers,
});
this.subscribeCallback({ state, matchID });
if (isSynchronous(this.storageAPI)) {
this.storageAPI.createMatch(key, { initialState, metadata });
}
else {
await this.storageAPI.createMatch(key, { initialState, metadata });
}
}
const filteredMetadata = metadata ? filterMatchData(metadata) : undefined;
const filteredState = {
...state,
G: this.game.playerView(state.G, state.ctx, playerID),
plugins: PlayerView(state, { playerID, game: this.game }),
deltalog: undefined,
_undo: [],
_redo: [],
};
log = redactLog(log, playerID);
const syncInfo = {
state: filteredState,
log,
filteredMetadata,
initialState,
};
this.transportAPI.send({
playerID,
type: 'sync',
args: [matchID, syncInfo],
});
return;
}
/**
* Called when a client connects or disconnects.
* Updates and sends out metadata to reflect the player’s connection status.
*/
async onConnectionChange(matchID, playerID, credentials, connected) {
const key = matchID;
// Ignore changes for clients without a playerID, e.g. spectators.
if (playerID === undefined || playerID === null) {
return;
}
let metadata;
if (isSynchronous(this.storageAPI)) {
({ metadata } = this.storageAPI.fetch(key, { metadata: true }));
}
else {
({ metadata } = await this.storageAPI.fetch(key, { metadata: true }));
}
if (metadata === undefined) {
error(`metadata not found for matchID=[${key}]`);
return { error: 'metadata not found' };
}
if (metadata.players[playerID] === undefined) {
error(`Player not in the match, matchID=[${key}] playerID=[${playerID}]`);
return { error: 'player not in the match' };
}
if (this.auth) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
metadata.players[playerID].isConnected = connected;
const filteredMetadata = filterMatchData(metadata);
this.transportAPI.sendAll(() => ({
type: 'matchData',
args: [matchID, filteredMetadata],
}));
if (isSynchronous(this.storageAPI)) {
this.storageAPI.setMetadata(key, metadata);
}
else {
await this.storageAPI.setMetadata(key, metadata);
}
}
async onChatMessage(matchID, chatMessage, credentials) {
const key = matchID;
if (this.auth) {
const { metadata } = await this.storageAPI.fetch(key, {
metadata: true,
});
const isAuthentic = await this.auth.authenticateCredentials({
playerID: chatMessage.sender,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
this.transportAPI.sendAll(() => ({
type: 'chat',
args: [matchID, chatMessage],
}));
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
class Transport {
constructor({ store, gameName, playerID, matchID, credentials, numPlayers, }) {
this.store = store;
this.gameName = gameName || 'default';
this.playerID = playerID || null;
this.matchID = matchID || 'default';
this.credentials = credentials;
this.numPlayers = numPlayers || 2;
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Returns null if it is not a bot's turn.
* Otherwise, returns a playerID of a bot that may play now.
*/
function GetBotPlayer(state, bots) {
if (state.ctx.gameover !== undefined) {
return null;
}
if (state.ctx.activePlayers) {
for (const key of Object.keys(bots)) {
if (key in state.ctx.activePlayers) {
return key;
}
}
}
else if (state.ctx.currentPlayer in bots) {
return state.ctx.currentPlayer;
}
return null;
}
/**
* Creates a local version of the master that the client
* can interact with.
*/
class LocalMaster extends Master {
constructor({ game, bots, storageKey, persist }) {
const clientCallbacks = {};
const initializedBots = {};
if (game && game.ai && bots) {
for (const playerID in bots) {
const bot = bots[playerID];
initializedBots[playerID] = new bot({
game,
enumerate: game.ai.enumerate,
seed: game.seed,
});
}
}
const send = ({ playerID, ...data }) => {
const callback = clientCallbacks[playerID];
if (callback !== undefined) {
callback(data);
}
};
const transportAPI = {
send,
sendAll: (makePlayerData) => {
for (const playerID in clientCallbacks) {
const data = makePlayerData(playerID);
send({ playerID, ...data });
}
},
};
const storage = persist ? new LocalStorage(storageKey) : new InMemory();
super(game, storage, transportAPI);
this.connect = (matchID, playerID, callback) => {
clientCallbacks[playerID] = callback;
};
this.subscribe(({ state, matchID }) => {
if (!bots) {
return;
}
const botPlayer = GetBotPlayer(state, initializedBots);
if (botPlayer !== null) {
setTimeout(async () => {
const botAction = await initializedBots[botPlayer].play(state, botPlayer);
await this.onUpdate(botAction.action, state._stateID, matchID, botAction.action.payload.playerID);
}, 100);
}
});
}
}
/**
* Local
*
* Transport interface that embeds a GameMaster within it
* that you can connect multiple clients to.
*/
class LocalTransport extends Transport {
/**
* Creates a new Mutiplayer instance.
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
*/
constructor({ master, store, matchID, playerID, credentials, gameName, numPlayers, }) {
super({ store, gameName, playerID, matchID, credentials, numPlayers });
this.master = master;
this.isConnected = true;
}
/**
* Called when any player sends a chat message and the
* master broadcasts the update to other clients (including
* this one).
*/
onChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.master.onChatMessage(...args);
}
/**
* Called when another player makes a move and the
* master broadcasts the update to other clients (including
* this one).
*/
async onUpdate(matchID, state, deltalog) {
const currentState = this.store.getState();
if (matchID == this.matchID && state._stateID >= currentState._stateID) {
const action = update$1(state, deltalog);
this.store.dispatch(action);
}
}
/**
* Called when the client first connects to the master
* and requests the current game state.
*/
onSync(matchID, syncInfo) {
if (matchID == this.matchID) {
const action = sync(syncInfo);
this.store.dispatch(action);
}
}
/**
* Called when an action that has to be relayed to the
* game master is made.
*/
onAction(state, action) {
this.master.onUpdate(action, state._stateID, this.matchID, this.playerID);
}
/**
* Connect to the master.
*/
connect() {
this.master.connect(this.matchID, this.playerID, (data) => {
switch (data.type) {
case 'sync':
return this.onSync(...data.args);
case 'update':
return this.onUpdate(...data.args);
case 'chat':
return this.chatMessageCallback(data.args[1]);
}
});
this.master.onSync(this.matchID, this.playerID, this.credentials, this.numPlayers);
}
/**
* Disconnect from the master.
*/
disconnect() { }
/**
* Subscribe to connection state changes.
*/
subscribe() { }
subscribeMatchData() { }
subscribeChatMessage(fn) {
this.chatMessageCallback = fn;
}
/**
* Dispatches a reset action, then requests a fresh sync from the master.
*/
resetAndSync() {
const action = reset(null);
this.store.dispatch(action);
this.connect();
}
/**
* Updates the game id.
* @param {string} id - The new game id.
*/
updateMatchID(id) {
this.matchID = id;
this.resetAndSync();
}
/**
* Updates the player associated with this client.
* @param {string} id - The new player id.
*/
updatePlayerID(id) {
this.playerID = id;
this.resetAndSync();
}
/**
* Updates the credentials associated with this client.
* @param {string|undefined} credentials - The new credentials to use.
*/
updateCredentials(credentials) {
this.credentials = credentials;
this.resetAndSync();
}
}
/**
* Global map storing local master instances.
*/
const localMasters = new Map();
/**
* Create a local transport.
*/
function Local({ bots, persist, storageKey } = {}) {
return (transportOpts) => {
const { gameKey, game } = transportOpts;
let master;
const instance = localMasters.get(gameKey);
if (instance &&
instance.bots === bots &&
instance.storageKey === storageKey &&
instance.persist === persist) {
master = instance.master;
}
if (!master) {
master = new LocalMaster({ game, bots, persist, storageKey });
localMasters.set(gameKey, { master, bots, persist, storageKey });
}
return new LocalTransport({ master, ...transportOpts });
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const io = ioNamespace__default;
/**
* SocketIO
*
* Transport interface that interacts with the Master via socket.io.
*/
class SocketIOTransport extends Transport {
/**
* Creates a new Mutiplayer instance.
* @param {object} socket - Override for unit tests.
* @param {object} socketOpts - Options to pass to socket.io.
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
* @param {string} server - The game server in the form of 'hostname:port'. Defaults to the server serving the client if not provided.
*/
constructor({ socket, socketOpts, store, matchID, playerID, credentials, gameName, numPlayers, server, } = {}) {
super({ store, gameName, playerID, matchID, credentials, numPlayers });
this.server = server;
this.socket = socket;
this.socketOpts = socketOpts;
this.isConnected = false;
this.callback = () => { };
this.matchDataCallback = () => { };
this.chatMessageCallback = () => { };
}
/**
* Called when an action that has to be relayed to the
* game master is made.
*/
onAction(state, action) {
const args = [
action,
state._stateID,
this.matchID,
this.playerID,
];
this.socket.emit('update', ...args);
}
onChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.socket.emit('chat', ...args);
}
/**
* Connect to the server.
*/
connect() {
if (!this.socket) {
if (this.server) {
let server = this.server;
if (server.search(/^https?:\/\//) == -1) {
server = 'http://' + this.server;
}
if (server.slice(-1) != '/') {
// add trailing slash if not already present
server = server + '/';
}
this.socket = io(server + this.gameName, this.socketOpts);
}
else {
this.socket = io('/' + this.gameName, this.socketOpts);
}
}
// Called when another player makes a move and the
// master broadcasts the update to other clients (including
// this one).
this.socket.on('update', (matchID, state, deltalog) => {
const currentState = this.store.getState();
if (matchID == this.matchID &&
state._stateID >= currentState._stateID) {
const action = update$1(state, deltalog);
this.store.dispatch(action);
}
});
// Called when the client first connects to the master
// and requests the current game state.
this.socket.on('sync', (matchID, syncInfo) => {
if (matchID == this.matchID) {
const action = sync(syncInfo);
this.matchDataCallback(syncInfo.filteredMetadata);
this.store.dispatch(action);
}
});
// Called when new player joins the match or changes
// it's connection status
this.socket.on('matchData', (matchID, matchData) => {
if (matchID == this.matchID) {
this.matchDataCallback(matchData);
}
});
this.socket.on('chat', (matchID, chatMessage) => {
if (matchID === this.matchID) {
this.chatMessageCallback(chatMessage);
}
});
// Keep track of connection status.
this.socket.on('connect', () => {
// Initial sync to get game state.
this.sync();
this.isConnected = true;
this.callback();
});
this.socket.on('disconnect', () => {
this.isConnected = false;
this.callback();
});
}
/**
* Disconnect from the server.
*/
disconnect() {
this.socket.close();
this.socket = null;
this.isConnected = false;
this.callback();
}
/**
* Subscribe to connection state changes.
*/
subscribe(fn) {
this.callback = fn;
}
subscribeMatchData(fn) {
this.matchDataCallback = fn;
}
subscribeChatMessage(fn) {
this.chatMessageCallback = fn;
}
/**
* Send a “sync” event to the server.
*/
sync() {
if (this.socket) {
const args = [
this.matchID,
this.playerID,
this.credentials,
this.numPlayers,
];
this.socket.emit('sync', ...args);
}
}
/**
* Dispatches a reset action, then requests a fresh sync from the server.
*/
resetAndSync() {
const action = reset(null);
this.store.dispatch(action);
this.sync();
}
/**
* Updates the game id.
* @param {string} id - The new game id.
*/
updateMatchID(id) {
this.matchID = id;
this.resetAndSync();
}
/**
* Updates the player associated with this client.
* @param {string} id - The new player id.
*/
updatePlayerID(id) {
this.playerID = id;
this.resetAndSync();
}
/**
* Updates the credentials associated with this client.
* @param {string|undefined} credentials - The new credentials to use.
*/
updateCredentials(credentials) {
this.credentials = credentials;
this.resetAndSync();
}
}
function SocketIO({ server, socketOpts } = {}) {
return (transportOpts) => new SocketIOTransport({
server,
socketOpts,
...transportOpts,
});
}
export { Client, Local, MCTSBot, RandomBot, Client$1 as ReactClient, Client$2 as ReactNativeClient, Simulate, SocketIO, Step, TurnOrder };
|
ajax/libs/primereact/6.5.0-rc.1/ripple/ripple.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler } from 'primereact/utils';
import PrimeReact from 'primereact/api';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Ripple = /*#__PURE__*/function (_Component) {
_inherits(Ripple, _Component);
var _super = _createSuper(Ripple);
function Ripple(props) {
var _this;
_classCallCheck(this, Ripple);
_this = _super.call(this, props);
_this.onMouseDown = _this.onMouseDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(Ripple, [{
key: "getTarget",
value: function getTarget() {
return this.ink && this.ink.parentElement;
}
}, {
key: "bindEvents",
value: function bindEvents() {
if (this.target) {
this.target.addEventListener('mousedown', this.onMouseDown);
}
}
}, {
key: "unbindEvents",
value: function unbindEvents() {
if (this.target) {
this.target.removeEventListener('mousedown', this.onMouseDown);
}
}
}, {
key: "onMouseDown",
value: function onMouseDown(event) {
if (!this.ink || getComputedStyle(this.ink, null).display === 'none') {
return;
}
DomHandler.removeClass(this.ink, 'p-ink-active');
if (!DomHandler.getHeight(this.ink) && !DomHandler.getWidth(this.ink)) {
var d = Math.max(DomHandler.getOuterWidth(this.target), DomHandler.getOuterHeight(this.target));
this.ink.style.height = d + 'px';
this.ink.style.width = d + 'px';
}
var offset = DomHandler.getOffset(this.target);
var x = event.pageX - offset.left + document.body.scrollTop - DomHandler.getWidth(this.ink) / 2;
var y = event.pageY - offset.top + document.body.scrollLeft - DomHandler.getHeight(this.ink) / 2;
this.ink.style.top = y + 'px';
this.ink.style.left = x + 'px';
DomHandler.addClass(this.ink, 'p-ink-active');
}
}, {
key: "onAnimationEnd",
value: function onAnimationEnd(event) {
DomHandler.removeClass(event.currentTarget, 'p-ink-active');
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.ink) {
this.target = this.getTarget();
this.bindEvents();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
if (this.ink && !this.target) {
this.target = this.getTarget();
this.bindEvents();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.ink) {
this.target = null;
this.unbindEvents();
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
return PrimeReact.ripple && /*#__PURE__*/React.createElement("span", {
ref: function ref(el) {
return _this2.ink = el;
},
className: "p-ink",
onAnimationEnd: this.onAnimationEnd
});
}
}]);
return Ripple;
}(Component);
export { Ripple };
|
ajax/libs/boardgame-io/0.49.4/boardgameio.es.js | cdnjs/cdnjs | import { nanoid } from 'nanoid/non-secure';
import { applyMiddleware, compose, createStore } from 'redux';
import produce from 'immer';
import isPlainObject from 'lodash.isplainobject';
import { applyPatch, createPatch } from 'rfc6902';
import { stringify, parse } from 'flatted';
import 'setimmediate';
import React from 'react';
import PropTypes from 'prop-types';
import ioNamespace__default from 'socket.io-client';
function noop() { }
const identity = x => x;
function assign(tar, src) {
// @ts-ignore
for (const k in src)
tar[k] = src[k];
return tar;
}
function run(fn) {
return fn();
}
function blank_object() {
return Object.create(null);
}
function run_all(fns) {
fns.forEach(run);
}
function is_function(thing) {
return typeof thing === 'function';
}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}
function is_empty(obj) {
return Object.keys(obj).length === 0;
}
function subscribe(store, ...callbacks) {
if (store == null) {
return noop;
}
const unsub = store.subscribe(...callbacks);
return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
function component_subscribe(component, store, callback) {
component.$$.on_destroy.push(subscribe(store, callback));
}
function create_slot(definition, ctx, $$scope, fn) {
if (definition) {
const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
return definition[0](slot_ctx);
}
}
function get_slot_context(definition, ctx, $$scope, fn) {
return definition[1] && fn
? assign($$scope.ctx.slice(), definition[1](fn(ctx)))
: $$scope.ctx;
}
function get_slot_changes(definition, $$scope, dirty, fn) {
if (definition[2] && fn) {
const lets = definition[2](fn(dirty));
if ($$scope.dirty === undefined) {
return lets;
}
if (typeof lets === 'object') {
const merged = [];
const len = Math.max($$scope.dirty.length, lets.length);
for (let i = 0; i < len; i += 1) {
merged[i] = $$scope.dirty[i] | lets[i];
}
return merged;
}
return $$scope.dirty | lets;
}
return $$scope.dirty;
}
function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
if (slot_changes) {
const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
slot.p(slot_context, slot_changes);
}
}
function get_all_dirty_from_scope($$scope) {
if ($$scope.ctx.length > 32) {
const dirty = [];
const length = $$scope.ctx.length / 32;
for (let i = 0; i < length; i++) {
dirty[i] = -1;
}
return dirty;
}
return -1;
}
function exclude_internal_props(props) {
const result = {};
for (const k in props)
if (k[0] !== '$')
result[k] = props[k];
return result;
}
function null_to_empty(value) {
return value == null ? '' : value;
}
const is_client = typeof window !== 'undefined';
let now = is_client
? () => window.performance.now()
: () => Date.now();
let raf = is_client ? cb => requestAnimationFrame(cb) : noop;
const tasks = new Set();
function run_tasks(now) {
tasks.forEach(task => {
if (!task.c(now)) {
tasks.delete(task);
task.f();
}
});
if (tasks.size !== 0)
raf(run_tasks);
}
/**
* Creates a new task that runs on each raf frame
* until it returns a falsy value or is aborted
*/
function loop(callback) {
let task;
if (tasks.size === 0)
raf(run_tasks);
return {
promise: new Promise(fulfill => {
tasks.add(task = { c: callback, f: fulfill });
}),
abort() {
tasks.delete(task);
}
};
}
function append(target, node) {
target.appendChild(node);
}
function append_styles(target, style_sheet_id, styles) {
const append_styles_to = get_root_for_style(target);
if (!append_styles_to.getElementById(style_sheet_id)) {
const style = element('style');
style.id = style_sheet_id;
style.textContent = styles;
append_stylesheet(append_styles_to, style);
}
}
function get_root_for_style(node) {
if (!node)
return document;
const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
if (root.host) {
return root;
}
return document;
}
function append_empty_stylesheet(node) {
const style_element = element('style');
append_stylesheet(get_root_for_style(node), style_element);
return style_element;
}
function append_stylesheet(node, style) {
append(node.head || node, style);
}
function insert(target, node, anchor) {
target.insertBefore(node, anchor || null);
}
function detach(node) {
node.parentNode.removeChild(node);
}
function destroy_each(iterations, detaching) {
for (let i = 0; i < iterations.length; i += 1) {
if (iterations[i])
iterations[i].d(detaching);
}
}
function element(name) {
return document.createElement(name);
}
function svg_element(name) {
return document.createElementNS('http://www.w3.org/2000/svg', name);
}
function text(data) {
return document.createTextNode(data);
}
function space() {
return text(' ');
}
function empty() {
return text('');
}
function listen(node, event, handler, options) {
node.addEventListener(event, handler, options);
return () => node.removeEventListener(event, handler, options);
}
function stop_propagation(fn) {
return function (event) {
event.stopPropagation();
// @ts-ignore
return fn.call(this, event);
};
}
function attr(node, attribute, value) {
if (value == null)
node.removeAttribute(attribute);
else if (node.getAttribute(attribute) !== value)
node.setAttribute(attribute, value);
}
function to_number(value) {
return value === '' ? null : +value;
}
function children(element) {
return Array.from(element.childNodes);
}
function set_data(text, data) {
data = '' + data;
if (text.wholeText !== data)
text.data = data;
}
function set_input_value(input, value) {
input.value = value == null ? '' : value;
}
function select_option(select, value) {
for (let i = 0; i < select.options.length; i += 1) {
const option = select.options[i];
if (option.__value === value) {
option.selected = true;
return;
}
}
}
function select_value(select) {
const selected_option = select.querySelector(':checked') || select.options[0];
return selected_option && selected_option.__value;
}
function toggle_class(element, name, toggle) {
element.classList[toggle ? 'add' : 'remove'](name);
}
function custom_event(type, detail, bubbles = false) {
const e = document.createEvent('CustomEvent');
e.initCustomEvent(type, bubbles, false, detail);
return e;
}
const active_docs = new Set();
let active = 0;
// https://github.com/darkskyapp/string-hash/blob/master/index.js
function hash(str) {
let hash = 5381;
let i = str.length;
while (i--)
hash = ((hash << 5) - hash) ^ str.charCodeAt(i);
return hash >>> 0;
}
function create_rule(node, a, b, duration, delay, ease, fn, uid = 0) {
const step = 16.666 / duration;
let keyframes = '{\n';
for (let p = 0; p <= 1; p += step) {
const t = a + (b - a) * ease(p);
keyframes += p * 100 + `%{${fn(t, 1 - t)}}\n`;
}
const rule = keyframes + `100% {${fn(b, 1 - b)}}\n}`;
const name = `__svelte_${hash(rule)}_${uid}`;
const doc = get_root_for_style(node);
active_docs.add(doc);
const stylesheet = doc.__svelte_stylesheet || (doc.__svelte_stylesheet = append_empty_stylesheet(node).sheet);
const current_rules = doc.__svelte_rules || (doc.__svelte_rules = {});
if (!current_rules[name]) {
current_rules[name] = true;
stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length);
}
const animation = node.style.animation || '';
node.style.animation = `${animation ? `${animation}, ` : ''}${name} ${duration}ms linear ${delay}ms 1 both`;
active += 1;
return name;
}
function delete_rule(node, name) {
const previous = (node.style.animation || '').split(', ');
const next = previous.filter(name
? anim => anim.indexOf(name) < 0 // remove specific animation
: anim => anim.indexOf('__svelte') === -1 // remove all Svelte animations
);
const deleted = previous.length - next.length;
if (deleted) {
node.style.animation = next.join(', ');
active -= deleted;
if (!active)
clear_rules();
}
}
function clear_rules() {
raf(() => {
if (active)
return;
active_docs.forEach(doc => {
const stylesheet = doc.__svelte_stylesheet;
let i = stylesheet.cssRules.length;
while (i--)
stylesheet.deleteRule(i);
doc.__svelte_rules = {};
});
active_docs.clear();
});
}
let current_component;
function set_current_component(component) {
current_component = component;
}
function get_current_component() {
if (!current_component)
throw new Error('Function called outside component initialization');
return current_component;
}
function afterUpdate(fn) {
get_current_component().$$.after_update.push(fn);
}
function onDestroy(fn) {
get_current_component().$$.on_destroy.push(fn);
}
function createEventDispatcher() {
const component = get_current_component();
return (type, detail) => {
const callbacks = component.$$.callbacks[type];
if (callbacks) {
// TODO are there situations where events could be dispatched
// in a server (non-DOM) environment?
const event = custom_event(type, detail);
callbacks.slice().forEach(fn => {
fn.call(component, event);
});
}
};
}
function setContext(key, context) {
get_current_component().$$.context.set(key, context);
}
function getContext(key) {
return get_current_component().$$.context.get(key);
}
// TODO figure out if we still want to support
// shorthand events, or if we want to implement
// a real bubbling mechanism
function bubble(component, event) {
const callbacks = component.$$.callbacks[event.type];
if (callbacks) {
// @ts-ignore
callbacks.slice().forEach(fn => fn.call(this, event));
}
}
const dirty_components = [];
const binding_callbacks = [];
const render_callbacks = [];
const flush_callbacks = [];
const resolved_promise = Promise.resolve();
let update_scheduled = false;
function schedule_update() {
if (!update_scheduled) {
update_scheduled = true;
resolved_promise.then(flush);
}
}
function add_render_callback(fn) {
render_callbacks.push(fn);
}
let flushing = false;
const seen_callbacks = new Set();
function flush() {
if (flushing)
return;
flushing = true;
do {
// first, call beforeUpdate functions
// and update components
for (let i = 0; i < dirty_components.length; i += 1) {
const component = dirty_components[i];
set_current_component(component);
update(component.$$);
}
set_current_component(null);
dirty_components.length = 0;
while (binding_callbacks.length)
binding_callbacks.pop()();
// then, once components are updated, call
// afterUpdate functions. This may cause
// subsequent updates...
for (let i = 0; i < render_callbacks.length; i += 1) {
const callback = render_callbacks[i];
if (!seen_callbacks.has(callback)) {
// ...so guard against infinite loops
seen_callbacks.add(callback);
callback();
}
}
render_callbacks.length = 0;
} while (dirty_components.length);
while (flush_callbacks.length) {
flush_callbacks.pop()();
}
update_scheduled = false;
flushing = false;
seen_callbacks.clear();
}
function update($$) {
if ($$.fragment !== null) {
$$.update();
run_all($$.before_update);
const dirty = $$.dirty;
$$.dirty = [-1];
$$.fragment && $$.fragment.p($$.ctx, dirty);
$$.after_update.forEach(add_render_callback);
}
}
let promise;
function wait() {
if (!promise) {
promise = Promise.resolve();
promise.then(() => {
promise = null;
});
}
return promise;
}
function dispatch(node, direction, kind) {
node.dispatchEvent(custom_event(`${direction ? 'intro' : 'outro'}${kind}`));
}
const outroing = new Set();
let outros;
function group_outros() {
outros = {
r: 0,
c: [],
p: outros // parent group
};
}
function check_outros() {
if (!outros.r) {
run_all(outros.c);
}
outros = outros.p;
}
function transition_in(block, local) {
if (block && block.i) {
outroing.delete(block);
block.i(local);
}
}
function transition_out(block, local, detach, callback) {
if (block && block.o) {
if (outroing.has(block))
return;
outroing.add(block);
outros.c.push(() => {
outroing.delete(block);
if (callback) {
if (detach)
block.d(1);
callback();
}
});
block.o(local);
}
}
const null_transition = { duration: 0 };
function create_in_transition(node, fn, params) {
let config = fn(node, params);
let running = false;
let animation_name;
let task;
let uid = 0;
function cleanup() {
if (animation_name)
delete_rule(node, animation_name);
}
function go() {
const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;
if (css)
animation_name = create_rule(node, 0, 1, duration, delay, easing, css, uid++);
tick(0, 1);
const start_time = now() + delay;
const end_time = start_time + duration;
if (task)
task.abort();
running = true;
add_render_callback(() => dispatch(node, true, 'start'));
task = loop(now => {
if (running) {
if (now >= end_time) {
tick(1, 0);
dispatch(node, true, 'end');
cleanup();
return running = false;
}
if (now >= start_time) {
const t = easing((now - start_time) / duration);
tick(t, 1 - t);
}
}
return running;
});
}
let started = false;
return {
start() {
if (started)
return;
started = true;
delete_rule(node);
if (is_function(config)) {
config = config();
wait().then(go);
}
else {
go();
}
},
invalidate() {
started = false;
},
end() {
if (running) {
cleanup();
running = false;
}
}
};
}
function create_out_transition(node, fn, params) {
let config = fn(node, params);
let running = true;
let animation_name;
const group = outros;
group.r += 1;
function go() {
const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;
if (css)
animation_name = create_rule(node, 1, 0, duration, delay, easing, css);
const start_time = now() + delay;
const end_time = start_time + duration;
add_render_callback(() => dispatch(node, false, 'start'));
loop(now => {
if (running) {
if (now >= end_time) {
tick(0, 1);
dispatch(node, false, 'end');
if (!--group.r) {
// this will result in `end()` being called,
// so we don't need to clean up here
run_all(group.c);
}
return false;
}
if (now >= start_time) {
const t = easing((now - start_time) / duration);
tick(1 - t, t);
}
}
return running;
});
}
if (is_function(config)) {
wait().then(() => {
// @ts-ignore
config = config();
go();
});
}
else {
go();
}
return {
end(reset) {
if (reset && config.tick) {
config.tick(1, 0);
}
if (running) {
if (animation_name)
delete_rule(node, animation_name);
running = false;
}
}
};
}
function create_bidirectional_transition(node, fn, params, intro) {
let config = fn(node, params);
let t = intro ? 0 : 1;
let running_program = null;
let pending_program = null;
let animation_name = null;
function clear_animation() {
if (animation_name)
delete_rule(node, animation_name);
}
function init(program, duration) {
const d = (program.b - t);
duration *= Math.abs(d);
return {
a: t,
b: program.b,
d,
duration,
start: program.start,
end: program.start + duration,
group: program.group
};
}
function go(b) {
const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;
const program = {
start: now() + delay,
b
};
if (!b) {
// @ts-ignore todo: improve typings
program.group = outros;
outros.r += 1;
}
if (running_program || pending_program) {
pending_program = program;
}
else {
// if this is an intro, and there's a delay, we need to do
// an initial tick and/or apply CSS animation immediately
if (css) {
clear_animation();
animation_name = create_rule(node, t, b, duration, delay, easing, css);
}
if (b)
tick(0, 1);
running_program = init(program, duration);
add_render_callback(() => dispatch(node, b, 'start'));
loop(now => {
if (pending_program && now > pending_program.start) {
running_program = init(pending_program, duration);
pending_program = null;
dispatch(node, running_program.b, 'start');
if (css) {
clear_animation();
animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css);
}
}
if (running_program) {
if (now >= running_program.end) {
tick(t = running_program.b, 1 - t);
dispatch(node, running_program.b, 'end');
if (!pending_program) {
// we're done
if (running_program.b) {
// intro — we can tidy up immediately
clear_animation();
}
else {
// outro — needs to be coordinated
if (!--running_program.group.r)
run_all(running_program.group.c);
}
}
running_program = null;
}
else if (now >= running_program.start) {
const p = now - running_program.start;
t = running_program.a + running_program.d * easing(p / running_program.duration);
tick(t, 1 - t);
}
}
return !!(running_program || pending_program);
});
}
}
return {
run(b) {
if (is_function(config)) {
wait().then(() => {
// @ts-ignore
config = config();
go(b);
});
}
else {
go(b);
}
},
end() {
clear_animation();
running_program = pending_program = null;
}
};
}
function get_spread_update(levels, updates) {
const update = {};
const to_null_out = {};
const accounted_for = { $$scope: 1 };
let i = levels.length;
while (i--) {
const o = levels[i];
const n = updates[i];
if (n) {
for (const key in o) {
if (!(key in n))
to_null_out[key] = 1;
}
for (const key in n) {
if (!accounted_for[key]) {
update[key] = n[key];
accounted_for[key] = 1;
}
}
levels[i] = n;
}
else {
for (const key in o) {
accounted_for[key] = 1;
}
}
}
for (const key in to_null_out) {
if (!(key in update))
update[key] = undefined;
}
return update;
}
function get_spread_object(spread_props) {
return typeof spread_props === 'object' && spread_props !== null ? spread_props : {};
}
function create_component(block) {
block && block.c();
}
function mount_component(component, target, anchor, customElement) {
const { fragment, on_mount, on_destroy, after_update } = component.$$;
fragment && fragment.m(target, anchor);
if (!customElement) {
// onMount happens before the initial afterUpdate
add_render_callback(() => {
const new_on_destroy = on_mount.map(run).filter(is_function);
if (on_destroy) {
on_destroy.push(...new_on_destroy);
}
else {
// Edge case - component was destroyed immediately,
// most likely as a result of a binding initialising
run_all(new_on_destroy);
}
component.$$.on_mount = [];
});
}
after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
const $$ = component.$$;
if ($$.fragment !== null) {
run_all($$.on_destroy);
$$.fragment && $$.fragment.d(detaching);
// TODO null out other refs, including component.$$ (but need to
// preserve final state?)
$$.on_destroy = $$.fragment = null;
$$.ctx = [];
}
}
function make_dirty(component, i) {
if (component.$$.dirty[0] === -1) {
dirty_components.push(component);
schedule_update();
component.$$.dirty.fill(0);
}
component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
}
function init(component, options, instance, create_fragment, not_equal, props, append_styles, dirty = [-1]) {
const parent_component = current_component;
set_current_component(component);
const $$ = component.$$ = {
fragment: null,
ctx: null,
// state
props,
update: noop,
not_equal,
bound: blank_object(),
// lifecycle
on_mount: [],
on_destroy: [],
on_disconnect: [],
before_update: [],
after_update: [],
context: new Map(parent_component ? parent_component.$$.context : options.context || []),
// everything else
callbacks: blank_object(),
dirty,
skip_bound: false,
root: options.target || parent_component.$$.root
};
append_styles && append_styles($$.root);
let ready = false;
$$.ctx = instance
? instance(component, options.props || {}, (i, ret, ...rest) => {
const value = rest.length ? rest[0] : ret;
if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
if (!$$.skip_bound && $$.bound[i])
$$.bound[i](value);
if (ready)
make_dirty(component, i);
}
return ret;
})
: [];
$$.update();
ready = true;
run_all($$.before_update);
// `false` as a special case of no DOM component
$$.fragment = create_fragment ? create_fragment($$.ctx) : false;
if (options.target) {
if (options.hydrate) {
const nodes = children(options.target);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.l(nodes);
nodes.forEach(detach);
}
else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.c();
}
if (options.intro)
transition_in(component.$$.fragment);
mount_component(component, options.target, options.anchor, options.customElement);
flush();
}
set_current_component(parent_component);
}
/**
* Base class for Svelte components. Used when dev=false.
*/
class SvelteComponent {
$destroy() {
destroy_component(this, 1);
this.$destroy = noop;
}
$on(type, callback) {
const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index !== -1)
callbacks.splice(index, 1);
};
}
$set($$props) {
if (this.$$set && !is_empty($$props)) {
this.$$.skip_bound = true;
this.$$set($$props);
this.$$.skip_bound = false;
}
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const MAKE_MOVE = 'MAKE_MOVE';
const GAME_EVENT = 'GAME_EVENT';
const REDO = 'REDO';
const RESET = 'RESET';
const SYNC = 'SYNC';
const UNDO = 'UNDO';
const UPDATE = 'UPDATE';
const PATCH = 'PATCH';
const PLUGIN = 'PLUGIN';
const STRIP_TRANSIENTS = 'STRIP_TRANSIENTS';
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Generate a move to be dispatched to the game move reducer.
*
* @param {string} type - The move type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const makeMove = (type, args, playerID, credentials) => ({
type: MAKE_MOVE,
payload: { type, args, playerID, credentials },
});
/**
* Generate a game event to be dispatched to the flow reducer.
*
* @param {string} type - The event type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const gameEvent = (type, args, playerID, credentials) => ({
type: GAME_EVENT,
payload: { type, args, playerID, credentials },
});
/**
* Generate an automatic game event that is a side-effect of a move.
* @param {string} type - The event type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const automaticGameEvent = (type, args, playerID, credentials) => ({
type: GAME_EVENT,
payload: { type, args, playerID, credentials },
automatic: true,
});
const sync = (info) => ({
type: SYNC,
state: info.state,
log: info.log,
initialState: info.initialState,
clientOnly: true,
});
/**
* Used to update the Redux store's state with patch in response to
* an action coming from another player.
* @param prevStateID previous stateID
* @param stateID stateID after this patch
* @param {Operation[]} patch - The patch to apply.
* @param {LogEntry[]} deltalog - A log delta.
*/
const patch = (prevStateID, stateID, patch, deltalog) => ({
type: PATCH,
prevStateID,
stateID,
patch,
deltalog,
clientOnly: true,
});
/**
* Used to update the Redux store's state in response to
* an action coming from another player.
* @param {object} state - The state to restore.
* @param {Array} deltalog - A log delta.
*/
const update$1 = (state, deltalog) => ({
type: UPDATE,
state,
deltalog,
clientOnly: true,
});
/**
* Used to reset the game state.
* @param {object} state - The initial state.
*/
const reset = (state) => ({
type: RESET,
state,
clientOnly: true,
});
/**
* Used to undo the last move.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const undo = (playerID, credentials) => ({
type: UNDO,
payload: { type: null, args: null, playerID, credentials },
});
/**
* Used to redo the last undone move.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const redo = (playerID, credentials) => ({
type: REDO,
payload: { type: null, args: null, playerID, credentials },
});
/**
* Allows plugins to define their own actions and intercept them.
*/
const plugin = (type, args, playerID, credentials) => ({
type: PLUGIN,
payload: { type, args, playerID, credentials },
});
/**
* Private action used to strip transient metadata (e.g. errors) from the game
* state.
*/
const stripTransients = () => ({
type: STRIP_TRANSIENTS,
});
var ActionCreators = /*#__PURE__*/Object.freeze({
__proto__: null,
makeMove: makeMove,
gameEvent: gameEvent,
automaticGameEvent: automaticGameEvent,
sync: sync,
patch: patch,
update: update$1,
reset: reset,
undo: undo,
redo: redo,
plugin: plugin,
stripTransients: stripTransients
});
/**
* Moves can return this when they want to indicate
* that the combination of arguments is illegal and
* the move ought to be discarded.
*/
const INVALID_MOVE = 'INVALID_MOVE';
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Plugin that allows using Immer to make immutable changes
* to G by just mutating it.
*/
const ImmerPlugin = {
name: 'plugin-immer',
fnWrap: (move) => (G, ctx, ...args) => {
let isInvalid = false;
const newG = produce(G, (G) => {
const result = move(G, ctx, ...args);
if (result === INVALID_MOVE) {
isInvalid = true;
return;
}
return result;
});
if (isInvalid)
return INVALID_MOVE;
return newG;
},
};
// Inlined version of Alea from https://github.com/davidbau/seedrandom.
// Converted to Typescript October 2020.
class Alea {
constructor(seed) {
const mash = Mash();
// Apply the seeding algorithm from Baagoe.
this.c = 1;
this.s0 = mash(' ');
this.s1 = mash(' ');
this.s2 = mash(' ');
this.s0 -= mash(seed);
if (this.s0 < 0) {
this.s0 += 1;
}
this.s1 -= mash(seed);
if (this.s1 < 0) {
this.s1 += 1;
}
this.s2 -= mash(seed);
if (this.s2 < 0) {
this.s2 += 1;
}
}
next() {
const t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
this.s0 = this.s1;
this.s1 = this.s2;
return (this.s2 = t - (this.c = Math.trunc(t)));
}
}
function Mash() {
let n = 0xefc8249d;
const mash = function (data) {
const str = data.toString();
for (let i = 0; i < str.length; i++) {
n += str.charCodeAt(i);
let h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
return mash;
}
function copy(f, t) {
t.c = f.c;
t.s0 = f.s0;
t.s1 = f.s1;
t.s2 = f.s2;
return t;
}
function alea(seed, state) {
const xg = new Alea(seed);
const prng = xg.next.bind(xg);
if (state)
copy(state, xg);
prng.state = () => copy(xg, {});
return prng;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Random
*
* Calls that require a pseudorandom number generator.
* Uses a seed from ctx, and also persists the PRNG
* state in ctx so that moves can stay pure.
*/
class Random {
/**
* constructor
* @param {object} ctx - The ctx object to initialize from.
*/
constructor(state) {
// If we are on the client, the seed is not present.
// Just use a temporary seed to execute the move without
// crashing it. The move state itself is discarded,
// so the actual value doesn't matter.
this.state = state || { seed: '0' };
this.used = false;
}
/**
* Generates a new seed from the current date / time.
*/
static seed() {
return Date.now().toString(36).slice(-10);
}
isUsed() {
return this.used;
}
getState() {
return this.state;
}
/**
* Generate a random number.
*/
_random() {
this.used = true;
const R = this.state;
const seed = R.prngstate ? '' : R.seed;
const rand = alea(seed, R.prngstate);
const number = rand();
this.state = {
...R,
prngstate: rand.state(),
};
return number;
}
api() {
const random = this._random.bind(this);
const SpotValue = {
D4: 4,
D6: 6,
D8: 8,
D10: 10,
D12: 12,
D20: 20,
};
// Generate functions for predefined dice values D4 - D20.
const predefined = {};
for (const key in SpotValue) {
const spotvalue = SpotValue[key];
predefined[key] = (diceCount) => {
return diceCount === undefined
? Math.floor(random() * spotvalue) + 1
: Array.from({ length: diceCount }).map(() => Math.floor(random() * spotvalue) + 1);
};
}
function Die(spotvalue = 6, diceCount) {
return diceCount === undefined
? Math.floor(random() * spotvalue) + 1
: Array.from({ length: diceCount }).map(() => Math.floor(random() * spotvalue) + 1);
}
return {
/**
* Similar to Die below, but with fixed spot values.
* Supports passing a diceCount
* if not defined, defaults to 1 and returns the value directly.
* if defined, returns an array containing the random dice values.
*
* D4: (diceCount) => value
* D6: (diceCount) => value
* D8: (diceCount) => value
* D10: (diceCount) => value
* D12: (diceCount) => value
* D20: (diceCount) => value
*/
...predefined,
/**
* Roll a die of specified spot value.
*
* @param {number} spotvalue - The die dimension (default: 6).
* @param {number} diceCount - number of dice to throw.
* if not defined, defaults to 1 and returns the value directly.
* if defined, returns an array containing the random dice values.
*/
Die,
/**
* Generate a random number between 0 and 1.
*/
Number: () => {
return random();
},
/**
* Shuffle an array.
*
* @param {Array} deck - The array to shuffle. Does not mutate
* the input, but returns the shuffled array.
*/
Shuffle: (deck) => {
const clone = [...deck];
let sourceIndex = deck.length;
let destinationIndex = 0;
const shuffled = Array.from({ length: sourceIndex });
while (sourceIndex) {
const randomIndex = Math.trunc(sourceIndex * random());
shuffled[destinationIndex++] = clone[randomIndex];
clone[randomIndex] = clone[--sourceIndex];
}
return shuffled;
},
_private: this,
};
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const RandomPlugin = {
name: 'random',
noClient: ({ api }) => {
return api._private.isUsed();
},
flush: ({ api }) => {
return api._private.getState();
},
api: ({ data }) => {
const random = new Random(data);
return random.api();
},
setup: ({ game }) => {
let { seed } = game;
if (seed === undefined) {
seed = Random.seed();
}
return { seed };
},
playerView: () => undefined,
};
var GameMethod;
(function (GameMethod) {
GameMethod["MOVE"] = "MOVE";
GameMethod["GAME_ON_END"] = "GAME_ON_END";
GameMethod["PHASE_ON_BEGIN"] = "PHASE_ON_BEGIN";
GameMethod["PHASE_ON_END"] = "PHASE_ON_END";
GameMethod["TURN_ON_BEGIN"] = "TURN_ON_BEGIN";
GameMethod["TURN_ON_MOVE"] = "TURN_ON_MOVE";
GameMethod["TURN_ON_END"] = "TURN_ON_END";
})(GameMethod || (GameMethod = {}));
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
var Errors;
(function (Errors) {
Errors["CalledOutsideHook"] = "Events must be called from moves or the `onBegin`, `onEnd`, and `onMove` hooks.\nThis error probably means you called an event from other game code, like an `endIf` trigger or one of the `turn.order` methods.";
Errors["EndTurnInOnEnd"] = "`endTurn` is disallowed in `onEnd` hooks \u2014 the turn is already ending.";
Errors["MaxTurnEndings"] = "Maximum number of turn endings exceeded for this update.\nThis likely means game code is triggering an infinite loop.";
Errors["PhaseEventInOnEnd"] = "`setPhase` & `endPhase` are disallowed in a phase\u2019s `onEnd` hook \u2014 the phase is already ending.\nIf you\u2019re trying to dynamically choose the next phase when a phase ends, use the phase\u2019s `next` trigger.";
Errors["StageEventInOnEnd"] = "`setStage`, `endStage` & `setActivePlayers` are disallowed in `onEnd` hooks.";
Errors["StageEventInPhaseBegin"] = "`setStage`, `endStage` & `setActivePlayers` are disallowed in a phase\u2019s `onBegin` hook.\nUse `setActivePlayers` in a `turn.onBegin` hook or declare stages with `turn.activePlayers` instead.";
Errors["StageEventInTurnBegin"] = "`setStage` & `endStage` are disallowed in `turn.onBegin`.\nUse `setActivePlayers` or declare stages with `turn.activePlayers` instead.";
})(Errors || (Errors = {}));
/**
* Events
*/
class Events {
constructor(flow, ctx, playerID) {
this.flow = flow;
this.playerID = playerID;
this.dispatch = [];
this.initialTurn = ctx.turn;
this.updateTurnContext(ctx, undefined);
// This is an arbitrarily large upper threshold, which could be made
// configurable via a game option if the need arises.
this.maxEndedTurnsPerAction = ctx.numPlayers * 100;
}
api() {
const events = {
_private: this,
};
for (const type of this.flow.eventNames) {
events[type] = (...args) => {
this.dispatch.push({
type,
args,
phase: this.currentPhase,
turn: this.currentTurn,
calledFrom: this.currentMethod,
// Used to capture a stack trace in case it is needed later.
error: new Error('Events Plugin Error'),
});
};
}
return events;
}
isUsed() {
return this.dispatch.length > 0;
}
updateTurnContext(ctx, methodType) {
this.currentPhase = ctx.phase;
this.currentTurn = ctx.turn;
this.currentMethod = methodType;
}
unsetCurrentMethod() {
this.currentMethod = undefined;
}
/**
* Updates ctx with the triggered events.
* @param {object} state - The state object { G, ctx }.
*/
update(state) {
const initialState = state;
const stateWithError = ({ stack }, message) => ({
...initialState,
plugins: {
...initialState.plugins,
events: {
...initialState.plugins.events,
data: { error: message + '\n' + stack },
},
},
});
EventQueue: for (let i = 0; i < this.dispatch.length; i++) {
const event = this.dispatch[i];
const turnHasEnded = event.turn !== state.ctx.turn;
// This protects against potential infinite loops if specific events are called on hooks.
// The moment we exceed the defined threshold, we just bail out of all phases.
const endedTurns = this.currentTurn - this.initialTurn;
if (endedTurns >= this.maxEndedTurnsPerAction) {
return stateWithError(event.error, Errors.MaxTurnEndings);
}
if (event.calledFrom === undefined) {
return stateWithError(event.error, Errors.CalledOutsideHook);
}
// Stop processing events once the game has finished.
if (state.ctx.gameover)
break EventQueue;
switch (event.type) {
case 'endStage':
case 'setStage':
case 'setActivePlayers': {
switch (event.calledFrom) {
// Disallow all stage events in onEnd and phase.onBegin hooks.
case GameMethod.TURN_ON_END:
case GameMethod.PHASE_ON_END:
return stateWithError(event.error, Errors.StageEventInOnEnd);
case GameMethod.PHASE_ON_BEGIN:
return stateWithError(event.error, Errors.StageEventInPhaseBegin);
// Disallow setStage & endStage in turn.onBegin hooks.
case GameMethod.TURN_ON_BEGIN:
if (event.type === 'setActivePlayers')
break;
return stateWithError(event.error, Errors.StageEventInTurnBegin);
}
// If the turn already ended, don't try to process stage events.
if (turnHasEnded)
continue EventQueue;
break;
}
case 'endTurn': {
if (event.calledFrom === GameMethod.TURN_ON_END ||
event.calledFrom === GameMethod.PHASE_ON_END) {
return stateWithError(event.error, Errors.EndTurnInOnEnd);
}
// If the turn already ended some other way,
// don't try to end the turn again.
if (turnHasEnded)
continue EventQueue;
break;
}
case 'endPhase':
case 'setPhase': {
if (event.calledFrom === GameMethod.PHASE_ON_END) {
return stateWithError(event.error, Errors.PhaseEventInOnEnd);
}
// If the phase already ended some other way,
// don't try to end the phase again.
if (event.phase !== state.ctx.phase)
continue EventQueue;
break;
}
}
const action = automaticGameEvent(event.type, event.args, this.playerID);
state = this.flow.processEvent(state, action);
}
return state;
}
}
/*
* Copyright 2020 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const EventsPlugin = {
name: 'events',
noClient: ({ api }) => api._private.isUsed(),
isInvalid: ({ data }) => data.error || false,
// Update the events plugin’s internal turn context each time a move
// or hook is called. This allows events called after turn or phase
// endings to dispatch the current turn and phase correctly.
fnWrap: (method, methodType) => (G, ctx, ...args) => {
const api = ctx.events;
if (api)
api._private.updateTurnContext(ctx, methodType);
G = method(G, ctx, ...args);
if (api)
api._private.unsetCurrentMethod();
return G;
},
dangerouslyFlushRawState: ({ state, api }) => api._private.update(state),
api: ({ game, ctx, playerID }) => new Events(game.flow, ctx, playerID).api(),
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Plugin that makes it possible to add metadata to log entries.
* During a move, you can set metadata using ctx.log.setMetadata and it will be
* available on the log entry for that move.
*/
const LogPlugin = {
name: 'log',
flush: () => ({}),
api: ({ data }) => {
return {
setMetadata: (metadata) => {
data.metadata = metadata;
},
};
},
setup: () => ({}),
};
/**
* Check if a value can be serialized (e.g. using `JSON.stringify`).
* Adapted from: https://stackoverflow.com/a/30712764/3829557
*/
function isSerializable(value) {
// Primitives are OK.
if (value === undefined ||
value === null ||
typeof value === 'boolean' ||
typeof value === 'number' ||
typeof value === 'string') {
return true;
}
// A non-primitive value that is neither a POJO or an array cannot be serialized.
if (!isPlainObject(value) && !Array.isArray(value)) {
return false;
}
// Recurse entries if the value is an object or array.
for (const key in value) {
if (!isSerializable(value[key]))
return false;
}
return true;
}
/**
* Plugin that checks whether state is serializable, in order to avoid
* network serialization bugs.
*/
const SerializablePlugin = {
name: 'plugin-serializable',
fnWrap: (move) => (G, ctx, ...args) => {
const result = move(G, ctx, ...args);
// Check state in non-production environments.
if (process.env.NODE_ENV !== 'production' && !isSerializable(result)) {
throw new Error('Move state is not JSON-serialiazable.\n' +
'See https://boardgame.io/documentation/#/?id=state for more information.');
}
return result;
},
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const production = process.env.NODE_ENV === 'production';
const logfn = production ? () => { } : (...msg) => console.log(...msg);
const errorfn = (...msg) => console.error(...msg);
function info(msg) {
logfn(`INFO: ${msg}`);
}
function error(error) {
errorfn('ERROR:', error);
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* List of plugins that are always added.
*/
const CORE_PLUGINS = [ImmerPlugin, RandomPlugin, LogPlugin, SerializablePlugin];
const DEFAULT_PLUGINS = [...CORE_PLUGINS, EventsPlugin];
/**
* Allow plugins to intercept actions and process them.
*/
const ProcessAction = (state, action, opts) => {
// TODO(#723): Extend error handling to plugins.
opts.game.plugins
.filter((plugin) => plugin.action !== undefined)
.filter((plugin) => plugin.name === action.payload.type)
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
const data = plugin.action(pluginState.data, action.payload);
state = {
...state,
plugins: {
...state.plugins,
[name]: { ...pluginState, data },
},
};
});
return state;
};
/**
* The API's created by various plugins are stored in the plugins
* section of the state object:
*
* {
* G: {},
* ctx: {},
* plugins: {
* plugin-a: {
* data: {}, // this is generated by the plugin at Setup / Flush.
* api: {}, // this is ephemeral and generated by Enhance.
* }
* }
* }
*
* This function takes these API's and stuffs them back into
* ctx for consumption inside a move function or hook.
*/
const EnhanceCtx = (state) => {
const ctx = { ...state.ctx };
const plugins = state.plugins || {};
Object.entries(plugins).forEach(([name, { api }]) => {
ctx[name] = api;
});
return ctx;
};
/**
* Applies the provided plugins to the given move / flow function.
*
* @param methodToWrap - The move function or hook to apply the plugins to.
* @param methodType - The type of the move or hook being wrapped.
* @param plugins - The list of plugins.
*/
const FnWrap = (methodToWrap, methodType, plugins) => {
return [...CORE_PLUGINS, ...plugins, EventsPlugin]
.filter((plugin) => plugin.fnWrap !== undefined)
.reduce((method, { fnWrap }) => fnWrap(method, methodType), methodToWrap);
};
/**
* Allows the plugin to generate its initial state.
*/
const Setup = (state, opts) => {
[...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.setup !== undefined)
.forEach((plugin) => {
const name = plugin.name;
const data = plugin.setup({
G: state.G,
ctx: state.ctx,
game: opts.game,
});
state = {
...state,
plugins: {
...state.plugins,
[name]: { data },
},
};
});
return state;
};
/**
* Invokes the plugin before a move or event.
* The API that the plugin generates is stored inside
* the `plugins` section of the state (which is subsequently
* merged into ctx).
*/
const Enhance = (state, opts) => {
[...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.api !== undefined)
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
const api = plugin.api({
G: state.G,
ctx: state.ctx,
data: pluginState.data,
game: opts.game,
playerID: opts.playerID,
});
state = {
...state,
plugins: {
...state.plugins,
[name]: { ...pluginState, api },
},
};
});
return state;
};
/**
* Allows plugins to update their state after a move / event.
*/
const Flush = (state, opts) => {
// We flush the events plugin first, then custom plugins and the core plugins.
// This means custom plugins cannot use the events API but will be available in event hooks.
// Note that plugins are flushed in reverse, to allow custom plugins calling each other.
[...CORE_PLUGINS, ...opts.game.plugins, EventsPlugin]
.reverse()
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
if (plugin.flush) {
const newData = plugin.flush({
G: state.G,
ctx: state.ctx,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
state = {
...state,
plugins: {
...state.plugins,
[plugin.name]: { data: newData },
},
};
}
else if (plugin.dangerouslyFlushRawState) {
state = plugin.dangerouslyFlushRawState({
state,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
// Remove everything other than data.
const data = state.plugins[name].data;
state = {
...state,
plugins: {
...state.plugins,
[plugin.name]: { data },
},
};
}
});
return state;
};
/**
* Allows plugins to indicate if they should not be materialized on the client.
* This will cause the client to discard the state update and wait for the
* master instead.
*/
const NoClient = (state, opts) => {
return [...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.noClient !== undefined)
.map((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name];
if (pluginState) {
return plugin.noClient({
G: state.G,
ctx: state.ctx,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
}
return false;
})
.includes(true);
};
/**
* Allows plugins to indicate if the entire action should be thrown out
* as invalid. This will cancel the entire state update.
*/
const IsInvalid = (state, opts) => {
const firstInvalidReturn = [...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.isInvalid !== undefined)
.map((plugin) => {
const { name } = plugin;
const pluginState = state.plugins[name];
const message = plugin.isInvalid({
G: state.G,
ctx: state.ctx,
game: opts.game,
data: pluginState && pluginState.data,
});
return message ? { plugin: name, message } : false;
})
.find((value) => value);
return firstInvalidReturn || false;
};
/**
* Update plugin state after move/event & check if plugins consider the update to be valid.
* @returns Tuple of `[updatedState]` or `[originalState, invalidError]`.
*/
const FlushAndValidate = (state, opts) => {
const updatedState = Flush(state, opts);
const isInvalid = IsInvalid(updatedState, opts);
if (!isInvalid)
return [updatedState];
const { plugin, message } = isInvalid;
error(`${plugin} plugin declared action invalid:\n${message}`);
return [state, isInvalid];
};
/**
* Allows plugins to customize their data for specific players.
* For example, a plugin may want to share no data with the client, or
* want to keep some player data secret from opponents.
*/
const PlayerView = ({ G, ctx, plugins = {} }, { game, playerID }) => {
[...DEFAULT_PLUGINS, ...game.plugins].forEach(({ name, playerView }) => {
if (!playerView)
return;
const { data } = plugins[name] || { data: {} };
const newData = playerView({ G, ctx, game, data, playerID });
plugins = {
...plugins,
[name]: { data: newData },
};
});
return plugins;
};
/**
* Adjust the given options to use the new minMoves/maxMoves if a legacy moveLimit was given
* @param options The options object to apply backwards compatibility to
* @param enforceMinMoves Use moveLimit to set both minMoves and maxMoves
*/
function supportDeprecatedMoveLimit(options, enforceMinMoves = false) {
if (options.moveLimit) {
if (enforceMinMoves) {
options.minMoves = options.moveLimit;
}
options.maxMoves = options.moveLimit;
delete options.moveLimit;
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function SetActivePlayers(ctx, arg) {
let activePlayers = {};
let _prevActivePlayers = [];
let _nextActivePlayers = null;
let _activePlayersMinMoves = {};
let _activePlayersMaxMoves = {};
if (Array.isArray(arg)) {
// support a simple array of player IDs as active players
const value = {};
arg.forEach((v) => (value[v] = Stage.NULL));
activePlayers = value;
}
else {
// process active players argument object
// stages previously did not enforce minMoves, this behaviour is kept intentionally
supportDeprecatedMoveLimit(arg);
if (arg.next) {
_nextActivePlayers = arg.next;
}
if (arg.revert) {
_prevActivePlayers = [
...ctx._prevActivePlayers,
{
activePlayers: ctx.activePlayers,
_activePlayersMinMoves: ctx._activePlayersMinMoves,
_activePlayersMaxMoves: ctx._activePlayersMaxMoves,
_activePlayersNumMoves: ctx._activePlayersNumMoves,
},
];
}
if (arg.currentPlayer !== undefined) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, ctx.currentPlayer, arg.currentPlayer);
}
if (arg.others !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
if (id !== ctx.currentPlayer) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, id, arg.others);
}
}
}
if (arg.all !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, id, arg.all);
}
}
if (arg.value) {
for (const id in arg.value) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, id, arg.value[id]);
}
}
if (arg.minMoves) {
for (const id in activePlayers) {
if (_activePlayersMinMoves[id] === undefined) {
_activePlayersMinMoves[id] = arg.minMoves;
}
}
}
if (arg.maxMoves) {
for (const id in activePlayers) {
if (_activePlayersMaxMoves[id] === undefined) {
_activePlayersMaxMoves[id] = arg.maxMoves;
}
}
}
}
if (Object.keys(activePlayers).length === 0) {
activePlayers = null;
}
if (Object.keys(_activePlayersMinMoves).length === 0) {
_activePlayersMinMoves = null;
}
if (Object.keys(_activePlayersMaxMoves).length === 0) {
_activePlayersMaxMoves = null;
}
const _activePlayersNumMoves = {};
for (const id in activePlayers) {
_activePlayersNumMoves[id] = 0;
}
return {
...ctx,
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
_activePlayersNumMoves,
_prevActivePlayers,
_nextActivePlayers,
};
}
/**
* Update activePlayers, setting it to previous, next or null values
* when it becomes empty.
* @param ctx
*/
function UpdateActivePlayersOnceEmpty(ctx) {
let { activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, _activePlayersNumMoves, _prevActivePlayers, _nextActivePlayers, } = ctx;
if (activePlayers && Object.keys(activePlayers).length === 0) {
if (_nextActivePlayers) {
ctx = SetActivePlayers(ctx, _nextActivePlayers);
({
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
_activePlayersNumMoves,
_prevActivePlayers,
} = ctx);
}
else if (_prevActivePlayers.length > 0) {
const lastIndex = _prevActivePlayers.length - 1;
({
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
_activePlayersNumMoves,
} = _prevActivePlayers[lastIndex]);
_prevActivePlayers = _prevActivePlayers.slice(0, lastIndex);
}
else {
activePlayers = null;
_activePlayersMinMoves = null;
_activePlayersMaxMoves = null;
}
}
return {
...ctx,
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
_activePlayersNumMoves,
_prevActivePlayers,
};
}
/**
* Apply an active player argument to the given player ID
* @param {Object} activePlayers
* @param {Object} _activePlayersMinMoves
* @param {Object} _activePlayersMaxMoves
* @param {String} playerID The player to apply the parameter to
* @param {(String|Object)} arg An active player argument
*/
function ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, playerID, arg) {
if (typeof arg !== 'object' || arg === Stage.NULL) {
arg = { stage: arg };
}
if (arg.stage !== undefined) {
// stages previously did not enforce minMoves, this behaviour is kept intentionally
supportDeprecatedMoveLimit(arg);
activePlayers[playerID] = arg.stage;
if (arg.minMoves)
_activePlayersMinMoves[playerID] = arg.minMoves;
if (arg.maxMoves)
_activePlayersMaxMoves[playerID] = arg.maxMoves;
}
}
/**
* Converts a playOrderPos index into its value in playOrder.
* @param {Array} playOrder - An array of player ID's.
* @param {number} playOrderPos - An index into the above.
*/
function getCurrentPlayer(playOrder, playOrderPos) {
// convert to string in case playOrder is set to number[]
return playOrder[playOrderPos] + '';
}
/**
* Called at the start of a turn to initialize turn order state.
*
* TODO: This is called inside StartTurn, which is called from
* both UpdateTurn and StartPhase (so it's called at the beginning
* of a new phase as well as between turns). We should probably
* split it into two.
*/
function InitTurnOrderState(state, turn) {
let { G, ctx } = state;
const { numPlayers } = ctx;
const ctxWithAPI = EnhanceCtx(state);
const order = turn.order;
let playOrder = [...Array.from({ length: numPlayers })].map((_, i) => i + '');
if (order.playOrder !== undefined) {
playOrder = order.playOrder(G, ctxWithAPI);
}
const playOrderPos = order.first(G, ctxWithAPI);
const posType = typeof playOrderPos;
if (posType !== 'number') {
error(`invalid value returned by turn.order.first — expected number got ${posType} “${playOrderPos}”.`);
}
const currentPlayer = getCurrentPlayer(playOrder, playOrderPos);
ctx = { ...ctx, currentPlayer, playOrderPos, playOrder };
ctx = SetActivePlayers(ctx, turn.activePlayers || {});
return ctx;
}
/**
* Called at the end of each turn to update the turn order state.
* @param {object} G - The game object G.
* @param {object} ctx - The game object ctx.
* @param {object} turn - A turn object for this phase.
* @param {string} endTurnArg - An optional argument to endTurn that
may specify the next player.
*/
function UpdateTurnOrderState(state, currentPlayer, turn, endTurnArg) {
const order = turn.order;
let { G, ctx } = state;
let playOrderPos = ctx.playOrderPos;
let endPhase = false;
if (endTurnArg && endTurnArg !== true) {
if (typeof endTurnArg !== 'object') {
error(`invalid argument to endTurn: ${endTurnArg}`);
}
Object.keys(endTurnArg).forEach((arg) => {
switch (arg) {
case 'remove':
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
break;
case 'next':
playOrderPos = ctx.playOrder.indexOf(endTurnArg.next);
currentPlayer = endTurnArg.next;
break;
default:
error(`invalid argument to endTurn: ${arg}`);
}
});
}
else {
const ctxWithAPI = EnhanceCtx(state);
const t = order.next(G, ctxWithAPI);
const type = typeof t;
if (t !== undefined && type !== 'number') {
error(`invalid value returned by turn.order.next — expected number or undefined got ${type} “${t}”.`);
}
if (t === undefined) {
endPhase = true;
}
else {
playOrderPos = t;
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
}
}
ctx = {
...ctx,
playOrderPos,
currentPlayer,
};
return { endPhase, ctx };
}
/**
* Set of different turn orders possible in a phase.
* These are meant to be passed to the `turn` setting
* in the flow objects.
*
* Each object defines the first player when the phase / game
* begins, and also a function `next` to determine who the
* next player is when the turn ends.
*
* The phase ends if next() returns undefined.
*/
const TurnOrder = {
/**
* DEFAULT
*
* The default round-robin turn order.
*/
DEFAULT: {
first: (G, ctx) => ctx.turn === 0
? ctx.playOrderPos
: (ctx.playOrderPos + 1) % ctx.playOrder.length,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* RESET
*
* Similar to DEFAULT, but starts from 0 each time.
*/
RESET: {
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* CONTINUE
*
* Similar to DEFAULT, but starts with the player who ended the last phase.
*/
CONTINUE: {
first: (G, ctx) => ctx.playOrderPos,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* ONCE
*
* Another round-robin turn order, but goes around just once.
* The phase ends after all players have played.
*/
ONCE: {
first: () => 0,
next: (G, ctx) => {
if (ctx.playOrderPos < ctx.playOrder.length - 1) {
return ctx.playOrderPos + 1;
}
},
},
/**
* CUSTOM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase.
*
* @param {Array} playOrder - The play order.
*/
CUSTOM: (playOrder) => ({
playOrder: () => playOrder,
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
/**
* CUSTOM_FROM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase to a value specified by a field
* in G.
*
* @param {string} playOrderField - Field in G.
*/
CUSTOM_FROM: (playOrderField) => ({
playOrder: (G) => G[playOrderField],
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
};
const Stage = {
NULL: null,
};
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Flow
*
* Creates a reducer that updates ctx (analogous to how moves update G).
*/
function Flow({ moves, phases, endIf, onEnd, turn, events, plugins, }) {
// Attach defaults.
if (moves === undefined) {
moves = {};
}
if (events === undefined) {
events = {};
}
if (plugins === undefined) {
plugins = [];
}
if (phases === undefined) {
phases = {};
}
if (!endIf)
endIf = () => undefined;
if (!onEnd)
onEnd = (G) => G;
if (!turn)
turn = {};
const phaseMap = { ...phases };
if ('' in phaseMap) {
error('cannot specify phase with empty name');
}
phaseMap[''] = {};
const moveMap = {};
const moveNames = new Set();
let startingPhase = null;
Object.keys(moves).forEach((name) => moveNames.add(name));
const HookWrapper = (hook, hookType) => {
const withPlugins = FnWrap(hook, hookType, plugins);
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return withPlugins(state.G, ctxWithAPI);
};
};
const TriggerWrapper = (trigger) => {
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return trigger(state.G, ctxWithAPI);
};
};
const wrapped = {
onEnd: HookWrapper(onEnd, GameMethod.GAME_ON_END),
endIf: TriggerWrapper(endIf),
};
for (const phase in phaseMap) {
const phaseConfig = phaseMap[phase];
if (phaseConfig.start === true) {
startingPhase = phase;
}
if (phaseConfig.moves !== undefined) {
for (const move of Object.keys(phaseConfig.moves)) {
moveMap[phase + '.' + move] = phaseConfig.moves[move];
moveNames.add(move);
}
}
if (phaseConfig.endIf === undefined) {
phaseConfig.endIf = () => undefined;
}
if (phaseConfig.onBegin === undefined) {
phaseConfig.onBegin = (G) => G;
}
if (phaseConfig.onEnd === undefined) {
phaseConfig.onEnd = (G) => G;
}
if (phaseConfig.turn === undefined) {
phaseConfig.turn = turn;
}
if (phaseConfig.turn.order === undefined) {
phaseConfig.turn.order = TurnOrder.DEFAULT;
}
if (phaseConfig.turn.onBegin === undefined) {
phaseConfig.turn.onBegin = (G) => G;
}
if (phaseConfig.turn.onEnd === undefined) {
phaseConfig.turn.onEnd = (G) => G;
}
if (phaseConfig.turn.endIf === undefined) {
phaseConfig.turn.endIf = () => false;
}
if (phaseConfig.turn.onMove === undefined) {
phaseConfig.turn.onMove = (G) => G;
}
if (phaseConfig.turn.stages === undefined) {
phaseConfig.turn.stages = {};
}
// turns previously treated moveLimit as both minMoves and maxMoves, this behaviour is kept intentionally
supportDeprecatedMoveLimit(phaseConfig.turn, true);
for (const stage in phaseConfig.turn.stages) {
const stageConfig = phaseConfig.turn.stages[stage];
const moves = stageConfig.moves || {};
for (const move of Object.keys(moves)) {
const key = phase + '.' + stage + '.' + move;
moveMap[key] = moves[move];
moveNames.add(move);
}
}
phaseConfig.wrapped = {
onBegin: HookWrapper(phaseConfig.onBegin, GameMethod.PHASE_ON_BEGIN),
onEnd: HookWrapper(phaseConfig.onEnd, GameMethod.PHASE_ON_END),
endIf: TriggerWrapper(phaseConfig.endIf),
};
phaseConfig.turn.wrapped = {
onMove: HookWrapper(phaseConfig.turn.onMove, GameMethod.TURN_ON_MOVE),
onBegin: HookWrapper(phaseConfig.turn.onBegin, GameMethod.TURN_ON_BEGIN),
onEnd: HookWrapper(phaseConfig.turn.onEnd, GameMethod.TURN_ON_END),
endIf: TriggerWrapper(phaseConfig.turn.endIf),
};
if (typeof phaseConfig.next !== 'function') {
const { next } = phaseConfig;
phaseConfig.next = () => next || null;
}
phaseConfig.wrapped.next = TriggerWrapper(phaseConfig.next);
}
function GetPhase(ctx) {
return ctx.phase ? phaseMap[ctx.phase] : phaseMap[''];
}
function OnMove(s) {
return s;
}
function Process(state, events) {
const phasesEnded = new Set();
const turnsEnded = new Set();
for (let i = 0; i < events.length; i++) {
const { fn, arg, ...rest } = events[i];
// Detect a loop of EndPhase calls.
// This could potentially even be an infinite loop
// if the endIf condition of each phase blindly
// returns true. The moment we detect a single
// loop, we just bail out of all phases.
if (fn === EndPhase) {
turnsEnded.clear();
const phase = state.ctx.phase;
if (phasesEnded.has(phase)) {
const ctx = { ...state.ctx, phase: null };
return { ...state, ctx };
}
phasesEnded.add(phase);
}
// Process event.
const next = [];
state = fn(state, {
...rest,
arg,
next,
});
if (fn === EndGame) {
break;
}
// Check if we should end the game.
const shouldEndGame = ShouldEndGame(state);
if (shouldEndGame) {
events.push({
fn: EndGame,
arg: shouldEndGame,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the phase.
const shouldEndPhase = ShouldEndPhase(state);
if (shouldEndPhase) {
events.push({
fn: EndPhase,
arg: shouldEndPhase,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the turn.
if ([OnMove, UpdateStage, UpdateActivePlayers].includes(fn)) {
const shouldEndTurn = ShouldEndTurn(state);
if (shouldEndTurn) {
events.push({
fn: EndTurn,
arg: shouldEndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
}
events.push(...next);
}
return state;
}
///////////
// Start //
///////////
function StartGame(state, { next }) {
next.push({ fn: StartPhase });
return state;
}
function StartPhase(state, { next }) {
let { G, ctx } = state;
const phaseConfig = GetPhase(ctx);
// Run any phase setup code provided by the user.
G = phaseConfig.wrapped.onBegin(state);
next.push({ fn: StartTurn });
return { ...state, G, ctx };
}
function StartTurn(state, { currentPlayer }) {
let { ctx } = state;
const phaseConfig = GetPhase(ctx);
// Initialize the turn order state.
if (currentPlayer) {
ctx = { ...ctx, currentPlayer };
if (phaseConfig.turn.activePlayers) {
ctx = SetActivePlayers(ctx, phaseConfig.turn.activePlayers);
}
}
else {
// This is only called at the beginning of the phase
// when there is no currentPlayer yet.
ctx = InitTurnOrderState(state, phaseConfig.turn);
}
const turn = ctx.turn + 1;
ctx = { ...ctx, turn, numMoves: 0, _prevActivePlayers: [] };
const G = phaseConfig.turn.wrapped.onBegin({ ...state, ctx });
return { ...state, G, ctx, _undo: [], _redo: [] };
}
////////////
// Update //
////////////
function UpdatePhase(state, { arg, next, phase }) {
const phaseConfig = GetPhase({ phase });
let { ctx } = state;
if (arg && arg.next) {
if (arg.next in phaseMap) {
ctx = { ...ctx, phase: arg.next };
}
else {
error('invalid phase: ' + arg.next);
return state;
}
}
else {
ctx = { ...ctx, phase: phaseConfig.wrapped.next(state) || null };
}
state = { ...state, ctx };
// Start the new phase.
next.push({ fn: StartPhase });
return state;
}
function UpdateTurn(state, { arg, currentPlayer, next }) {
let { G, ctx } = state;
const phaseConfig = GetPhase(ctx);
// Update turn order state.
const { endPhase, ctx: newCtx } = UpdateTurnOrderState(state, currentPlayer, phaseConfig.turn, arg);
ctx = newCtx;
state = { ...state, G, ctx };
if (endPhase) {
next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase });
}
else {
next.push({ fn: StartTurn, currentPlayer: ctx.currentPlayer });
}
return state;
}
function UpdateStage(state, { arg, playerID }) {
if (typeof arg === 'string' || arg === Stage.NULL) {
arg = { stage: arg };
}
if (typeof arg !== 'object')
return state;
// `arg` should be of type `StageArg`, loose typing as `any` here for historic reasons
// stages previously did not enforce minMoves, this behaviour is kept intentionally
supportDeprecatedMoveLimit(arg);
let { ctx } = state;
let { activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, _activePlayersNumMoves, } = ctx;
// Checking if stage is valid, even Stage.NULL
if (arg.stage !== undefined) {
if (activePlayers === null) {
activePlayers = {};
}
activePlayers[playerID] = arg.stage;
_activePlayersNumMoves[playerID] = 0;
if (arg.minMoves) {
if (_activePlayersMinMoves === null) {
_activePlayersMinMoves = {};
}
_activePlayersMinMoves[playerID] = arg.minMoves;
}
if (arg.maxMoves) {
if (_activePlayersMaxMoves === null) {
_activePlayersMaxMoves = {};
}
_activePlayersMaxMoves[playerID] = arg.maxMoves;
}
}
ctx = {
...ctx,
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
_activePlayersNumMoves,
};
return { ...state, ctx };
}
function UpdateActivePlayers(state, { arg }) {
return { ...state, ctx: SetActivePlayers(state.ctx, arg) };
}
///////////////
// ShouldEnd //
///////////////
function ShouldEndGame(state) {
return wrapped.endIf(state);
}
function ShouldEndPhase(state) {
const phaseConfig = GetPhase(state.ctx);
return phaseConfig.wrapped.endIf(state);
}
function ShouldEndTurn(state) {
const phaseConfig = GetPhase(state.ctx);
// End the turn if the required number of moves has been made.
const currentPlayerMoves = state.ctx.numMoves || 0;
if (phaseConfig.turn.maxMoves &&
currentPlayerMoves >= phaseConfig.turn.maxMoves) {
return true;
}
return phaseConfig.turn.wrapped.endIf(state);
}
/////////
// End //
/////////
function EndGame(state, { arg, phase }) {
state = EndPhase(state, { phase });
if (arg === undefined) {
arg = true;
}
state = { ...state, ctx: { ...state.ctx, gameover: arg } };
// Run game end hook.
const G = wrapped.onEnd(state);
return { ...state, G };
}
function EndPhase(state, { arg, next, turn: initialTurn, automatic }) {
// End the turn first.
state = EndTurn(state, { turn: initialTurn, force: true, automatic: true });
const { phase, turn } = state.ctx;
if (next) {
next.push({ fn: UpdatePhase, arg, phase });
}
// If we aren't in a phase, there is nothing else to do.
if (phase === null) {
return state;
}
// Run any cleanup code for the phase that is about to end.
const phaseConfig = GetPhase(state.ctx);
const G = phaseConfig.wrapped.onEnd(state);
// Reset the phase.
const ctx = { ...state.ctx, phase: null };
// Add log entry.
const action = gameEvent('endPhase', arg);
const { _stateID } = state;
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog };
}
function EndTurn(state, { arg, next, turn: initialTurn, force, automatic, playerID }) {
// This is not the turn that EndTurn was originally
// called for. The turn was probably ended some other way.
if (initialTurn !== state.ctx.turn) {
return state;
}
const { currentPlayer, numMoves, phase, turn } = state.ctx;
const phaseConfig = GetPhase(state.ctx);
// Prevent ending the turn if minMoves haven't been reached.
const currentPlayerMoves = numMoves || 0;
if (!force &&
phaseConfig.turn.minMoves &&
currentPlayerMoves < phaseConfig.turn.minMoves) {
info(`cannot end turn before making ${phaseConfig.turn.minMoves} moves`);
return state;
}
// Run turn-end triggers.
const G = phaseConfig.turn.wrapped.onEnd(state);
if (next) {
next.push({ fn: UpdateTurn, arg, currentPlayer });
}
// Reset activePlayers.
let ctx = { ...state.ctx, activePlayers: null };
// Remove player from playerOrder
if (arg && arg.remove) {
playerID = playerID || currentPlayer;
const playOrder = ctx.playOrder.filter((i) => i != playerID);
const playOrderPos = ctx.playOrderPos > playOrder.length - 1 ? 0 : ctx.playOrderPos;
ctx = { ...ctx, playOrder, playOrderPos };
if (playOrder.length === 0) {
next.push({ fn: EndPhase, turn, phase });
return state;
}
}
// Create log entry.
const action = gameEvent('endTurn', arg);
const { _stateID } = state;
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog, _undo: [], _redo: [] };
}
function EndStage(state, { arg, next, automatic, playerID }) {
playerID = playerID || state.ctx.currentPlayer;
let { ctx, _stateID } = state;
let { activePlayers, _activePlayersNumMoves, _activePlayersMinMoves, _activePlayersMaxMoves, phase, turn, } = ctx;
const playerInStage = activePlayers !== null && playerID in activePlayers;
const phaseConfig = GetPhase(ctx);
if (!arg && playerInStage) {
const stage = phaseConfig.turn.stages[activePlayers[playerID]];
if (stage && stage.next) {
arg = stage.next;
}
}
// Checking if arg is a valid stage, even Stage.NULL
if (next) {
next.push({ fn: UpdateStage, arg, playerID });
}
// If player isn’t in a stage, there is nothing else to do.
if (!playerInStage)
return state;
// Prevent ending the stage if minMoves haven't been reached.
const currentPlayerMoves = _activePlayersNumMoves[playerID] || 0;
if (_activePlayersMinMoves &&
_activePlayersMinMoves[playerID] &&
currentPlayerMoves < _activePlayersMinMoves[playerID]) {
info(`cannot end stage before making ${_activePlayersMinMoves[playerID]} moves`);
return state;
}
// Remove player from activePlayers.
activePlayers = { ...activePlayers };
delete activePlayers[playerID];
if (_activePlayersMinMoves) {
// Remove player from _activePlayersMinMoves.
_activePlayersMinMoves = { ..._activePlayersMinMoves };
delete _activePlayersMinMoves[playerID];
}
if (_activePlayersMaxMoves) {
// Remove player from _activePlayersMaxMoves.
_activePlayersMaxMoves = { ..._activePlayersMaxMoves };
delete _activePlayersMaxMoves[playerID];
}
ctx = UpdateActivePlayersOnceEmpty({
...ctx,
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
});
// Create log entry.
const action = gameEvent('endStage', arg);
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, ctx, deltalog };
}
/**
* Retrieves the relevant move that can be played by playerID.
*
* If ctx.activePlayers is set (i.e. one or more players are in some stage),
* then it attempts to find the move inside the stages config for
* that turn. If the stage for a player is '', then the player is
* allowed to make a move (as determined by the phase config), but
* isn't restricted to a particular set as defined in the stage config.
*
* If not, it then looks for the move inside the phase.
*
* If it doesn't find the move there, it looks at the global move definition.
*
* @param {object} ctx
* @param {string} name
* @param {string} playerID
*/
function GetMove(ctx, name, playerID) {
const phaseConfig = GetPhase(ctx);
const stages = phaseConfig.turn.stages;
const { activePlayers } = ctx;
if (activePlayers &&
activePlayers[playerID] !== undefined &&
activePlayers[playerID] !== Stage.NULL &&
stages[activePlayers[playerID]] !== undefined &&
stages[activePlayers[playerID]].moves !== undefined) {
// Check if moves are defined for the player's stage.
const stage = stages[activePlayers[playerID]];
const moves = stage.moves;
if (name in moves) {
return moves[name];
}
}
else if (phaseConfig.moves) {
// Check if moves are defined for the current phase.
if (name in phaseConfig.moves) {
return phaseConfig.moves[name];
}
}
else if (name in moves) {
// Check for the move globally.
return moves[name];
}
return null;
}
function ProcessMove(state, action) {
const { playerID, type } = action;
const { ctx } = state;
const { currentPlayer, activePlayers, _activePlayersMaxMoves } = ctx;
const move = GetMove(ctx, type, playerID);
const shouldCount = !move || typeof move === 'function' || move.noLimit !== true;
let { numMoves, _activePlayersNumMoves } = ctx;
if (shouldCount) {
if (playerID === currentPlayer)
numMoves++;
if (activePlayers)
_activePlayersNumMoves[playerID]++;
}
state = {
...state,
ctx: {
...ctx,
numMoves,
_activePlayersNumMoves,
},
};
if (_activePlayersMaxMoves &&
_activePlayersNumMoves[playerID] >= _activePlayersMaxMoves[playerID]) {
state = EndStage(state, { playerID, automatic: true });
}
const phaseConfig = GetPhase(ctx);
const G = phaseConfig.turn.wrapped.onMove({
...state,
ctx: { ...ctx, playerID },
});
state = { ...state, G };
const events = [{ fn: OnMove }];
return Process(state, events);
}
function SetStageEvent(state, playerID, arg) {
return Process(state, [{ fn: EndStage, arg, playerID }]);
}
function EndStageEvent(state, playerID) {
return Process(state, [{ fn: EndStage, playerID }]);
}
function SetActivePlayersEvent(state, _playerID, arg) {
return Process(state, [{ fn: UpdateActivePlayers, arg }]);
}
function SetPhaseEvent(state, _playerID, newPhase) {
return Process(state, [
{
fn: EndPhase,
phase: state.ctx.phase,
turn: state.ctx.turn,
arg: { next: newPhase },
},
]);
}
function EndPhaseEvent(state) {
return Process(state, [
{ fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn },
]);
}
function EndTurnEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
function PassEvent(state, _playerID, arg) {
return Process(state, [
{
fn: EndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
force: true,
arg,
},
]);
}
function EndGameEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndGame, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
const eventHandlers = {
endStage: EndStageEvent,
setStage: SetStageEvent,
endTurn: EndTurnEvent,
pass: PassEvent,
endPhase: EndPhaseEvent,
setPhase: SetPhaseEvent,
endGame: EndGameEvent,
setActivePlayers: SetActivePlayersEvent,
};
const enabledEventNames = [];
if (events.endTurn !== false) {
enabledEventNames.push('endTurn');
}
if (events.pass !== false) {
enabledEventNames.push('pass');
}
if (events.endPhase !== false) {
enabledEventNames.push('endPhase');
}
if (events.setPhase !== false) {
enabledEventNames.push('setPhase');
}
if (events.endGame !== false) {
enabledEventNames.push('endGame');
}
if (events.setActivePlayers !== false) {
enabledEventNames.push('setActivePlayers');
}
if (events.endStage !== false) {
enabledEventNames.push('endStage');
}
if (events.setStage !== false) {
enabledEventNames.push('setStage');
}
function ProcessEvent(state, action) {
const { type, playerID, args } = action.payload;
if (typeof eventHandlers[type] !== 'function')
return state;
return eventHandlers[type](state, playerID, ...(Array.isArray(args) ? args : [args]));
}
function IsPlayerActive(_G, ctx, playerID) {
if (ctx.activePlayers) {
return playerID in ctx.activePlayers;
}
return ctx.currentPlayer === playerID;
}
return {
ctx: (numPlayers) => ({
numPlayers,
turn: 0,
currentPlayer: '0',
playOrder: [...Array.from({ length: numPlayers })].map((_, i) => i + ''),
playOrderPos: 0,
phase: startingPhase,
activePlayers: null,
}),
init: (state) => {
return Process(state, [{ fn: StartGame }]);
},
isPlayerActive: IsPlayerActive,
eventHandlers,
eventNames: Object.keys(eventHandlers),
enabledEventNames,
moveMap,
moveNames: [...moveNames.values()],
processMove: ProcessMove,
processEvent: ProcessEvent,
getMove: GetMove,
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function IsProcessed(game) {
return game.processMove !== undefined;
}
/**
* Helper to generate the game move reducer. The returned
* reducer has the following signature:
*
* (G, action, ctx) => {}
*
* You can roll your own if you like, or use any Redux
* addon to generate such a reducer.
*
* The convention used in this framework is to
* have action.type contain the name of the move, and
* action.args contain any additional arguments as an
* Array.
*/
function ProcessGameConfig(game) {
// The Game() function has already been called on this
// config object, so just pass it through.
if (IsProcessed(game)) {
return game;
}
if (game.name === undefined)
game.name = 'default';
if (game.deltaState === undefined)
game.deltaState = false;
if (game.disableUndo === undefined)
game.disableUndo = false;
if (game.setup === undefined)
game.setup = () => ({});
if (game.moves === undefined)
game.moves = {};
if (game.playerView === undefined)
game.playerView = (G) => G;
if (game.plugins === undefined)
game.plugins = [];
game.plugins.forEach((plugin) => {
if (plugin.name === undefined) {
throw new Error('Plugin missing name attribute');
}
if (plugin.name.includes(' ')) {
throw new Error(plugin.name + ': Plugin name must not include spaces');
}
});
if (game.name.includes(' ')) {
throw new Error(game.name + ': Game name must not include spaces');
}
const flow = Flow(game);
return {
...game,
flow,
moveNames: flow.moveNames,
pluginNames: game.plugins.map((p) => p.name),
processMove: (state, action) => {
let moveFn = flow.getMove(state.ctx, action.type, action.playerID);
if (IsLongFormMove(moveFn)) {
moveFn = moveFn.move;
}
if (moveFn instanceof Function) {
const fn = FnWrap(moveFn, GameMethod.MOVE, game.plugins);
const ctxWithAPI = {
...EnhanceCtx(state),
playerID: action.playerID,
};
let args = [];
if (action.args !== undefined) {
args = Array.isArray(action.args) ? action.args : [action.args];
}
return fn(state.G, ctxWithAPI, ...args);
}
error(`invalid move object: ${action.type}`);
return state.G;
},
};
}
function IsLongFormMove(move) {
return move instanceof Object && move.move !== undefined;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
var UpdateErrorType;
(function (UpdateErrorType) {
// The action’s credentials were missing or invalid
UpdateErrorType["UnauthorizedAction"] = "update/unauthorized_action";
// The action’s matchID was not found
UpdateErrorType["MatchNotFound"] = "update/match_not_found";
// Could not apply Patch operation (rfc6902).
UpdateErrorType["PatchFailed"] = "update/patch_failed";
})(UpdateErrorType || (UpdateErrorType = {}));
var ActionErrorType;
(function (ActionErrorType) {
// The action contained a stale state ID
ActionErrorType["StaleStateId"] = "action/stale_state_id";
// The requested move is unknown or not currently available
ActionErrorType["UnavailableMove"] = "action/unavailable_move";
// The move declared it was invalid (INVALID_MOVE constant)
ActionErrorType["InvalidMove"] = "action/invalid_move";
// The player making the action is not currently active
ActionErrorType["InactivePlayer"] = "action/inactive_player";
// The game has finished
ActionErrorType["GameOver"] = "action/gameover";
// The requested action is disabled (e.g. undo/redo, events)
ActionErrorType["ActionDisabled"] = "action/action_disabled";
// The requested action is not currently possible
ActionErrorType["ActionInvalid"] = "action/action_invalid";
// The requested action was declared invalid by a plugin
ActionErrorType["PluginActionInvalid"] = "action/plugin_invalid";
})(ActionErrorType || (ActionErrorType = {}));
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Check if the payload for the passed action contains a playerID.
*/
const actionHasPlayerID = (action) => action.payload.playerID !== null && action.payload.playerID !== undefined;
/**
* Returns true if a move can be undone.
*/
const CanUndoMove = (G, ctx, move) => {
function HasUndoable(move) {
return move.undoable !== undefined;
}
function IsFunction(undoable) {
return undoable instanceof Function;
}
if (!HasUndoable(move)) {
return true;
}
if (IsFunction(move.undoable)) {
return move.undoable(G, ctx);
}
return move.undoable;
};
/**
* Update the undo and redo stacks for a move or event.
*/
function updateUndoRedoState(state, opts) {
if (opts.game.disableUndo)
return state;
const undoEntry = {
G: state.G,
ctx: state.ctx,
plugins: state.plugins,
playerID: opts.action.payload.playerID || state.ctx.currentPlayer,
};
if (opts.action.type === 'MAKE_MOVE') {
undoEntry.moveType = opts.action.payload.type;
}
return {
...state,
_undo: [...state._undo, undoEntry],
// Always reset redo stack when making a move or event
_redo: [],
};
}
/**
* Process state, adding the initial deltalog for this action.
*/
function initializeDeltalog(state, action, move) {
// Create a log entry for this action.
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
const pluginLogMetadata = state.plugins.log.data.metadata;
if (pluginLogMetadata !== undefined) {
logEntry.metadata = pluginLogMetadata;
}
if (typeof move === 'object' && move.redact === true) {
logEntry.redact = true;
}
return {
...state,
deltalog: [logEntry],
};
}
/**
* Update plugin state after move/event & check if plugins consider the action to be valid.
* @param state Current version of state in the reducer.
* @param oldState State to revert to in case of error.
* @param pluginOpts Plugin configuration options.
* @returns Tuple of the new state updated after flushing plugins and the old
* state augmented with an error if a plugin declared the action invalid.
*/
function flushAndValidatePlugins(state, oldState, pluginOpts) {
const [newState, isInvalid] = FlushAndValidate(state, pluginOpts);
if (!isInvalid)
return [newState];
return [
newState,
WithError(oldState, ActionErrorType.PluginActionInvalid, isInvalid),
];
}
/**
* ExtractTransientsFromState
*
* Split out transients from the a TransientState
*/
function ExtractTransients(transientState) {
if (!transientState) {
// We preserve null for the state for legacy callers, but the transient
// field should be undefined if not present to be consistent with the
// code path below.
return [null, undefined];
}
const { transients, ...state } = transientState;
return [state, transients];
}
/**
* WithError
*
* Augment a State instance with transient error information.
*/
function WithError(state, errorType, payload) {
const error = {
type: errorType,
payload,
};
return {
...state,
transients: {
error,
},
};
}
/**
* Middleware for processing TransientState associated with the reducer
* returned by CreateGameReducer.
* This should pretty much be used everywhere you want realistic state
* transitions and error handling.
*/
const TransientHandlingMiddleware = (store) => (next) => (action) => {
const result = next(action);
switch (action.type) {
case STRIP_TRANSIENTS: {
return result;
}
default: {
const [, transients] = ExtractTransients(store.getState());
if (typeof transients !== 'undefined') {
store.dispatch(stripTransients());
// Dev Note: If parent middleware needs to correlate the spawned
// StripTransients action to the triggering action, instrument here.
//
// This is a bit tricky; for more details, see:
// https://github.com/boardgameio/boardgame.io/pull/940#discussion_r636200648
return {
...result,
transients,
};
}
return result;
}
}
};
/**
* CreateGameReducer
*
* Creates the main game state reducer.
*/
function CreateGameReducer({ game, isClient, }) {
game = ProcessGameConfig(game);
/**
* GameReducer
*
* Redux reducer that maintains the overall game state.
* @param {object} state - The state before the action.
* @param {object} action - A Redux action.
*/
return (stateWithTransients = null, action) => {
let [state /*, transients */] = ExtractTransients(stateWithTransients);
switch (action.type) {
case STRIP_TRANSIENTS: {
// This action indicates that transient metadata in the state has been
// consumed and should now be stripped from the state..
return state;
}
case GAME_EVENT: {
state = { ...state, deltalog: [] };
// Process game events only on the server.
// These events like `endTurn` typically
// contain code that may rely on secret state
// and cannot be computed on the client.
if (isClient) {
return state;
}
// Disallow events once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot call event after game end`);
return WithError(state, ActionErrorType.GameOver);
}
// Ignore the event if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed event: ${action.payload.type}`);
return WithError(state, ActionErrorType.InactivePlayer);
}
// Execute plugins.
state = Enhance(state, {
game,
isClient: false,
playerID: action.payload.playerID,
});
// Process event.
let newState = game.flow.processEvent(state, action);
// Execute plugins.
let stateWithError;
[newState, stateWithError] = flushAndValidatePlugins(newState, state, {
game,
isClient: false,
});
if (stateWithError)
return stateWithError;
// Update undo / redo state.
newState = updateUndoRedoState(newState, { game, action });
return { ...newState, _stateID: state._stateID + 1 };
}
case MAKE_MOVE: {
const oldState = (state = { ...state, deltalog: [] });
// Check whether the move is allowed at this time.
const move = game.flow.getMove(state.ctx, action.payload.type, action.payload.playerID || state.ctx.currentPlayer);
if (move === null) {
error(`disallowed move: ${action.payload.type}`);
return WithError(state, ActionErrorType.UnavailableMove);
}
// Don't run move on client if move says so.
if (isClient && move.client === false) {
return state;
}
// Disallow moves once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot make move after game end`);
return WithError(state, ActionErrorType.GameOver);
}
// Ignore the move if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed move: ${action.payload.type}`);
return WithError(state, ActionErrorType.InactivePlayer);
}
// Execute plugins.
state = Enhance(state, {
game,
isClient,
playerID: action.payload.playerID,
});
// Process the move.
const G = game.processMove(state, action.payload);
// The game declared the move as invalid.
if (G === INVALID_MOVE) {
error(`invalid move: ${action.payload.type} args: ${action.payload.args}`);
// TODO(#723): Marshal a nice error payload with the processed move.
return WithError(state, ActionErrorType.InvalidMove);
}
const newState = { ...state, G };
// Some plugin indicated that it is not suitable to be
// materialized on the client (and must wait for the server
// response instead).
if (isClient && NoClient(newState, { game })) {
return state;
}
state = newState;
// If we're on the client, just process the move
// and no triggers in multiplayer mode.
// These will be processed on the server, which
// will send back a state update.
if (isClient) {
let stateWithError;
[state, stateWithError] = flushAndValidatePlugins(state, oldState, {
game,
isClient: true,
});
if (stateWithError)
return stateWithError;
return {
...state,
_stateID: state._stateID + 1,
};
}
// On the server, construct the deltalog.
state = initializeDeltalog(state, action, move);
// Allow the flow reducer to process any triggers that happen after moves.
state = game.flow.processMove(state, action.payload);
let stateWithError;
[state, stateWithError] = flushAndValidatePlugins(state, oldState, {
game,
});
if (stateWithError)
return stateWithError;
// Update undo / redo state.
state = updateUndoRedoState(state, { game, action });
return {
...state,
_stateID: state._stateID + 1,
};
}
case RESET:
case UPDATE:
case SYNC: {
return action.state;
}
case UNDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Undo is not enabled');
return WithError(state, ActionErrorType.ActionDisabled);
}
const { G, ctx, _undo, _redo, _stateID } = state;
if (_undo.length < 2) {
error(`No moves to undo`);
return WithError(state, ActionErrorType.ActionInvalid);
}
const last = _undo[_undo.length - 1];
const restore = _undo[_undo.length - 2];
// Only allow players to undo their own moves.
if (actionHasPlayerID(action) &&
action.payload.playerID !== last.playerID) {
error(`Cannot undo other players' moves`);
return WithError(state, ActionErrorType.ActionInvalid);
}
// If undoing a move, check it is undoable.
if (last.moveType) {
const lastMove = game.flow.getMove(restore.ctx, last.moveType, last.playerID);
if (!CanUndoMove(G, ctx, lastMove)) {
error(`Move cannot be undone`);
return WithError(state, ActionErrorType.ActionInvalid);
}
}
state = initializeDeltalog(state, action);
return {
...state,
G: restore.G,
ctx: restore.ctx,
plugins: restore.plugins,
_stateID: _stateID + 1,
_undo: _undo.slice(0, -1),
_redo: [last, ..._redo],
};
}
case REDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Redo is not enabled');
return WithError(state, ActionErrorType.ActionDisabled);
}
const { _undo, _redo, _stateID } = state;
if (_redo.length === 0) {
error(`No moves to redo`);
return WithError(state, ActionErrorType.ActionInvalid);
}
const first = _redo[0];
// Only allow players to redo their own undos.
if (actionHasPlayerID(action) &&
action.payload.playerID !== first.playerID) {
error(`Cannot redo other players' moves`);
return WithError(state, ActionErrorType.ActionInvalid);
}
state = initializeDeltalog(state, action);
return {
...state,
G: first.G,
ctx: first.ctx,
plugins: first.plugins,
_stateID: _stateID + 1,
_undo: [..._undo, first],
_redo: _redo.slice(1),
};
}
case PLUGIN: {
// TODO(#723): Expose error semantics to plugin processing.
return ProcessAction(state, action, { game });
}
case PATCH: {
const oldState = state;
const newState = JSON.parse(JSON.stringify(oldState));
const patchError = applyPatch(newState, action.patch);
const hasError = patchError.some((entry) => entry !== null);
if (hasError) {
error(`Patch ${JSON.stringify(action.patch)} apply failed`);
return WithError(oldState, UpdateErrorType.PatchFailed, patchError);
}
else {
return newState;
}
}
default: {
return state;
}
}
};
}
/*
* Copyright 2020 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Creates the initial game state.
*/
function InitializeGame({ game, numPlayers, setupData, }) {
game = ProcessGameConfig(game);
if (!numPlayers) {
numPlayers = 2;
}
const ctx = game.flow.ctx(numPlayers);
let state = {
// User managed state.
G: {},
// Framework managed state.
ctx,
// Plugin related state.
plugins: {},
};
// Run plugins over initial state.
state = Setup(state, { game });
state = Enhance(state, { game, playerID: undefined });
const enhancedCtx = EnhanceCtx(state);
state.G = game.setup(enhancedCtx, setupData);
let initial = {
...state,
// List of {G, ctx} pairs that can be undone.
_undo: [],
// List of {G, ctx} pairs that can be redone.
_redo: [],
// A monotonically non-decreasing ID to ensure that
// state updates are only allowed from clients that
// are at the same version that the server.
_stateID: 0,
};
initial = game.flow.init(initial);
[initial] = FlushAndValidate(initial, { game });
// Initialize undo stack.
if (!game.disableUndo) {
initial._undo = [
{
G: initial.G,
ctx: initial.ctx,
plugins: initial.plugins,
},
];
}
return initial;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
class Transport {
constructor({ transportDataCallback, gameName, playerID, matchID, credentials, numPlayers, }) {
/** Callback to let the client know when the connection status has changed. */
this.connectionStatusCallback = () => { };
this.isConnected = false;
this.transportDataCallback = transportDataCallback;
this.gameName = gameName || 'default';
this.playerID = playerID || null;
this.matchID = matchID || 'default';
this.credentials = credentials;
this.numPlayers = numPlayers || 2;
}
/** Subscribe to connection state changes. */
subscribeToConnectionStatus(fn) {
this.connectionStatusCallback = fn;
}
/** Transport implementations should call this when they connect/disconnect. */
setConnectionStatus(isConnected) {
this.isConnected = isConnected;
this.connectionStatusCallback();
}
/** Transport implementations should call this when they receive data from a master. */
notifyClient(data) {
this.transportDataCallback(data);
}
}
/**
* This class doesn’t do anything, but simplifies the client class by providing
* dummy functions to call, so we don’t need to mock them in the client.
*/
class DummyImpl extends Transport {
connect() { }
disconnect() { }
sendAction() { }
sendChatMessage() { }
requestSync() { }
updateCredentials() { }
updateMatchID() { }
updatePlayerID() { }
}
const DummyTransport = (opts) => new DummyImpl(opts);
const subscriber_queue = [];
/**
* Create a `Writable` store that allows both updating and reading by subscription.
* @param {*=}value initial value
* @param {StartStopNotifier=}start start and stop notifications for subscriptions
*/
function writable(value, start = noop) {
let stop;
const subscribers = new Set();
function set(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
if (stop) { // store is ready
const run_queue = !subscriber_queue.length;
for (const subscriber of subscribers) {
subscriber[1]();
subscriber_queue.push(subscriber, value);
}
if (run_queue) {
for (let i = 0; i < subscriber_queue.length; i += 2) {
subscriber_queue[i][0](subscriber_queue[i + 1]);
}
subscriber_queue.length = 0;
}
}
}
}
function update(fn) {
set(fn(value));
}
function subscribe(run, invalidate = noop) {
const subscriber = [run, invalidate];
subscribers.add(subscriber);
if (subscribers.size === 1) {
stop = start(set) || noop;
}
run(value);
return () => {
subscribers.delete(subscriber);
if (subscribers.size === 0) {
stop();
stop = null;
}
};
}
return { set, update, subscribe };
}
function cubicOut(t) {
const f = t - 1.0;
return f * f * f + 1.0;
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function fly(node, { delay = 0, duration = 400, easing = cubicOut, x = 0, y = 0, opacity = 0 } = {}) {
const style = getComputedStyle(node);
const target_opacity = +style.opacity;
const transform = style.transform === 'none' ? '' : style.transform;
const od = target_opacity * (1 - opacity);
return {
delay,
duration,
easing,
css: (t, u) => `
transform: ${transform} translate(${(1 - t) * x}px, ${(1 - t) * y}px);
opacity: ${target_opacity - (od * u)}`
};
}
function crossfade(_a) {
var { fallback } = _a, defaults = __rest(_a, ["fallback"]);
const to_receive = new Map();
const to_send = new Map();
function crossfade(from, node, params) {
const { delay = 0, duration = d => Math.sqrt(d) * 30, easing = cubicOut } = assign(assign({}, defaults), params);
const to = node.getBoundingClientRect();
const dx = from.left - to.left;
const dy = from.top - to.top;
const dw = from.width / to.width;
const dh = from.height / to.height;
const d = Math.sqrt(dx * dx + dy * dy);
const style = getComputedStyle(node);
const transform = style.transform === 'none' ? '' : style.transform;
const opacity = +style.opacity;
return {
delay,
duration: is_function(duration) ? duration(d) : duration,
easing,
css: (t, u) => `
opacity: ${t * opacity};
transform-origin: top left;
transform: ${transform} translate(${u * dx}px,${u * dy}px) scale(${t + (1 - t) * dw}, ${t + (1 - t) * dh});
`
};
}
function transition(items, counterparts, intro) {
return (node, params) => {
items.set(params.key, {
rect: node.getBoundingClientRect()
});
return () => {
if (counterparts.has(params.key)) {
const { rect } = counterparts.get(params.key);
counterparts.delete(params.key);
return crossfade(rect, node, params);
}
// if the node is disappearing altogether
// (i.e. wasn't claimed by the other list)
// then we need to supply an outro
items.delete(params.key);
return fallback && fallback(node, params, intro);
};
};
}
return [
transition(to_send, to_receive, false),
transition(to_receive, to_send, true)
];
}
/* node_modules/svelte-icons/components/IconBase.svelte generated by Svelte v3.41.0 */
function add_css(target) {
append_styles(target, "svelte-c8tyih", "svg.svelte-c8tyih{stroke:currentColor;fill:currentColor;stroke-width:0;width:100%;height:auto;max-height:100%}");
}
// (18:2) {#if title}
function create_if_block(ctx) {
let title_1;
let t;
return {
c() {
title_1 = svg_element("title");
t = text(/*title*/ ctx[0]);
},
m(target, anchor) {
insert(target, title_1, anchor);
append(title_1, t);
},
p(ctx, dirty) {
if (dirty & /*title*/ 1) set_data(t, /*title*/ ctx[0]);
},
d(detaching) {
if (detaching) detach(title_1);
}
};
}
function create_fragment(ctx) {
let svg;
let if_block_anchor;
let current;
let if_block = /*title*/ ctx[0] && create_if_block(ctx);
const default_slot_template = /*#slots*/ ctx[3].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[2], null);
return {
c() {
svg = svg_element("svg");
if (if_block) if_block.c();
if_block_anchor = empty();
if (default_slot) default_slot.c();
attr(svg, "xmlns", "http://www.w3.org/2000/svg");
attr(svg, "viewBox", /*viewBox*/ ctx[1]);
attr(svg, "class", "svelte-c8tyih");
},
m(target, anchor) {
insert(target, svg, anchor);
if (if_block) if_block.m(svg, null);
append(svg, if_block_anchor);
if (default_slot) {
default_slot.m(svg, null);
}
current = true;
},
p(ctx, [dirty]) {
if (/*title*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block(ctx);
if_block.c();
if_block.m(svg, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (default_slot) {
if (default_slot.p && (!current || dirty & /*$$scope*/ 4)) {
update_slot_base(
default_slot,
default_slot_template,
ctx,
/*$$scope*/ ctx[2],
!current
? get_all_dirty_from_scope(/*$$scope*/ ctx[2])
: get_slot_changes(default_slot_template, /*$$scope*/ ctx[2], dirty, null),
null
);
}
}
if (!current || dirty & /*viewBox*/ 2) {
attr(svg, "viewBox", /*viewBox*/ ctx[1]);
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (detaching) detach(svg);
if (if_block) if_block.d();
if (default_slot) default_slot.d(detaching);
}
};
}
function instance($$self, $$props, $$invalidate) {
let { $$slots: slots = {}, $$scope } = $$props;
let { title = null } = $$props;
let { viewBox } = $$props;
$$self.$$set = $$props => {
if ('title' in $$props) $$invalidate(0, title = $$props.title);
if ('viewBox' in $$props) $$invalidate(1, viewBox = $$props.viewBox);
if ('$$scope' in $$props) $$invalidate(2, $$scope = $$props.$$scope);
};
return [title, viewBox, $$scope, slots];
}
class IconBase extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, create_fragment, safe_not_equal, { title: 0, viewBox: 1 }, add_css);
}
}
/* node_modules/svelte-icons/fa/FaChevronRight.svelte generated by Svelte v3.41.0 */
function create_default_slot(ctx) {
let path;
return {
c() {
path = svg_element("path");
attr(path, "d", "M285.476 272.971L91.132 467.314c-9.373 9.373-24.569 9.373-33.941 0l-22.667-22.667c-9.357-9.357-9.375-24.522-.04-33.901L188.505 256 34.484 101.255c-9.335-9.379-9.317-24.544.04-33.901l22.667-22.667c9.373-9.373 24.569-9.373 33.941 0L285.475 239.03c9.373 9.372 9.373 24.568.001 33.941z");
},
m(target, anchor) {
insert(target, path, anchor);
},
d(detaching) {
if (detaching) detach(path);
}
};
}
function create_fragment$1(ctx) {
let iconbase;
let current;
const iconbase_spread_levels = [{ viewBox: "0 0 320 512" }, /*$$props*/ ctx[0]];
let iconbase_props = {
$$slots: { default: [create_default_slot] },
$$scope: { ctx }
};
for (let i = 0; i < iconbase_spread_levels.length; i += 1) {
iconbase_props = assign(iconbase_props, iconbase_spread_levels[i]);
}
iconbase = new IconBase({ props: iconbase_props });
return {
c() {
create_component(iconbase.$$.fragment);
},
m(target, anchor) {
mount_component(iconbase, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const iconbase_changes = (dirty & /*$$props*/ 1)
? get_spread_update(iconbase_spread_levels, [iconbase_spread_levels[0], get_spread_object(/*$$props*/ ctx[0])])
: {};
if (dirty & /*$$scope*/ 2) {
iconbase_changes.$$scope = { dirty, ctx };
}
iconbase.$set(iconbase_changes);
},
i(local) {
if (current) return;
transition_in(iconbase.$$.fragment, local);
current = true;
},
o(local) {
transition_out(iconbase.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(iconbase, detaching);
}
};
}
function instance$1($$self, $$props, $$invalidate) {
$$self.$$set = $$new_props => {
$$invalidate(0, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
};
$$props = exclude_internal_props($$props);
return [$$props];
}
class FaChevronRight extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$1, create_fragment$1, safe_not_equal, {});
}
}
/* src/client/debug/Menu.svelte generated by Svelte v3.41.0 */
function add_css$1(target) {
append_styles(target, "svelte-1xg9v5h", ".menu.svelte-1xg9v5h{display:flex;margin-top:43px;flex-direction:row-reverse;border:1px solid #ccc;border-radius:5px 5px 0 0;height:25px;line-height:25px;margin-right:-500px;transform-origin:bottom right;transform:rotate(-90deg) translate(0, -500px)}.menu-item.svelte-1xg9v5h{line-height:25px;cursor:pointer;border:0;background:#fefefe;color:#555;padding-left:15px;padding-right:15px;text-align:center}.menu-item.svelte-1xg9v5h:first-child{border-radius:0 5px 0 0}.menu-item.svelte-1xg9v5h:last-child{border-radius:5px 0 0 0}.menu-item.active.svelte-1xg9v5h{cursor:default;font-weight:bold;background:#ddd;color:#555}.menu-item.svelte-1xg9v5h:hover,.menu-item.svelte-1xg9v5h:focus{background:#eee;color:#555}");
}
function get_each_context(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[4] = list[i][0];
child_ctx[5] = list[i][1].label;
return child_ctx;
}
// (57:2) {#each Object.entries(panes) as [key, {label}
function create_each_block(ctx) {
let button;
let t0_value = /*label*/ ctx[5] + "";
let t0;
let t1;
let mounted;
let dispose;
function click_handler() {
return /*click_handler*/ ctx[3](/*key*/ ctx[4]);
}
return {
c() {
button = element("button");
t0 = text(t0_value);
t1 = space();
attr(button, "class", "menu-item svelte-1xg9v5h");
toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, t0);
append(button, t1);
if (!mounted) {
dispose = listen(button, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*panes*/ 2 && t0_value !== (t0_value = /*label*/ ctx[5] + "")) set_data(t0, t0_value);
if (dirty & /*pane, Object, panes*/ 3) {
toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]);
}
},
d(detaching) {
if (detaching) detach(button);
mounted = false;
dispose();
}
};
}
function create_fragment$2(ctx) {
let nav;
let each_value = Object.entries(/*panes*/ ctx[1]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
}
return {
c() {
nav = element("nav");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(nav, "class", "menu svelte-1xg9v5h");
},
m(target, anchor) {
insert(target, nav, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(nav, null);
}
},
p(ctx, [dirty]) {
if (dirty & /*pane, Object, panes, dispatch*/ 7) {
each_value = Object.entries(/*panes*/ ctx[1]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block(child_ctx);
each_blocks[i].c();
each_blocks[i].m(nav, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(nav);
destroy_each(each_blocks, detaching);
}
};
}
function instance$2($$self, $$props, $$invalidate) {
let { pane } = $$props;
let { panes } = $$props;
const dispatch = createEventDispatcher();
const click_handler = key => dispatch('change', key);
$$self.$$set = $$props => {
if ('pane' in $$props) $$invalidate(0, pane = $$props.pane);
if ('panes' in $$props) $$invalidate(1, panes = $$props.panes);
};
return [pane, panes, dispatch, click_handler];
}
class Menu extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$2, create_fragment$2, safe_not_equal, { pane: 0, panes: 1 }, add_css$1);
}
}
var contextKey = {};
/* node_modules/svelte-json-tree-auto/src/JSONArrow.svelte generated by Svelte v3.41.0 */
function add_css$2(target) {
append_styles(target, "svelte-1vyml86", ".container.svelte-1vyml86{display:inline-block;cursor:pointer;transform:translate(calc(0px - var(--li-identation)), -50%);position:absolute;top:50%;padding-right:100%}.arrow.svelte-1vyml86{transform-origin:25% 50%;position:relative;line-height:1.1em;font-size:0.75em;margin-left:0;transition:150ms;color:var(--arrow-sign);user-select:none;font-family:'Courier New', Courier, monospace}.expanded.svelte-1vyml86{transform:rotateZ(90deg) translateX(-3px)}");
}
function create_fragment$3(ctx) {
let div1;
let div0;
let mounted;
let dispose;
return {
c() {
div1 = element("div");
div0 = element("div");
div0.textContent = `${'\u25B6'}`;
attr(div0, "class", "arrow svelte-1vyml86");
toggle_class(div0, "expanded", /*expanded*/ ctx[0]);
attr(div1, "class", "container svelte-1vyml86");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, div0);
if (!mounted) {
dispose = listen(div1, "click", /*click_handler*/ ctx[1]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*expanded*/ 1) {
toggle_class(div0, "expanded", /*expanded*/ ctx[0]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div1);
mounted = false;
dispose();
}
};
}
function instance$3($$self, $$props, $$invalidate) {
let { expanded } = $$props;
function click_handler(event) {
bubble.call(this, $$self, event);
}
$$self.$$set = $$props => {
if ('expanded' in $$props) $$invalidate(0, expanded = $$props.expanded);
};
return [expanded, click_handler];
}
class JSONArrow extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$3, create_fragment$3, safe_not_equal, { expanded: 0 }, add_css$2);
}
}
/* node_modules/svelte-json-tree-auto/src/JSONKey.svelte generated by Svelte v3.41.0 */
function add_css$3(target) {
append_styles(target, "svelte-1vlbacg", "label.svelte-1vlbacg{display:inline-block;color:var(--label-color);padding:0}.spaced.svelte-1vlbacg{padding-right:var(--li-colon-space)}");
}
// (16:0) {#if showKey && key}
function create_if_block$1(ctx) {
let label;
let span;
let t0;
let t1;
let mounted;
let dispose;
return {
c() {
label = element("label");
span = element("span");
t0 = text(/*key*/ ctx[0]);
t1 = text(/*colon*/ ctx[2]);
attr(label, "class", "svelte-1vlbacg");
toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]);
},
m(target, anchor) {
insert(target, label, anchor);
append(label, span);
append(span, t0);
append(span, t1);
if (!mounted) {
dispose = listen(label, "click", /*click_handler*/ ctx[5]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*key*/ 1) set_data(t0, /*key*/ ctx[0]);
if (dirty & /*colon*/ 4) set_data(t1, /*colon*/ ctx[2]);
if (dirty & /*isParentExpanded*/ 2) {
toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]);
}
},
d(detaching) {
if (detaching) detach(label);
mounted = false;
dispose();
}
};
}
function create_fragment$4(ctx) {
let if_block_anchor;
let if_block = /*showKey*/ ctx[3] && /*key*/ ctx[0] && create_if_block$1(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*showKey*/ ctx[3] && /*key*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$1(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop,
o: noop,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function instance$4($$self, $$props, $$invalidate) {
let showKey;
let { key, isParentExpanded, isParentArray = false, colon = ':' } = $$props;
function click_handler(event) {
bubble.call(this, $$self, event);
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ('colon' in $$props) $$invalidate(2, colon = $$props.colon);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*isParentExpanded, isParentArray, key*/ 19) {
$$invalidate(3, showKey = isParentExpanded || !isParentArray || key != +key);
}
};
return [key, isParentExpanded, colon, showKey, isParentArray, click_handler];
}
class JSONKey extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$4,
create_fragment$4,
safe_not_equal,
{
key: 0,
isParentExpanded: 1,
isParentArray: 4,
colon: 2
},
add_css$3
);
}
}
/* node_modules/svelte-json-tree-auto/src/JSONNested.svelte generated by Svelte v3.41.0 */
function add_css$4(target) {
append_styles(target, "svelte-rwxv37", "label.svelte-rwxv37{display:inline-block}.indent.svelte-rwxv37{padding-left:var(--li-identation)}.collapse.svelte-rwxv37{--li-display:inline;display:inline;font-style:italic}.comma.svelte-rwxv37{margin-left:-0.5em;margin-right:0.5em}label.svelte-rwxv37{position:relative}");
}
function get_each_context$1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[12] = list[i];
child_ctx[20] = i;
return child_ctx;
}
// (57:4) {#if expandable && isParentExpanded}
function create_if_block_3(ctx) {
let jsonarrow;
let current;
jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } });
jsonarrow.$on("click", /*toggleExpand*/ ctx[15]);
return {
c() {
create_component(jsonarrow.$$.fragment);
},
m(target, anchor) {
mount_component(jsonarrow, target, anchor);
current = true;
},
p(ctx, dirty) {
const jsonarrow_changes = {};
if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0];
jsonarrow.$set(jsonarrow_changes);
},
i(local) {
if (current) return;
transition_in(jsonarrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonarrow.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonarrow, detaching);
}
};
}
// (75:4) {:else}
function create_else_block(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = "…";
},
m(target, anchor) {
insert(target, span, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(span);
}
};
}
// (63:4) {#if isParentExpanded}
function create_if_block$2(ctx) {
let ul;
let t;
let current;
let mounted;
let dispose;
let each_value = /*slicedKeys*/ ctx[13];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$1(get_each_context$1(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block = /*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length && create_if_block_1();
return {
c() {
ul = element("ul");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t = space();
if (if_block) if_block.c();
attr(ul, "class", "svelte-rwxv37");
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
},
m(target, anchor) {
insert(target, ul, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(ul, null);
}
append(ul, t);
if (if_block) if_block.m(ul, null);
current = true;
if (!mounted) {
dispose = listen(ul, "click", /*expand*/ ctx[16]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*expanded, previewKeys, getKey, slicedKeys, isArray, getValue, getPreviewValue*/ 10129) {
each_value = /*slicedKeys*/ ctx[13];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$1(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$1(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(ul, t);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length) {
if (if_block) ; else {
if_block = create_if_block_1();
if_block.c();
if_block.m(ul, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*expanded*/ 1) {
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_each(each_blocks, detaching);
if (if_block) if_block.d();
mounted = false;
dispose();
}
};
}
// (67:10) {#if !expanded && index < previewKeys.length - 1}
function create_if_block_2(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = ",";
attr(span, "class", "comma svelte-rwxv37");
},
m(target, anchor) {
insert(target, span, anchor);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
// (65:8) {#each slicedKeys as key, index}
function create_each_block$1(ctx) {
let jsonnode;
let t;
let if_block_anchor;
let current;
jsonnode = new JSONNode({
props: {
key: /*getKey*/ ctx[8](/*key*/ ctx[12]),
isParentExpanded: /*expanded*/ ctx[0],
isParentArray: /*isArray*/ ctx[4],
value: /*expanded*/ ctx[0]
? /*getValue*/ ctx[9](/*key*/ ctx[12])
: /*getPreviewValue*/ ctx[10](/*key*/ ctx[12])
}
});
let if_block = !/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1 && create_if_block_2();
return {
c() {
create_component(jsonnode.$$.fragment);
t = space();
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
mount_component(jsonnode, target, anchor);
insert(target, t, anchor);
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const jsonnode_changes = {};
if (dirty & /*getKey, slicedKeys*/ 8448) jsonnode_changes.key = /*getKey*/ ctx[8](/*key*/ ctx[12]);
if (dirty & /*expanded*/ 1) jsonnode_changes.isParentExpanded = /*expanded*/ ctx[0];
if (dirty & /*isArray*/ 16) jsonnode_changes.isParentArray = /*isArray*/ ctx[4];
if (dirty & /*expanded, getValue, slicedKeys, getPreviewValue*/ 9729) jsonnode_changes.value = /*expanded*/ ctx[0]
? /*getValue*/ ctx[9](/*key*/ ctx[12])
: /*getPreviewValue*/ ctx[10](/*key*/ ctx[12]);
jsonnode.$set(jsonnode_changes);
if (!/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1) {
if (if_block) ; else {
if_block = create_if_block_2();
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnode, detaching);
if (detaching) detach(t);
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (71:8) {#if slicedKeys.length < previewKeys.length }
function create_if_block_1(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = "…";
},
m(target, anchor) {
insert(target, span, anchor);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
function create_fragment$5(ctx) {
let li;
let label_1;
let t0;
let jsonkey;
let t1;
let span1;
let span0;
let t2;
let t3;
let t4;
let current_block_type_index;
let if_block1;
let t5;
let span2;
let t6;
let current;
let mounted;
let dispose;
let if_block0 = /*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2] && create_if_block_3(ctx);
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[12],
colon: /*context*/ ctx[14].colon,
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3]
}
});
jsonkey.$on("click", /*toggleExpand*/ ctx[15]);
const if_block_creators = [create_if_block$2, create_else_block];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*isParentExpanded*/ ctx[2]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
li = element("li");
label_1 = element("label");
if (if_block0) if_block0.c();
t0 = space();
create_component(jsonkey.$$.fragment);
t1 = space();
span1 = element("span");
span0 = element("span");
t2 = text(/*label*/ ctx[1]);
t3 = text(/*bracketOpen*/ ctx[5]);
t4 = space();
if_block1.c();
t5 = space();
span2 = element("span");
t6 = text(/*bracketClose*/ ctx[6]);
attr(label_1, "class", "svelte-rwxv37");
attr(li, "class", "svelte-rwxv37");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]);
},
m(target, anchor) {
insert(target, li, anchor);
append(li, label_1);
if (if_block0) if_block0.m(label_1, null);
append(label_1, t0);
mount_component(jsonkey, label_1, null);
append(label_1, t1);
append(label_1, span1);
append(span1, span0);
append(span0, t2);
append(span1, t3);
append(li, t4);
if_blocks[current_block_type_index].m(li, null);
append(li, t5);
append(li, span2);
append(span2, t6);
current = true;
if (!mounted) {
dispose = listen(span1, "click", /*toggleExpand*/ ctx[15]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2]) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*expandable, isParentExpanded*/ 2052) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_3(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(label_1, t0);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
const jsonkey_changes = {};
if (dirty & /*key*/ 4096) jsonkey_changes.key = /*key*/ ctx[12];
if (dirty & /*isParentExpanded*/ 4) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[3];
jsonkey.$set(jsonkey_changes);
if (!current || dirty & /*label*/ 2) set_data(t2, /*label*/ ctx[1]);
if (!current || dirty & /*bracketOpen*/ 32) set_data(t3, /*bracketOpen*/ ctx[5]);
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block1 = if_blocks[current_block_type_index];
if (!if_block1) {
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block1.c();
} else {
if_block1.p(ctx, dirty);
}
transition_in(if_block1, 1);
if_block1.m(li, t5);
}
if (!current || dirty & /*bracketClose*/ 64) set_data(t6, /*bracketClose*/ ctx[6]);
if (dirty & /*isParentExpanded*/ 4) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(jsonkey.$$.fragment, local);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(jsonkey.$$.fragment, local);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (detaching) detach(li);
if (if_block0) if_block0.d();
destroy_component(jsonkey);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$5($$self, $$props, $$invalidate) {
let slicedKeys;
let { key, keys, colon = ':', label = '', isParentExpanded, isParentArray, isArray = false, bracketOpen, bracketClose } = $$props;
let { previewKeys = keys } = $$props;
let { getKey = key => key } = $$props;
let { getValue = key => key } = $$props;
let { getPreviewValue = getValue } = $$props;
let { expanded = false, expandable = true } = $$props;
const context = getContext(contextKey);
setContext(contextKey, { ...context, colon });
function toggleExpand() {
$$invalidate(0, expanded = !expanded);
}
function expand() {
$$invalidate(0, expanded = true);
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(12, key = $$props.key);
if ('keys' in $$props) $$invalidate(17, keys = $$props.keys);
if ('colon' in $$props) $$invalidate(18, colon = $$props.colon);
if ('label' in $$props) $$invalidate(1, label = $$props.label);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ('isArray' in $$props) $$invalidate(4, isArray = $$props.isArray);
if ('bracketOpen' in $$props) $$invalidate(5, bracketOpen = $$props.bracketOpen);
if ('bracketClose' in $$props) $$invalidate(6, bracketClose = $$props.bracketClose);
if ('previewKeys' in $$props) $$invalidate(7, previewKeys = $$props.previewKeys);
if ('getKey' in $$props) $$invalidate(8, getKey = $$props.getKey);
if ('getValue' in $$props) $$invalidate(9, getValue = $$props.getValue);
if ('getPreviewValue' in $$props) $$invalidate(10, getPreviewValue = $$props.getPreviewValue);
if ('expanded' in $$props) $$invalidate(0, expanded = $$props.expanded);
if ('expandable' in $$props) $$invalidate(11, expandable = $$props.expandable);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*isParentExpanded*/ 4) {
if (!isParentExpanded) {
$$invalidate(0, expanded = false);
}
}
if ($$self.$$.dirty & /*expanded, keys, previewKeys*/ 131201) {
$$invalidate(13, slicedKeys = expanded ? keys : previewKeys.slice(0, 5));
}
};
return [
expanded,
label,
isParentExpanded,
isParentArray,
isArray,
bracketOpen,
bracketClose,
previewKeys,
getKey,
getValue,
getPreviewValue,
expandable,
key,
slicedKeys,
context,
toggleExpand,
expand,
keys,
colon
];
}
class JSONNested extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$5,
create_fragment$5,
safe_not_equal,
{
key: 12,
keys: 17,
colon: 18,
label: 1,
isParentExpanded: 2,
isParentArray: 3,
isArray: 4,
bracketOpen: 5,
bracketClose: 6,
previewKeys: 7,
getKey: 8,
getValue: 9,
getPreviewValue: 10,
expanded: 0,
expandable: 11
},
add_css$4
);
}
}
/* node_modules/svelte-json-tree-auto/src/JSONObjectNode.svelte generated by Svelte v3.41.0 */
function create_fragment$6(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[5],
previewKeys: /*keys*/ ctx[5],
getValue: /*getValue*/ ctx[6],
label: "" + (/*nodeType*/ ctx[3] + " "),
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5];
if (dirty & /*keys*/ 32) jsonnested_changes.previewKeys = /*keys*/ ctx[5];
if (dirty & /*nodeType*/ 8) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + " ");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$6($$self, $$props, $$invalidate) {
let keys;
let { key, value, isParentExpanded, isParentArray, nodeType } = $$props;
let { expanded = true } = $$props;
function getValue(key) {
return value[key];
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(7, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(3, nodeType = $$props.nodeType);
if ('expanded' in $$props) $$invalidate(4, expanded = $$props.expanded);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 128) {
$$invalidate(5, keys = Object.getOwnPropertyNames(value));
}
};
return [
key,
isParentExpanded,
isParentArray,
nodeType,
expanded,
keys,
getValue,
value
];
}
class JSONObjectNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$6, create_fragment$6, safe_not_equal, {
key: 0,
value: 7,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONArrayNode.svelte generated by Svelte v3.41.0 */
function create_fragment$7(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
isArray: true,
keys: /*keys*/ ctx[5],
previewKeys: /*previewKeys*/ ctx[6],
getValue: /*getValue*/ ctx[7],
label: "Array(" + /*value*/ ctx[1].length + ")",
bracketOpen: "[",
bracketClose: "]"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5];
if (dirty & /*previewKeys*/ 64) jsonnested_changes.previewKeys = /*previewKeys*/ ctx[6];
if (dirty & /*value*/ 2) jsonnested_changes.label = "Array(" + /*value*/ ctx[1].length + ")";
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$7($$self, $$props, $$invalidate) {
let keys;
let previewKeys;
let { key, value, isParentExpanded, isParentArray } = $$props;
let { expanded = JSON.stringify(value).length < 1024 } = $$props;
const filteredKey = new Set(['length']);
function getValue(key) {
return value[key];
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ('expanded' in $$props) $$invalidate(4, expanded = $$props.expanded);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 2) {
$$invalidate(5, keys = Object.getOwnPropertyNames(value));
}
if ($$self.$$.dirty & /*keys*/ 32) {
$$invalidate(6, previewKeys = keys.filter(key => !filteredKey.has(key)));
}
};
return [
key,
value,
isParentExpanded,
isParentArray,
expanded,
keys,
previewKeys,
getValue
];
}
class JSONArrayNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$7, create_fragment$7, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONIterableArrayNode.svelte generated by Svelte v3.41.0 */
function create_fragment$8(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[4],
getKey,
getValue,
isArray: true,
label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"),
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4];
if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function getKey(key) {
return String(key[0]);
}
function getValue(key) {
return key[1];
}
function instance$8($$self, $$props, $$invalidate) {
let { key, value, isParentExpanded, isParentArray, nodeType } = $$props;
let keys = [];
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(5, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(3, nodeType = $$props.nodeType);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 32) {
{
let result = [];
let i = 0;
for (const entry of value) {
result.push([i++, entry]);
}
$$invalidate(4, keys = result);
}
}
};
return [key, isParentExpanded, isParentArray, nodeType, keys, value];
}
class JSONIterableArrayNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$8, create_fragment$8, safe_not_equal, {
key: 0,
value: 5,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3
});
}
}
class MapEntry {
constructor(key, value) {
this.key = key;
this.value = value;
}
}
/* node_modules/svelte-json-tree-auto/src/JSONIterableMapNode.svelte generated by Svelte v3.41.0 */
function create_fragment$9(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[4],
getKey: getKey$1,
getValue: getValue$1,
label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"),
colon: "",
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4];
if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function getKey$1(entry) {
return entry[0];
}
function getValue$1(entry) {
return entry[1];
}
function instance$9($$self, $$props, $$invalidate) {
let { key, value, isParentExpanded, isParentArray, nodeType } = $$props;
let keys = [];
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(5, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(3, nodeType = $$props.nodeType);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 32) {
{
let result = [];
let i = 0;
for (const entry of value) {
result.push([i++, new MapEntry(entry[0], entry[1])]);
}
$$invalidate(4, keys = result);
}
}
};
return [key, isParentExpanded, isParentArray, nodeType, keys, value];
}
class JSONIterableMapNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$9, create_fragment$9, safe_not_equal, {
key: 0,
value: 5,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONMapEntryNode.svelte generated by Svelte v3.41.0 */
function create_fragment$a(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
key: /*isParentExpanded*/ ctx[2]
? String(/*key*/ ctx[0])
: /*value*/ ctx[1].key,
keys: /*keys*/ ctx[5],
getValue: /*getValue*/ ctx[6],
label: /*isParentExpanded*/ ctx[2] ? 'Entry ' : '=> ',
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*isParentExpanded, key, value*/ 7) jsonnested_changes.key = /*isParentExpanded*/ ctx[2]
? String(/*key*/ ctx[0])
: /*value*/ ctx[1].key;
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.label = /*isParentExpanded*/ ctx[2] ? 'Entry ' : '=> ';
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$a($$self, $$props, $$invalidate) {
let { key, value, isParentExpanded, isParentArray } = $$props;
let { expanded = false } = $$props;
const keys = ['key', 'value'];
function getValue(key) {
return value[key];
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ('expanded' in $$props) $$invalidate(4, expanded = $$props.expanded);
};
return [key, value, isParentExpanded, isParentArray, expanded, keys, getValue];
}
class JSONMapEntryNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$a, create_fragment$a, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONValueNode.svelte generated by Svelte v3.41.0 */
function add_css$5(target) {
append_styles(target, "svelte-3bjyvl", "li.svelte-3bjyvl{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-3bjyvl{padding-left:var(--li-identation)}.String.svelte-3bjyvl{color:var(--string-color)}.Date.svelte-3bjyvl{color:var(--date-color)}.Number.svelte-3bjyvl{color:var(--number-color)}.Boolean.svelte-3bjyvl{color:var(--boolean-color)}.Null.svelte-3bjyvl{color:var(--null-color)}.Undefined.svelte-3bjyvl{color:var(--undefined-color)}.Function.svelte-3bjyvl{color:var(--function-color);font-style:italic}.Symbol.svelte-3bjyvl{color:var(--symbol-color)}");
}
function create_fragment$b(ctx) {
let li;
let jsonkey;
let t0;
let span;
let t1_value = (/*valueGetter*/ ctx[2]
? /*valueGetter*/ ctx[2](/*value*/ ctx[1])
: /*value*/ ctx[1]) + "";
let t1;
let span_class_value;
let current;
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[0],
colon: /*colon*/ ctx[6],
isParentExpanded: /*isParentExpanded*/ ctx[3],
isParentArray: /*isParentArray*/ ctx[4]
}
});
return {
c() {
li = element("li");
create_component(jsonkey.$$.fragment);
t0 = space();
span = element("span");
t1 = text(t1_value);
attr(span, "class", span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl"));
attr(li, "class", "svelte-3bjyvl");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(jsonkey, li, null);
append(li, t0);
append(li, span);
append(span, t1);
current = true;
},
p(ctx, [dirty]) {
const jsonkey_changes = {};
if (dirty & /*key*/ 1) jsonkey_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4];
jsonkey.$set(jsonkey_changes);
if ((!current || dirty & /*valueGetter, value*/ 6) && t1_value !== (t1_value = (/*valueGetter*/ ctx[2]
? /*valueGetter*/ ctx[2](/*value*/ ctx[1])
: /*value*/ ctx[1]) + "")) set_data(t1, t1_value);
if (!current || dirty & /*nodeType*/ 32 && span_class_value !== (span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl"))) {
attr(span, "class", span_class_value);
}
if (dirty & /*isParentExpanded*/ 8) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
}
},
i(local) {
if (current) return;
transition_in(jsonkey.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonkey.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(jsonkey);
}
};
}
function instance$b($$self, $$props, $$invalidate) {
let { key, value, valueGetter = null, isParentExpanded, isParentArray, nodeType } = $$props;
const { colon } = getContext(contextKey);
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('valueGetter' in $$props) $$invalidate(2, valueGetter = $$props.valueGetter);
if ('isParentExpanded' in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(5, nodeType = $$props.nodeType);
};
return [key, value, valueGetter, isParentExpanded, isParentArray, nodeType, colon];
}
class JSONValueNode extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$b,
create_fragment$b,
safe_not_equal,
{
key: 0,
value: 1,
valueGetter: 2,
isParentExpanded: 3,
isParentArray: 4,
nodeType: 5
},
add_css$5
);
}
}
/* node_modules/svelte-json-tree-auto/src/ErrorNode.svelte generated by Svelte v3.41.0 */
function add_css$6(target) {
append_styles(target, "svelte-1ca3gb2", "li.svelte-1ca3gb2{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-1ca3gb2{padding-left:var(--li-identation)}.collapse.svelte-1ca3gb2{--li-display:inline;display:inline;font-style:italic}");
}
function get_each_context$2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[8] = list[i];
child_ctx[10] = i;
return child_ctx;
}
// (40:2) {#if isParentExpanded}
function create_if_block_2$1(ctx) {
let jsonarrow;
let current;
jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } });
jsonarrow.$on("click", /*toggleExpand*/ ctx[7]);
return {
c() {
create_component(jsonarrow.$$.fragment);
},
m(target, anchor) {
mount_component(jsonarrow, target, anchor);
current = true;
},
p(ctx, dirty) {
const jsonarrow_changes = {};
if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0];
jsonarrow.$set(jsonarrow_changes);
},
i(local) {
if (current) return;
transition_in(jsonarrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonarrow.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonarrow, detaching);
}
};
}
// (45:2) {#if isParentExpanded}
function create_if_block$3(ctx) {
let ul;
let current;
let if_block = /*expanded*/ ctx[0] && create_if_block_1$1(ctx);
return {
c() {
ul = element("ul");
if (if_block) if_block.c();
attr(ul, "class", "svelte-1ca3gb2");
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
},
m(target, anchor) {
insert(target, ul, anchor);
if (if_block) if_block.m(ul, null);
current = true;
},
p(ctx, dirty) {
if (/*expanded*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*expanded*/ 1) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$1(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(ul, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
if (dirty & /*expanded*/ 1) {
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
if (if_block) if_block.d();
}
};
}
// (47:6) {#if expanded}
function create_if_block_1$1(ctx) {
let jsonnode;
let t0;
let li;
let jsonkey;
let t1;
let span;
let current;
jsonnode = new JSONNode({
props: {
key: "message",
value: /*value*/ ctx[2].message
}
});
jsonkey = new JSONKey({
props: {
key: "stack",
colon: ":",
isParentExpanded: /*isParentExpanded*/ ctx[3]
}
});
let each_value = /*stack*/ ctx[5];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$2(get_each_context$2(ctx, each_value, i));
}
return {
c() {
create_component(jsonnode.$$.fragment);
t0 = space();
li = element("li");
create_component(jsonkey.$$.fragment);
t1 = space();
span = element("span");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(li, "class", "svelte-1ca3gb2");
},
m(target, anchor) {
mount_component(jsonnode, target, anchor);
insert(target, t0, anchor);
insert(target, li, anchor);
mount_component(jsonkey, li, null);
append(li, t1);
append(li, span);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(span, null);
}
current = true;
},
p(ctx, dirty) {
const jsonnode_changes = {};
if (dirty & /*value*/ 4) jsonnode_changes.value = /*value*/ ctx[2].message;
jsonnode.$set(jsonnode_changes);
const jsonkey_changes = {};
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
jsonkey.$set(jsonkey_changes);
if (dirty & /*stack*/ 32) {
each_value = /*stack*/ ctx[5];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$2(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$2(child_ctx);
each_blocks[i].c();
each_blocks[i].m(span, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
transition_in(jsonkey.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
transition_out(jsonkey.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnode, detaching);
if (detaching) detach(t0);
if (detaching) detach(li);
destroy_component(jsonkey);
destroy_each(each_blocks, detaching);
}
};
}
// (52:12) {#each stack as line, index}
function create_each_block$2(ctx) {
let span;
let t_value = /*line*/ ctx[8] + "";
let t;
let br;
return {
c() {
span = element("span");
t = text(t_value);
br = element("br");
attr(span, "class", "svelte-1ca3gb2");
toggle_class(span, "indent", /*index*/ ctx[10] > 0);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
insert(target, br, anchor);
},
p(ctx, dirty) {
if (dirty & /*stack*/ 32 && t_value !== (t_value = /*line*/ ctx[8] + "")) set_data(t, t_value);
},
d(detaching) {
if (detaching) detach(span);
if (detaching) detach(br);
}
};
}
function create_fragment$c(ctx) {
let li;
let t0;
let jsonkey;
let t1;
let span;
let t2;
let t3_value = (/*expanded*/ ctx[0] ? '' : /*value*/ ctx[2].message) + "";
let t3;
let t4;
let current;
let mounted;
let dispose;
let if_block0 = /*isParentExpanded*/ ctx[3] && create_if_block_2$1(ctx);
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[1],
colon: /*context*/ ctx[6].colon,
isParentExpanded: /*isParentExpanded*/ ctx[3],
isParentArray: /*isParentArray*/ ctx[4]
}
});
let if_block1 = /*isParentExpanded*/ ctx[3] && create_if_block$3(ctx);
return {
c() {
li = element("li");
if (if_block0) if_block0.c();
t0 = space();
create_component(jsonkey.$$.fragment);
t1 = space();
span = element("span");
t2 = text("Error: ");
t3 = text(t3_value);
t4 = space();
if (if_block1) if_block1.c();
attr(li, "class", "svelte-1ca3gb2");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
},
m(target, anchor) {
insert(target, li, anchor);
if (if_block0) if_block0.m(li, null);
append(li, t0);
mount_component(jsonkey, li, null);
append(li, t1);
append(li, span);
append(span, t2);
append(span, t3);
append(li, t4);
if (if_block1) if_block1.m(li, null);
current = true;
if (!mounted) {
dispose = listen(span, "click", /*toggleExpand*/ ctx[7]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*isParentExpanded*/ ctx[3]) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*isParentExpanded*/ 8) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_2$1(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(li, t0);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
const jsonkey_changes = {};
if (dirty & /*key*/ 2) jsonkey_changes.key = /*key*/ ctx[1];
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4];
jsonkey.$set(jsonkey_changes);
if ((!current || dirty & /*expanded, value*/ 5) && t3_value !== (t3_value = (/*expanded*/ ctx[0] ? '' : /*value*/ ctx[2].message) + "")) set_data(t3, t3_value);
if (/*isParentExpanded*/ ctx[3]) {
if (if_block1) {
if_block1.p(ctx, dirty);
if (dirty & /*isParentExpanded*/ 8) {
transition_in(if_block1, 1);
}
} else {
if_block1 = create_if_block$3(ctx);
if_block1.c();
transition_in(if_block1, 1);
if_block1.m(li, null);
}
} else if (if_block1) {
group_outros();
transition_out(if_block1, 1, 1, () => {
if_block1 = null;
});
check_outros();
}
if (dirty & /*isParentExpanded*/ 8) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(jsonkey.$$.fragment, local);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(jsonkey.$$.fragment, local);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (detaching) detach(li);
if (if_block0) if_block0.d();
destroy_component(jsonkey);
if (if_block1) if_block1.d();
mounted = false;
dispose();
}
};
}
function instance$c($$self, $$props, $$invalidate) {
let stack;
let { key, value, isParentExpanded, isParentArray } = $$props;
let { expanded = false } = $$props;
const context = getContext(contextKey);
setContext(contextKey, { ...context, colon: ':' });
function toggleExpand() {
$$invalidate(0, expanded = !expanded);
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(1, key = $$props.key);
if ('value' in $$props) $$invalidate(2, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ('expanded' in $$props) $$invalidate(0, expanded = $$props.expanded);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 4) {
$$invalidate(5, stack = value.stack.split('\n'));
}
if ($$self.$$.dirty & /*isParentExpanded*/ 8) {
if (!isParentExpanded) {
$$invalidate(0, expanded = false);
}
}
};
return [
expanded,
key,
value,
isParentExpanded,
isParentArray,
stack,
context,
toggleExpand
];
}
class ErrorNode extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$c,
create_fragment$c,
safe_not_equal,
{
key: 1,
value: 2,
isParentExpanded: 3,
isParentArray: 4,
expanded: 0
},
add_css$6
);
}
}
function objType(obj) {
const type = Object.prototype.toString.call(obj).slice(8, -1);
if (type === 'Object') {
if (typeof obj[Symbol.iterator] === 'function') {
return 'Iterable';
}
return obj.constructor.name;
}
return type;
}
/* node_modules/svelte-json-tree-auto/src/JSONNode.svelte generated by Svelte v3.41.0 */
function create_fragment$d(ctx) {
let switch_instance;
let switch_instance_anchor;
let current;
var switch_value = /*componentType*/ ctx[6];
function switch_props(ctx) {
return {
props: {
key: /*key*/ ctx[0],
value: /*value*/ ctx[1],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
nodeType: /*nodeType*/ ctx[4],
valueGetter: /*valueGetter*/ ctx[5]
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
if (switch_instance) create_component(switch_instance.$$.fragment);
switch_instance_anchor = empty();
},
m(target, anchor) {
if (switch_instance) {
mount_component(switch_instance, target, anchor);
}
insert(target, switch_instance_anchor, anchor);
current = true;
},
p(ctx, [dirty]) {
const switch_instance_changes = {};
if (dirty & /*key*/ 1) switch_instance_changes.key = /*key*/ ctx[0];
if (dirty & /*value*/ 2) switch_instance_changes.value = /*value*/ ctx[1];
if (dirty & /*isParentExpanded*/ 4) switch_instance_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) switch_instance_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*nodeType*/ 16) switch_instance_changes.nodeType = /*nodeType*/ ctx[4];
if (dirty & /*valueGetter*/ 32) switch_instance_changes.valueGetter = /*valueGetter*/ ctx[5];
if (switch_value !== (switch_value = /*componentType*/ ctx[6])) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(switch_instance_anchor);
if (switch_instance) destroy_component(switch_instance, detaching);
}
};
}
function instance$d($$self, $$props, $$invalidate) {
let nodeType;
let componentType;
let valueGetter;
let { key, value, isParentExpanded, isParentArray } = $$props;
function getComponent(nodeType) {
switch (nodeType) {
case 'Object':
return JSONObjectNode;
case 'Error':
return ErrorNode;
case 'Array':
return JSONArrayNode;
case 'Iterable':
case 'Map':
case 'Set':
return typeof value.set === 'function'
? JSONIterableMapNode
: JSONIterableArrayNode;
case 'MapEntry':
return JSONMapEntryNode;
default:
return JSONValueNode;
}
}
function getValueGetter(nodeType) {
switch (nodeType) {
case 'Object':
case 'Error':
case 'Array':
case 'Iterable':
case 'Map':
case 'Set':
case 'MapEntry':
case 'Number':
return undefined;
case 'String':
return raw => `"${raw}"`;
case 'Boolean':
return raw => raw ? 'true' : 'false';
case 'Date':
return raw => raw.toISOString();
case 'Null':
return () => 'null';
case 'Undefined':
return () => 'undefined';
case 'Function':
case 'Symbol':
return raw => raw.toString();
default:
return () => `<${nodeType}>`;
}
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 2) {
$$invalidate(4, nodeType = objType(value));
}
if ($$self.$$.dirty & /*nodeType*/ 16) {
$$invalidate(6, componentType = getComponent(nodeType));
}
if ($$self.$$.dirty & /*nodeType*/ 16) {
$$invalidate(5, valueGetter = getValueGetter(nodeType));
}
};
return [
key,
value,
isParentExpanded,
isParentArray,
nodeType,
valueGetter,
componentType
];
}
class JSONNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$d, create_fragment$d, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3
});
}
}
/* node_modules/svelte-json-tree-auto/src/Root.svelte generated by Svelte v3.41.0 */
function add_css$7(target) {
append_styles(target, "svelte-773n60", "ul.svelte-773n60{--string-color:var(--json-tree-string-color, #cb3f41);--symbol-color:var(--json-tree-symbol-color, #cb3f41);--boolean-color:var(--json-tree-boolean-color, #112aa7);--function-color:var(--json-tree-function-color, #112aa7);--number-color:var(--json-tree-number-color, #3029cf);--label-color:var(--json-tree-label-color, #871d8f);--arrow-color:var(--json-tree-arrow-color, #727272);--null-color:var(--json-tree-null-color, #8d8d8d);--undefined-color:var(--json-tree-undefined-color, #8d8d8d);--date-color:var(--json-tree-date-color, #8d8d8d);--li-identation:var(--json-tree-li-indentation, 1em);--li-line-height:var(--json-tree-li-line-height, 1.3);--li-colon-space:0.3em;font-size:var(--json-tree-font-size, 12px);font-family:var(--json-tree-font-family, 'Courier New', Courier, monospace)}ul.svelte-773n60 li{line-height:var(--li-line-height);display:var(--li-display, list-item);list-style:none}ul.svelte-773n60,ul.svelte-773n60 ul{padding:0;margin:0}");
}
function create_fragment$e(ctx) {
let ul;
let jsonnode;
let current;
jsonnode = new JSONNode({
props: {
key: /*key*/ ctx[0],
value: /*value*/ ctx[1],
isParentExpanded: true,
isParentArray: false
}
});
return {
c() {
ul = element("ul");
create_component(jsonnode.$$.fragment);
attr(ul, "class", "svelte-773n60");
},
m(target, anchor) {
insert(target, ul, anchor);
mount_component(jsonnode, ul, null);
current = true;
},
p(ctx, [dirty]) {
const jsonnode_changes = {};
if (dirty & /*key*/ 1) jsonnode_changes.key = /*key*/ ctx[0];
if (dirty & /*value*/ 2) jsonnode_changes.value = /*value*/ ctx[1];
jsonnode.$set(jsonnode_changes);
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_component(jsonnode);
}
};
}
function instance$e($$self, $$props, $$invalidate) {
setContext(contextKey, {});
let { key = '', value } = $$props;
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
};
return [key, value];
}
class Root extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$e, create_fragment$e, safe_not_equal, { key: 0, value: 1 }, add_css$7);
}
}
/* src/client/debug/main/ClientSwitcher.svelte generated by Svelte v3.41.0 */
function add_css$8(target) {
append_styles(target, "svelte-jvfq3i", ".svelte-jvfq3i{box-sizing:border-box}section.switcher.svelte-jvfq3i{position:sticky;bottom:0;transform:translateY(20px);margin:40px -20px 0;border-top:1px solid #999;padding:20px;background:#fff}label.svelte-jvfq3i{display:flex;align-items:baseline;gap:5px;font-weight:bold}select.svelte-jvfq3i{min-width:140px}");
}
function get_each_context$3(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
child_ctx[9] = i;
return child_ctx;
}
// (42:0) {#if debuggableClients.length > 1}
function create_if_block$4(ctx) {
let section;
let label;
let t;
let select;
let mounted;
let dispose;
let each_value = /*debuggableClients*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$3(get_each_context$3(ctx, each_value, i));
}
return {
c() {
section = element("section");
label = element("label");
t = text("Client\n \n ");
select = element("select");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(select, "id", selectId);
attr(select, "class", "svelte-jvfq3i");
if (/*selected*/ ctx[2] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[6].call(select));
attr(label, "class", "svelte-jvfq3i");
attr(section, "class", "switcher svelte-jvfq3i");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, label);
append(label, t);
append(label, select);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(select, null);
}
select_option(select, /*selected*/ ctx[2]);
if (!mounted) {
dispose = [
listen(select, "change", /*handleSelection*/ ctx[3]),
listen(select, "change", /*select_change_handler*/ ctx[6])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*debuggableClients, JSON*/ 2) {
each_value = /*debuggableClients*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$3(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$3(child_ctx);
each_blocks[i].c();
each_blocks[i].m(select, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (dirty & /*selected*/ 4) {
select_option(select, /*selected*/ ctx[2]);
}
},
d(detaching) {
if (detaching) detach(section);
destroy_each(each_blocks, detaching);
mounted = false;
run_all(dispose);
}
};
}
// (48:8) {#each debuggableClients as clientOption, index}
function create_each_block$3(ctx) {
let option;
let t0;
let t1;
let t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + "";
let t2;
let t3;
let t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + "";
let t4;
let t5;
let t6_value = /*clientOption*/ ctx[7].game.name + "";
let t6;
let t7;
let option_value_value;
return {
c() {
option = element("option");
t0 = text(/*index*/ ctx[9]);
t1 = text(" —\n playerID: ");
t2 = text(t2_value);
t3 = text(",\n matchID: ");
t4 = text(t4_value);
t5 = text("\n (");
t6 = text(t6_value);
t7 = text(")\n ");
option.__value = option_value_value = /*index*/ ctx[9];
option.value = option.__value;
attr(option, "class", "svelte-jvfq3i");
},
m(target, anchor) {
insert(target, option, anchor);
append(option, t0);
append(option, t1);
append(option, t2);
append(option, t3);
append(option, t4);
append(option, t5);
append(option, t6);
append(option, t7);
},
p(ctx, dirty) {
if (dirty & /*debuggableClients*/ 2 && t2_value !== (t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + "")) set_data(t2, t2_value);
if (dirty & /*debuggableClients*/ 2 && t4_value !== (t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + "")) set_data(t4, t4_value);
if (dirty & /*debuggableClients*/ 2 && t6_value !== (t6_value = /*clientOption*/ ctx[7].game.name + "")) set_data(t6, t6_value);
},
d(detaching) {
if (detaching) detach(option);
}
};
}
function create_fragment$f(ctx) {
let if_block_anchor;
let if_block = /*debuggableClients*/ ctx[1].length > 1 && create_if_block$4(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*debuggableClients*/ ctx[1].length > 1) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$4(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop,
o: noop,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
const selectId = 'bgio-debug-select-client';
function instance$f($$self, $$props, $$invalidate) {
let client;
let debuggableClients;
let selected;
let $clientManager,
$$unsubscribe_clientManager = noop,
$$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(5, $clientManager = $$value)), clientManager);
$$self.$$.on_destroy.push(() => $$unsubscribe_clientManager());
let { clientManager } = $$props;
$$subscribe_clientManager();
const handleSelection = e => {
// Request to switch to the selected client.
const selectedClient = debuggableClients[e.target.value];
clientManager.switchToClient(selectedClient);
// Maintain focus on the client select menu after switching clients.
// Necessary because switching clients will usually trigger a mount/unmount.
const select = document.getElementById(selectId);
if (select) select.focus();
};
function select_change_handler() {
selected = select_value(this);
((($$invalidate(2, selected), $$invalidate(1, debuggableClients)), $$invalidate(4, client)), $$invalidate(5, $clientManager));
}
$$self.$$set = $$props => {
if ('clientManager' in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager));
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$clientManager*/ 32) {
$$invalidate(4, { client, debuggableClients } = $clientManager, client, ($$invalidate(1, debuggableClients), $$invalidate(5, $clientManager)));
}
if ($$self.$$.dirty & /*debuggableClients, client*/ 18) {
$$invalidate(2, selected = debuggableClients.indexOf(client));
}
};
return [
clientManager,
debuggableClients,
selected,
handleSelection,
client,
$clientManager,
select_change_handler
];
}
class ClientSwitcher extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$f, create_fragment$f, safe_not_equal, { clientManager: 0 }, add_css$8);
}
}
/* src/client/debug/main/Hotkey.svelte generated by Svelte v3.41.0 */
function add_css$9(target) {
append_styles(target, "svelte-1vfj1mn", ".key.svelte-1vfj1mn.svelte-1vfj1mn{display:flex;flex-direction:row;align-items:center}button.svelte-1vfj1mn.svelte-1vfj1mn{cursor:pointer;min-width:10px;padding-left:5px;padding-right:5px;height:20px;line-height:20px;text-align:center;border:1px solid #ccc;box-shadow:1px 1px 1px #888;background:#eee;color:#444}button.svelte-1vfj1mn.svelte-1vfj1mn:hover{background:#ddd}.key.active.svelte-1vfj1mn button.svelte-1vfj1mn{background:#ddd;border:1px solid #999;box-shadow:none}label.svelte-1vfj1mn.svelte-1vfj1mn{margin-left:10px}");
}
// (78:2) {#if label}
function create_if_block$5(ctx) {
let label_1;
let t0;
let t1;
let span;
let t2_value = `(shortcut: ${/*value*/ ctx[0]})` + "";
let t2;
return {
c() {
label_1 = element("label");
t0 = text(/*label*/ ctx[1]);
t1 = space();
span = element("span");
t2 = text(t2_value);
attr(span, "class", "screen-reader-only");
attr(label_1, "for", /*id*/ ctx[5]);
attr(label_1, "class", "svelte-1vfj1mn");
},
m(target, anchor) {
insert(target, label_1, anchor);
append(label_1, t0);
append(label_1, t1);
append(label_1, span);
append(span, t2);
},
p(ctx, dirty) {
if (dirty & /*label*/ 2) set_data(t0, /*label*/ ctx[1]);
if (dirty & /*value*/ 1 && t2_value !== (t2_value = `(shortcut: ${/*value*/ ctx[0]})` + "")) set_data(t2, t2_value);
},
d(detaching) {
if (detaching) detach(label_1);
}
};
}
function create_fragment$g(ctx) {
let div;
let button;
let t0;
let t1;
let mounted;
let dispose;
let if_block = /*label*/ ctx[1] && create_if_block$5(ctx);
return {
c() {
div = element("div");
button = element("button");
t0 = text(/*value*/ ctx[0]);
t1 = space();
if (if_block) if_block.c();
attr(button, "id", /*id*/ ctx[5]);
button.disabled = /*disable*/ ctx[2];
attr(button, "class", "svelte-1vfj1mn");
attr(div, "class", "key svelte-1vfj1mn");
toggle_class(div, "active", /*active*/ ctx[3]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, button);
append(button, t0);
append(div, t1);
if (if_block) if_block.m(div, null);
if (!mounted) {
dispose = [
listen(window, "keydown", /*Keypress*/ ctx[7]),
listen(button, "click", /*Activate*/ ctx[6])
];
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*value*/ 1) set_data(t0, /*value*/ ctx[0]);
if (dirty & /*disable*/ 4) {
button.disabled = /*disable*/ ctx[2];
}
if (/*label*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$5(ctx);
if_block.c();
if_block.m(div, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*active*/ 8) {
toggle_class(div, "active", /*active*/ ctx[3]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
if (if_block) if_block.d();
mounted = false;
run_all(dispose);
}
};
}
function instance$g($$self, $$props, $$invalidate) {
let $disableHotkeys;
let { value } = $$props;
let { onPress = null } = $$props;
let { label = null } = $$props;
let { disable = false } = $$props;
const { disableHotkeys } = getContext('hotkeys');
component_subscribe($$self, disableHotkeys, value => $$invalidate(9, $disableHotkeys = value));
let active = false;
let id = `key-${value}`;
function Deactivate() {
$$invalidate(3, active = false);
}
function Activate() {
$$invalidate(3, active = true);
setTimeout(Deactivate, 200);
if (onPress) {
setTimeout(onPress, 1);
}
}
function Keypress(e) {
if (!$disableHotkeys && !disable && !e.ctrlKey && !e.metaKey && e.key == value) {
e.preventDefault();
Activate();
}
}
$$self.$$set = $$props => {
if ('value' in $$props) $$invalidate(0, value = $$props.value);
if ('onPress' in $$props) $$invalidate(8, onPress = $$props.onPress);
if ('label' in $$props) $$invalidate(1, label = $$props.label);
if ('disable' in $$props) $$invalidate(2, disable = $$props.disable);
};
return [value, label, disable, active, disableHotkeys, id, Activate, Keypress, onPress];
}
class Hotkey extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$g,
create_fragment$g,
safe_not_equal,
{
value: 0,
onPress: 8,
label: 1,
disable: 2
},
add_css$9
);
}
}
/* src/client/debug/main/InteractiveFunction.svelte generated by Svelte v3.41.0 */
function add_css$a(target) {
append_styles(target, "svelte-1mppqmp", ".move.svelte-1mppqmp{display:flex;flex-direction:row;cursor:pointer;margin-left:10px;color:#666}.move.svelte-1mppqmp:hover{color:#333}.move.active.svelte-1mppqmp{color:#111;font-weight:bold}.arg-field.svelte-1mppqmp{outline:none;font-family:monospace}");
}
function create_fragment$h(ctx) {
let div;
let span0;
let t0;
let t1;
let span1;
let t3;
let span2;
let t4;
let span3;
let mounted;
let dispose;
return {
c() {
div = element("div");
span0 = element("span");
t0 = text(/*name*/ ctx[2]);
t1 = space();
span1 = element("span");
span1.textContent = "(";
t3 = space();
span2 = element("span");
t4 = space();
span3 = element("span");
span3.textContent = ")";
attr(span2, "class", "arg-field svelte-1mppqmp");
attr(span2, "contenteditable", "");
attr(div, "class", "move svelte-1mppqmp");
toggle_class(div, "active", /*active*/ ctx[3]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, span0);
append(span0, t0);
append(div, t1);
append(div, span1);
append(div, t3);
append(div, span2);
/*span2_binding*/ ctx[6](span2);
append(div, t4);
append(div, span3);
if (!mounted) {
dispose = [
listen(span2, "focus", function () {
if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments);
}),
listen(span2, "blur", function () {
if (is_function(/*Deactivate*/ ctx[1])) /*Deactivate*/ ctx[1].apply(this, arguments);
}),
listen(span2, "keypress", stop_propagation(keypress_handler)),
listen(span2, "keydown", /*OnKeyDown*/ ctx[5]),
listen(div, "click", function () {
if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments);
})
];
mounted = true;
}
},
p(new_ctx, [dirty]) {
ctx = new_ctx;
if (dirty & /*name*/ 4) set_data(t0, /*name*/ ctx[2]);
if (dirty & /*active*/ 8) {
toggle_class(div, "active", /*active*/ ctx[3]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
/*span2_binding*/ ctx[6](null);
mounted = false;
run_all(dispose);
}
};
}
const keypress_handler = () => {
};
function instance$h($$self, $$props, $$invalidate) {
let { Activate } = $$props;
let { Deactivate } = $$props;
let { name } = $$props;
let { active } = $$props;
let span;
const dispatch = createEventDispatcher();
function Submit() {
try {
const value = span.innerText;
let argArray = new Function(`return [${value}]`)();
dispatch('submit', argArray);
} catch(error) {
dispatch('error', error);
}
$$invalidate(4, span.innerText = '', span);
}
function OnKeyDown(e) {
if (e.key == 'Enter') {
e.preventDefault();
Submit();
}
if (e.key == 'Escape') {
e.preventDefault();
Deactivate();
}
}
afterUpdate(() => {
if (active) {
span.focus();
} else {
span.blur();
}
});
function span2_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
span = $$value;
$$invalidate(4, span);
});
}
$$self.$$set = $$props => {
if ('Activate' in $$props) $$invalidate(0, Activate = $$props.Activate);
if ('Deactivate' in $$props) $$invalidate(1, Deactivate = $$props.Deactivate);
if ('name' in $$props) $$invalidate(2, name = $$props.name);
if ('active' in $$props) $$invalidate(3, active = $$props.active);
};
return [Activate, Deactivate, name, active, span, OnKeyDown, span2_binding];
}
class InteractiveFunction extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$h,
create_fragment$h,
safe_not_equal,
{
Activate: 0,
Deactivate: 1,
name: 2,
active: 3
},
add_css$a
);
}
}
/* src/client/debug/main/Move.svelte generated by Svelte v3.41.0 */
function add_css$b(target) {
append_styles(target, "svelte-smqssc", ".move-error.svelte-smqssc{color:#a00;font-weight:bold}.wrapper.svelte-smqssc{display:flex;flex-direction:row;align-items:center}");
}
// (65:2) {#if error}
function create_if_block$6(ctx) {
let span;
let t;
return {
c() {
span = element("span");
t = text(/*error*/ ctx[2]);
attr(span, "class", "move-error svelte-smqssc");
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
},
p(ctx, dirty) {
if (dirty & /*error*/ 4) set_data(t, /*error*/ ctx[2]);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
function create_fragment$i(ctx) {
let div1;
let div0;
let hotkey;
let t0;
let interactivefunction;
let t1;
let current;
hotkey = new Hotkey({
props: {
value: /*shortcut*/ ctx[0],
onPress: /*Activate*/ ctx[4]
}
});
interactivefunction = new InteractiveFunction({
props: {
Activate: /*Activate*/ ctx[4],
Deactivate: /*Deactivate*/ ctx[5],
name: /*name*/ ctx[1],
active: /*active*/ ctx[3]
}
});
interactivefunction.$on("submit", /*Submit*/ ctx[6]);
interactivefunction.$on("error", /*Error*/ ctx[7]);
let if_block = /*error*/ ctx[2] && create_if_block$6(ctx);
return {
c() {
div1 = element("div");
div0 = element("div");
create_component(hotkey.$$.fragment);
t0 = space();
create_component(interactivefunction.$$.fragment);
t1 = space();
if (if_block) if_block.c();
attr(div0, "class", "wrapper svelte-smqssc");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, div0);
mount_component(hotkey, div0, null);
append(div0, t0);
mount_component(interactivefunction, div0, null);
append(div1, t1);
if (if_block) if_block.m(div1, null);
current = true;
},
p(ctx, [dirty]) {
const hotkey_changes = {};
if (dirty & /*shortcut*/ 1) hotkey_changes.value = /*shortcut*/ ctx[0];
hotkey.$set(hotkey_changes);
const interactivefunction_changes = {};
if (dirty & /*name*/ 2) interactivefunction_changes.name = /*name*/ ctx[1];
if (dirty & /*active*/ 8) interactivefunction_changes.active = /*active*/ ctx[3];
interactivefunction.$set(interactivefunction_changes);
if (/*error*/ ctx[2]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$6(ctx);
if_block.c();
if_block.m(div1, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i(local) {
if (current) return;
transition_in(hotkey.$$.fragment, local);
transition_in(interactivefunction.$$.fragment, local);
current = true;
},
o(local) {
transition_out(hotkey.$$.fragment, local);
transition_out(interactivefunction.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div1);
destroy_component(hotkey);
destroy_component(interactivefunction);
if (if_block) if_block.d();
}
};
}
function instance$i($$self, $$props, $$invalidate) {
let { shortcut } = $$props;
let { name } = $$props;
let { fn } = $$props;
const { disableHotkeys } = getContext('hotkeys');
let error$1 = '';
let active = false;
function Activate() {
disableHotkeys.set(true);
$$invalidate(3, active = true);
}
function Deactivate() {
disableHotkeys.set(false);
$$invalidate(2, error$1 = '');
$$invalidate(3, active = false);
}
function Submit(e) {
$$invalidate(2, error$1 = '');
Deactivate();
fn.apply(this, e.detail);
}
function Error(e) {
$$invalidate(2, error$1 = e.detail);
error(e.detail);
}
$$self.$$set = $$props => {
if ('shortcut' in $$props) $$invalidate(0, shortcut = $$props.shortcut);
if ('name' in $$props) $$invalidate(1, name = $$props.name);
if ('fn' in $$props) $$invalidate(8, fn = $$props.fn);
};
return [shortcut, name, error$1, active, Activate, Deactivate, Submit, Error, fn];
}
class Move extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$i, create_fragment$i, safe_not_equal, { shortcut: 0, name: 1, fn: 8 }, add_css$b);
}
}
/* src/client/debug/main/Controls.svelte generated by Svelte v3.41.0 */
function add_css$c(target) {
append_styles(target, "svelte-c3lavh", "ul.svelte-c3lavh{padding-left:0}li.svelte-c3lavh{list-style:none;margin:none;margin-bottom:5px}");
}
function create_fragment$j(ctx) {
let ul;
let li0;
let hotkey0;
let t0;
let li1;
let hotkey1;
let t1;
let li2;
let hotkey2;
let t2;
let li3;
let hotkey3;
let current;
hotkey0 = new Hotkey({
props: {
value: "1",
onPress: /*client*/ ctx[0].reset,
label: "reset"
}
});
hotkey1 = new Hotkey({
props: {
value: "2",
onPress: /*Save*/ ctx[2],
label: "save"
}
});
hotkey2 = new Hotkey({
props: {
value: "3",
onPress: /*Restore*/ ctx[3],
label: "restore"
}
});
hotkey3 = new Hotkey({
props: {
value: ".",
onPress: /*ToggleVisibility*/ ctx[1],
label: "hide"
}
});
return {
c() {
ul = element("ul");
li0 = element("li");
create_component(hotkey0.$$.fragment);
t0 = space();
li1 = element("li");
create_component(hotkey1.$$.fragment);
t1 = space();
li2 = element("li");
create_component(hotkey2.$$.fragment);
t2 = space();
li3 = element("li");
create_component(hotkey3.$$.fragment);
attr(li0, "class", "svelte-c3lavh");
attr(li1, "class", "svelte-c3lavh");
attr(li2, "class", "svelte-c3lavh");
attr(li3, "class", "svelte-c3lavh");
attr(ul, "id", "debug-controls");
attr(ul, "class", "controls svelte-c3lavh");
},
m(target, anchor) {
insert(target, ul, anchor);
append(ul, li0);
mount_component(hotkey0, li0, null);
append(ul, t0);
append(ul, li1);
mount_component(hotkey1, li1, null);
append(ul, t1);
append(ul, li2);
mount_component(hotkey2, li2, null);
append(ul, t2);
append(ul, li3);
mount_component(hotkey3, li3, null);
current = true;
},
p(ctx, [dirty]) {
const hotkey0_changes = {};
if (dirty & /*client*/ 1) hotkey0_changes.onPress = /*client*/ ctx[0].reset;
hotkey0.$set(hotkey0_changes);
const hotkey3_changes = {};
if (dirty & /*ToggleVisibility*/ 2) hotkey3_changes.onPress = /*ToggleVisibility*/ ctx[1];
hotkey3.$set(hotkey3_changes);
},
i(local) {
if (current) return;
transition_in(hotkey0.$$.fragment, local);
transition_in(hotkey1.$$.fragment, local);
transition_in(hotkey2.$$.fragment, local);
transition_in(hotkey3.$$.fragment, local);
current = true;
},
o(local) {
transition_out(hotkey0.$$.fragment, local);
transition_out(hotkey1.$$.fragment, local);
transition_out(hotkey2.$$.fragment, local);
transition_out(hotkey3.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_component(hotkey0);
destroy_component(hotkey1);
destroy_component(hotkey2);
destroy_component(hotkey3);
}
};
}
function instance$j($$self, $$props, $$invalidate) {
let { client } = $$props;
let { ToggleVisibility } = $$props;
function Save() {
// get state to persist and overwrite deltalog, _undo, and _redo
const state = client.getState();
const json = stringify({
...state,
_undo: [],
_redo: [],
deltalog: []
});
window.localStorage.setItem('gamestate', json);
window.localStorage.setItem('initialState', stringify(client.initialState));
}
function Restore() {
const gamestateJSON = window.localStorage.getItem('gamestate');
const initialStateJSON = window.localStorage.getItem('initialState');
if (gamestateJSON !== null && initialStateJSON !== null) {
const gamestate = parse(gamestateJSON);
const initialState = parse(initialStateJSON);
client.store.dispatch(sync({ state: gamestate, initialState }));
}
}
$$self.$$set = $$props => {
if ('client' in $$props) $$invalidate(0, client = $$props.client);
if ('ToggleVisibility' in $$props) $$invalidate(1, ToggleVisibility = $$props.ToggleVisibility);
};
return [client, ToggleVisibility, Save, Restore];
}
class Controls extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$j, create_fragment$j, safe_not_equal, { client: 0, ToggleVisibility: 1 }, add_css$c);
}
}
/* src/client/debug/main/PlayerInfo.svelte generated by Svelte v3.41.0 */
function add_css$d(target) {
append_styles(target, "svelte-19aan9p", ".player-box.svelte-19aan9p{display:flex;flex-direction:row}.player.svelte-19aan9p{cursor:pointer;text-align:center;width:30px;height:30px;line-height:30px;background:#eee;border:3px solid #fefefe;box-sizing:content-box;padding:0}.player.current.svelte-19aan9p{background:#555;color:#eee;font-weight:bold}.player.active.svelte-19aan9p{border:3px solid #ff7f50}");
}
function get_each_context$4(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
return child_ctx;
}
// (59:2) {#each players as player}
function create_each_block$4(ctx) {
let button;
let t0_value = /*player*/ ctx[7] + "";
let t0;
let t1;
let button_aria_label_value;
let mounted;
let dispose;
function click_handler() {
return /*click_handler*/ ctx[5](/*player*/ ctx[7]);
}
return {
c() {
button = element("button");
t0 = text(t0_value);
t1 = space();
attr(button, "class", "player svelte-19aan9p");
attr(button, "aria-label", button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7]));
toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer);
toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, t0);
append(button, t1);
if (!mounted) {
dispose = listen(button, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*players*/ 4 && t0_value !== (t0_value = /*player*/ ctx[7] + "")) set_data(t0, t0_value);
if (dirty & /*players*/ 4 && button_aria_label_value !== (button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7]))) {
attr(button, "aria-label", button_aria_label_value);
}
if (dirty & /*players, ctx*/ 5) {
toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer);
}
if (dirty & /*players, playerID*/ 6) {
toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]);
}
},
d(detaching) {
if (detaching) detach(button);
mounted = false;
dispose();
}
};
}
function create_fragment$k(ctx) {
let div;
let each_value = /*players*/ ctx[2];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$4(get_each_context$4(ctx, each_value, i));
}
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "player-box svelte-19aan9p");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
},
p(ctx, [dirty]) {
if (dirty & /*playerLabel, players, ctx, playerID, OnClick*/ 31) {
each_value = /*players*/ ctx[2];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$4(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$4(child_ctx);
each_blocks[i].c();
each_blocks[i].m(div, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
}
};
}
function instance$k($$self, $$props, $$invalidate) {
let { ctx } = $$props;
let { playerID } = $$props;
const dispatch = createEventDispatcher();
function OnClick(player) {
if (player == playerID) {
dispatch("change", { playerID: null });
} else {
dispatch("change", { playerID: player });
}
}
function playerLabel(player) {
const properties = [];
if (player == ctx.currentPlayer) properties.push('current');
if (player == playerID) properties.push('active');
let label = `Player ${player}`;
if (properties.length) label += ` (${properties.join(', ')})`;
return label;
}
let players;
const click_handler = player => OnClick(player);
$$self.$$set = $$props => {
if ('ctx' in $$props) $$invalidate(0, ctx = $$props.ctx);
if ('playerID' in $$props) $$invalidate(1, playerID = $$props.playerID);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*ctx*/ 1) {
$$invalidate(2, players = ctx
? [...Array(ctx.numPlayers).keys()].map(i => i.toString())
: []);
}
};
return [ctx, playerID, players, OnClick, playerLabel, click_handler];
}
class PlayerInfo extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$k, create_fragment$k, safe_not_equal, { ctx: 0, playerID: 1 }, add_css$d);
}
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = it.call(o);
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function AssignShortcuts(moveNames, blacklist) {
var shortcuts = {};
var taken = {};
var _iterator = _createForOfIteratorHelper(blacklist),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var c = _step.value;
taken[c] = true;
} // Try assigning the first char of each move as the shortcut.
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var t = taken;
var canUseFirstChar = true;
for (var name in moveNames) {
var shortcut = name[0];
if (t[shortcut]) {
canUseFirstChar = false;
break;
}
t[shortcut] = true;
shortcuts[name] = shortcut;
}
if (canUseFirstChar) {
return shortcuts;
} // If those aren't unique, use a-z.
t = taken;
var next = 97;
shortcuts = {};
for (var _name in moveNames) {
var _shortcut = String.fromCharCode(next);
while (t[_shortcut]) {
next++;
_shortcut = String.fromCharCode(next);
}
t[_shortcut] = true;
shortcuts[_name] = _shortcut;
}
return shortcuts;
}
/* src/client/debug/main/Main.svelte generated by Svelte v3.41.0 */
function add_css$e(target) {
append_styles(target, "svelte-146sq5f", ".tree.svelte-146sq5f{--json-tree-font-family:monospace;--json-tree-font-size:14px;--json-tree-null-color:#757575}.label.svelte-146sq5f{margin-bottom:0;text-transform:none}h3.svelte-146sq5f{text-transform:uppercase}ul.svelte-146sq5f{padding-left:0}li.svelte-146sq5f{list-style:none;margin:0;margin-bottom:5px}");
}
function get_each_context$5(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[10] = list[i][0];
child_ctx[11] = list[i][1];
return child_ctx;
}
// (78:4) {#each Object.entries(moves) as [name, fn]}
function create_each_block$5(ctx) {
let li;
let move;
let t;
let current;
move = new Move({
props: {
shortcut: /*shortcuts*/ ctx[8][/*name*/ ctx[10]],
fn: /*fn*/ ctx[11],
name: /*name*/ ctx[10]
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
t = space();
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
append(li, t);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*moves*/ 16) move_changes.shortcut = /*shortcuts*/ ctx[8][/*name*/ ctx[10]];
if (dirty & /*moves*/ 16) move_changes.fn = /*fn*/ ctx[11];
if (dirty & /*moves*/ 16) move_changes.name = /*name*/ ctx[10];
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (90:2) {#if ctx.activePlayers && events.endStage}
function create_if_block_2$2(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endStage",
shortcut: 7,
fn: /*events*/ ctx[5].endStage
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 32) move_changes.fn = /*events*/ ctx[5].endStage;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (95:2) {#if events.endTurn}
function create_if_block_1$2(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endTurn",
shortcut: 8,
fn: /*events*/ ctx[5].endTurn
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 32) move_changes.fn = /*events*/ ctx[5].endTurn;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (100:2) {#if ctx.phase && events.endPhase}
function create_if_block$7(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endPhase",
shortcut: 9,
fn: /*events*/ ctx[5].endPhase
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 32) move_changes.fn = /*events*/ ctx[5].endPhase;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
function create_fragment$l(ctx) {
let section0;
let h30;
let t1;
let controls;
let t2;
let section1;
let h31;
let t4;
let playerinfo;
let t5;
let section2;
let h32;
let t7;
let ul0;
let t8;
let section3;
let h33;
let t10;
let ul1;
let t11;
let t12;
let t13;
let section4;
let h34;
let t15;
let jsontree0;
let t16;
let section5;
let h35;
let t18;
let jsontree1;
let t19;
let clientswitcher;
let current;
controls = new Controls({
props: {
client: /*client*/ ctx[0],
ToggleVisibility: /*ToggleVisibility*/ ctx[2]
}
});
playerinfo = new PlayerInfo({
props: {
ctx: /*ctx*/ ctx[6],
playerID: /*playerID*/ ctx[3]
}
});
playerinfo.$on("change", /*change_handler*/ ctx[9]);
let each_value = Object.entries(/*moves*/ ctx[4]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$5(get_each_context$5(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block0 = /*ctx*/ ctx[6].activePlayers && /*events*/ ctx[5].endStage && create_if_block_2$2(ctx);
let if_block1 = /*events*/ ctx[5].endTurn && create_if_block_1$2(ctx);
let if_block2 = /*ctx*/ ctx[6].phase && /*events*/ ctx[5].endPhase && create_if_block$7(ctx);
jsontree0 = new Root({ props: { value: /*G*/ ctx[7] } });
jsontree1 = new Root({
props: { value: SanitizeCtx(/*ctx*/ ctx[6]) }
});
clientswitcher = new ClientSwitcher({
props: { clientManager: /*clientManager*/ ctx[1] }
});
return {
c() {
section0 = element("section");
h30 = element("h3");
h30.textContent = "Controls";
t1 = space();
create_component(controls.$$.fragment);
t2 = space();
section1 = element("section");
h31 = element("h3");
h31.textContent = "Players";
t4 = space();
create_component(playerinfo.$$.fragment);
t5 = space();
section2 = element("section");
h32 = element("h3");
h32.textContent = "Moves";
t7 = space();
ul0 = element("ul");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t8 = space();
section3 = element("section");
h33 = element("h3");
h33.textContent = "Events";
t10 = space();
ul1 = element("ul");
if (if_block0) if_block0.c();
t11 = space();
if (if_block1) if_block1.c();
t12 = space();
if (if_block2) if_block2.c();
t13 = space();
section4 = element("section");
h34 = element("h3");
h34.textContent = "G";
t15 = space();
create_component(jsontree0.$$.fragment);
t16 = space();
section5 = element("section");
h35 = element("h3");
h35.textContent = "ctx";
t18 = space();
create_component(jsontree1.$$.fragment);
t19 = space();
create_component(clientswitcher.$$.fragment);
attr(h30, "class", "svelte-146sq5f");
attr(h31, "class", "svelte-146sq5f");
attr(h32, "class", "svelte-146sq5f");
attr(ul0, "class", "svelte-146sq5f");
attr(h33, "class", "svelte-146sq5f");
attr(ul1, "class", "svelte-146sq5f");
attr(h34, "class", "label svelte-146sq5f");
attr(section4, "class", "tree svelte-146sq5f");
attr(h35, "class", "label svelte-146sq5f");
attr(section5, "class", "tree svelte-146sq5f");
},
m(target, anchor) {
insert(target, section0, anchor);
append(section0, h30);
append(section0, t1);
mount_component(controls, section0, null);
insert(target, t2, anchor);
insert(target, section1, anchor);
append(section1, h31);
append(section1, t4);
mount_component(playerinfo, section1, null);
insert(target, t5, anchor);
insert(target, section2, anchor);
append(section2, h32);
append(section2, t7);
append(section2, ul0);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(ul0, null);
}
insert(target, t8, anchor);
insert(target, section3, anchor);
append(section3, h33);
append(section3, t10);
append(section3, ul1);
if (if_block0) if_block0.m(ul1, null);
append(ul1, t11);
if (if_block1) if_block1.m(ul1, null);
append(ul1, t12);
if (if_block2) if_block2.m(ul1, null);
insert(target, t13, anchor);
insert(target, section4, anchor);
append(section4, h34);
append(section4, t15);
mount_component(jsontree0, section4, null);
insert(target, t16, anchor);
insert(target, section5, anchor);
append(section5, h35);
append(section5, t18);
mount_component(jsontree1, section5, null);
insert(target, t19, anchor);
mount_component(clientswitcher, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const controls_changes = {};
if (dirty & /*client*/ 1) controls_changes.client = /*client*/ ctx[0];
if (dirty & /*ToggleVisibility*/ 4) controls_changes.ToggleVisibility = /*ToggleVisibility*/ ctx[2];
controls.$set(controls_changes);
const playerinfo_changes = {};
if (dirty & /*ctx*/ 64) playerinfo_changes.ctx = /*ctx*/ ctx[6];
if (dirty & /*playerID*/ 8) playerinfo_changes.playerID = /*playerID*/ ctx[3];
playerinfo.$set(playerinfo_changes);
if (dirty & /*shortcuts, Object, moves*/ 272) {
each_value = Object.entries(/*moves*/ ctx[4]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$5(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$5(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(ul0, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*ctx*/ ctx[6].activePlayers && /*events*/ ctx[5].endStage) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*ctx, events*/ 96) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_2$2(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(ul1, t11);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
if (/*events*/ ctx[5].endTurn) {
if (if_block1) {
if_block1.p(ctx, dirty);
if (dirty & /*events*/ 32) {
transition_in(if_block1, 1);
}
} else {
if_block1 = create_if_block_1$2(ctx);
if_block1.c();
transition_in(if_block1, 1);
if_block1.m(ul1, t12);
}
} else if (if_block1) {
group_outros();
transition_out(if_block1, 1, 1, () => {
if_block1 = null;
});
check_outros();
}
if (/*ctx*/ ctx[6].phase && /*events*/ ctx[5].endPhase) {
if (if_block2) {
if_block2.p(ctx, dirty);
if (dirty & /*ctx, events*/ 96) {
transition_in(if_block2, 1);
}
} else {
if_block2 = create_if_block$7(ctx);
if_block2.c();
transition_in(if_block2, 1);
if_block2.m(ul1, null);
}
} else if (if_block2) {
group_outros();
transition_out(if_block2, 1, 1, () => {
if_block2 = null;
});
check_outros();
}
const jsontree0_changes = {};
if (dirty & /*G*/ 128) jsontree0_changes.value = /*G*/ ctx[7];
jsontree0.$set(jsontree0_changes);
const jsontree1_changes = {};
if (dirty & /*ctx*/ 64) jsontree1_changes.value = SanitizeCtx(/*ctx*/ ctx[6]);
jsontree1.$set(jsontree1_changes);
const clientswitcher_changes = {};
if (dirty & /*clientManager*/ 2) clientswitcher_changes.clientManager = /*clientManager*/ ctx[1];
clientswitcher.$set(clientswitcher_changes);
},
i(local) {
if (current) return;
transition_in(controls.$$.fragment, local);
transition_in(playerinfo.$$.fragment, local);
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
transition_in(if_block0);
transition_in(if_block1);
transition_in(if_block2);
transition_in(jsontree0.$$.fragment, local);
transition_in(jsontree1.$$.fragment, local);
transition_in(clientswitcher.$$.fragment, local);
current = true;
},
o(local) {
transition_out(controls.$$.fragment, local);
transition_out(playerinfo.$$.fragment, local);
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
transition_out(if_block0);
transition_out(if_block1);
transition_out(if_block2);
transition_out(jsontree0.$$.fragment, local);
transition_out(jsontree1.$$.fragment, local);
transition_out(clientswitcher.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(section0);
destroy_component(controls);
if (detaching) detach(t2);
if (detaching) detach(section1);
destroy_component(playerinfo);
if (detaching) detach(t5);
if (detaching) detach(section2);
destroy_each(each_blocks, detaching);
if (detaching) detach(t8);
if (detaching) detach(section3);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
if (if_block2) if_block2.d();
if (detaching) detach(t13);
if (detaching) detach(section4);
destroy_component(jsontree0);
if (detaching) detach(t16);
if (detaching) detach(section5);
destroy_component(jsontree1);
if (detaching) detach(t19);
destroy_component(clientswitcher, detaching);
}
};
}
function SanitizeCtx(ctx) {
let r = {};
for (const key in ctx) {
if (!key.startsWith('_')) {
r[key] = ctx[key];
}
}
return r;
}
function instance$l($$self, $$props, $$invalidate) {
let { client } = $$props;
let { clientManager } = $$props;
let { ToggleVisibility } = $$props;
const shortcuts = AssignShortcuts(client.moves, 'mlia');
let { playerID, moves, events } = client;
let ctx = {};
let G = {};
client.subscribe(state => {
if (state) $$invalidate(7, { G, ctx } = state, G, $$invalidate(6, ctx));
$$invalidate(3, { playerID, moves, events } = client, playerID, $$invalidate(4, moves), $$invalidate(5, events));
});
const change_handler = e => clientManager.switchPlayerID(e.detail.playerID);
$$self.$$set = $$props => {
if ('client' in $$props) $$invalidate(0, client = $$props.client);
if ('clientManager' in $$props) $$invalidate(1, clientManager = $$props.clientManager);
if ('ToggleVisibility' in $$props) $$invalidate(2, ToggleVisibility = $$props.ToggleVisibility);
};
return [
client,
clientManager,
ToggleVisibility,
playerID,
moves,
events,
ctx,
G,
shortcuts,
change_handler
];
}
class Main extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$l,
create_fragment$l,
safe_not_equal,
{
client: 0,
clientManager: 1,
ToggleVisibility: 2
},
add_css$e
);
}
}
/* src/client/debug/info/Item.svelte generated by Svelte v3.41.0 */
function add_css$f(target) {
append_styles(target, "svelte-13qih23", ".item.svelte-13qih23.svelte-13qih23{padding:10px}.item.svelte-13qih23.svelte-13qih23:not(:first-child){border-top:1px dashed #aaa}.item.svelte-13qih23 div.svelte-13qih23{float:right;text-align:right}");
}
function create_fragment$m(ctx) {
let div1;
let strong;
let t0;
let t1;
let div0;
let t2_value = JSON.stringify(/*value*/ ctx[1]) + "";
let t2;
return {
c() {
div1 = element("div");
strong = element("strong");
t0 = text(/*name*/ ctx[0]);
t1 = space();
div0 = element("div");
t2 = text(t2_value);
attr(div0, "class", "svelte-13qih23");
attr(div1, "class", "item svelte-13qih23");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, strong);
append(strong, t0);
append(div1, t1);
append(div1, div0);
append(div0, t2);
},
p(ctx, [dirty]) {
if (dirty & /*name*/ 1) set_data(t0, /*name*/ ctx[0]);
if (dirty & /*value*/ 2 && t2_value !== (t2_value = JSON.stringify(/*value*/ ctx[1]) + "")) set_data(t2, t2_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div1);
}
};
}
function instance$m($$self, $$props, $$invalidate) {
let { name } = $$props;
let { value } = $$props;
$$self.$$set = $$props => {
if ('name' in $$props) $$invalidate(0, name = $$props.name);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
};
return [name, value];
}
class Item extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$m, create_fragment$m, safe_not_equal, { name: 0, value: 1 }, add_css$f);
}
}
/* src/client/debug/info/Info.svelte generated by Svelte v3.41.0 */
function add_css$g(target) {
append_styles(target, "svelte-1yzq5o8", ".gameinfo.svelte-1yzq5o8{padding:10px}");
}
// (19:2) {#if client.multiplayer}
function create_if_block$8(ctx) {
let item;
let current;
item = new Item({
props: {
name: "isConnected",
value: /*$client*/ ctx[1].isConnected
}
});
return {
c() {
create_component(item.$$.fragment);
},
m(target, anchor) {
mount_component(item, target, anchor);
current = true;
},
p(ctx, dirty) {
const item_changes = {};
if (dirty & /*$client*/ 2) item_changes.value = /*$client*/ ctx[1].isConnected;
item.$set(item_changes);
},
i(local) {
if (current) return;
transition_in(item.$$.fragment, local);
current = true;
},
o(local) {
transition_out(item.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(item, detaching);
}
};
}
function create_fragment$n(ctx) {
let section;
let item0;
let t0;
let item1;
let t1;
let item2;
let t2;
let current;
item0 = new Item({
props: {
name: "matchID",
value: /*client*/ ctx[0].matchID
}
});
item1 = new Item({
props: {
name: "playerID",
value: /*client*/ ctx[0].playerID
}
});
item2 = new Item({
props: {
name: "isActive",
value: /*$client*/ ctx[1].isActive
}
});
let if_block = /*client*/ ctx[0].multiplayer && create_if_block$8(ctx);
return {
c() {
section = element("section");
create_component(item0.$$.fragment);
t0 = space();
create_component(item1.$$.fragment);
t1 = space();
create_component(item2.$$.fragment);
t2 = space();
if (if_block) if_block.c();
attr(section, "class", "gameinfo svelte-1yzq5o8");
},
m(target, anchor) {
insert(target, section, anchor);
mount_component(item0, section, null);
append(section, t0);
mount_component(item1, section, null);
append(section, t1);
mount_component(item2, section, null);
append(section, t2);
if (if_block) if_block.m(section, null);
current = true;
},
p(ctx, [dirty]) {
const item0_changes = {};
if (dirty & /*client*/ 1) item0_changes.value = /*client*/ ctx[0].matchID;
item0.$set(item0_changes);
const item1_changes = {};
if (dirty & /*client*/ 1) item1_changes.value = /*client*/ ctx[0].playerID;
item1.$set(item1_changes);
const item2_changes = {};
if (dirty & /*$client*/ 2) item2_changes.value = /*$client*/ ctx[1].isActive;
item2.$set(item2_changes);
if (/*client*/ ctx[0].multiplayer) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*client*/ 1) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$8(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(section, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(item0.$$.fragment, local);
transition_in(item1.$$.fragment, local);
transition_in(item2.$$.fragment, local);
transition_in(if_block);
current = true;
},
o(local) {
transition_out(item0.$$.fragment, local);
transition_out(item1.$$.fragment, local);
transition_out(item2.$$.fragment, local);
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(item0);
destroy_component(item1);
destroy_component(item2);
if (if_block) if_block.d();
}
};
}
function instance$n($$self, $$props, $$invalidate) {
let $client,
$$unsubscribe_client = noop,
$$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(1, $client = $$value)), client);
$$self.$$.on_destroy.push(() => $$unsubscribe_client());
let { client } = $$props;
$$subscribe_client();
let { clientManager } = $$props;
let { ToggleVisibility } = $$props;
$$self.$$set = $$props => {
if ('client' in $$props) $$subscribe_client($$invalidate(0, client = $$props.client));
if ('clientManager' in $$props) $$invalidate(2, clientManager = $$props.clientManager);
if ('ToggleVisibility' in $$props) $$invalidate(3, ToggleVisibility = $$props.ToggleVisibility);
};
return [client, $client, clientManager, ToggleVisibility];
}
class Info extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$n,
create_fragment$n,
safe_not_equal,
{
client: 0,
clientManager: 2,
ToggleVisibility: 3
},
add_css$g
);
}
}
/* src/client/debug/log/TurnMarker.svelte generated by Svelte v3.41.0 */
function add_css$h(target) {
append_styles(target, "svelte-6eza86", ".turn-marker.svelte-6eza86{display:flex;justify-content:center;align-items:center;grid-column:1;background:#555;color:#eee;text-align:center;font-weight:bold;border:1px solid #888}");
}
function create_fragment$o(ctx) {
let div;
let t;
return {
c() {
div = element("div");
t = text(/*turn*/ ctx[0]);
attr(div, "class", "turn-marker svelte-6eza86");
attr(div, "style", /*style*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*turn*/ 1) set_data(t, /*turn*/ ctx[0]);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$o($$self, $$props, $$invalidate) {
let { turn } = $$props;
let { numEvents } = $$props;
const style = `grid-row: span ${numEvents}`;
$$self.$$set = $$props => {
if ('turn' in $$props) $$invalidate(0, turn = $$props.turn);
if ('numEvents' in $$props) $$invalidate(2, numEvents = $$props.numEvents);
};
return [turn, style, numEvents];
}
class TurnMarker extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$o, create_fragment$o, safe_not_equal, { turn: 0, numEvents: 2 }, add_css$h);
}
}
/* src/client/debug/log/PhaseMarker.svelte generated by Svelte v3.41.0 */
function add_css$i(target) {
append_styles(target, "svelte-1t4xap", ".phase-marker.svelte-1t4xap{grid-column:3;background:#555;border:1px solid #888;color:#eee;text-align:center;font-weight:bold;padding-top:10px;padding-bottom:10px;text-orientation:sideways;writing-mode:vertical-rl;line-height:30px;width:100%}");
}
function create_fragment$p(ctx) {
let div;
let t_value = (/*phase*/ ctx[0] || '') + "";
let t;
return {
c() {
div = element("div");
t = text(t_value);
attr(div, "class", "phase-marker svelte-1t4xap");
attr(div, "style", /*style*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*phase*/ 1 && t_value !== (t_value = (/*phase*/ ctx[0] || '') + "")) set_data(t, t_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$p($$self, $$props, $$invalidate) {
let { phase } = $$props;
let { numEvents } = $$props;
const style = `grid-row: span ${numEvents}`;
$$self.$$set = $$props => {
if ('phase' in $$props) $$invalidate(0, phase = $$props.phase);
if ('numEvents' in $$props) $$invalidate(2, numEvents = $$props.numEvents);
};
return [phase, style, numEvents];
}
class PhaseMarker extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$p, create_fragment$p, safe_not_equal, { phase: 0, numEvents: 2 }, add_css$i);
}
}
/* src/client/debug/log/LogMetadata.svelte generated by Svelte v3.41.0 */
function create_fragment$q(ctx) {
let div;
return {
c() {
div = element("div");
div.textContent = `${/*renderedMetadata*/ ctx[0]}`;
},
m(target, anchor) {
insert(target, div, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$q($$self, $$props, $$invalidate) {
let { metadata } = $$props;
const renderedMetadata = metadata !== undefined
? JSON.stringify(metadata, null, 4)
: '';
$$self.$$set = $$props => {
if ('metadata' in $$props) $$invalidate(1, metadata = $$props.metadata);
};
return [renderedMetadata, metadata];
}
class LogMetadata extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$q, create_fragment$q, safe_not_equal, { metadata: 1 });
}
}
/* src/client/debug/log/LogEvent.svelte generated by Svelte v3.41.0 */
function add_css$j(target) {
append_styles(target, "svelte-vajd9z", ".log-event.svelte-vajd9z{grid-column:2;cursor:pointer;overflow:hidden;display:flex;flex-direction:column;justify-content:center;background:#fff;border:1px dotted #ccc;border-left:5px solid #ccc;padding:5px;text-align:center;color:#666;font-size:14px;min-height:25px;line-height:25px}.log-event.svelte-vajd9z:hover,.log-event.svelte-vajd9z:focus{border-style:solid;background:#eee}.log-event.pinned.svelte-vajd9z{border-style:solid;background:#eee;opacity:1}.args.svelte-vajd9z{text-align:left;white-space:pre-wrap}.player0.svelte-vajd9z{border-left-color:#ff851b}.player1.svelte-vajd9z{border-left-color:#7fdbff}.player2.svelte-vajd9z{border-left-color:#0074d9}.player3.svelte-vajd9z{border-left-color:#39cccc}.player4.svelte-vajd9z{border-left-color:#3d9970}.player5.svelte-vajd9z{border-left-color:#2ecc40}.player6.svelte-vajd9z{border-left-color:#01ff70}.player7.svelte-vajd9z{border-left-color:#ffdc00}.player8.svelte-vajd9z{border-left-color:#001f3f}.player9.svelte-vajd9z{border-left-color:#ff4136}.player10.svelte-vajd9z{border-left-color:#85144b}.player11.svelte-vajd9z{border-left-color:#f012be}.player12.svelte-vajd9z{border-left-color:#b10dc9}.player13.svelte-vajd9z{border-left-color:#111111}.player14.svelte-vajd9z{border-left-color:#aaaaaa}.player15.svelte-vajd9z{border-left-color:#dddddd}");
}
// (146:2) {:else}
function create_else_block$1(ctx) {
let logmetadata;
let current;
logmetadata = new LogMetadata({ props: { metadata: /*metadata*/ ctx[2] } });
return {
c() {
create_component(logmetadata.$$.fragment);
},
m(target, anchor) {
mount_component(logmetadata, target, anchor);
current = true;
},
p(ctx, dirty) {
const logmetadata_changes = {};
if (dirty & /*metadata*/ 4) logmetadata_changes.metadata = /*metadata*/ ctx[2];
logmetadata.$set(logmetadata_changes);
},
i(local) {
if (current) return;
transition_in(logmetadata.$$.fragment, local);
current = true;
},
o(local) {
transition_out(logmetadata.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(logmetadata, detaching);
}
};
}
// (144:2) {#if metadataComponent}
function create_if_block$9(ctx) {
let switch_instance;
let switch_instance_anchor;
let current;
var switch_value = /*metadataComponent*/ ctx[3];
function switch_props(ctx) {
return { props: { metadata: /*metadata*/ ctx[2] } };
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
if (switch_instance) create_component(switch_instance.$$.fragment);
switch_instance_anchor = empty();
},
m(target, anchor) {
if (switch_instance) {
mount_component(switch_instance, target, anchor);
}
insert(target, switch_instance_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const switch_instance_changes = {};
if (dirty & /*metadata*/ 4) switch_instance_changes.metadata = /*metadata*/ ctx[2];
if (switch_value !== (switch_value = /*metadataComponent*/ ctx[3])) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(switch_instance_anchor);
if (switch_instance) destroy_component(switch_instance, detaching);
}
};
}
function create_fragment$r(ctx) {
let button;
let div;
let t0;
let t1;
let t2;
let t3;
let t4;
let current_block_type_index;
let if_block;
let button_class_value;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$9, create_else_block$1];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*metadataComponent*/ ctx[3]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
button = element("button");
div = element("div");
t0 = text(/*actionType*/ ctx[4]);
t1 = text("(");
t2 = text(/*renderedArgs*/ ctx[6]);
t3 = text(")");
t4 = space();
if_block.c();
attr(div, "class", "args svelte-vajd9z");
attr(button, "class", button_class_value = "log-event player" + /*playerID*/ ctx[7] + " svelte-vajd9z");
toggle_class(button, "pinned", /*pinned*/ ctx[1]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, div);
append(div, t0);
append(div, t1);
append(div, t2);
append(div, t3);
append(button, t4);
if_blocks[current_block_type_index].m(button, null);
current = true;
if (!mounted) {
dispose = [
listen(button, "click", /*click_handler*/ ctx[9]),
listen(button, "mouseenter", /*mouseenter_handler*/ ctx[10]),
listen(button, "focus", /*focus_handler*/ ctx[11]),
listen(button, "mouseleave", /*mouseleave_handler*/ ctx[12]),
listen(button, "blur", /*blur_handler*/ ctx[13])
];
mounted = true;
}
},
p(ctx, [dirty]) {
if (!current || dirty & /*actionType*/ 16) set_data(t0, /*actionType*/ ctx[4]);
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
} else {
if_block.p(ctx, dirty);
}
transition_in(if_block, 1);
if_block.m(button, null);
}
if (dirty & /*pinned*/ 2) {
toggle_class(button, "pinned", /*pinned*/ ctx[1]);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(button);
if_blocks[current_block_type_index].d();
mounted = false;
run_all(dispose);
}
};
}
function instance$r($$self, $$props, $$invalidate) {
let { logIndex } = $$props;
let { action } = $$props;
let { pinned } = $$props;
let { metadata } = $$props;
let { metadataComponent } = $$props;
const dispatch = createEventDispatcher();
const args = action.payload.args;
const renderedArgs = Array.isArray(args)
? args.map(arg => JSON.stringify(arg, null, 2)).join(',')
: JSON.stringify(args, null, 2) || '';
const playerID = action.payload.playerID;
let actionType;
switch (action.type) {
case 'UNDO':
actionType = 'undo';
break;
case 'REDO':
actionType = 'redo';
case 'GAME_EVENT':
case 'MAKE_MOVE':
default:
actionType = action.payload.type;
break;
}
const click_handler = () => dispatch('click', { logIndex });
const mouseenter_handler = () => dispatch('mouseenter', { logIndex });
const focus_handler = () => dispatch('mouseenter', { logIndex });
const mouseleave_handler = () => dispatch('mouseleave');
const blur_handler = () => dispatch('mouseleave');
$$self.$$set = $$props => {
if ('logIndex' in $$props) $$invalidate(0, logIndex = $$props.logIndex);
if ('action' in $$props) $$invalidate(8, action = $$props.action);
if ('pinned' in $$props) $$invalidate(1, pinned = $$props.pinned);
if ('metadata' in $$props) $$invalidate(2, metadata = $$props.metadata);
if ('metadataComponent' in $$props) $$invalidate(3, metadataComponent = $$props.metadataComponent);
};
return [
logIndex,
pinned,
metadata,
metadataComponent,
actionType,
dispatch,
renderedArgs,
playerID,
action,
click_handler,
mouseenter_handler,
focus_handler,
mouseleave_handler,
blur_handler
];
}
class LogEvent extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$r,
create_fragment$r,
safe_not_equal,
{
logIndex: 0,
action: 8,
pinned: 1,
metadata: 2,
metadataComponent: 3
},
add_css$j
);
}
}
/* node_modules/svelte-icons/fa/FaArrowAltCircleDown.svelte generated by Svelte v3.41.0 */
function create_default_slot$1(ctx) {
let path;
return {
c() {
path = svg_element("path");
attr(path, "d", "M504 256c0 137-111 248-248 248S8 393 8 256 119 8 256 8s248 111 248 248zM212 140v116h-70.9c-10.7 0-16.1 13-8.5 20.5l114.9 114.3c4.7 4.7 12.2 4.7 16.9 0l114.9-114.3c7.6-7.6 2.2-20.5-8.5-20.5H300V140c0-6.6-5.4-12-12-12h-64c-6.6 0-12 5.4-12 12z");
},
m(target, anchor) {
insert(target, path, anchor);
},
d(detaching) {
if (detaching) detach(path);
}
};
}
function create_fragment$s(ctx) {
let iconbase;
let current;
const iconbase_spread_levels = [{ viewBox: "0 0 512 512" }, /*$$props*/ ctx[0]];
let iconbase_props = {
$$slots: { default: [create_default_slot$1] },
$$scope: { ctx }
};
for (let i = 0; i < iconbase_spread_levels.length; i += 1) {
iconbase_props = assign(iconbase_props, iconbase_spread_levels[i]);
}
iconbase = new IconBase({ props: iconbase_props });
return {
c() {
create_component(iconbase.$$.fragment);
},
m(target, anchor) {
mount_component(iconbase, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const iconbase_changes = (dirty & /*$$props*/ 1)
? get_spread_update(iconbase_spread_levels, [iconbase_spread_levels[0], get_spread_object(/*$$props*/ ctx[0])])
: {};
if (dirty & /*$$scope*/ 2) {
iconbase_changes.$$scope = { dirty, ctx };
}
iconbase.$set(iconbase_changes);
},
i(local) {
if (current) return;
transition_in(iconbase.$$.fragment, local);
current = true;
},
o(local) {
transition_out(iconbase.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(iconbase, detaching);
}
};
}
function instance$s($$self, $$props, $$invalidate) {
$$self.$$set = $$new_props => {
$$invalidate(0, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
};
$$props = exclude_internal_props($$props);
return [$$props];
}
class FaArrowAltCircleDown extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$s, create_fragment$s, safe_not_equal, {});
}
}
/* src/client/debug/mcts/Action.svelte generated by Svelte v3.41.0 */
function add_css$k(target) {
append_styles(target, "svelte-1a7time", "div.svelte-1a7time{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;max-width:500px}");
}
function create_fragment$t(ctx) {
let div;
let t;
return {
c() {
div = element("div");
t = text(/*text*/ ctx[0]);
attr(div, "alt", /*text*/ ctx[0]);
attr(div, "class", "svelte-1a7time");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*text*/ 1) set_data(t, /*text*/ ctx[0]);
if (dirty & /*text*/ 1) {
attr(div, "alt", /*text*/ ctx[0]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$t($$self, $$props, $$invalidate) {
let { action } = $$props;
let text;
$$self.$$set = $$props => {
if ('action' in $$props) $$invalidate(1, action = $$props.action);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*action*/ 2) {
{
const { type, args } = action.payload;
const argsFormatted = (args || []).join(',');
$$invalidate(0, text = `${type}(${argsFormatted})`);
}
}
};
return [text, action];
}
class Action extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$t, create_fragment$t, safe_not_equal, { action: 1 }, add_css$k);
}
}
/* src/client/debug/mcts/Table.svelte generated by Svelte v3.41.0 */
function add_css$l(target) {
append_styles(target, "svelte-ztcwsu", "table.svelte-ztcwsu.svelte-ztcwsu{font-size:12px;border-collapse:collapse;border:1px solid #ddd;padding:0}tr.svelte-ztcwsu.svelte-ztcwsu{cursor:pointer}tr.svelte-ztcwsu:hover td.svelte-ztcwsu{background:#eee}tr.selected.svelte-ztcwsu td.svelte-ztcwsu{background:#eee}td.svelte-ztcwsu.svelte-ztcwsu{padding:10px;height:10px;line-height:10px;font-size:12px;border:none}th.svelte-ztcwsu.svelte-ztcwsu{background:#888;color:#fff;padding:10px;text-align:center}");
}
function get_each_context$6(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[10] = list[i];
child_ctx[12] = i;
return child_ctx;
}
// (86:2) {#each children as child, i}
function create_each_block$6(ctx) {
let tr;
let td0;
let t0_value = /*child*/ ctx[10].value + "";
let t0;
let t1;
let td1;
let t2_value = /*child*/ ctx[10].visits + "";
let t2;
let t3;
let td2;
let action;
let t4;
let current;
let mounted;
let dispose;
action = new Action({
props: { action: /*child*/ ctx[10].parentAction }
});
function click_handler() {
return /*click_handler*/ ctx[6](/*child*/ ctx[10], /*i*/ ctx[12]);
}
function mouseout_handler() {
return /*mouseout_handler*/ ctx[7](/*i*/ ctx[12]);
}
function mouseover_handler() {
return /*mouseover_handler*/ ctx[8](/*child*/ ctx[10], /*i*/ ctx[12]);
}
return {
c() {
tr = element("tr");
td0 = element("td");
t0 = text(t0_value);
t1 = space();
td1 = element("td");
t2 = text(t2_value);
t3 = space();
td2 = element("td");
create_component(action.$$.fragment);
t4 = space();
attr(td0, "class", "svelte-ztcwsu");
attr(td1, "class", "svelte-ztcwsu");
attr(td2, "class", "svelte-ztcwsu");
attr(tr, "class", "svelte-ztcwsu");
toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0);
toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]);
},
m(target, anchor) {
insert(target, tr, anchor);
append(tr, td0);
append(td0, t0);
append(tr, t1);
append(tr, td1);
append(td1, t2);
append(tr, t3);
append(tr, td2);
mount_component(action, td2, null);
append(tr, t4);
current = true;
if (!mounted) {
dispose = [
listen(tr, "click", click_handler),
listen(tr, "mouseout", mouseout_handler),
listen(tr, "mouseover", mouseover_handler)
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if ((!current || dirty & /*children*/ 2) && t0_value !== (t0_value = /*child*/ ctx[10].value + "")) set_data(t0, t0_value);
if ((!current || dirty & /*children*/ 2) && t2_value !== (t2_value = /*child*/ ctx[10].visits + "")) set_data(t2, t2_value);
const action_changes = {};
if (dirty & /*children*/ 2) action_changes.action = /*child*/ ctx[10].parentAction;
action.$set(action_changes);
if (dirty & /*children*/ 2) {
toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0);
}
if (dirty & /*selectedIndex*/ 1) {
toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]);
}
},
i(local) {
if (current) return;
transition_in(action.$$.fragment, local);
current = true;
},
o(local) {
transition_out(action.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(tr);
destroy_component(action);
mounted = false;
run_all(dispose);
}
};
}
function create_fragment$u(ctx) {
let table;
let thead;
let t5;
let tbody;
let current;
let each_value = /*children*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$6(get_each_context$6(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
table = element("table");
thead = element("thead");
thead.innerHTML = `<th class="svelte-ztcwsu">Value</th>
<th class="svelte-ztcwsu">Visits</th>
<th class="svelte-ztcwsu">Action</th>`;
t5 = space();
tbody = element("tbody");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(table, "class", "svelte-ztcwsu");
},
m(target, anchor) {
insert(target, table, anchor);
append(table, thead);
append(table, t5);
append(table, tbody);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(tbody, null);
}
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*children, selectedIndex, Select, Preview*/ 15) {
each_value = /*children*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$6(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$6(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(tbody, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(table);
destroy_each(each_blocks, detaching);
}
};
}
function instance$u($$self, $$props, $$invalidate) {
let { root } = $$props;
let { selectedIndex = null } = $$props;
const dispatch = createEventDispatcher();
let parents = [];
let children = [];
function Select(node, i) {
dispatch('select', { node, selectedIndex: i });
}
function Preview(node, i) {
if (selectedIndex === null) {
dispatch('preview', { node });
}
}
const click_handler = (child, i) => Select(child, i);
const mouseout_handler = i => Preview(null);
const mouseover_handler = (child, i) => Preview(child);
$$self.$$set = $$props => {
if ('root' in $$props) $$invalidate(4, root = $$props.root);
if ('selectedIndex' in $$props) $$invalidate(0, selectedIndex = $$props.selectedIndex);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*root, parents*/ 48) {
{
let t = root;
$$invalidate(5, parents = []);
while (t.parent) {
const parent = t.parent;
const { type, args } = t.parentAction.payload;
const argsFormatted = (args || []).join(',');
const arrowText = `${type}(${argsFormatted})`;
parents.push({ parent, arrowText });
t = parent;
}
parents.reverse();
$$invalidate(1, children = [...root.children].sort((a, b) => a.visits < b.visits ? 1 : -1).slice(0, 50));
}
}
};
return [
selectedIndex,
children,
Select,
Preview,
root,
parents,
click_handler,
mouseout_handler,
mouseover_handler
];
}
class Table extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$u, create_fragment$u, safe_not_equal, { root: 4, selectedIndex: 0 }, add_css$l);
}
}
/* src/client/debug/mcts/MCTS.svelte generated by Svelte v3.41.0 */
function add_css$m(target) {
append_styles(target, "svelte-1f0amz4", ".visualizer.svelte-1f0amz4{display:flex;flex-direction:column;align-items:center;padding:50px}.preview.svelte-1f0amz4{opacity:0.5}.icon.svelte-1f0amz4{color:#777;width:32px;height:32px;margin-bottom:20px}");
}
function get_each_context$7(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[9] = list[i].node;
child_ctx[10] = list[i].selectedIndex;
child_ctx[12] = i;
return child_ctx;
}
// (50:4) {#if i !== 0}
function create_if_block_2$3(ctx) {
let div;
let arrow;
let current;
arrow = new FaArrowAltCircleDown({});
return {
c() {
div = element("div");
create_component(arrow.$$.fragment);
attr(div, "class", "icon svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
mount_component(arrow, div, null);
current = true;
},
i(local) {
if (current) return;
transition_in(arrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(arrow.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_component(arrow);
}
};
}
// (61:6) {:else}
function create_else_block$2(ctx) {
let table;
let current;
function select_handler_1(...args) {
return /*select_handler_1*/ ctx[7](/*i*/ ctx[12], ...args);
}
table = new Table({
props: {
root: /*node*/ ctx[9],
selectedIndex: /*selectedIndex*/ ctx[10]
}
});
table.$on("select", select_handler_1);
return {
c() {
create_component(table.$$.fragment);
},
m(target, anchor) {
mount_component(table, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const table_changes = {};
if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9];
if (dirty & /*nodes*/ 1) table_changes.selectedIndex = /*selectedIndex*/ ctx[10];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(table, detaching);
}
};
}
// (57:6) {#if i === nodes.length - 1}
function create_if_block_1$3(ctx) {
let table;
let current;
function select_handler(...args) {
return /*select_handler*/ ctx[5](/*i*/ ctx[12], ...args);
}
function preview_handler(...args) {
return /*preview_handler*/ ctx[6](/*i*/ ctx[12], ...args);
}
table = new Table({ props: { root: /*node*/ ctx[9] } });
table.$on("select", select_handler);
table.$on("preview", preview_handler);
return {
c() {
create_component(table.$$.fragment);
},
m(target, anchor) {
mount_component(table, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const table_changes = {};
if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(table, detaching);
}
};
}
// (49:2) {#each nodes as { node, selectedIndex }
function create_each_block$7(ctx) {
let t;
let section;
let current_block_type_index;
let if_block1;
let current;
let if_block0 = /*i*/ ctx[12] !== 0 && create_if_block_2$3();
const if_block_creators = [create_if_block_1$3, create_else_block$2];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*i*/ ctx[12] === /*nodes*/ ctx[0].length - 1) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
if (if_block0) if_block0.c();
t = space();
section = element("section");
if_block1.c();
},
m(target, anchor) {
if (if_block0) if_block0.m(target, anchor);
insert(target, t, anchor);
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
},
p(ctx, dirty) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block1 = if_blocks[current_block_type_index];
if (!if_block1) {
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block1.c();
} else {
if_block1.p(ctx, dirty);
}
transition_in(if_block1, 1);
if_block1.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t);
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
}
};
}
// (69:2) {#if preview}
function create_if_block$a(ctx) {
let div;
let arrow;
let t;
let section;
let table;
let current;
arrow = new FaArrowAltCircleDown({});
table = new Table({ props: { root: /*preview*/ ctx[1] } });
return {
c() {
div = element("div");
create_component(arrow.$$.fragment);
t = space();
section = element("section");
create_component(table.$$.fragment);
attr(div, "class", "icon svelte-1f0amz4");
attr(section, "class", "preview svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
mount_component(arrow, div, null);
insert(target, t, anchor);
insert(target, section, anchor);
mount_component(table, section, null);
current = true;
},
p(ctx, dirty) {
const table_changes = {};
if (dirty & /*preview*/ 2) table_changes.root = /*preview*/ ctx[1];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(arrow.$$.fragment, local);
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(arrow.$$.fragment, local);
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_component(arrow);
if (detaching) detach(t);
if (detaching) detach(section);
destroy_component(table);
}
};
}
function create_fragment$v(ctx) {
let div;
let t;
let current;
let each_value = /*nodes*/ ctx[0];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$7(get_each_context$7(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block = /*preview*/ ctx[1] && create_if_block$a(ctx);
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t = space();
if (if_block) if_block.c();
attr(div, "class", "visualizer svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
append(div, t);
if (if_block) if_block.m(div, null);
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*nodes, SelectNode, PreviewNode*/ 13) {
each_value = /*nodes*/ ctx[0];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$7(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$7(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div, t);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*preview*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*preview*/ 2) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$a(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(div, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
transition_in(if_block);
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
if (if_block) if_block.d();
}
};
}
function instance$v($$self, $$props, $$invalidate) {
let { metadata } = $$props;
let nodes = [];
let preview = null;
function SelectNode({ node, selectedIndex }, i) {
$$invalidate(1, preview = null);
$$invalidate(0, nodes[i].selectedIndex = selectedIndex, nodes);
$$invalidate(0, nodes = [...nodes.slice(0, i + 1), { node }]);
}
function PreviewNode({ node }, i) {
$$invalidate(1, preview = node);
}
const select_handler = (i, e) => SelectNode(e.detail, i);
const preview_handler = (i, e) => PreviewNode(e.detail);
const select_handler_1 = (i, e) => SelectNode(e.detail, i);
$$self.$$set = $$props => {
if ('metadata' in $$props) $$invalidate(4, metadata = $$props.metadata);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*metadata*/ 16) {
{
$$invalidate(0, nodes = [{ node: metadata }]);
}
}
};
return [
nodes,
preview,
SelectNode,
PreviewNode,
metadata,
select_handler,
preview_handler,
select_handler_1
];
}
class MCTS extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$v, create_fragment$v, safe_not_equal, { metadata: 4 }, add_css$m);
}
}
/* src/client/debug/log/Log.svelte generated by Svelte v3.41.0 */
function add_css$n(target) {
append_styles(target, "svelte-1pq5e4b", ".gamelog.svelte-1pq5e4b{display:grid;grid-template-columns:30px 1fr 30px;grid-auto-rows:auto;grid-auto-flow:column}");
}
function get_each_context$8(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[16] = list[i].phase;
child_ctx[18] = i;
return child_ctx;
}
function get_each_context_1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[19] = list[i].action;
child_ctx[20] = list[i].metadata;
child_ctx[18] = i;
return child_ctx;
}
function get_each_context_2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[22] = list[i].turn;
child_ctx[18] = i;
return child_ctx;
}
// (136:4) {#if i in turnBoundaries}
function create_if_block_1$4(ctx) {
let turnmarker;
let current;
turnmarker = new TurnMarker({
props: {
turn: /*turn*/ ctx[22],
numEvents: /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]]
}
});
return {
c() {
create_component(turnmarker.$$.fragment);
},
m(target, anchor) {
mount_component(turnmarker, target, anchor);
current = true;
},
p(ctx, dirty) {
const turnmarker_changes = {};
if (dirty & /*renderedLogEntries*/ 2) turnmarker_changes.turn = /*turn*/ ctx[22];
if (dirty & /*turnBoundaries*/ 8) turnmarker_changes.numEvents = /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]];
turnmarker.$set(turnmarker_changes);
},
i(local) {
if (current) return;
transition_in(turnmarker.$$.fragment, local);
current = true;
},
o(local) {
transition_out(turnmarker.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(turnmarker, detaching);
}
};
}
// (135:2) {#each renderedLogEntries as { turn }
function create_each_block_2(ctx) {
let if_block_anchor;
let current;
let if_block = /*i*/ ctx[18] in /*turnBoundaries*/ ctx[3] && create_if_block_1$4(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
if (/*i*/ ctx[18] in /*turnBoundaries*/ ctx[3]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*turnBoundaries*/ 8) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$4(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (141:2) {#each renderedLogEntries as { action, metadata }
function create_each_block_1(ctx) {
let logevent;
let current;
logevent = new LogEvent({
props: {
pinned: /*i*/ ctx[18] === /*pinned*/ ctx[2],
logIndex: /*i*/ ctx[18],
action: /*action*/ ctx[19],
metadata: /*metadata*/ ctx[20]
}
});
logevent.$on("click", /*OnLogClick*/ ctx[5]);
logevent.$on("mouseenter", /*OnMouseEnter*/ ctx[6]);
logevent.$on("mouseleave", /*OnMouseLeave*/ ctx[7]);
return {
c() {
create_component(logevent.$$.fragment);
},
m(target, anchor) {
mount_component(logevent, target, anchor);
current = true;
},
p(ctx, dirty) {
const logevent_changes = {};
if (dirty & /*pinned*/ 4) logevent_changes.pinned = /*i*/ ctx[18] === /*pinned*/ ctx[2];
if (dirty & /*renderedLogEntries*/ 2) logevent_changes.action = /*action*/ ctx[19];
if (dirty & /*renderedLogEntries*/ 2) logevent_changes.metadata = /*metadata*/ ctx[20];
logevent.$set(logevent_changes);
},
i(local) {
if (current) return;
transition_in(logevent.$$.fragment, local);
current = true;
},
o(local) {
transition_out(logevent.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(logevent, detaching);
}
};
}
// (153:4) {#if i in phaseBoundaries}
function create_if_block$b(ctx) {
let phasemarker;
let current;
phasemarker = new PhaseMarker({
props: {
phase: /*phase*/ ctx[16],
numEvents: /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]]
}
});
return {
c() {
create_component(phasemarker.$$.fragment);
},
m(target, anchor) {
mount_component(phasemarker, target, anchor);
current = true;
},
p(ctx, dirty) {
const phasemarker_changes = {};
if (dirty & /*renderedLogEntries*/ 2) phasemarker_changes.phase = /*phase*/ ctx[16];
if (dirty & /*phaseBoundaries*/ 16) phasemarker_changes.numEvents = /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]];
phasemarker.$set(phasemarker_changes);
},
i(local) {
if (current) return;
transition_in(phasemarker.$$.fragment, local);
current = true;
},
o(local) {
transition_out(phasemarker.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(phasemarker, detaching);
}
};
}
// (152:2) {#each renderedLogEntries as { phase }
function create_each_block$8(ctx) {
let if_block_anchor;
let current;
let if_block = /*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4] && create_if_block$b(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
if (/*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*phaseBoundaries*/ 16) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$b(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function create_fragment$w(ctx) {
let div;
let t0;
let t1;
let current;
let mounted;
let dispose;
let each_value_2 = /*renderedLogEntries*/ ctx[1];
let each_blocks_2 = [];
for (let i = 0; i < each_value_2.length; i += 1) {
each_blocks_2[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i));
}
const out = i => transition_out(each_blocks_2[i], 1, 1, () => {
each_blocks_2[i] = null;
});
let each_value_1 = /*renderedLogEntries*/ ctx[1];
let each_blocks_1 = [];
for (let i = 0; i < each_value_1.length; i += 1) {
each_blocks_1[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i));
}
const out_1 = i => transition_out(each_blocks_1[i], 1, 1, () => {
each_blocks_1[i] = null;
});
let each_value = /*renderedLogEntries*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$8(get_each_context$8(ctx, each_value, i));
}
const out_2 = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks_2.length; i += 1) {
each_blocks_2[i].c();
}
t0 = space();
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].c();
}
t1 = space();
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "gamelog svelte-1pq5e4b");
toggle_class(div, "pinned", /*pinned*/ ctx[2]);
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks_2.length; i += 1) {
each_blocks_2[i].m(div, null);
}
append(div, t0);
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].m(div, null);
}
append(div, t1);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
current = true;
if (!mounted) {
dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[8]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*renderedLogEntries, turnBoundaries*/ 10) {
each_value_2 = /*renderedLogEntries*/ ctx[1];
let i;
for (i = 0; i < each_value_2.length; i += 1) {
const child_ctx = get_each_context_2(ctx, each_value_2, i);
if (each_blocks_2[i]) {
each_blocks_2[i].p(child_ctx, dirty);
transition_in(each_blocks_2[i], 1);
} else {
each_blocks_2[i] = create_each_block_2(child_ctx);
each_blocks_2[i].c();
transition_in(each_blocks_2[i], 1);
each_blocks_2[i].m(div, t0);
}
}
group_outros();
for (i = each_value_2.length; i < each_blocks_2.length; i += 1) {
out(i);
}
check_outros();
}
if (dirty & /*pinned, renderedLogEntries, OnLogClick, OnMouseEnter, OnMouseLeave*/ 230) {
each_value_1 = /*renderedLogEntries*/ ctx[1];
let i;
for (i = 0; i < each_value_1.length; i += 1) {
const child_ctx = get_each_context_1(ctx, each_value_1, i);
if (each_blocks_1[i]) {
each_blocks_1[i].p(child_ctx, dirty);
transition_in(each_blocks_1[i], 1);
} else {
each_blocks_1[i] = create_each_block_1(child_ctx);
each_blocks_1[i].c();
transition_in(each_blocks_1[i], 1);
each_blocks_1[i].m(div, t1);
}
}
group_outros();
for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
out_1(i);
}
check_outros();
}
if (dirty & /*renderedLogEntries, phaseBoundaries*/ 18) {
each_value = /*renderedLogEntries*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$8(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$8(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out_2(i);
}
check_outros();
}
if (dirty & /*pinned*/ 4) {
toggle_class(div, "pinned", /*pinned*/ ctx[2]);
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value_2.length; i += 1) {
transition_in(each_blocks_2[i]);
}
for (let i = 0; i < each_value_1.length; i += 1) {
transition_in(each_blocks_1[i]);
}
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks_2 = each_blocks_2.filter(Boolean);
for (let i = 0; i < each_blocks_2.length; i += 1) {
transition_out(each_blocks_2[i]);
}
each_blocks_1 = each_blocks_1.filter(Boolean);
for (let i = 0; i < each_blocks_1.length; i += 1) {
transition_out(each_blocks_1[i]);
}
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks_2, detaching);
destroy_each(each_blocks_1, detaching);
destroy_each(each_blocks, detaching);
mounted = false;
dispose();
}
};
}
function instance$w($$self, $$props, $$invalidate) {
let $client,
$$unsubscribe_client = noop,
$$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(10, $client = $$value)), client);
$$self.$$.on_destroy.push(() => $$unsubscribe_client());
let { client } = $$props;
$$subscribe_client();
const { secondaryPane } = getContext('secondaryPane');
const reducer = CreateGameReducer({ game: client.game });
const initialState = client.getInitialState();
let { log } = $client;
let pinned = null;
function rewind(logIndex) {
let state = initialState;
for (let i = 0; i < log.length; i++) {
const { action, automatic } = log[i];
if (!automatic) {
state = reducer(state, action);
if (logIndex == 0) {
break;
}
logIndex--;
}
}
return {
G: state.G,
ctx: state.ctx,
plugins: state.plugins
};
}
function OnLogClick(e) {
const { logIndex } = e.detail;
const state = rewind(logIndex);
const renderedLogEntries = log.filter(e => !e.automatic);
client.overrideGameState(state);
if (pinned == logIndex) {
$$invalidate(2, pinned = null);
secondaryPane.set(null);
} else {
$$invalidate(2, pinned = logIndex);
const { metadata } = renderedLogEntries[logIndex].action.payload;
if (metadata) {
secondaryPane.set({ component: MCTS, metadata });
}
}
}
function OnMouseEnter(e) {
const { logIndex } = e.detail;
if (pinned === null) {
const state = rewind(logIndex);
client.overrideGameState(state);
}
}
function OnMouseLeave() {
if (pinned === null) {
client.overrideGameState(null);
}
}
function Reset() {
$$invalidate(2, pinned = null);
client.overrideGameState(null);
secondaryPane.set(null);
}
onDestroy(Reset);
function OnKeyDown(e) {
// ESC.
if (e.keyCode == 27) {
Reset();
}
}
let renderedLogEntries;
let turnBoundaries = {};
let phaseBoundaries = {};
$$self.$$set = $$props => {
if ('client' in $$props) $$subscribe_client($$invalidate(0, client = $$props.client));
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$client, log, renderedLogEntries*/ 1538) {
{
$$invalidate(9, log = $client.log);
$$invalidate(1, renderedLogEntries = log.filter(e => !e.automatic));
let eventsInCurrentPhase = 0;
let eventsInCurrentTurn = 0;
$$invalidate(3, turnBoundaries = {});
$$invalidate(4, phaseBoundaries = {});
for (let i = 0; i < renderedLogEntries.length; i++) {
const { action, payload, turn, phase } = renderedLogEntries[i];
eventsInCurrentTurn++;
eventsInCurrentPhase++;
if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].turn != turn) {
$$invalidate(3, turnBoundaries[i] = eventsInCurrentTurn, turnBoundaries);
eventsInCurrentTurn = 0;
}
if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].phase != phase) {
$$invalidate(4, phaseBoundaries[i] = eventsInCurrentPhase, phaseBoundaries);
eventsInCurrentPhase = 0;
}
}
}
}
};
return [
client,
renderedLogEntries,
pinned,
turnBoundaries,
phaseBoundaries,
OnLogClick,
OnMouseEnter,
OnMouseLeave,
OnKeyDown,
log,
$client
];
}
class Log extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$w, create_fragment$w, safe_not_equal, { client: 0 }, add_css$n);
}
}
/* src/client/debug/ai/Options.svelte generated by Svelte v3.41.0 */
function add_css$o(target) {
append_styles(target, "svelte-1fu900w", "label.svelte-1fu900w{color:#666}.option.svelte-1fu900w{margin-bottom:20px}.value.svelte-1fu900w{font-weight:bold;color:#000}input[type='checkbox'].svelte-1fu900w{vertical-align:middle}");
}
function get_each_context$9(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[6] = list[i][0];
child_ctx[7] = list[i][1];
child_ctx[8] = list;
child_ctx[9] = i;
return child_ctx;
}
// (44:47)
function create_if_block_1$5(ctx) {
let input;
let input_id_value;
let mounted;
let dispose;
function input_change_handler() {
/*input_change_handler*/ ctx[5].call(input, /*key*/ ctx[6]);
}
return {
c() {
input = element("input");
attr(input, "id", input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6]));
attr(input, "type", "checkbox");
attr(input, "class", "svelte-1fu900w");
},
m(target, anchor) {
insert(target, input, anchor);
input.checked = /*values*/ ctx[1][/*key*/ ctx[6]];
if (!mounted) {
dispose = [
listen(input, "change", input_change_handler),
listen(input, "change", /*OnChange*/ ctx[2])
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*bot*/ 1 && input_id_value !== (input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6]))) {
attr(input, "id", input_id_value);
}
if (dirty & /*values, Object, bot*/ 3) {
input.checked = /*values*/ ctx[1][/*key*/ ctx[6]];
}
},
d(detaching) {
if (detaching) detach(input);
mounted = false;
run_all(dispose);
}
};
}
// (41:4) {#if value.range}
function create_if_block$c(ctx) {
let span;
let t0_value = /*values*/ ctx[1][/*key*/ ctx[6]] + "";
let t0;
let t1;
let input;
let input_id_value;
let input_min_value;
let input_max_value;
let mounted;
let dispose;
function input_change_input_handler() {
/*input_change_input_handler*/ ctx[4].call(input, /*key*/ ctx[6]);
}
return {
c() {
span = element("span");
t0 = text(t0_value);
t1 = space();
input = element("input");
attr(span, "class", "value svelte-1fu900w");
attr(input, "id", input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6]));
attr(input, "type", "range");
attr(input, "min", input_min_value = /*value*/ ctx[7].range.min);
attr(input, "max", input_max_value = /*value*/ ctx[7].range.max);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t0);
insert(target, t1, anchor);
insert(target, input, anchor);
set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[6]]);
if (!mounted) {
dispose = [
listen(input, "change", input_change_input_handler),
listen(input, "input", input_change_input_handler),
listen(input, "change", /*OnChange*/ ctx[2])
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*values, bot*/ 3 && t0_value !== (t0_value = /*values*/ ctx[1][/*key*/ ctx[6]] + "")) set_data(t0, t0_value);
if (dirty & /*bot*/ 1 && input_id_value !== (input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6]))) {
attr(input, "id", input_id_value);
}
if (dirty & /*bot*/ 1 && input_min_value !== (input_min_value = /*value*/ ctx[7].range.min)) {
attr(input, "min", input_min_value);
}
if (dirty & /*bot*/ 1 && input_max_value !== (input_max_value = /*value*/ ctx[7].range.max)) {
attr(input, "max", input_max_value);
}
if (dirty & /*values, Object, bot*/ 3) {
set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[6]]);
}
},
d(detaching) {
if (detaching) detach(span);
if (detaching) detach(t1);
if (detaching) detach(input);
mounted = false;
run_all(dispose);
}
};
}
// (37:0) {#each Object.entries(bot.opts()) as [key, value]}
function create_each_block$9(ctx) {
let div;
let label;
let t0_value = /*key*/ ctx[6] + "";
let t0;
let label_for_value;
let t1;
let t2;
function select_block_type(ctx, dirty) {
if (/*value*/ ctx[7].range) return create_if_block$c;
if (typeof /*value*/ ctx[7].value === 'boolean') return create_if_block_1$5;
}
let current_block_type = select_block_type(ctx);
let if_block = current_block_type && current_block_type(ctx);
return {
c() {
div = element("div");
label = element("label");
t0 = text(t0_value);
t1 = space();
if (if_block) if_block.c();
t2 = space();
attr(label, "for", label_for_value = /*makeID*/ ctx[3](/*key*/ ctx[6]));
attr(label, "class", "svelte-1fu900w");
attr(div, "class", "option svelte-1fu900w");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, label);
append(label, t0);
append(div, t1);
if (if_block) if_block.m(div, null);
append(div, t2);
},
p(ctx, dirty) {
if (dirty & /*bot*/ 1 && t0_value !== (t0_value = /*key*/ ctx[6] + "")) set_data(t0, t0_value);
if (dirty & /*bot*/ 1 && label_for_value !== (label_for_value = /*makeID*/ ctx[3](/*key*/ ctx[6]))) {
attr(label, "for", label_for_value);
}
if (current_block_type === (current_block_type = select_block_type(ctx)) && if_block) {
if_block.p(ctx, dirty);
} else {
if (if_block) if_block.d(1);
if_block = current_block_type && current_block_type(ctx);
if (if_block) {
if_block.c();
if_block.m(div, t2);
}
}
},
d(detaching) {
if (detaching) detach(div);
if (if_block) {
if_block.d();
}
}
};
}
function create_fragment$x(ctx) {
let each_1_anchor;
let each_value = Object.entries(/*bot*/ ctx[0].opts());
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$9(get_each_context$9(ctx, each_value, i));
}
return {
c() {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
each_1_anchor = empty();
},
m(target, anchor) {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(target, anchor);
}
insert(target, each_1_anchor, anchor);
},
p(ctx, [dirty]) {
if (dirty & /*makeID, Object, bot, values, OnChange*/ 15) {
each_value = Object.entries(/*bot*/ ctx[0].opts());
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$9(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$9(child_ctx);
each_blocks[i].c();
each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
destroy_each(each_blocks, detaching);
if (detaching) detach(each_1_anchor);
}
};
}
function instance$x($$self, $$props, $$invalidate) {
let { bot } = $$props;
let values = {};
for (let [key, value] of Object.entries(bot.opts())) {
values[key] = value.value;
}
function OnChange() {
for (let [key, value] of Object.entries(values)) {
bot.setOpt(key, value);
}
}
const makeID = key => 'ai-option-' + key;
function input_change_input_handler(key) {
values[key] = to_number(this.value);
$$invalidate(1, values);
$$invalidate(0, bot);
}
function input_change_handler(key) {
values[key] = this.checked;
$$invalidate(1, values);
$$invalidate(0, bot);
}
$$self.$$set = $$props => {
if ('bot' in $$props) $$invalidate(0, bot = $$props.bot);
};
return [
bot,
values,
OnChange,
makeID,
input_change_input_handler,
input_change_handler
];
}
class Options extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$x, create_fragment$x, safe_not_equal, { bot: 0 }, add_css$o);
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Base class that bots can extend.
*/
class Bot {
constructor({ enumerate, seed, }) {
this.enumerateFn = enumerate;
this.seed = seed;
this.iterationCounter = 0;
this._opts = {};
}
addOpt({ key, range, initial, }) {
this._opts[key] = {
range,
value: initial,
};
}
getOpt(key) {
return this._opts[key].value;
}
setOpt(key, value) {
if (key in this._opts) {
this._opts[key].value = value;
}
}
opts() {
return this._opts;
}
enumerate(G, ctx, playerID) {
const actions = this.enumerateFn(G, ctx, playerID);
return actions.map((a) => {
if ('payload' in a) {
return a;
}
if ('move' in a) {
return makeMove(a.move, a.args, playerID);
}
if ('event' in a) {
return gameEvent(a.event, a.args, playerID);
}
});
}
random(arg) {
let number;
if (this.seed !== undefined) {
const seed = this.prngstate ? '' : this.seed;
const rand = alea(seed, this.prngstate);
number = rand();
this.prngstate = rand.state();
}
else {
number = Math.random();
}
if (arg) {
if (Array.isArray(arg)) {
const id = Math.floor(number * arg.length);
return arg[id];
}
else {
return Math.floor(number * arg);
}
}
return number;
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* The number of iterations to run before yielding to
* the JS event loop (in async mode).
*/
const CHUNK_SIZE = 25;
/**
* Bot that uses Monte-Carlo Tree Search to find promising moves.
*/
class MCTSBot extends Bot {
constructor({ enumerate, seed, objectives, game, iterations, playoutDepth, iterationCallback, }) {
super({ enumerate, seed });
if (objectives === undefined) {
objectives = () => ({});
}
this.objectives = objectives;
this.iterationCallback = iterationCallback || (() => { });
this.reducer = CreateGameReducer({ game });
this.iterations = iterations;
this.playoutDepth = playoutDepth;
this.addOpt({
key: 'async',
initial: false,
});
this.addOpt({
key: 'iterations',
initial: typeof iterations === 'number' ? iterations : 1000,
range: { min: 1, max: 2000 },
});
this.addOpt({
key: 'playoutDepth',
initial: typeof playoutDepth === 'number' ? playoutDepth : 50,
range: { min: 1, max: 100 },
});
}
createNode({ state, parentAction, parent, playerID, }) {
const { G, ctx } = state;
let actions = [];
let objectives = [];
if (playerID !== undefined) {
actions = this.enumerate(G, ctx, playerID);
objectives = this.objectives(G, ctx, playerID);
}
else if (ctx.activePlayers) {
for (const playerID in ctx.activePlayers) {
actions.push(...this.enumerate(G, ctx, playerID));
objectives.push(this.objectives(G, ctx, playerID));
}
}
else {
actions = this.enumerate(G, ctx, ctx.currentPlayer);
objectives = this.objectives(G, ctx, ctx.currentPlayer);
}
return {
state,
parent,
parentAction,
actions,
objectives,
children: [],
visits: 0,
value: 0,
};
}
select(node) {
// This node has unvisited children.
if (node.actions.length > 0) {
return node;
}
// This is a terminal node.
if (node.children.length === 0) {
return node;
}
let selectedChild = null;
let best = 0;
for (const child of node.children) {
const childVisits = child.visits + Number.EPSILON;
const uct = child.value / childVisits +
Math.sqrt((2 * Math.log(node.visits)) / childVisits);
if (selectedChild == null || uct > best) {
best = uct;
selectedChild = child;
}
}
return this.select(selectedChild);
}
expand(node) {
const actions = node.actions;
if (actions.length === 0 || node.state.ctx.gameover !== undefined) {
return node;
}
const id = this.random(actions.length);
const action = actions[id];
node.actions.splice(id, 1);
const childState = this.reducer(node.state, action);
const childNode = this.createNode({
state: childState,
parentAction: action,
parent: node,
});
node.children.push(childNode);
return childNode;
}
playout({ state }) {
let playoutDepth = this.getOpt('playoutDepth');
if (typeof this.playoutDepth === 'function') {
playoutDepth = this.playoutDepth(state.G, state.ctx);
}
for (let i = 0; i < playoutDepth && state.ctx.gameover === undefined; i++) {
const { G, ctx } = state;
let playerID = ctx.currentPlayer;
if (ctx.activePlayers) {
playerID = Object.keys(ctx.activePlayers)[0];
}
const moves = this.enumerate(G, ctx, playerID);
// Check if any objectives are met.
const objectives = this.objectives(G, ctx, playerID);
const score = Object.keys(objectives).reduce((score, key) => {
const objective = objectives[key];
if (objective.checker(G, ctx)) {
return score + objective.weight;
}
return score;
}, 0);
// If so, stop and return the score.
if (score > 0) {
return { score };
}
if (!moves || moves.length === 0) {
return undefined;
}
const id = this.random(moves.length);
const childState = this.reducer(state, moves[id]);
state = childState;
}
return state.ctx.gameover;
}
backpropagate(node, result = {}) {
node.visits++;
if (result.score !== undefined) {
node.value += result.score;
}
if (result.draw === true) {
node.value += 0.5;
}
if (node.parentAction &&
result.winner === node.parentAction.payload.playerID) {
node.value++;
}
if (node.parent) {
this.backpropagate(node.parent, result);
}
}
play(state, playerID) {
const root = this.createNode({ state, playerID });
let numIterations = this.getOpt('iterations');
if (typeof this.iterations === 'function') {
numIterations = this.iterations(state.G, state.ctx);
}
const getResult = () => {
let selectedChild = null;
for (const child of root.children) {
if (selectedChild == null || child.visits > selectedChild.visits) {
selectedChild = child;
}
}
const action = selectedChild && selectedChild.parentAction;
const metadata = root;
return { action, metadata };
};
return new Promise((resolve) => {
const iteration = () => {
for (let i = 0; i < CHUNK_SIZE && this.iterationCounter < numIterations; i++) {
const leaf = this.select(root);
const child = this.expand(leaf);
const result = this.playout(child);
this.backpropagate(child, result);
this.iterationCounter++;
}
this.iterationCallback({
iterationCounter: this.iterationCounter,
numIterations,
metadata: root,
});
};
this.iterationCounter = 0;
if (this.getOpt('async')) {
const asyncIteration = () => {
if (this.iterationCounter < numIterations) {
iteration();
setImmediate(asyncIteration);
}
else {
resolve(getResult());
}
};
asyncIteration();
}
else {
while (this.iterationCounter < numIterations) {
iteration();
}
resolve(getResult());
}
});
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Bot that picks a move at random.
*/
class RandomBot extends Bot {
play({ G, ctx }, playerID) {
const moves = this.enumerate(G, ctx, playerID);
return Promise.resolve({ action: this.random(moves) });
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Make a single move on the client with a bot.
*
* @param {...object} client - The game client.
* @param {...object} bot - The bot.
*/
async function Step(client, bot) {
const state = client.store.getState();
let playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
const { action, metadata } = await bot.play(state, playerID);
if (action) {
const a = {
...action,
payload: {
...action.payload,
metadata,
},
};
client.store.dispatch(a);
return a;
}
}
/**
* Simulates the game till the end or a max depth.
*
* @param {...object} game - The game object.
* @param {...object} bots - An array of bots.
* @param {...object} state - The game state to start from.
*/
async function Simulate({ game, bots, state, depth, }) {
if (depth === undefined)
depth = 10000;
const reducer = CreateGameReducer({ game });
let metadata = null;
let iter = 0;
while (state.ctx.gameover === undefined && iter < depth) {
let playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
const bot = bots instanceof Bot ? bots : bots[playerID];
const t = await bot.play(state, playerID);
if (!t.action) {
break;
}
metadata = t.metadata;
state = reducer(state, t.action);
iter++;
}
return { state, metadata };
}
/* src/client/debug/ai/AI.svelte generated by Svelte v3.41.0 */
function add_css$p(target) {
append_styles(target, "svelte-lifdi8", "ul.svelte-lifdi8{padding-left:0}li.svelte-lifdi8{list-style:none;margin:none;margin-bottom:5px}h3.svelte-lifdi8{text-transform:uppercase}label.svelte-lifdi8{color:#666}input[type='checkbox'].svelte-lifdi8{vertical-align:middle}");
}
function get_each_context$a(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
return child_ctx;
}
// (202:4) {:else}
function create_else_block$3(ctx) {
let p0;
let t1;
let p1;
return {
c() {
p0 = element("p");
p0.textContent = "No bots available.";
t1 = space();
p1 = element("p");
p1.innerHTML = `Follow the instructions
<a href="https://boardgame.io/documentation/#/tutorial?id=bots" target="_blank">here</a>
to set up bots.`;
},
m(target, anchor) {
insert(target, p0, anchor);
insert(target, t1, anchor);
insert(target, p1, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(p0);
if (detaching) detach(t1);
if (detaching) detach(p1);
}
};
}
// (200:4) {#if client.multiplayer}
function create_if_block_5(ctx) {
let p;
return {
c() {
p = element("p");
p.textContent = "The bot debugger is only available in singleplayer mode.";
},
m(target, anchor) {
insert(target, p, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(p);
}
};
}
// (150:2) {#if client.game.ai && !client.multiplayer}
function create_if_block$d(ctx) {
let section0;
let h30;
let t1;
let ul;
let li0;
let hotkey0;
let t2;
let li1;
let hotkey1;
let t3;
let li2;
let hotkey2;
let t4;
let section1;
let h31;
let t6;
let select;
let t7;
let show_if = Object.keys(/*bot*/ ctx[7].opts()).length;
let t8;
let if_block1_anchor;
let current;
let mounted;
let dispose;
hotkey0 = new Hotkey({
props: {
value: "1",
onPress: /*Reset*/ ctx[13],
label: "reset"
}
});
hotkey1 = new Hotkey({
props: {
value: "2",
onPress: /*Step*/ ctx[11],
label: "play"
}
});
hotkey2 = new Hotkey({
props: {
value: "3",
onPress: /*Simulate*/ ctx[12],
label: "simulate"
}
});
let each_value = Object.keys(/*bots*/ ctx[8]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$a(get_each_context$a(ctx, each_value, i));
}
let if_block0 = show_if && create_if_block_4(ctx);
let if_block1 = (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) && create_if_block_1$6(ctx);
return {
c() {
section0 = element("section");
h30 = element("h3");
h30.textContent = "Controls";
t1 = space();
ul = element("ul");
li0 = element("li");
create_component(hotkey0.$$.fragment);
t2 = space();
li1 = element("li");
create_component(hotkey1.$$.fragment);
t3 = space();
li2 = element("li");
create_component(hotkey2.$$.fragment);
t4 = space();
section1 = element("section");
h31 = element("h3");
h31.textContent = "Bot";
t6 = space();
select = element("select");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t7 = space();
if (if_block0) if_block0.c();
t8 = space();
if (if_block1) if_block1.c();
if_block1_anchor = empty();
attr(h30, "class", "svelte-lifdi8");
attr(li0, "class", "svelte-lifdi8");
attr(li1, "class", "svelte-lifdi8");
attr(li2, "class", "svelte-lifdi8");
attr(ul, "class", "svelte-lifdi8");
attr(h31, "class", "svelte-lifdi8");
if (/*selectedBot*/ ctx[4] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[17].call(select));
},
m(target, anchor) {
insert(target, section0, anchor);
append(section0, h30);
append(section0, t1);
append(section0, ul);
append(ul, li0);
mount_component(hotkey0, li0, null);
append(ul, t2);
append(ul, li1);
mount_component(hotkey1, li1, null);
append(ul, t3);
append(ul, li2);
mount_component(hotkey2, li2, null);
insert(target, t4, anchor);
insert(target, section1, anchor);
append(section1, h31);
append(section1, t6);
append(section1, select);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(select, null);
}
select_option(select, /*selectedBot*/ ctx[4]);
insert(target, t7, anchor);
if (if_block0) if_block0.m(target, anchor);
insert(target, t8, anchor);
if (if_block1) if_block1.m(target, anchor);
insert(target, if_block1_anchor, anchor);
current = true;
if (!mounted) {
dispose = [
listen(select, "change", /*select_change_handler*/ ctx[17]),
listen(select, "change", /*ChangeBot*/ ctx[10])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*Object, bots*/ 256) {
each_value = Object.keys(/*bots*/ ctx[8]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$a(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$a(child_ctx);
each_blocks[i].c();
each_blocks[i].m(select, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (dirty & /*selectedBot, Object, bots*/ 272) {
select_option(select, /*selectedBot*/ ctx[4]);
}
if (dirty & /*bot*/ 128) show_if = Object.keys(/*bot*/ ctx[7].opts()).length;
if (show_if) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*bot*/ 128) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_4(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(t8.parentNode, t8);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
if (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_1$6(ctx);
if_block1.c();
if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
i(local) {
if (current) return;
transition_in(hotkey0.$$.fragment, local);
transition_in(hotkey1.$$.fragment, local);
transition_in(hotkey2.$$.fragment, local);
transition_in(if_block0);
current = true;
},
o(local) {
transition_out(hotkey0.$$.fragment, local);
transition_out(hotkey1.$$.fragment, local);
transition_out(hotkey2.$$.fragment, local);
transition_out(if_block0);
current = false;
},
d(detaching) {
if (detaching) detach(section0);
destroy_component(hotkey0);
destroy_component(hotkey1);
destroy_component(hotkey2);
if (detaching) detach(t4);
if (detaching) detach(section1);
destroy_each(each_blocks, detaching);
if (detaching) detach(t7);
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t8);
if (if_block1) if_block1.d(detaching);
if (detaching) detach(if_block1_anchor);
mounted = false;
run_all(dispose);
}
};
}
// (169:8) {#each Object.keys(bots) as bot}
function create_each_block$a(ctx) {
let option;
let t_value = /*bot*/ ctx[7] + "";
let t;
let option_value_value;
return {
c() {
option = element("option");
t = text(t_value);
option.__value = option_value_value = /*bot*/ ctx[7];
option.value = option.__value;
},
m(target, anchor) {
insert(target, option, anchor);
append(option, t);
},
p: noop,
d(detaching) {
if (detaching) detach(option);
}
};
}
// (175:4) {#if Object.keys(bot.opts()).length}
function create_if_block_4(ctx) {
let section;
let h3;
let t1;
let label;
let t3;
let input;
let t4;
let options;
let current;
let mounted;
let dispose;
options = new Options({ props: { bot: /*bot*/ ctx[7] } });
return {
c() {
section = element("section");
h3 = element("h3");
h3.textContent = "Options";
t1 = space();
label = element("label");
label.textContent = "debug";
t3 = space();
input = element("input");
t4 = space();
create_component(options.$$.fragment);
attr(h3, "class", "svelte-lifdi8");
attr(label, "for", "ai-option-debug");
attr(label, "class", "svelte-lifdi8");
attr(input, "id", "ai-option-debug");
attr(input, "type", "checkbox");
attr(input, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, h3);
append(section, t1);
append(section, label);
append(section, t3);
append(section, input);
input.checked = /*debug*/ ctx[1];
append(section, t4);
mount_component(options, section, null);
current = true;
if (!mounted) {
dispose = [
listen(input, "change", /*input_change_handler*/ ctx[18]),
listen(input, "change", /*OnDebug*/ ctx[9])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*debug*/ 2) {
input.checked = /*debug*/ ctx[1];
}
const options_changes = {};
if (dirty & /*bot*/ 128) options_changes.bot = /*bot*/ ctx[7];
options.$set(options_changes);
},
i(local) {
if (current) return;
transition_in(options.$$.fragment, local);
current = true;
},
o(local) {
transition_out(options.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(options);
mounted = false;
run_all(dispose);
}
};
}
// (184:4) {#if botAction || iterationCounter}
function create_if_block_1$6(ctx) {
let section;
let h3;
let t1;
let t2;
let if_block0 = /*progress*/ ctx[2] && /*progress*/ ctx[2] < 1.0 && create_if_block_3$1(ctx);
let if_block1 = /*botAction*/ ctx[5] && create_if_block_2$4(ctx);
return {
c() {
section = element("section");
h3 = element("h3");
h3.textContent = "Result";
t1 = space();
if (if_block0) if_block0.c();
t2 = space();
if (if_block1) if_block1.c();
attr(h3, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, h3);
append(section, t1);
if (if_block0) if_block0.m(section, null);
append(section, t2);
if (if_block1) if_block1.m(section, null);
},
p(ctx, dirty) {
if (/*progress*/ ctx[2] && /*progress*/ ctx[2] < 1.0) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_3$1(ctx);
if_block0.c();
if_block0.m(section, t2);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (/*botAction*/ ctx[5]) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_2$4(ctx);
if_block1.c();
if_block1.m(section, null);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
d(detaching) {
if (detaching) detach(section);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
}
};
}
// (187:6) {#if progress && progress < 1.0}
function create_if_block_3$1(ctx) {
let progress_1;
return {
c() {
progress_1 = element("progress");
progress_1.value = /*progress*/ ctx[2];
},
m(target, anchor) {
insert(target, progress_1, anchor);
},
p(ctx, dirty) {
if (dirty & /*progress*/ 4) {
progress_1.value = /*progress*/ ctx[2];
}
},
d(detaching) {
if (detaching) detach(progress_1);
}
};
}
// (191:6) {#if botAction}
function create_if_block_2$4(ctx) {
let ul;
let li0;
let t0;
let t1;
let t2;
let li1;
let t3;
let t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + "";
let t4;
return {
c() {
ul = element("ul");
li0 = element("li");
t0 = text("Action: ");
t1 = text(/*botAction*/ ctx[5]);
t2 = space();
li1 = element("li");
t3 = text("Args: ");
t4 = text(t4_value);
attr(li0, "class", "svelte-lifdi8");
attr(li1, "class", "svelte-lifdi8");
attr(ul, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, ul, anchor);
append(ul, li0);
append(li0, t0);
append(li0, t1);
append(ul, t2);
append(ul, li1);
append(li1, t3);
append(li1, t4);
},
p(ctx, dirty) {
if (dirty & /*botAction*/ 32) set_data(t1, /*botAction*/ ctx[5]);
if (dirty & /*botActionArgs*/ 64 && t4_value !== (t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + "")) set_data(t4, t4_value);
},
d(detaching) {
if (detaching) detach(ul);
}
};
}
function create_fragment$y(ctx) {
let section;
let current_block_type_index;
let if_block;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$d, create_if_block_5, create_else_block$3];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*client*/ ctx[0].game.ai && !/*client*/ ctx[0].multiplayer) return 0;
if (/*client*/ ctx[0].multiplayer) return 1;
return 2;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
section = element("section");
if_block.c();
},
m(target, anchor) {
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
if (!mounted) {
dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[14]);
mounted = true;
}
},
p(ctx, [dirty]) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
} else {
if_block.p(ctx, dirty);
}
transition_in(if_block, 1);
if_block.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$y($$self, $$props, $$invalidate) {
let { client } = $$props;
let { clientManager } = $$props;
let { ToggleVisibility } = $$props;
const { secondaryPane } = getContext('secondaryPane');
const bots = { 'MCTS': MCTSBot, 'Random': RandomBot };
let debug = false;
let progress = null;
let iterationCounter = 0;
let metadata = null;
const iterationCallback = ({ iterationCounter: c, numIterations, metadata: m }) => {
$$invalidate(3, iterationCounter = c);
$$invalidate(2, progress = c / numIterations);
metadata = m;
if (debug && metadata) {
secondaryPane.set({ component: MCTS, metadata });
}
};
function OnDebug() {
if (debug && metadata) {
secondaryPane.set({ component: MCTS, metadata });
} else {
secondaryPane.set(null);
}
}
let bot;
if (client.game.ai) {
bot = new MCTSBot({
game: client.game,
enumerate: client.game.ai.enumerate,
iterationCallback
});
bot.setOpt('async', true);
}
let selectedBot;
let botAction;
let botActionArgs;
function ChangeBot() {
const botConstructor = bots[selectedBot];
$$invalidate(7, bot = new botConstructor({
game: client.game,
enumerate: client.game.ai.enumerate,
iterationCallback
}));
bot.setOpt('async', true);
$$invalidate(5, botAction = null);
metadata = null;
secondaryPane.set(null);
$$invalidate(3, iterationCounter = 0);
}
async function Step$1() {
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
const t = await Step(client, bot);
if (t) {
$$invalidate(5, botAction = t.payload.type);
$$invalidate(6, botActionArgs = t.payload.args);
}
}
function Simulate(iterations = 10000, sleepTimeout = 100) {
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
const step = async () => {
for (let i = 0; i < iterations; i++) {
const action = await Step(client, bot);
if (!action) break;
await new Promise(resolve => setTimeout(resolve, sleepTimeout));
}
};
return step();
}
function Exit() {
client.overrideGameState(null);
secondaryPane.set(null);
$$invalidate(1, debug = false);
}
function Reset() {
client.reset();
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
Exit();
}
function OnKeyDown(e) {
// ESC.
if (e.keyCode == 27) {
Exit();
}
}
onDestroy(Exit);
function select_change_handler() {
selectedBot = select_value(this);
$$invalidate(4, selectedBot);
$$invalidate(8, bots);
}
function input_change_handler() {
debug = this.checked;
$$invalidate(1, debug);
}
$$self.$$set = $$props => {
if ('client' in $$props) $$invalidate(0, client = $$props.client);
if ('clientManager' in $$props) $$invalidate(15, clientManager = $$props.clientManager);
if ('ToggleVisibility' in $$props) $$invalidate(16, ToggleVisibility = $$props.ToggleVisibility);
};
return [
client,
debug,
progress,
iterationCounter,
selectedBot,
botAction,
botActionArgs,
bot,
bots,
OnDebug,
ChangeBot,
Step$1,
Simulate,
Reset,
OnKeyDown,
clientManager,
ToggleVisibility,
select_change_handler,
input_change_handler
];
}
class AI extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$y,
create_fragment$y,
safe_not_equal,
{
client: 0,
clientManager: 15,
ToggleVisibility: 16
},
add_css$p
);
}
}
/* src/client/debug/Debug.svelte generated by Svelte v3.41.0 */
function add_css$q(target) {
append_styles(target, "svelte-8ymctk", ".debug-panel.svelte-8ymctk.svelte-8ymctk{position:fixed;color:#555;font-family:monospace;right:0;top:0;height:100%;font-size:14px;opacity:0.9;z-index:99999}.panel.svelte-8ymctk.svelte-8ymctk{display:flex;position:relative;flex-direction:row;height:100%}.visibility-toggle.svelte-8ymctk.svelte-8ymctk{position:absolute;box-sizing:border-box;top:7px;border:1px solid #ccc;border-radius:5px;width:48px;height:48px;padding:8px;background:white;color:#555;box-shadow:0 0 5px rgba(0, 0, 0, 0.2)}.visibility-toggle.svelte-8ymctk.svelte-8ymctk:hover,.visibility-toggle.svelte-8ymctk.svelte-8ymctk:focus{background:#eee}.opener.svelte-8ymctk.svelte-8ymctk{right:10px}.closer.svelte-8ymctk.svelte-8ymctk{left:-326px}@keyframes svelte-8ymctk-rotateFromZero{from{transform:rotateZ(0deg)}to{transform:rotateZ(180deg)}}.icon.svelte-8ymctk.svelte-8ymctk{display:flex;height:100%;animation:svelte-8ymctk-rotateFromZero 0.4s cubic-bezier(0.68, -0.55, 0.27, 1.55) 0s 1\n normal forwards}.closer.svelte-8ymctk .icon.svelte-8ymctk{animation-direction:reverse}.pane.svelte-8ymctk.svelte-8ymctk{flex-grow:2;overflow-x:hidden;overflow-y:scroll;background:#fefefe;padding:20px;border-left:1px solid #ccc;box-shadow:-1px 0 5px rgba(0, 0, 0, 0.2);box-sizing:border-box;width:280px}.secondary-pane.svelte-8ymctk.svelte-8ymctk{background:#fefefe;overflow-y:scroll}.debug-panel.svelte-8ymctk button,.debug-panel.svelte-8ymctk select{cursor:pointer;font-size:14px;font-family:monospace}.debug-panel.svelte-8ymctk select{background:#eee;border:1px solid #bbb;color:#555;padding:3px;border-radius:3px}.debug-panel.svelte-8ymctk section{margin-bottom:20px}.debug-panel.svelte-8ymctk .screen-reader-only{clip:rect(0 0 0 0);clip-path:inset(50%);height:1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px}");
}
// (194:2) {:else}
function create_else_block$4(ctx) {
let div1;
let button;
let span;
let chevron;
let button_intro;
let button_outro;
let t0;
let menu;
let t1;
let div0;
let switch_instance;
let t2;
let div1_transition;
let current;
let mounted;
let dispose;
chevron = new FaChevronRight({});
menu = new Menu({
props: {
panes: /*panes*/ ctx[6],
pane: /*pane*/ ctx[2]
}
});
menu.$on("change", /*MenuChange*/ ctx[8]);
var switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component;
function switch_props(ctx) {
return {
props: {
client: /*client*/ ctx[4],
clientManager: /*clientManager*/ ctx[0],
ToggleVisibility: /*ToggleVisibility*/ ctx[9]
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
let if_block = /*$secondaryPane*/ ctx[5] && create_if_block_1$7(ctx);
return {
c() {
div1 = element("div");
button = element("button");
span = element("span");
create_component(chevron.$$.fragment);
t0 = space();
create_component(menu.$$.fragment);
t1 = space();
div0 = element("div");
if (switch_instance) create_component(switch_instance.$$.fragment);
t2 = space();
if (if_block) if_block.c();
attr(span, "class", "icon svelte-8ymctk");
attr(span, "aria-hidden", "true");
attr(button, "class", "visibility-toggle closer svelte-8ymctk");
attr(button, "title", "Hide Debug Panel");
attr(div0, "class", "pane svelte-8ymctk");
attr(div0, "role", "region");
attr(div0, "aria-label", /*pane*/ ctx[2]);
attr(div0, "tabindex", "-1");
attr(div1, "class", "panel svelte-8ymctk");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, button);
append(button, span);
mount_component(chevron, span, null);
append(div1, t0);
mount_component(menu, div1, null);
append(div1, t1);
append(div1, div0);
if (switch_instance) {
mount_component(switch_instance, div0, null);
}
/*div0_binding*/ ctx[15](div0);
append(div1, t2);
if (if_block) if_block.m(div1, null);
current = true;
if (!mounted) {
dispose = listen(button, "click", /*ToggleVisibility*/ ctx[9]);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
const menu_changes = {};
if (dirty & /*pane*/ 4) menu_changes.pane = /*pane*/ ctx[2];
menu.$set(menu_changes);
const switch_instance_changes = {};
if (dirty & /*client*/ 16) switch_instance_changes.client = /*client*/ ctx[4];
if (dirty & /*clientManager*/ 1) switch_instance_changes.clientManager = /*clientManager*/ ctx[0];
if (switch_value !== (switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component)) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, div0, null);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
if (!current || dirty & /*pane*/ 4) {
attr(div0, "aria-label", /*pane*/ ctx[2]);
}
if (/*$secondaryPane*/ ctx[5]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*$secondaryPane*/ 32) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$7(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(div1, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(chevron.$$.fragment, local);
add_render_callback(() => {
if (button_outro) button_outro.end(1);
button_intro = create_in_transition(button, /*receive*/ ctx[13], { key: 'toggle' });
button_intro.start();
});
transition_in(menu.$$.fragment, local);
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
transition_in(if_block);
add_render_callback(() => {
if (!div1_transition) div1_transition = create_bidirectional_transition(div1, fly, { x: 400, .../*transitionOpts*/ ctx[11] }, true);
div1_transition.run(1);
});
current = true;
},
o(local) {
transition_out(chevron.$$.fragment, local);
if (button_intro) button_intro.invalidate();
button_outro = create_out_transition(button, /*send*/ ctx[12], { key: 'toggle' });
transition_out(menu.$$.fragment, local);
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
transition_out(if_block);
if (!div1_transition) div1_transition = create_bidirectional_transition(div1, fly, { x: 400, .../*transitionOpts*/ ctx[11] }, false);
div1_transition.run(0);
current = false;
},
d(detaching) {
if (detaching) detach(div1);
destroy_component(chevron);
if (detaching && button_outro) button_outro.end();
destroy_component(menu);
if (switch_instance) destroy_component(switch_instance);
/*div0_binding*/ ctx[15](null);
if (if_block) if_block.d();
if (detaching && div1_transition) div1_transition.end();
mounted = false;
dispose();
}
};
}
// (182:2) {#if !visible}
function create_if_block$e(ctx) {
let button;
let span;
let chevron;
let button_intro;
let button_outro;
let current;
let mounted;
let dispose;
chevron = new FaChevronRight({});
return {
c() {
button = element("button");
span = element("span");
create_component(chevron.$$.fragment);
attr(span, "class", "icon svelte-8ymctk");
attr(span, "aria-hidden", "true");
attr(button, "class", "visibility-toggle opener svelte-8ymctk");
attr(button, "title", "Show Debug Panel");
},
m(target, anchor) {
insert(target, button, anchor);
append(button, span);
mount_component(chevron, span, null);
current = true;
if (!mounted) {
dispose = listen(button, "click", /*ToggleVisibility*/ ctx[9]);
mounted = true;
}
},
p: noop,
i(local) {
if (current) return;
transition_in(chevron.$$.fragment, local);
add_render_callback(() => {
if (button_outro) button_outro.end(1);
button_intro = create_in_transition(button, /*receive*/ ctx[13], { key: 'toggle' });
button_intro.start();
});
current = true;
},
o(local) {
transition_out(chevron.$$.fragment, local);
if (button_intro) button_intro.invalidate();
button_outro = create_out_transition(button, /*send*/ ctx[12], { key: 'toggle' });
current = false;
},
d(detaching) {
if (detaching) detach(button);
destroy_component(chevron);
if (detaching && button_outro) button_outro.end();
mounted = false;
dispose();
}
};
}
// (222:6) {#if $secondaryPane}
function create_if_block_1$7(ctx) {
let div;
let switch_instance;
let current;
var switch_value = /*$secondaryPane*/ ctx[5].component;
function switch_props(ctx) {
return {
props: {
metadata: /*$secondaryPane*/ ctx[5].metadata
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
div = element("div");
if (switch_instance) create_component(switch_instance.$$.fragment);
attr(div, "class", "secondary-pane svelte-8ymctk");
},
m(target, anchor) {
insert(target, div, anchor);
if (switch_instance) {
mount_component(switch_instance, div, null);
}
current = true;
},
p(ctx, dirty) {
const switch_instance_changes = {};
if (dirty & /*$secondaryPane*/ 32) switch_instance_changes.metadata = /*$secondaryPane*/ ctx[5].metadata;
if (switch_value !== (switch_value = /*$secondaryPane*/ ctx[5].component)) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, div, null);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
if (switch_instance) destroy_component(switch_instance);
}
};
}
function create_fragment$z(ctx) {
let section;
let current_block_type_index;
let if_block;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$e, create_else_block$4];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (!/*visible*/ ctx[3]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
section = element("section");
if_block.c();
attr(section, "aria-label", "boardgame.io Debug Panel");
attr(section, "class", "debug-panel svelte-8ymctk");
},
m(target, anchor) {
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
if (!mounted) {
dispose = listen(window, "keypress", /*Keypress*/ ctx[10]);
mounted = true;
}
},
p(ctx, [dirty]) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
} else {
if_block.p(ctx, dirty);
}
transition_in(if_block, 1);
if_block.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$z($$self, $$props, $$invalidate) {
let client;
let $clientManager,
$$unsubscribe_clientManager = noop,
$$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(14, $clientManager = $$value)), clientManager);
let $secondaryPane;
$$self.$$.on_destroy.push(() => $$unsubscribe_clientManager());
let { clientManager } = $$props;
$$subscribe_clientManager();
const panes = {
main: {
label: 'Main',
shortcut: 'm',
component: Main
},
log: {
label: 'Log',
shortcut: 'l',
component: Log
},
info: {
label: 'Info',
shortcut: 'i',
component: Info
},
ai: {
label: 'AI',
shortcut: 'a',
component: AI
}
};
const disableHotkeys = writable(false);
const secondaryPane = writable(null);
component_subscribe($$self, secondaryPane, value => $$invalidate(5, $secondaryPane = value));
setContext('hotkeys', { disableHotkeys });
setContext('secondaryPane', { secondaryPane });
let paneDiv;
let pane = 'main';
function MenuChange(e) {
$$invalidate(2, pane = e.detail);
paneDiv.focus();
}
// Toggle debugger visibilty
function ToggleVisibility() {
$$invalidate(3, visible = !visible);
}
let visible = true;
function Keypress(e) {
if (e.key == '.') {
ToggleVisibility();
return;
}
// Set displayed pane
if (!visible) return;
Object.entries(panes).forEach(([key, { shortcut }]) => {
if (e.key == shortcut) {
$$invalidate(2, pane = key);
}
});
}
const transitionOpts = { duration: 150, easing: cubicOut };
const [send, receive] = crossfade(transitionOpts);
function div0_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
paneDiv = $$value;
$$invalidate(1, paneDiv);
});
}
$$self.$$set = $$props => {
if ('clientManager' in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager));
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$clientManager*/ 16384) {
$$invalidate(4, client = $clientManager.client);
}
};
return [
clientManager,
paneDiv,
pane,
visible,
client,
$secondaryPane,
panes,
secondaryPane,
MenuChange,
ToggleVisibility,
Keypress,
transitionOpts,
send,
receive,
$clientManager,
div0_binding
];
}
class Debug extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$z, create_fragment$z, safe_not_equal, { clientManager: 0 }, add_css$q);
}
}
/**
* Class to manage boardgame.io clients and limit debug panel rendering.
*/
class ClientManager {
constructor() {
this.debugPanel = null;
this.currentClient = null;
this.clients = new Map();
this.subscribers = new Map();
}
/**
* Register a client with the client manager.
*/
register(client) {
// Add client to clients map.
this.clients.set(client, client);
// Mount debug for this client (no-op if another debug is already mounted).
this.mountDebug(client);
this.notifySubscribers();
}
/**
* Unregister a client from the client manager.
*/
unregister(client) {
// Remove client from clients map.
this.clients.delete(client);
if (this.currentClient === client) {
// If the removed client owned the debug panel, unmount it.
this.unmountDebug();
// Mount debug panel for next available client.
for (const [client] of this.clients) {
if (this.debugPanel)
break;
this.mountDebug(client);
}
}
this.notifySubscribers();
}
/**
* Subscribe to the client manager state.
* Calls the passed callback each time the current client changes or a client
* registers/unregisters.
* Returns a function to unsubscribe from the state updates.
*/
subscribe(callback) {
const id = Symbol();
this.subscribers.set(id, callback);
callback(this.getState());
return () => {
this.subscribers.delete(id);
};
}
/**
* Switch to a client with a matching playerID.
*/
switchPlayerID(playerID) {
// For multiplayer clients, try switching control to a different client
// that is using the same transport layer.
if (this.currentClient.multiplayer) {
for (const [client] of this.clients) {
if (client.playerID === playerID &&
client.debugOpt !== false &&
client.multiplayer === this.currentClient.multiplayer) {
this.switchToClient(client);
return;
}
}
}
// If no client matches, update the playerID for the current client.
this.currentClient.updatePlayerID(playerID);
this.notifySubscribers();
}
/**
* Set the passed client as the active client for debugging.
*/
switchToClient(client) {
if (client === this.currentClient)
return;
this.unmountDebug();
this.mountDebug(client);
this.notifySubscribers();
}
/**
* Notify all subscribers of changes to the client manager state.
*/
notifySubscribers() {
const arg = this.getState();
this.subscribers.forEach((cb) => {
cb(arg);
});
}
/**
* Get the client manager state.
*/
getState() {
return {
client: this.currentClient,
debuggableClients: this.getDebuggableClients(),
};
}
/**
* Get an array of the registered clients that haven’t disabled the debug panel.
*/
getDebuggableClients() {
return [...this.clients.values()].filter((client) => client.debugOpt !== false);
}
/**
* Mount the debug panel using the passed client.
*/
mountDebug(client) {
if (client.debugOpt === false ||
this.debugPanel !== null ||
typeof document === 'undefined') {
return;
}
let DebugImpl;
let target = document.body;
if (process.env.NODE_ENV !== 'production') {
DebugImpl = Debug;
}
if (client.debugOpt && client.debugOpt !== true) {
DebugImpl = client.debugOpt.impl || DebugImpl;
target = client.debugOpt.target || target;
}
if (DebugImpl) {
this.currentClient = client;
this.debugPanel = new DebugImpl({
target,
props: { clientManager: this },
});
}
}
/**
* Unmount the debug panel.
*/
unmountDebug() {
this.debugPanel.$destroy();
this.debugPanel = null;
this.currentClient = null;
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Global client manager instance that all clients register with.
*/
const GlobalClientManager = new ClientManager();
/**
* Standardise the passed playerID, using currentPlayer if appropriate.
*/
function assumedPlayerID(playerID, store, multiplayer) {
// In singleplayer mode, if the client does not have a playerID
// associated with it, we attach the currentPlayer as playerID.
if (!multiplayer && (playerID === null || playerID === undefined)) {
const state = store.getState();
playerID = state.ctx.currentPlayer;
}
return playerID;
}
/**
* createDispatchers
*
* Create action dispatcher wrappers with bound playerID and credentials
*/
function createDispatchers(storeActionType, innerActionNames, store, playerID, credentials, multiplayer) {
const dispatchers = {};
for (const name of innerActionNames) {
dispatchers[name] = (...args) => {
const action = ActionCreators[storeActionType](name, args, assumedPlayerID(playerID, store, multiplayer), credentials);
store.dispatch(action);
};
}
return dispatchers;
}
// Creates a set of dispatchers to make moves.
const createMoveDispatchers = createDispatchers.bind(null, 'makeMove');
// Creates a set of dispatchers to dispatch game flow events.
const createEventDispatchers = createDispatchers.bind(null, 'gameEvent');
// Creates a set of dispatchers to dispatch actions to plugins.
const createPluginDispatchers = createDispatchers.bind(null, 'plugin');
/**
* Implementation of Client (see below).
*/
class _ClientImpl {
constructor({ game, debug, numPlayers, multiplayer, matchID: matchID, playerID, credentials, enhancer, }) {
this.game = ProcessGameConfig(game);
this.playerID = playerID;
this.matchID = matchID || 'default';
this.credentials = credentials;
this.multiplayer = multiplayer;
this.debugOpt = debug;
this.manager = GlobalClientManager;
this.gameStateOverride = null;
this.subscribers = {};
this._running = false;
this.reducer = CreateGameReducer({
game: this.game,
isClient: multiplayer !== undefined,
});
this.initialState = null;
if (!multiplayer) {
this.initialState = InitializeGame({ game: this.game, numPlayers });
}
this.reset = () => {
this.store.dispatch(reset(this.initialState));
};
this.undo = () => {
const undo$1 = undo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials);
this.store.dispatch(undo$1);
};
this.redo = () => {
const redo$1 = redo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials);
this.store.dispatch(redo$1);
};
this.log = [];
/**
* Middleware that manages the log object.
* Reducers generate deltalogs, which are log events
* that are the result of application of a single action.
* The master may also send back a deltalog or the entire
* log depending on the type of request.
* The middleware below takes care of all these cases while
* managing the log object.
*/
const LogMiddleware = (store) => (next) => (action) => {
const result = next(action);
const state = store.getState();
switch (action.type) {
case MAKE_MOVE:
case GAME_EVENT:
case UNDO:
case REDO: {
const deltalog = state.deltalog;
this.log = [...this.log, ...deltalog];
break;
}
case RESET: {
this.log = [];
break;
}
case PATCH:
case UPDATE: {
let id = -1;
if (this.log.length > 0) {
id = this.log[this.log.length - 1]._stateID;
}
let deltalog = action.deltalog || [];
// Filter out actions that are already present
// in the current log. This may occur when the
// client adds an entry to the log followed by
// the update from the master here.
deltalog = deltalog.filter((l) => l._stateID > id);
this.log = [...this.log, ...deltalog];
break;
}
case SYNC: {
this.initialState = action.initialState;
this.log = action.log || [];
break;
}
}
return result;
};
/**
* Middleware that intercepts actions and sends them to the master,
* which keeps the authoritative version of the state.
*/
const TransportMiddleware = (store) => (next) => (action) => {
const baseState = store.getState();
const result = next(action);
if (!('clientOnly' in action) &&
action.type !== STRIP_TRANSIENTS) {
this.transport.sendAction(baseState, action);
}
return result;
};
/**
* Middleware that intercepts actions and invokes the subscription callback.
*/
const SubscriptionMiddleware = () => (next) => (action) => {
const result = next(action);
this.notifySubscribers();
return result;
};
const middleware = applyMiddleware(TransientHandlingMiddleware, SubscriptionMiddleware, TransportMiddleware, LogMiddleware);
enhancer =
enhancer !== undefined ? compose(middleware, enhancer) : middleware;
this.store = createStore(this.reducer, this.initialState, enhancer);
if (!multiplayer)
multiplayer = DummyTransport;
this.transport = multiplayer({
transportDataCallback: (data) => this.receiveTransportData(data),
gameKey: game,
game: this.game,
matchID,
playerID,
credentials,
gameName: this.game.name,
numPlayers,
});
this.createDispatchers();
this.chatMessages = [];
this.sendChatMessage = (payload) => {
this.transport.sendChatMessage(this.matchID, {
id: nanoid(7),
sender: this.playerID,
payload: payload,
});
};
}
/** Handle incoming match data from a multiplayer transport. */
receiveMatchData(matchData) {
this.matchData = matchData;
this.notifySubscribers();
}
/** Handle an incoming chat message from a multiplayer transport. */
receiveChatMessage(message) {
this.chatMessages = [...this.chatMessages, message];
this.notifySubscribers();
}
/** Handle all incoming updates from a multiplayer transport. */
receiveTransportData(data) {
const [matchID] = data.args;
if (matchID !== this.matchID)
return;
switch (data.type) {
case 'sync': {
const [, syncInfo] = data.args;
const action = sync(syncInfo);
this.receiveMatchData(syncInfo.filteredMetadata);
this.store.dispatch(action);
break;
}
case 'update': {
const [, state, deltalog] = data.args;
const currentState = this.store.getState();
if (state._stateID >= currentState._stateID) {
const action = update$1(state, deltalog);
this.store.dispatch(action);
}
break;
}
case 'patch': {
const [, prevStateID, stateID, patch$1, deltalog] = data.args;
const currentStateID = this.store.getState()._stateID;
if (prevStateID !== currentStateID)
break;
const action = patch(prevStateID, stateID, patch$1, deltalog);
this.store.dispatch(action);
// Emit sync if patch apply failed.
if (this.store.getState()._stateID === currentStateID) {
this.transport.requestSync();
}
break;
}
case 'matchData': {
const [, matchData] = data.args;
this.receiveMatchData(matchData);
break;
}
case 'chat': {
const [, chatMessage] = data.args;
this.receiveChatMessage(chatMessage);
break;
}
}
}
notifySubscribers() {
Object.values(this.subscribers).forEach((fn) => fn(this.getState()));
}
overrideGameState(state) {
this.gameStateOverride = state;
this.notifySubscribers();
}
start() {
this.transport.connect();
this._running = true;
this.manager.register(this);
}
stop() {
this.transport.disconnect();
this._running = false;
this.manager.unregister(this);
}
subscribe(fn) {
const id = Object.keys(this.subscribers).length;
this.subscribers[id] = fn;
this.transport.subscribeToConnectionStatus(() => this.notifySubscribers());
if (this._running || !this.multiplayer) {
fn(this.getState());
}
// Return a handle that allows the caller to unsubscribe.
return () => {
delete this.subscribers[id];
};
}
getInitialState() {
return this.initialState;
}
getState() {
let state = this.store.getState();
if (this.gameStateOverride !== null) {
state = this.gameStateOverride;
}
// This is the state before a sync with the game master.
if (state === null) {
return state;
}
// isActive.
let isActive = true;
const isPlayerActive = this.game.flow.isPlayerActive(state.G, state.ctx, this.playerID);
if (this.multiplayer && !isPlayerActive) {
isActive = false;
}
if (!this.multiplayer &&
this.playerID !== null &&
this.playerID !== undefined &&
!isPlayerActive) {
isActive = false;
}
if (state.ctx.gameover !== undefined) {
isActive = false;
}
// Secrets are normally stripped on the server,
// but we also strip them here so that game developers
// can see their effects while prototyping.
// Do not strip again if this is a multiplayer game
// since the server has already stripped secret info. (issue #818)
if (!this.multiplayer) {
state = {
...state,
G: this.game.playerView(state.G, state.ctx, this.playerID),
plugins: PlayerView(state, this),
};
}
// Combine into return value.
return {
...state,
log: this.log,
isActive,
isConnected: this.transport.isConnected,
};
}
createDispatchers() {
this.moves = createMoveDispatchers(this.game.moveNames, this.store, this.playerID, this.credentials, this.multiplayer);
this.events = createEventDispatchers(this.game.flow.enabledEventNames, this.store, this.playerID, this.credentials, this.multiplayer);
this.plugins = createPluginDispatchers(this.game.pluginNames, this.store, this.playerID, this.credentials, this.multiplayer);
}
updatePlayerID(playerID) {
this.playerID = playerID;
this.createDispatchers();
this.transport.updatePlayerID(playerID);
this.notifySubscribers();
}
updateMatchID(matchID) {
this.matchID = matchID;
this.createDispatchers();
this.transport.updateMatchID(matchID);
this.notifySubscribers();
}
updateCredentials(credentials) {
this.credentials = credentials;
this.createDispatchers();
this.transport.updateCredentials(credentials);
this.notifySubscribers();
}
}
/**
* Client
*
* boardgame.io JS client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} matchID - The matchID that you want to connect to.
* @param {...object} playerID - The playerID associated with this client.
* @param {...string} credentials - The authentication credentials associated with this client.
*
* Returns:
* A JS object that provides an API to interact with the
* game by dispatching moves and events.
*/
function Client(opts) {
return new _ClientImpl(opts);
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Client
*
* boardgame.io React client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} debug - Enables the Debug UI.
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET,
* UNDO and REDO.
*/
function Client$1(opts) {
var _a;
const { game, numPlayers, board, multiplayer, enhancer } = opts;
let { loading, debug } = opts;
// Component that is displayed before the client has synced
// with the game master.
if (loading === undefined) {
const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting...");
loading = Loading;
}
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _a = class WrappedBoard extends React.Component {
constructor(props) {
super(props);
if (debug === undefined) {
debug = props.debug;
}
this.client = Client({
game,
debug,
numPlayers,
multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
enhancer,
});
}
componentDidMount() {
this.unsubscribe = this.client.subscribe(() => this.forceUpdate());
this.client.start();
}
componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
componentDidUpdate(prevProps) {
if (this.props.matchID != prevProps.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (this.props.playerID != prevProps.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (this.props.credentials != prevProps.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
render() {
const state = this.client.getState();
if (state === null) {
return React.createElement(loading);
}
let _board = null;
if (board) {
_board = React.createElement(board, {
...state,
...this.props,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
matchID: this.client.matchID,
playerID: this.client.playerID,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
log: this.client.log,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages,
});
}
return React.createElement("div", { className: "bgio-client" }, _board);
}
},
_a.propTypes = {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string,
// Enable / disable the Debug UI.
debug: PropTypes.any,
},
_a.defaultProps = {
matchID: 'default',
playerID: null,
credentials: null,
debug: true,
},
_a;
}
var _excluded = ["matchID", "playerID"];
/**
* Client
*
* boardgame.io React Native client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React Native component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE.
*/
function Client$2(opts) {
var _class, _temp;
var game = opts.game,
numPlayers = opts.numPlayers,
board = opts.board,
multiplayer = opts.multiplayer,
enhancer = opts.enhancer;
var loading = opts.loading; // Component that is displayed before the client has synced
// with the game master.
if (loading === undefined) {
var Loading = function Loading() {
return /*#__PURE__*/React.createElement(React.Fragment, null);
};
loading = Loading;
}
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _temp = _class = /*#__PURE__*/function (_React$Component) {
_inherits(WrappedBoard, _React$Component);
var _super = _createSuper(WrappedBoard);
function WrappedBoard(props) {
var _this;
_classCallCheck(this, WrappedBoard);
_this = _super.call(this, props);
_this.client = Client({
game: game,
numPlayers: numPlayers,
multiplayer: multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
debug: false,
enhancer: enhancer
});
return _this;
}
_createClass(WrappedBoard, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
this.unsubscribe = this.client.subscribe(function () {
return _this2.forceUpdate();
});
this.client.start();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.matchID != this.props.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (prevProps.playerID != this.props.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (prevProps.credentials != this.props.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
}, {
key: "render",
value: function render() {
var _board = null;
var state = this.client.getState();
if (state === null) {
return /*#__PURE__*/React.createElement(loading);
}
var _this$props = this.props,
matchID = _this$props.matchID,
playerID = _this$props.playerID,
rest = _objectWithoutProperties(_this$props, _excluded);
if (board) {
_board = /*#__PURE__*/React.createElement(board, _objectSpread2(_objectSpread2(_objectSpread2({}, state), rest), {}, {
matchID: matchID,
playerID: playerID,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
step: this.client.step,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages
}));
}
return _board;
}
}]);
return WrappedBoard;
}(React.Component), _defineProperty(_class, "propTypes", {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string
}), _defineProperty(_class, "defaultProps", {
matchID: 'default',
playerID: null,
credentials: null
}), _temp;
}
var Type;
(function (Type) {
Type[Type["SYNC"] = 0] = "SYNC";
Type[Type["ASYNC"] = 1] = "ASYNC";
})(Type || (Type = {}));
/**
* Type guard that checks if a storage implementation is synchronous.
*/
function isSynchronous(storageAPI) {
return storageAPI.type() === Type.SYNC;
}
class Sync {
type() {
return Type.SYNC;
}
/**
* Connect.
*/
connect() {
return;
}
/**
* Create a new match.
*
* This might just need to call setState and setMetadata in
* most implementations.
*
* However, it exists as a separate call so that the
* implementation can provision things differently when
* a match is created. For example, it might stow away the
* initial match state in a separate field for easier retrieval.
*/
/* istanbul ignore next */
createMatch(matchID, opts) {
if (this.createGame) {
console.warn('The database connector does not implement a createMatch method.', '\nUsing the deprecated createGame method instead.');
return this.createGame(matchID, opts);
}
else {
console.error('The database connector does not implement a createMatch method.');
}
}
/**
* Return all matches.
*/
/* istanbul ignore next */
listMatches(opts) {
if (this.listGames) {
console.warn('The database connector does not implement a listMatches method.', '\nUsing the deprecated listGames method instead.');
return this.listGames(opts);
}
else {
console.error('The database connector does not implement a listMatches method.');
}
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* InMemory data storage.
*/
class InMemory extends Sync {
/**
* Creates a new InMemory storage.
*/
constructor() {
super();
this.state = new Map();
this.initial = new Map();
this.metadata = new Map();
this.log = new Map();
}
/**
* Create a new match.
*
* @override
*/
createMatch(matchID, opts) {
this.initial.set(matchID, opts.initialState);
this.setState(matchID, opts.initialState);
this.setMetadata(matchID, opts.metadata);
}
/**
* Write the match metadata to the in-memory object.
*/
setMetadata(matchID, metadata) {
this.metadata.set(matchID, metadata);
}
/**
* Write the match state to the in-memory object.
*/
setState(matchID, state, deltalog) {
if (deltalog && deltalog.length > 0) {
const log = this.log.get(matchID) || [];
this.log.set(matchID, [...log, ...deltalog]);
}
this.state.set(matchID, state);
}
/**
* Fetches state for a particular matchID.
*/
fetch(matchID, opts) {
const result = {};
if (opts.state) {
result.state = this.state.get(matchID);
}
if (opts.metadata) {
result.metadata = this.metadata.get(matchID);
}
if (opts.log) {
result.log = this.log.get(matchID) || [];
}
if (opts.initialState) {
result.initialState = this.initial.get(matchID);
}
return result;
}
/**
* Remove the match state from the in-memory object.
*/
wipe(matchID) {
this.state.delete(matchID);
this.metadata.delete(matchID);
}
/**
* Return all keys.
*
* @override
*/
listMatches(opts) {
return [...this.metadata.entries()]
.filter(([, metadata]) => {
if (!opts) {
return true;
}
if (opts.gameName !== undefined &&
metadata.gameName !== opts.gameName) {
return false;
}
if (opts.where !== undefined) {
if (opts.where.isGameover !== undefined) {
const isGameover = metadata.gameover !== undefined;
if (isGameover !== opts.where.isGameover) {
return false;
}
}
if (opts.where.updatedBefore !== undefined &&
metadata.updatedAt >= opts.where.updatedBefore) {
return false;
}
if (opts.where.updatedAfter !== undefined &&
metadata.updatedAt <= opts.where.updatedAfter) {
return false;
}
}
return true;
})
.map(([key]) => key);
}
}
class WithLocalStorageMap extends Map {
constructor(key) {
super();
this.key = key;
const cache = JSON.parse(localStorage.getItem(this.key)) || [];
cache.forEach((entry) => this.set(...entry));
}
sync() {
const entries = [...this.entries()];
localStorage.setItem(this.key, JSON.stringify(entries));
}
set(key, value) {
super.set(key, value);
this.sync();
return this;
}
delete(key) {
const result = super.delete(key);
this.sync();
return result;
}
}
/**
* locaStorage data storage.
*/
class LocalStorage extends InMemory {
constructor(storagePrefix = 'bgio') {
super();
const StorageMap = (stateKey) => new WithLocalStorageMap(`${storagePrefix}_${stateKey}`);
this.state = StorageMap('state');
this.initial = StorageMap('initial');
this.metadata = StorageMap('metadata');
this.log = StorageMap('log');
}
}
/**
* Creates a new match metadata object.
*/
const createMetadata = ({ game, unlisted, setupData, numPlayers, }) => {
const metadata = {
gameName: game.name,
unlisted: !!unlisted,
players: {},
createdAt: Date.now(),
updatedAt: Date.now(),
};
if (setupData !== undefined)
metadata.setupData = setupData;
for (let playerIndex = 0; playerIndex < numPlayers; playerIndex++) {
metadata.players[playerIndex] = { id: playerIndex };
}
return metadata;
};
/**
* Creates initial state and metadata for a new match.
* If the provided `setupData` doesn’t pass the game’s validation,
* an error object is returned instead.
*/
const createMatch = ({ game, numPlayers, setupData, unlisted, }) => {
if (!numPlayers || typeof numPlayers !== 'number')
numPlayers = 2;
const setupDataError = game.validateSetupData && game.validateSetupData(setupData, numPlayers);
if (setupDataError !== undefined)
return { setupDataError };
const metadata = createMetadata({ game, numPlayers, setupData, unlisted });
const initialState = InitializeGame({ game, numPlayers, setupData });
return { metadata, initialState };
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Filter match data to get a player metadata object with credentials stripped.
*/
const filterMatchData = (matchData) => Object.values(matchData.players).map((player) => {
const { credentials, ...filteredData } = player;
return filteredData;
});
/**
* Remove player credentials from action payload
*/
const stripCredentialsFromAction = (action) => {
const { credentials, ...payload } = action.payload;
return { ...action, payload };
};
/**
* Master
*
* Class that runs the game and maintains the authoritative state.
* It uses the transportAPI to communicate with clients and the
* storageAPI to communicate with the database.
*/
class Master {
constructor(game, storageAPI, transportAPI, auth) {
this.game = ProcessGameConfig(game);
this.storageAPI = storageAPI;
this.transportAPI = transportAPI;
this.subscribeCallback = () => { };
this.auth = auth;
}
subscribe(fn) {
this.subscribeCallback = fn;
}
/**
* Called on each move / event made by the client.
* Computes the new value of the game state and returns it
* along with a deltalog.
*/
async onUpdate(credAction, stateID, matchID, playerID) {
if (!credAction || !credAction.payload) {
return { error: 'missing action or action payload' };
}
let metadata;
if (isSynchronous(this.storageAPI)) {
({ metadata } = this.storageAPI.fetch(matchID, { metadata: true }));
}
else {
({ metadata } = await this.storageAPI.fetch(matchID, { metadata: true }));
}
if (this.auth) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials: credAction.payload.credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized action' };
}
}
const action = stripCredentialsFromAction(credAction);
const key = matchID;
let state;
if (isSynchronous(this.storageAPI)) {
({ state } = this.storageAPI.fetch(key, { state: true }));
}
else {
({ state } = await this.storageAPI.fetch(key, { state: true }));
}
if (state === undefined) {
error(`game not found, matchID=[${key}]`);
return { error: 'game not found' };
}
if (state.ctx.gameover !== undefined) {
error(`game over - matchID=[${key}] - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
const reducer = CreateGameReducer({
game: this.game,
});
const middleware = applyMiddleware(TransientHandlingMiddleware);
const store = createStore(reducer, state, middleware);
// Only allow UNDO / REDO if there is exactly one player
// that can make moves right now and the person doing the
// action is that player.
if (action.type == UNDO || action.type == REDO) {
const hasActivePlayers = state.ctx.activePlayers !== null;
const isCurrentPlayer = state.ctx.currentPlayer === playerID;
if (
// If activePlayers is empty, non-current players can’t undo.
(!hasActivePlayers && !isCurrentPlayer) ||
// If player is not active or multiple players are active, can’t undo.
(hasActivePlayers &&
(state.ctx.activePlayers[playerID] === undefined ||
Object.keys(state.ctx.activePlayers).length > 1))) {
error(`playerID=[${playerID}] cannot undo / redo right now`);
return;
}
}
// Check whether the player is active.
if (!this.game.flow.isPlayerActive(state.G, state.ctx, playerID)) {
error(`player not active - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
// Get move for further checks
const move = action.type == MAKE_MOVE
? this.game.flow.getMove(state.ctx, action.payload.type, playerID)
: null;
// Check whether the player is allowed to make the move.
if (action.type == MAKE_MOVE && !move) {
error(`move not processed - canPlayerMakeMove=false - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
// Check if action's stateID is different than store's stateID
// and if move does not have ignoreStaleStateID truthy.
if (state._stateID !== stateID &&
!(move && IsLongFormMove(move) && move.ignoreStaleStateID)) {
error(`invalid stateID, was=[${stateID}], expected=[${state._stateID}]` +
` - playerID=[${playerID}] - action[${action.payload.type}]`);
return;
}
const prevState = store.getState();
// Update server's version of the store.
store.dispatch(action);
state = store.getState();
this.subscribeCallback({
state,
action,
matchID,
});
if (this.game.deltaState) {
this.transportAPI.sendAll({
type: 'patch',
args: [matchID, stateID, prevState, state],
});
}
else {
this.transportAPI.sendAll({
type: 'update',
args: [matchID, state],
});
}
const { deltalog, ...stateWithoutDeltalog } = state;
let newMetadata;
if (metadata &&
(metadata.gameover === undefined || metadata.gameover === null)) {
newMetadata = {
...metadata,
updatedAt: Date.now(),
};
if (state.ctx.gameover !== undefined) {
newMetadata.gameover = state.ctx.gameover;
}
}
if (isSynchronous(this.storageAPI)) {
this.storageAPI.setState(key, stateWithoutDeltalog, deltalog);
if (newMetadata)
this.storageAPI.setMetadata(key, newMetadata);
}
else {
const writes = [
this.storageAPI.setState(key, stateWithoutDeltalog, deltalog),
];
if (newMetadata) {
writes.push(this.storageAPI.setMetadata(key, newMetadata));
}
await Promise.all(writes);
}
}
/**
* Called when the client connects / reconnects.
* Returns the latest game state and the entire log.
*/
async onSync(matchID, playerID, credentials, numPlayers = 2) {
const key = matchID;
const fetchOpts = {
state: true,
metadata: true,
log: true,
initialState: true,
};
const fetchResult = isSynchronous(this.storageAPI)
? this.storageAPI.fetch(key, fetchOpts)
: await this.storageAPI.fetch(key, fetchOpts);
let { state, initialState, log, metadata } = fetchResult;
if (this.auth && playerID !== undefined && playerID !== null) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
// If the game doesn't exist, then create one on demand.
// TODO: Move this out of the sync call.
if (state === undefined) {
const match = createMatch({
game: this.game,
unlisted: true,
numPlayers,
setupData: undefined,
});
if ('setupDataError' in match) {
return { error: 'game requires setupData' };
}
initialState = state = match.initialState;
metadata = match.metadata;
this.subscribeCallback({ state, matchID });
if (isSynchronous(this.storageAPI)) {
this.storageAPI.createMatch(key, { initialState, metadata });
}
else {
await this.storageAPI.createMatch(key, { initialState, metadata });
}
}
const filteredMetadata = metadata ? filterMatchData(metadata) : undefined;
const syncInfo = {
state,
log,
filteredMetadata,
initialState,
};
this.transportAPI.send({
playerID,
type: 'sync',
args: [matchID, syncInfo],
});
return;
}
/**
* Called when a client connects or disconnects.
* Updates and sends out metadata to reflect the player’s connection status.
*/
async onConnectionChange(matchID, playerID, credentials, connected) {
const key = matchID;
// Ignore changes for clients without a playerID, e.g. spectators.
if (playerID === undefined || playerID === null) {
return;
}
let metadata;
if (isSynchronous(this.storageAPI)) {
({ metadata } = this.storageAPI.fetch(key, { metadata: true }));
}
else {
({ metadata } = await this.storageAPI.fetch(key, { metadata: true }));
}
if (metadata === undefined) {
error(`metadata not found for matchID=[${key}]`);
return { error: 'metadata not found' };
}
if (metadata.players[playerID] === undefined) {
error(`Player not in the match, matchID=[${key}] playerID=[${playerID}]`);
return { error: 'player not in the match' };
}
if (this.auth) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
metadata.players[playerID].isConnected = connected;
const filteredMetadata = filterMatchData(metadata);
this.transportAPI.sendAll({
type: 'matchData',
args: [matchID, filteredMetadata],
});
if (isSynchronous(this.storageAPI)) {
this.storageAPI.setMetadata(key, metadata);
}
else {
await this.storageAPI.setMetadata(key, metadata);
}
}
async onChatMessage(matchID, chatMessage, credentials) {
const key = matchID;
if (this.auth) {
const { metadata } = await this.storageAPI.fetch(key, {
metadata: true,
});
if (!(chatMessage && typeof chatMessage.sender === 'string')) {
return { error: 'unauthorized' };
}
const isAuthentic = await this.auth.authenticateCredentials({
playerID: chatMessage.sender,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
this.transportAPI.sendAll({
type: 'chat',
args: [matchID, chatMessage],
});
}
}
const applyPlayerView = (game, playerID, state) => ({
...state,
G: game.playerView(state.G, state.ctx, playerID),
plugins: PlayerView(state, { playerID, game }),
deltalog: undefined,
_undo: [],
_redo: [],
});
/** Gets a function that filters the TransportData for a given player and game. */
const getFilterPlayerView = (game) => (playerID, payload) => {
switch (payload.type) {
case 'patch': {
const [matchID, stateID, prevState, state] = payload.args;
const log = redactLog(state.deltalog, playerID);
const filteredState = applyPlayerView(game, playerID, state);
const newStateID = state._stateID;
const prevFilteredState = applyPlayerView(game, playerID, prevState);
const patch = createPatch(prevFilteredState, filteredState);
return {
type: 'patch',
args: [matchID, stateID, newStateID, patch, log],
};
}
case 'update': {
const [matchID, state] = payload.args;
const log = redactLog(state.deltalog, playerID);
const filteredState = applyPlayerView(game, playerID, state);
return {
type: 'update',
args: [matchID, filteredState, log],
};
}
case 'sync': {
const [matchID, syncInfo] = payload.args;
const filteredState = applyPlayerView(game, playerID, syncInfo.state);
const log = redactLog(syncInfo.log, playerID);
const newSyncInfo = {
...syncInfo,
state: filteredState,
log,
};
return {
type: 'sync',
args: [matchID, newSyncInfo],
};
}
default: {
return payload;
}
}
};
/**
* Redact the log.
*
* @param {Array} log - The game log (or deltalog).
* @param {String} playerID - The playerID that this log is
* to be sent to.
*/
function redactLog(log, playerID) {
if (log === undefined) {
return log;
}
return log.map((logEvent) => {
// filter for all other players and spectators.
if (playerID !== null && +playerID === +logEvent.action.payload.playerID) {
return logEvent;
}
if (logEvent.redact !== true) {
return logEvent;
}
const payload = {
...logEvent.action.payload,
args: null,
};
const filteredEvent = {
...logEvent,
action: { ...logEvent.action, payload },
};
const { redact, ...remaining } = filteredEvent;
return remaining;
});
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Returns null if it is not a bot's turn.
* Otherwise, returns a playerID of a bot that may play now.
*/
function GetBotPlayer(state, bots) {
if (state.ctx.gameover !== undefined) {
return null;
}
if (state.ctx.activePlayers) {
for (const key of Object.keys(bots)) {
if (key in state.ctx.activePlayers) {
return key;
}
}
}
else if (state.ctx.currentPlayer in bots) {
return state.ctx.currentPlayer;
}
return null;
}
/**
* Creates a local version of the master that the client
* can interact with.
*/
class LocalMaster extends Master {
constructor({ game, bots, storageKey, persist }) {
const clientCallbacks = {};
const initializedBots = {};
if (game && game.ai && bots) {
for (const playerID in bots) {
const bot = bots[playerID];
initializedBots[playerID] = new bot({
game,
enumerate: game.ai.enumerate,
seed: game.seed,
});
}
}
const send = ({ playerID, ...data }) => {
const callback = clientCallbacks[playerID];
if (callback !== undefined) {
callback(filterPlayerView(playerID, data));
}
};
const filterPlayerView = getFilterPlayerView(game);
const transportAPI = {
send,
sendAll: (payload) => {
for (const playerID in clientCallbacks) {
send({ playerID, ...payload });
}
},
};
const storage = persist ? new LocalStorage(storageKey) : new InMemory();
super(game, storage, transportAPI);
this.connect = (playerID, callback) => {
clientCallbacks[playerID] = callback;
};
this.subscribe(({ state, matchID }) => {
if (!bots) {
return;
}
const botPlayer = GetBotPlayer(state, initializedBots);
if (botPlayer !== null) {
setTimeout(async () => {
const botAction = await initializedBots[botPlayer].play(state, botPlayer);
await this.onUpdate(botAction.action, state._stateID, matchID, botAction.action.payload.playerID);
}, 100);
}
});
}
}
/**
* Local
*
* Transport interface that embeds a GameMaster within it
* that you can connect multiple clients to.
*/
class LocalTransport extends Transport {
/**
* Creates a new Mutiplayer instance.
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
*/
constructor({ master, ...opts }) {
super(opts);
this.master = master;
}
sendChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.master.onChatMessage(...args);
}
sendAction(state, action) {
this.master.onUpdate(action, state._stateID, this.matchID, this.playerID);
}
requestSync() {
this.master.onSync(this.matchID, this.playerID, this.credentials, this.numPlayers);
}
connect() {
this.setConnectionStatus(true);
this.master.connect(this.playerID, (data) => this.notifyClient(data));
this.requestSync();
}
disconnect() {
this.setConnectionStatus(false);
}
updateMatchID(id) {
this.matchID = id;
this.connect();
}
updatePlayerID(id) {
this.playerID = id;
this.connect();
}
updateCredentials(credentials) {
this.credentials = credentials;
this.connect();
}
}
/**
* Global map storing local master instances.
*/
const localMasters = new Map();
/**
* Create a local transport.
*/
function Local({ bots, persist, storageKey } = {}) {
return (transportOpts) => {
const { gameKey, game } = transportOpts;
let master;
const instance = localMasters.get(gameKey);
if (instance &&
instance.bots === bots &&
instance.storageKey === storageKey &&
instance.persist === persist) {
master = instance.master;
}
if (!master) {
master = new LocalMaster({ game, bots, persist, storageKey });
localMasters.set(gameKey, { master, bots, persist, storageKey });
}
return new LocalTransport({ master, ...transportOpts });
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const io = ioNamespace__default;
/**
* SocketIO
*
* Transport interface that interacts with the Master via socket.io.
*/
class SocketIOTransport extends Transport {
/**
* Creates a new Multiplayer instance.
* @param {object} socket - Override for unit tests.
* @param {object} socketOpts - Options to pass to socket.io.
* @param {object} store - Redux store
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} credentials - Authentication credentials
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
* @param {string} server - The game server in the form of 'hostname:port'. Defaults to the server serving the client if not provided.
*/
constructor({ socket, socketOpts, server, ...opts }) {
super(opts);
this.server = server;
this.socket = socket;
this.socketOpts = socketOpts;
}
sendAction(state, action) {
const args = [
action,
state._stateID,
this.matchID,
this.playerID,
];
this.socket.emit('update', ...args);
}
sendChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.socket.emit('chat', ...args);
}
connect() {
if (!this.socket) {
if (this.server) {
let server = this.server;
if (server.search(/^https?:\/\//) == -1) {
server = 'http://' + this.server;
}
if (server.slice(-1) != '/') {
// add trailing slash if not already present
server = server + '/';
}
this.socket = io(server + this.gameName, this.socketOpts);
}
else {
this.socket = io('/' + this.gameName, this.socketOpts);
}
}
// Called when another player makes a move and the
// master broadcasts the update as a patch to other clients (including
// this one).
this.socket.on('patch', (matchID, prevStateID, stateID, patch, deltalog) => {
this.notifyClient({
type: 'patch',
args: [matchID, prevStateID, stateID, patch, deltalog],
});
});
// Called when another player makes a move and the
// master broadcasts the update to other clients (including
// this one).
this.socket.on('update', (matchID, state, deltalog) => {
this.notifyClient({
type: 'update',
args: [matchID, state, deltalog],
});
});
// Called when the client first connects to the master
// and requests the current game state.
this.socket.on('sync', (matchID, syncInfo) => {
this.notifyClient({ type: 'sync', args: [matchID, syncInfo] });
});
// Called when new player joins the match or changes
// it's connection status
this.socket.on('matchData', (matchID, matchData) => {
this.notifyClient({ type: 'matchData', args: [matchID, matchData] });
});
this.socket.on('chat', (matchID, chatMessage) => {
this.notifyClient({ type: 'chat', args: [matchID, chatMessage] });
});
// Keep track of connection status.
this.socket.on('connect', () => {
// Initial sync to get game state.
this.requestSync();
this.setConnectionStatus(true);
});
this.socket.on('disconnect', () => {
this.setConnectionStatus(false);
});
}
disconnect() {
this.socket.close();
this.socket = null;
this.setConnectionStatus(false);
}
requestSync() {
if (this.socket) {
const args = [
this.matchID,
this.playerID,
this.credentials,
this.numPlayers,
];
this.socket.emit('sync', ...args);
}
}
updateMatchID(id) {
this.matchID = id;
this.requestSync();
}
updatePlayerID(id) {
this.playerID = id;
this.requestSync();
}
updateCredentials(credentials) {
this.credentials = credentials;
this.requestSync();
}
}
function SocketIO({ server, socketOpts } = {}) {
return (transportOpts) => new SocketIOTransport({
server,
socketOpts,
...transportOpts,
});
}
export { Client, Local, MCTSBot, RandomBot, Client$1 as ReactClient, Client$2 as ReactNativeClient, Simulate, SocketIO, Step, TurnOrder };
|
ajax/libs/react-native-web/0.0.0-466063b7e/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/recompose/0.20.0/Recompose.js | cdnjs/cdnjs | (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["Recompose"] = factory(require("react"));
else
root["Recompose"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_3__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(29);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var createHelper = function createHelper(func, helperName) {
var setDisplayName = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
var noArgs = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3];
if (false) {
var _ret = function () {
/* eslint-disable global-require */
var wrapDisplayName = require('./wrapDisplayName').default;
/* eslint-enable global-require */
if (noArgs) {
return {
v: function v(BaseComponent) {
var Component = func(BaseComponent);
Component.displayName = wrapDisplayName(BaseComponent, helperName);
return Component;
}
};
}
return {
v: function v() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args.length > func.length) {
/* eslint-disable */
console.error(
/* eslint-enable */
'Too many arguments passed to ' + helperName + '(). It should called ' + ('like so: ' + helperName + '(...args)(BaseComponent).'));
}
return function (BaseComponent) {
var Component = func.apply(undefined, args)(BaseComponent);
Component.displayName = wrapDisplayName(BaseComponent, helperName);
return Component;
};
}
};
}();
if (typeof _ret === "object") return _ret.v;
}
return func;
};
exports.default = createHelper;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createEagerElementUtil = __webpack_require__(18);
var _createEagerElementUtil2 = _interopRequireDefault(_createEagerElementUtil);
var _isReferentiallyTransparentFunctionComponent = __webpack_require__(16);
var _isReferentiallyTransparentFunctionComponent2 = _interopRequireDefault(_isReferentiallyTransparentFunctionComponent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var createFactory = function createFactory(type) {
var isReferentiallyTransparent = (0, _isReferentiallyTransparentFunctionComponent2.default)(type);
return function (p, c) {
return (0, _createEagerElementUtil2.default)(false, isReferentiallyTransparent, type, p, c);
};
};
exports.default = createFactory;
/***/ },
/* 3 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_3__;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var mapProps = function mapProps(propsMapper) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return function (props) {
return factory(propsMapper(props));
};
};
};
exports.default = (0, _createHelper2.default)(mapProps, 'mapProps');
/***/ },
/* 5 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var config = {
fromESObservable: null,
toESObservable: null
};
var fromESObservable = exports.fromESObservable = function fromESObservable(observable) {
return typeof config.fromESObservable === 'function' ? config.fromESObservable(observable) : observable;
};
var toESObservable = exports.toESObservable = function toESObservable(stream) {
return typeof config.toESObservable === 'function' ? config.toESObservable(stream) : stream;
};
var configureObservable = function configureObservable(c) {
config = c;
};
exports.default = configureObservable;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _shallowEqual = __webpack_require__(49);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _shallowEqual2.default;
/***/ },
/* 7 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var getDisplayName = function getDisplayName(Component) {
if (typeof Component === 'string') {
return Component;
}
if (!Component) {
return undefined;
}
return Component.displayName || Component.name || 'Component';
};
exports.default = getDisplayName;
/***/ },
/* 8 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
var isClassComponent = function isClassComponent(Component) {
return Boolean(Component && Component.prototype && typeof Component.prototype.isReactComponent === 'object');
};
exports.default = isClassComponent;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var setStatic = function setStatic(key, value) {
return function (BaseComponent) {
/* eslint-disable no-param-reassign */
BaseComponent[key] = value;
/* eslint-enable no-param-reassign */
return BaseComponent;
};
};
exports.default = (0, _createHelper2.default)(setStatic, 'setStatic', false);
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var shouldUpdate = function shouldUpdate(test) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return function (_Component) {
_inherits(_class, _Component);
function _class() {
_classCallCheck(this, _class);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
_class.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
return test(this.props, nextProps);
};
_class.prototype.render = function render() {
return factory(this.props);
};
return _class;
}(_react.Component);
};
};
exports.default = (0, _createHelper2.default)(shouldUpdate, 'shouldUpdate');
/***/ },
/* 11 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var omit = function omit(obj, keys) {
var rest = _objectWithoutProperties(obj, []);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (rest.hasOwnProperty(key)) {
delete rest[key];
}
}
return rest;
};
exports.default = omit;
/***/ },
/* 12 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
var pick = function pick(obj, keys) {
var result = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (obj.hasOwnProperty(key)) {
result[key] = obj[key];
}
}
return result;
};
exports.default = pick;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/* global window */
'use strict';
module.exports = __webpack_require__(51)(global || window || this);
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
var _changeEmitter = __webpack_require__(19);
var _symbolObservable = __webpack_require__(13);
var _symbolObservable2 = _interopRequireDefault(_symbolObservable);
var _setObservableConfig = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var componentFromStream = function componentFromStream(propsToVdom) {
return function (_Component) {
_inherits(ComponentFromStream, _Component);
function ComponentFromStream() {
var _fromESObservable;
var _temp, _this, _ret;
_classCallCheck(this, ComponentFromStream);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = { vdom: null }, _this.propsEmitter = (0, _changeEmitter.createChangeEmitter)(), _this.props$ = (0, _setObservableConfig.fromESObservable)((_fromESObservable = {
subscribe: function subscribe(observer) {
var unsubscribe = _this.propsEmitter.listen(function (props) {
return observer.next(props);
});
return { unsubscribe: unsubscribe };
}
}, _fromESObservable[_symbolObservable2.default] = function () {
return this;
}, _fromESObservable)), _this.vdom$ = (0, _setObservableConfig.toESObservable)(propsToVdom(_this.props$)), _temp), _possibleConstructorReturn(_this, _ret);
}
// Stream of props
// Stream of vdom
ComponentFromStream.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
// Subscribe to child prop changes so we know when to re-render
this.subscription = this.vdom$.subscribe({
next: function next(vdom) {
_this2.setState({ vdom: vdom });
}
});
this.propsEmitter.emit(this.props);
};
ComponentFromStream.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
// Receive new props from the owner
this.propsEmitter.emit(nextProps);
};
ComponentFromStream.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) {
return nextState.vdom !== this.state.vdom;
};
ComponentFromStream.prototype.componentWillUnmount = function componentWillUnmount() {
// Clean-up subscription before un-mounting
this.subscription.unsubscribe();
};
ComponentFromStream.prototype.render = function render() {
return this.state.vdom;
};
return ComponentFromStream;
}(_react.Component);
};
exports.default = componentFromStream;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createEagerElementUtil = __webpack_require__(18);
var _createEagerElementUtil2 = _interopRequireDefault(_createEagerElementUtil);
var _isReferentiallyTransparentFunctionComponent = __webpack_require__(16);
var _isReferentiallyTransparentFunctionComponent2 = _interopRequireDefault(_isReferentiallyTransparentFunctionComponent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var createEagerElement = function createEagerElement(type, props, children) {
var isReferentiallyTransparent = (0, _isReferentiallyTransparentFunctionComponent2.default)(type);
/* eslint-disable */
var hasKey = props && props.hasOwnProperty('key');
/* eslint-enable */
return (0, _createEagerElementUtil2.default)(hasKey, isReferentiallyTransparent, type, props, children);
};
exports.default = createEagerElement;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _isClassComponent = __webpack_require__(8);
var _isClassComponent2 = _interopRequireDefault(_isClassComponent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isReferentiallyTransparentFunctionComponent = function isReferentiallyTransparentFunctionComponent(Component) {
return Boolean(typeof Component === 'function' && !(0, _isClassComponent2.default)(Component) && !Component.defaultProps && !Component.contextTypes && !Component.propTypes);
};
exports.default = isReferentiallyTransparentFunctionComponent;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _shouldUpdate = __webpack_require__(10);
var _shouldUpdate2 = _interopRequireDefault(_shouldUpdate);
var _shallowEqual = __webpack_require__(6);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _pick = __webpack_require__(12);
var _pick2 = _interopRequireDefault(_pick);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var onlyUpdateForKeys = function onlyUpdateForKeys(propKeys) {
return (0, _shouldUpdate2.default)(function (props, nextProps) {
return !(0, _shallowEqual2.default)((0, _pick2.default)(nextProps, propKeys), (0, _pick2.default)(props, propKeys));
});
};
exports.default = (0, _createHelper2.default)(onlyUpdateForKeys, 'onlyUpdateForKeys');
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var createEagerElementUtil = function createEagerElementUtil(hasKey, isReferentiallyTransparent, type, props, children) {
if (!hasKey && isReferentiallyTransparent) {
if (children) {
return type(_extends({}, props, { children: children }));
}
return type(props);
}
var Component = type;
if (children) {
return _react2.default.createElement(
Component,
props,
children
);
}
return _react2.default.createElement(Component, props);
};
exports.default = createEagerElementUtil;
/***/ },
/* 19 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var createChangeEmitter = exports.createChangeEmitter = function createChangeEmitter() {
var currentListeners = [];
var nextListeners = currentListeners;
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice();
}
}
function listen(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected listener to be a function.');
}
var isSubscribed = true;
ensureCanMutateNextListeners();
nextListeners.push(listener);
return function () {
if (!isSubscribed) {
return;
}
isSubscribed = false;
ensureCanMutateNextListeners();
var index = nextListeners.indexOf(listener);
nextListeners.splice(index, 1);
};
}
function emit() {
currentListeners = nextListeners;
var listeners = currentListeners;
for (var i = 0; i < listeners.length; i++) {
listeners[i].apply(listeners, arguments);
}
}
return {
listen: listen,
emit: emit
};
};
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var branch = function branch(test, left, right) {
return function (BaseComponent) {
return function (_React$Component) {
_inherits(_class2, _React$Component);
function _class2(props, context) {
_classCallCheck(this, _class2);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.LeftComponent = null;
_this.RightComponent = null;
_this.computeChildComponent(_this.props);
return _this;
}
_class2.prototype.computeChildComponent = function computeChildComponent(props) {
if (test(props)) {
this.leftFactory = this.leftFactory || (0, _createEagerFactory2.default)(left(BaseComponent));
this.factory = this.leftFactory;
} else {
this.rightFactory = this.rightFactory || (0, _createEagerFactory2.default)(right(BaseComponent));
this.factory = this.rightFactory;
}
};
_class2.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
this.computeChildComponent(nextProps);
};
_class2.prototype.render = function render() {
return this.factory(this.props);
};
return _class2;
}(_react2.default.Component);
};
};
exports.default = (0, _createHelper2.default)(branch, 'branch');
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _omit = __webpack_require__(11);
var _omit2 = _interopRequireDefault(_omit);
var _createEagerElement = __webpack_require__(15);
var _createEagerElement2 = _interopRequireDefault(_createEagerElement);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var componentFromProp = function componentFromProp(propName) {
var Component = function Component(props) {
return (0, _createEagerElement2.default)(props[propName], (0, _omit2.default)(props, [propName]));
};
Component.displayName = 'componentFromProp(' + propName + ')';
return Component;
};
exports.default = componentFromProp;
/***/ },
/* 22 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports.default = compose;
function compose() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
if (funcs.length === 0) {
return function (arg) {
return arg;
};
}
if (funcs.length === 1) {
return funcs[0];
}
var last = funcs[funcs.length - 1];
return function () {
var result = last.apply(undefined, arguments);
for (var i = funcs.length - 2; i >= 0; i--) {
var f = funcs[i];
result = f(result);
}
return result;
};
}
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _symbolObservable = __webpack_require__(13);
var _symbolObservable2 = _interopRequireDefault(_symbolObservable);
var _changeEmitter = __webpack_require__(19);
var _setObservableConfig = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var createEventHandler = function createEventHandler() {
var _fromESObservable;
var emitter = (0, _changeEmitter.createChangeEmitter)();
var stream = (0, _setObservableConfig.fromESObservable)((_fromESObservable = {
subscribe: function subscribe(observer) {
var unsubscribe = emitter.listen(function (value) {
return observer.next(value);
});
return { unsubscribe: unsubscribe };
}
}, _fromESObservable[_symbolObservable2.default] = function () {
return this;
}, _fromESObservable));
return {
handler: emitter.emit,
stream: stream
};
};
exports.default = createEventHandler;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var createSink = function createSink(callback) {
return function (_Component) {
_inherits(Sink, _Component);
function Sink() {
_classCallCheck(this, Sink);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
Sink.prototype.componentWillMount = function componentWillMount() {
callback(this.props);
};
Sink.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
callback(nextProps);
};
Sink.prototype.render = function render() {
return null;
};
return Sink;
}(_react.Component);
};
exports.default = createSink;
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var defaultProps = function defaultProps(props) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
var DefaultProps = function DefaultProps(ownerProps) {
return factory(ownerProps);
};
DefaultProps.defaultProps = props;
return DefaultProps;
};
};
exports.default = (0, _createHelper2.default)(defaultProps, 'defaultProps');
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var flattenProp = function flattenProp(propName) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return function (props) {
return factory(_extends({}, props, props[propName]));
};
};
};
exports.default = (0, _createHelper2.default)(flattenProp, 'flattenProp');
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var getContext = function getContext(contextTypes) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
var GetContext = function GetContext(ownerProps, context) {
return factory(_extends({}, ownerProps, context));
};
GetContext.contextTypes = contextTypes;
return GetContext;
};
};
exports.default = (0, _createHelper2.default)(getContext, 'getContext');
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _hoistNonReactStatics = __webpack_require__(50);
var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var hoistStatics = function hoistStatics(higherOrderComponent) {
return function (BaseComponent) {
var NewComponent = higherOrderComponent(BaseComponent);
(0, _hoistNonReactStatics2.default)(NewComponent, BaseComponent);
return NewComponent;
};
};
exports.default = hoistStatics;
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.setObservableConfig = exports.createEventHandler = exports.mapPropsStream = exports.componentFromStream = exports.hoistStatics = exports.nest = exports.componentFromProp = exports.createSink = exports.createEagerFactory = exports.createEagerElement = exports.isClassComponent = exports.shallowEqual = exports.wrapDisplayName = exports.getDisplayName = exports.compose = exports.setDisplayName = exports.setPropTypes = exports.setStatic = exports.toClass = exports.lifecycle = exports.getContext = exports.withContext = exports.onlyUpdateForPropTypes = exports.onlyUpdateForKeys = exports.pure = exports.shouldUpdate = exports.renderNothing = exports.renderComponent = exports.branch = exports.withReducer = exports.withState = exports.flattenProp = exports.renameProps = exports.renameProp = exports.defaultProps = exports.withHandlers = exports.withPropsOnChange = exports.withProps = exports.mapProps = undefined;
var _mapProps2 = __webpack_require__(4);
var _mapProps3 = _interopRequireDefault(_mapProps2);
var _withProps2 = __webpack_require__(44);
var _withProps3 = _interopRequireDefault(_withProps2);
var _withPropsOnChange2 = __webpack_require__(45);
var _withPropsOnChange3 = _interopRequireDefault(_withPropsOnChange2);
var _withHandlers2 = __webpack_require__(43);
var _withHandlers3 = _interopRequireDefault(_withHandlers2);
var _defaultProps2 = __webpack_require__(25);
var _defaultProps3 = _interopRequireDefault(_defaultProps2);
var _renameProp2 = __webpack_require__(35);
var _renameProp3 = _interopRequireDefault(_renameProp2);
var _renameProps2 = __webpack_require__(36);
var _renameProps3 = _interopRequireDefault(_renameProps2);
var _flattenProp2 = __webpack_require__(26);
var _flattenProp3 = _interopRequireDefault(_flattenProp2);
var _withState2 = __webpack_require__(47);
var _withState3 = _interopRequireDefault(_withState2);
var _withReducer2 = __webpack_require__(46);
var _withReducer3 = _interopRequireDefault(_withReducer2);
var _branch2 = __webpack_require__(20);
var _branch3 = _interopRequireDefault(_branch2);
var _renderComponent2 = __webpack_require__(37);
var _renderComponent3 = _interopRequireDefault(_renderComponent2);
var _renderNothing2 = __webpack_require__(38);
var _renderNothing3 = _interopRequireDefault(_renderNothing2);
var _shouldUpdate2 = __webpack_require__(10);
var _shouldUpdate3 = _interopRequireDefault(_shouldUpdate2);
var _pure2 = __webpack_require__(34);
var _pure3 = _interopRequireDefault(_pure2);
var _onlyUpdateForKeys2 = __webpack_require__(17);
var _onlyUpdateForKeys3 = _interopRequireDefault(_onlyUpdateForKeys2);
var _onlyUpdateForPropTypes2 = __webpack_require__(33);
var _onlyUpdateForPropTypes3 = _interopRequireDefault(_onlyUpdateForPropTypes2);
var _withContext2 = __webpack_require__(42);
var _withContext3 = _interopRequireDefault(_withContext2);
var _getContext2 = __webpack_require__(27);
var _getContext3 = _interopRequireDefault(_getContext2);
var _lifecycle2 = __webpack_require__(30);
var _lifecycle3 = _interopRequireDefault(_lifecycle2);
var _toClass2 = __webpack_require__(41);
var _toClass3 = _interopRequireDefault(_toClass2);
var _setStatic2 = __webpack_require__(9);
var _setStatic3 = _interopRequireDefault(_setStatic2);
var _setPropTypes2 = __webpack_require__(40);
var _setPropTypes3 = _interopRequireDefault(_setPropTypes2);
var _setDisplayName2 = __webpack_require__(39);
var _setDisplayName3 = _interopRequireDefault(_setDisplayName2);
var _compose2 = __webpack_require__(22);
var _compose3 = _interopRequireDefault(_compose2);
var _getDisplayName2 = __webpack_require__(7);
var _getDisplayName3 = _interopRequireDefault(_getDisplayName2);
var _wrapDisplayName2 = __webpack_require__(48);
var _wrapDisplayName3 = _interopRequireDefault(_wrapDisplayName2);
var _shallowEqual2 = __webpack_require__(6);
var _shallowEqual3 = _interopRequireDefault(_shallowEqual2);
var _isClassComponent2 = __webpack_require__(8);
var _isClassComponent3 = _interopRequireDefault(_isClassComponent2);
var _createEagerElement2 = __webpack_require__(15);
var _createEagerElement3 = _interopRequireDefault(_createEagerElement2);
var _createEagerFactory2 = __webpack_require__(2);
var _createEagerFactory3 = _interopRequireDefault(_createEagerFactory2);
var _createSink2 = __webpack_require__(24);
var _createSink3 = _interopRequireDefault(_createSink2);
var _componentFromProp2 = __webpack_require__(21);
var _componentFromProp3 = _interopRequireDefault(_componentFromProp2);
var _nest2 = __webpack_require__(32);
var _nest3 = _interopRequireDefault(_nest2);
var _hoistStatics2 = __webpack_require__(28);
var _hoistStatics3 = _interopRequireDefault(_hoistStatics2);
var _componentFromStream2 = __webpack_require__(14);
var _componentFromStream3 = _interopRequireDefault(_componentFromStream2);
var _mapPropsStream2 = __webpack_require__(31);
var _mapPropsStream3 = _interopRequireDefault(_mapPropsStream2);
var _createEventHandler2 = __webpack_require__(23);
var _createEventHandler3 = _interopRequireDefault(_createEventHandler2);
var _setObservableConfig2 = __webpack_require__(5);
var _setObservableConfig3 = _interopRequireDefault(_setObservableConfig2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.mapProps = _mapProps3.default; // Higher-order component helpers
exports.withProps = _withProps3.default;
exports.withPropsOnChange = _withPropsOnChange3.default;
exports.withHandlers = _withHandlers3.default;
exports.defaultProps = _defaultProps3.default;
exports.renameProp = _renameProp3.default;
exports.renameProps = _renameProps3.default;
exports.flattenProp = _flattenProp3.default;
exports.withState = _withState3.default;
exports.withReducer = _withReducer3.default;
exports.branch = _branch3.default;
exports.renderComponent = _renderComponent3.default;
exports.renderNothing = _renderNothing3.default;
exports.shouldUpdate = _shouldUpdate3.default;
exports.pure = _pure3.default;
exports.onlyUpdateForKeys = _onlyUpdateForKeys3.default;
exports.onlyUpdateForPropTypes = _onlyUpdateForPropTypes3.default;
exports.withContext = _withContext3.default;
exports.getContext = _getContext3.default;
exports.lifecycle = _lifecycle3.default;
exports.toClass = _toClass3.default;
// Static property helpers
exports.setStatic = _setStatic3.default;
exports.setPropTypes = _setPropTypes3.default;
exports.setDisplayName = _setDisplayName3.default;
// Composition function
exports.compose = _compose3.default;
// Other utils
exports.getDisplayName = _getDisplayName3.default;
exports.wrapDisplayName = _wrapDisplayName3.default;
exports.shallowEqual = _shallowEqual3.default;
exports.isClassComponent = _isClassComponent3.default;
exports.createEagerElement = _createEagerElement3.default;
exports.createEagerFactory = _createEagerFactory3.default;
exports.createSink = _createSink3.default;
exports.componentFromProp = _componentFromProp3.default;
exports.nest = _nest3.default;
exports.hoistStatics = _hoistStatics3.default;
// Observable helpers
exports.componentFromStream = _componentFromStream3.default;
exports.mapPropsStream = _mapPropsStream3.default;
exports.createEventHandler = _createEventHandler3.default;
exports.setObservableConfig = _setObservableConfig3.default;
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _react = __webpack_require__(3);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var lifecycle = function lifecycle(spec) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
if (false) {
console.error('lifecycle() does not support the render method; its behavior is to ' + 'pass all props and state to the base component.');
}
/* eslint-disable react/prefer-es6-class */
return (0, _react.createClass)(_extends({}, spec, {
render: function render() {
return factory(_extends({}, this.props, this.state));
}
}));
/* eslint-enable react/prefer-es6-class */
};
};
exports.default = (0, _createHelper2.default)(lifecycle, 'lifecycle');
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _symbolObservable = __webpack_require__(13);
var _symbolObservable2 = _interopRequireDefault(_symbolObservable);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _componentFromStream = __webpack_require__(14);
var _componentFromStream2 = _interopRequireDefault(_componentFromStream);
var _setObservableConfig = __webpack_require__(5);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var mapPropsStream = function mapPropsStream(transform) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return (0, _componentFromStream2.default)(function (ownerProps$) {
var _ref;
return _ref = {
subscribe: function subscribe(observer) {
var subscription = (0, _setObservableConfig.toESObservable)(transform(ownerProps$)).subscribe({
next: function next(childProps) {
return observer.next(factory(childProps));
}
});
return {
unsubscribe: function unsubscribe() {
return subscription.unsubscribe();
}
};
}
}, _ref[_symbolObservable2.default] = function () {
return this;
}, _ref;
});
};
};
exports.default = (0, _createHelper2.default)(mapPropsStream, 'mapPropsStream');
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var nest = function nest() {
for (var _len = arguments.length, Components = Array(_len), _key = 0; _key < _len; _key++) {
Components[_key] = arguments[_key];
}
var factories = Components.map(_createEagerFactory2.default);
var Nest = function Nest(_ref) {
var props = _objectWithoutProperties(_ref, []);
var children = _ref.children;
return factories.reduceRight(function (child, factory) {
return factory(props, child);
}, children);
};
if (false) {
/* eslint-disable global-require */
var getDisplayName = require('./getDisplayName').default;
/* eslint-enable global-require */
var displayNames = Components.map(getDisplayName);
Nest.displayName = 'nest(' + displayNames.join(', ') + ')';
}
return Nest;
};
exports.default = nest;
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _onlyUpdateForKeys = __webpack_require__(17);
var _onlyUpdateForKeys2 = _interopRequireDefault(_onlyUpdateForKeys);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var onlyUpdateForPropTypes = function onlyUpdateForPropTypes(BaseComponent) {
var propTypes = BaseComponent.propTypes;
if (false) {
/* eslint-disable global-require */
var getDisplayName = require('./getDisplayName').default;
/* eslint-enable global-require */
if (!propTypes) {
/* eslint-disable */
console.error('A component without any `propTypes` was passed to ' + '`onlyUpdateForPropTypes()`. Check the implementation of the ' + ('component with display name "' + getDisplayName(BaseComponent) + '".'));
/* eslint-enable */
}
}
var propKeys = Object.keys(propTypes || {});
var OnlyUpdateForPropTypes = (0, _onlyUpdateForKeys2.default)(propKeys)(BaseComponent);
return OnlyUpdateForPropTypes;
};
exports.default = (0, _createHelper2.default)(onlyUpdateForPropTypes, 'onlyUpdateForPropTypes', true, true);
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _shouldUpdate = __webpack_require__(10);
var _shouldUpdate2 = _interopRequireDefault(_shouldUpdate);
var _shallowEqual = __webpack_require__(6);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var pure = (0, _shouldUpdate2.default)(function (props, nextProps) {
return !(0, _shallowEqual2.default)(props, nextProps);
});
exports.default = (0, _createHelper2.default)(pure, 'pure', true, true);
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _omit = __webpack_require__(11);
var _omit2 = _interopRequireDefault(_omit);
var _mapProps = __webpack_require__(4);
var _mapProps2 = _interopRequireDefault(_mapProps);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var renameProp = function renameProp(oldName, newName) {
return (0, _mapProps2.default)(function (props) {
var _extends2;
return _extends({}, (0, _omit2.default)(props, [oldName]), (_extends2 = {}, _extends2[newName] = props[oldName], _extends2));
});
};
exports.default = (0, _createHelper2.default)(renameProp, 'renameProp');
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _omit = __webpack_require__(11);
var _omit2 = _interopRequireDefault(_omit);
var _pick = __webpack_require__(12);
var _pick2 = _interopRequireDefault(_pick);
var _mapProps = __webpack_require__(4);
var _mapProps2 = _interopRequireDefault(_mapProps);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var keys = Object.keys;
var mapKeys = function mapKeys(obj, func) {
return keys(obj).reduce(function (result, key) {
var val = obj[key];
/* eslint-disable no-param-reassign */
result[func(val, key)] = val;
/* eslint-enable no-param-reassign */
return result;
}, {});
};
var renameProps = function renameProps(nameMap) {
return (0, _mapProps2.default)(function (props) {
return _extends({}, (0, _omit2.default)(props, keys(nameMap)), mapKeys((0, _pick2.default)(props, keys(nameMap)), function (_, oldName) {
return nameMap[oldName];
}));
});
};
exports.default = (0, _createHelper2.default)(renameProps, 'renameProps');
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// import React from 'react'
var renderComponent = function renderComponent(Component) {
return function (_) {
var factory = (0, _createEagerFactory2.default)(Component);
var RenderComponent = function RenderComponent(props) {
return factory(props);
};
// const RenderComponent = props => <Component {...props} />
if (false) {
/* eslint-disable global-require */
var wrapDisplayName = require('./wrapDisplayName').default;
/* eslint-enable global-require */
RenderComponent.displayName = wrapDisplayName(Component, 'renderComponent');
}
return RenderComponent;
};
};
exports.default = (0, _createHelper2.default)(renderComponent, 'renderComponent', false);
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var renderNothing = function renderNothing(_) {
var Nothing = function Nothing() {
return null;
};
Nothing.displayName = 'Nothing';
return Nothing;
};
exports.default = (0, _createHelper2.default)(renderNothing, 'renderNothing', false, true);
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _setStatic = __webpack_require__(9);
var _setStatic2 = _interopRequireDefault(_setStatic);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var setDisplayName = function setDisplayName(displayName) {
return (0, _setStatic2.default)('displayName', displayName);
};
exports.default = (0, _createHelper2.default)(setDisplayName, 'setDisplayName', false);
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _setStatic = __webpack_require__(9);
var _setStatic2 = _interopRequireDefault(_setStatic);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var setPropTypes = function setPropTypes(propTypes) {
return (0, _setStatic2.default)('propTypes', propTypes);
};
exports.default = (0, _createHelper2.default)(setPropTypes, 'setPropTypes', false);
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _getDisplayName = __webpack_require__(7);
var _getDisplayName2 = _interopRequireDefault(_getDisplayName);
var _isClassComponent = __webpack_require__(8);
var _isClassComponent2 = _interopRequireDefault(_isClassComponent);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var toClass = function toClass(baseComponent) {
if ((0, _isClassComponent2.default)(baseComponent)) {
return baseComponent;
}
var ToClass = function (_Component) {
_inherits(ToClass, _Component);
function ToClass() {
_classCallCheck(this, ToClass);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
ToClass.prototype.render = function render() {
if (typeof baseComponent === 'string') {
return _react2.default.createElement('baseComponent', this.props);
}
return baseComponent(this.props, this.context);
};
return ToClass;
}(_react.Component);
ToClass.displayName = (0, _getDisplayName2.default)(baseComponent);
ToClass.propTypes = baseComponent.propTypes;
ToClass.contextTypes = baseComponent.contextTypes;
ToClass.defaultProps = baseComponent.defaultProps;
return ToClass;
};
exports.default = toClass;
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(3);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var withContext = function withContext(childContextTypes, getChildContext) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
var WithContext = function (_Component) {
_inherits(WithContext, _Component);
function WithContext() {
var _temp, _this, _ret;
_classCallCheck(this, WithContext);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.getChildContext = function () {
return getChildContext(_this.props);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
WithContext.prototype.render = function render() {
return factory(this.props);
};
return WithContext;
}(_react.Component);
WithContext.childContextTypes = childContextTypes;
return WithContext;
};
};
exports.default = (0, _createHelper2.default)(withContext, 'withContext');
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _react = __webpack_require__(3);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var mapValues = function mapValues(obj, func) {
var result = [];
var i = 0;
/* eslint-disable no-restricted-syntax */
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
i += 1;
result[key] = func(obj[key], key, i);
}
}
/* eslint-enable no-restricted-syntax */
return result;
};
var withHandlers = function withHandlers(handlers) {
return function (BaseComponent) {
var _class, _temp2, _initialiseProps;
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return _temp2 = _class = function (_Component) {
_inherits(_class, _Component);
function _class() {
var _temp, _this, _ret;
_classCallCheck(this, _class);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _initialiseProps.call(_this), _temp), _possibleConstructorReturn(_this, _ret);
}
_class.prototype.componentWillReceiveProps = function componentWillReceiveProps() {
this.cachedHandlers = {};
};
_class.prototype.render = function render() {
return factory(_extends({}, this.props, this.handlers));
};
return _class;
}(_react.Component), _initialiseProps = function _initialiseProps() {
var _this2 = this;
this.cachedHandlers = {};
this.handlers = mapValues(handlers, function (createHandler, handlerName) {
return function () {
var cachedHandler = _this2.cachedHandlers[handlerName];
if (cachedHandler) {
return cachedHandler.apply(undefined, arguments);
}
var handler = createHandler(_this2.props);
_this2.cachedHandlers[handlerName] = handler;
if (false) {
console.error('withHandlers(): Expected a map of higher-order functions. ' + 'Refer to the docs for more info.');
}
return handler.apply(undefined, arguments);
};
});
}, _temp2;
};
};
exports.default = (0, _createHelper2.default)(withHandlers, 'withHandlers');
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _mapProps = __webpack_require__(4);
var _mapProps2 = _interopRequireDefault(_mapProps);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var withProps = function withProps(input) {
return (0, _mapProps2.default)(function (props) {
return _extends({}, props, typeof input === 'function' ? input(props) : input);
});
};
exports.default = (0, _createHelper2.default)(withProps, 'withProps');
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _react = __webpack_require__(3);
var _pick = __webpack_require__(12);
var _pick2 = _interopRequireDefault(_pick);
var _shallowEqual = __webpack_require__(6);
var _shallowEqual2 = _interopRequireDefault(_shallowEqual);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var withPropsOnChange = function withPropsOnChange(shouldMapOrKeys, propsMapper) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
var shouldMap = typeof shouldMapOrKeys === 'function' ? shouldMapOrKeys : function (props, nextProps) {
return !(0, _shallowEqual2.default)((0, _pick2.default)(props, shouldMapOrKeys), (0, _pick2.default)(nextProps, shouldMapOrKeys));
};
return function (_Component) {
_inherits(_class2, _Component);
function _class2() {
var _temp, _this, _ret;
_classCallCheck(this, _class2);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.computedProps = propsMapper(_this.props), _temp), _possibleConstructorReturn(_this, _ret);
}
_class2.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (shouldMap(this.props, nextProps)) {
this.computedProps = propsMapper(nextProps);
}
};
_class2.prototype.render = function render() {
return factory(_extends({}, this.props, this.computedProps));
};
return _class2;
}(_react.Component);
};
};
exports.default = (0, _createHelper2.default)(withPropsOnChange, 'withPropsOnChange');
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _react = __webpack_require__(3);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var withReducer = function withReducer(stateName, dispatchName, reducer, initialState) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return function (_Component) {
_inherits(_class2, _Component);
function _class2() {
var _temp, _this, _ret;
_classCallCheck(this, _class2);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = {
stateValue: typeof initialState === 'function' ? initialState(_this.props) : initialState
}, _this.dispatch = function (action) {
return _this.setState(function (_ref) {
var stateValue = _ref.stateValue;
return {
stateValue: reducer(stateValue, action)
};
});
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_class2.prototype.render = function render() {
var _extends2;
return factory(_extends({}, this.props, (_extends2 = {}, _extends2[stateName] = this.state.stateValue, _extends2[dispatchName] = this.dispatch, _extends2)));
};
return _class2;
}(_react.Component);
};
};
exports.default = (0, _createHelper2.default)(withReducer, 'withReducer');
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = 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 _react = __webpack_require__(3);
var _createHelper = __webpack_require__(1);
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createEagerFactory = __webpack_require__(2);
var _createEagerFactory2 = _interopRequireDefault(_createEagerFactory);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var withState = function withState(stateName, stateUpdaterName, initialState) {
return function (BaseComponent) {
var factory = (0, _createEagerFactory2.default)(BaseComponent);
return function (_Component) {
_inherits(_class2, _Component);
function _class2() {
var _temp, _this, _ret;
_classCallCheck(this, _class2);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.state = {
stateValue: typeof initialState === 'function' ? initialState(_this.props) : initialState
}, _this.updateStateValue = function (updateFn, callback) {
return _this.setState(function (_ref) {
var stateValue = _ref.stateValue;
return {
stateValue: typeof updateFn === 'function' ? updateFn(stateValue) : updateFn
};
}, callback);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_class2.prototype.render = function render() {
var _extends2;
return factory(_extends({}, this.props, (_extends2 = {}, _extends2[stateName] = this.state.stateValue, _extends2[stateUpdaterName] = this.updateStateValue, _extends2)));
};
return _class2;
}(_react.Component);
};
};
exports.default = (0, _createHelper2.default)(withState, 'withState');
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _getDisplayName = __webpack_require__(7);
var _getDisplayName2 = _interopRequireDefault(_getDisplayName);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var wrapDisplayName = function wrapDisplayName(BaseComponent, hocName) {
return hocName + '(' + (0, _getDisplayName2.default)(BaseComponent) + ')';
};
exports.default = wrapDisplayName;
/***/ },
/* 49 */
/***/ function(module, exports) {
/**
* 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.
*
* @typechecks
*
*/
/*eslint-disable no-self-compare */
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (is(objA, objB)) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
for (var i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
/***/ },
/* 50 */
/***/ function(module, exports) {
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
var REACT_STATICS = {
childContextTypes: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
arguments: true,
arity: true
};
module.exports = function hoistNonReactStatics(targetComponent, sourceComponent) {
if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components
var keys = Object.getOwnPropertyNames(sourceComponent);
for (var i=0; i<keys.length; ++i) {
if (!REACT_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]]) {
try {
targetComponent[keys[i]] = sourceComponent[keys[i]];
} catch (error) {
}
}
}
}
return targetComponent;
};
/***/ },
/* 51 */
/***/ function(module, exports) {
'use strict';
module.exports = function symbolObservablePonyfill(root) {
var result;
var Symbol = root.Symbol;
if (typeof Symbol === 'function') {
if (Symbol.observable) {
result = Symbol.observable;
} else {
result = Symbol('observable');
Symbol.observable = result;
}
} else {
result = '@@observable';
}
return result;
};
/***/ }
/******/ ])
});
; |
ajax/libs/primereact/7.0.1/card/card.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { ObjectUtils, classNames } from 'primereact/utils';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Card = /*#__PURE__*/function (_Component) {
_inherits(Card, _Component);
var _super = _createSuper(Card);
function Card() {
_classCallCheck(this, Card);
return _super.apply(this, arguments);
}
_createClass(Card, [{
key: "renderHeader",
value: function renderHeader() {
if (this.props.header) {
return /*#__PURE__*/React.createElement("div", {
className: "p-card-header"
}, ObjectUtils.getJSXElement(this.props.header, this.props));
}
return null;
}
}, {
key: "renderBody",
value: function renderBody() {
var title = this.props.title && /*#__PURE__*/React.createElement("div", {
className: "p-card-title"
}, ObjectUtils.getJSXElement(this.props.title, this.props));
var subTitle = this.props.subTitle && /*#__PURE__*/React.createElement("div", {
className: "p-card-subtitle"
}, ObjectUtils.getJSXElement(this.props.subTitle, this.props));
var children = this.props.children && /*#__PURE__*/React.createElement("div", {
className: "p-card-content"
}, this.props.children);
var footer = this.props.footer && /*#__PURE__*/React.createElement("div", {
className: "p-card-footer"
}, ObjectUtils.getJSXElement(this.props.footer, this.props));
return /*#__PURE__*/React.createElement("div", {
className: "p-card-body"
}, title, subTitle, children, footer);
}
}, {
key: "render",
value: function render() {
var header = this.renderHeader();
var body = this.renderBody();
var className = classNames('p-card p-component', this.props.className);
return /*#__PURE__*/React.createElement("div", {
className: className,
style: this.props.style,
id: this.props.id
}, header, body);
}
}]);
return Card;
}(Component);
_defineProperty(Card, "defaultProps", {
id: null,
header: null,
footer: null,
title: null,
subTitle: null,
style: null,
className: null
});
export { Card };
|
ajax/libs/boardgame-io/0.44.1/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-db9d5a63.js';
import 'redux';
import './turn-order-ec34409c.js';
import 'immer';
import 'lodash.isplainobject';
import './reducer-fcd5a508.js';
import 'rfc6902';
import './initialize-b7b6b696.js';
import './transport-0079de87.js';
import { C as Client$1 } from './client-b6b7ebef.js';
import 'flatted';
import './ai-81cc5833.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/boardgame-io/0.39.16/esm/react-native.js | cdnjs/cdnjs | import './Debug-91f604ee.js';
import 'redux';
import { x as _inherits, _ as _createClass, y as _defineProperty, w as _classCallCheck, z as _possibleConstructorReturn, B as _getPrototypeOf, J as _objectWithoutProperties, K as _objectSpread2 } from './turn-order-dce10a02.js';
import 'immer';
import './reducer-b11048c2.js';
import 'flatted';
import './ai-9b435d0e.js';
import './initialize-63a95034.js';
import { C as Client$1 } from './client-ef3f3b30.js';
import React from 'react';
import PropTypes from 'prop-types';
/**
* 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/react-native-web/0.14.12/exports/Touchable/index.js | cdnjs/cdnjs | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import AccessibilityUtil from '../../modules/AccessibilityUtil';
import BoundingDimensions from './BoundingDimensions';
import findNodeHandle from '../findNodeHandle';
import normalizeColor from 'normalize-css-color';
import Position from './Position';
import React from 'react';
import UIManager from '../UIManager';
import View from '../View';
var extractSingleTouch = function extractSingleTouch(nativeEvent) {
var touches = nativeEvent.touches;
var changedTouches = nativeEvent.changedTouches;
var hasTouches = touches && touches.length > 0;
var hasChangedTouches = changedTouches && changedTouches.length > 0;
return !hasTouches && hasChangedTouches ? changedTouches[0] : hasTouches ? touches[0] : nativeEvent;
};
/**
* `Touchable`: Taps done right.
*
* You hook your `ResponderEventPlugin` events into `Touchable`. `Touchable`
* will measure time/geometry and tells you when to give feedback to the user.
*
* ====================== Touchable Tutorial ===============================
* The `Touchable` mixin helps you handle the "press" interaction. It analyzes
* the geometry of elements, and observes when another responder (scroll view
* etc) has stolen the touch lock. It notifies your component when it should
* give feedback to the user. (bouncing/highlighting/unhighlighting).
*
* - When a touch was activated (typically you highlight)
* - When a touch was deactivated (typically you unhighlight)
* - When a touch was "pressed" - a touch ended while still within the geometry
* of the element, and no other element (like scroller) has "stolen" touch
* lock ("responder") (Typically you bounce the element).
*
* A good tap interaction isn't as simple as you might think. There should be a
* slight delay before showing a highlight when starting a touch. If a
* subsequent touch move exceeds the boundary of the element, it should
* unhighlight, but if that same touch is brought back within the boundary, it
* should rehighlight again. A touch can move in and out of that boundary
* several times, each time toggling highlighting, but a "press" is only
* triggered if that touch ends while within the element's boundary and no
* scroller (or anything else) has stolen the lock on touches.
*
* To create a new type of component that handles interaction using the
* `Touchable` mixin, do the following:
*
* - Initialize the `Touchable` state.
*
* getInitialState: function() {
* return merge(this.touchableGetInitialState(), yourComponentState);
* }
*
* - Choose the rendered component who's touches should start the interactive
* sequence. On that rendered node, forward all `Touchable` responder
* handlers. You can choose any rendered node you like. Choose a node whose
* hit target you'd like to instigate the interaction sequence:
*
* // In render function:
* return (
* <View
* onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
* onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest}
* onResponderGrant={this.touchableHandleResponderGrant}
* onResponderMove={this.touchableHandleResponderMove}
* onResponderRelease={this.touchableHandleResponderRelease}
* onResponderTerminate={this.touchableHandleResponderTerminate}>
* <View>
* Even though the hit detection/interactions are triggered by the
* wrapping (typically larger) node, we usually end up implementing
* custom logic that highlights this inner one.
* </View>
* </View>
* );
*
* - You may set up your own handlers for each of these events, so long as you
* also invoke the `touchable*` handlers inside of your custom handler.
*
* - Implement the handlers on your component class in order to provide
* feedback to the user. See documentation for each of these class methods
* that you should implement.
*
* touchableHandlePress: function() {
* this.performBounceAnimation(); // or whatever you want to do.
* },
* touchableHandleActivePressIn: function() {
* this.beginHighlighting(...); // Whatever you like to convey activation
* },
* touchableHandleActivePressOut: function() {
* this.endHighlighting(...); // Whatever you like to convey deactivation
* },
*
* - There are more advanced methods you can implement (see documentation below):
* touchableGetHighlightDelayMS: function() {
* return 20;
* }
* // In practice, *always* use a predeclared constant (conserve memory).
* touchableGetPressRectOffset: function() {
* return {top: 20, left: 20, right: 20, bottom: 100};
* }
*/
/**
* Touchable states.
*/
var States = {
NOT_RESPONDER: 'NOT_RESPONDER',
// Not the responder
RESPONDER_INACTIVE_PRESS_IN: 'RESPONDER_INACTIVE_PRESS_IN',
// Responder, inactive, in the `PressRect`
RESPONDER_INACTIVE_PRESS_OUT: 'RESPONDER_INACTIVE_PRESS_OUT',
// Responder, inactive, out of `PressRect`
RESPONDER_ACTIVE_PRESS_IN: 'RESPONDER_ACTIVE_PRESS_IN',
// Responder, active, in the `PressRect`
RESPONDER_ACTIVE_PRESS_OUT: 'RESPONDER_ACTIVE_PRESS_OUT',
// Responder, active, out of `PressRect`
RESPONDER_ACTIVE_LONG_PRESS_IN: 'RESPONDER_ACTIVE_LONG_PRESS_IN',
// Responder, active, in the `PressRect`, after long press threshold
RESPONDER_ACTIVE_LONG_PRESS_OUT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT',
// Responder, active, out of `PressRect`, after long press threshold
ERROR: 'ERROR'
};
/*
* Quick lookup map for states that are considered to be "active"
*/
var baseStatesConditions = {
NOT_RESPONDER: false,
RESPONDER_INACTIVE_PRESS_IN: false,
RESPONDER_INACTIVE_PRESS_OUT: false,
RESPONDER_ACTIVE_PRESS_IN: false,
RESPONDER_ACTIVE_PRESS_OUT: false,
RESPONDER_ACTIVE_LONG_PRESS_IN: false,
RESPONDER_ACTIVE_LONG_PRESS_OUT: false,
ERROR: false
};
var IsActive = _objectSpread({}, baseStatesConditions, {
RESPONDER_ACTIVE_PRESS_OUT: true,
RESPONDER_ACTIVE_PRESS_IN: true
});
/**
* Quick lookup for states that are considered to be "pressing" and are
* therefore eligible to result in a "selection" if the press stops.
*/
var IsPressingIn = _objectSpread({}, baseStatesConditions, {
RESPONDER_INACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_LONG_PRESS_IN: true
});
var IsLongPressingIn = _objectSpread({}, baseStatesConditions, {
RESPONDER_ACTIVE_LONG_PRESS_IN: true
});
/**
* Inputs to the state machine.
*/
var Signals = {
DELAY: 'DELAY',
RESPONDER_GRANT: 'RESPONDER_GRANT',
RESPONDER_RELEASE: 'RESPONDER_RELEASE',
RESPONDER_TERMINATED: 'RESPONDER_TERMINATED',
ENTER_PRESS_RECT: 'ENTER_PRESS_RECT',
LEAVE_PRESS_RECT: 'LEAVE_PRESS_RECT',
LONG_PRESS_DETECTED: 'LONG_PRESS_DETECTED'
};
/**
* Mapping from States x Signals => States
*/
var Transitions = {
NOT_RESPONDER: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.ERROR,
RESPONDER_TERMINATED: States.ERROR,
ENTER_PRESS_RECT: States.ERROR,
LEAVE_PRESS_RECT: States.ERROR,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_INACTIVE_PRESS_IN: {
DELAY: States.RESPONDER_ACTIVE_PRESS_IN,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_INACTIVE_PRESS_OUT: {
DELAY: States.RESPONDER_ACTIVE_PRESS_OUT,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_ACTIVE_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN
},
RESPONDER_ACTIVE_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_ACTIVE_LONG_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT,
LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN
},
RESPONDER_ACTIVE_LONG_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
error: {
DELAY: States.NOT_RESPONDER,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.NOT_RESPONDER,
LEAVE_PRESS_RECT: States.NOT_RESPONDER,
LONG_PRESS_DETECTED: States.NOT_RESPONDER
}
}; // ==== Typical Constants for integrating into UI components ====
// var HIT_EXPAND_PX = 20;
// var HIT_VERT_OFFSET_PX = 10;
var HIGHLIGHT_DELAY_MS = 130;
var PRESS_EXPAND_PX = 20;
var LONG_PRESS_THRESHOLD = 500;
var LONG_PRESS_DELAY_MS = LONG_PRESS_THRESHOLD - HIGHLIGHT_DELAY_MS;
var LONG_PRESS_ALLOWED_MOVEMENT = 10; // Default amount "active" region protrudes beyond box
/**
* By convention, methods prefixed with underscores are meant to be @private,
* and not @protected. Mixers shouldn't access them - not even to provide them
* as callback handlers.
*
*
* ========== Geometry =========
* `Touchable` only assumes that there exists a `HitRect` node. The `PressRect`
* is an abstract box that is extended beyond the `HitRect`.
*
* +--------------------------+
* | | - "Start" events in `HitRect` cause `HitRect`
* | +--------------------+ | to become the responder.
* | | +--------------+ | | - `HitRect` is typically expanded around
* | | | | | | the `VisualRect`, but shifted downward.
* | | | VisualRect | | | - After pressing down, after some delay,
* | | | | | | and before letting up, the Visual React
* | | +--------------+ | | will become "active". This makes it eligible
* | | HitRect | | for being highlighted (so long as the
* | +--------------------+ | press remains in the `PressRect`).
* | PressRect o |
* +----------------------|---+
* Out Region |
* +-----+ This gap between the `HitRect` and
* `PressRect` allows a touch to move far away
* from the original hit rect, and remain
* highlighted, and eligible for a "Press".
* Customize this via
* `touchableGetPressRectOffset()`.
*
*
*
* ======= State Machine =======
*
* +-------------+ <---+ RESPONDER_RELEASE
* |NOT_RESPONDER|
* +-------------+ <---+ RESPONDER_TERMINATED
* +
* | RESPONDER_GRANT (HitRect)
* v
* +---------------------------+ DELAY +-------------------------+ T + DELAY +------------------------------+
* |RESPONDER_INACTIVE_PRESS_IN|+-------->|RESPONDER_ACTIVE_PRESS_IN| +------------> |RESPONDER_ACTIVE_LONG_PRESS_IN|
* +---------------------------+ +-------------------------+ +------------------------------+
* + ^ + ^ + ^
* |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ |LEAVE_ |ENTER_
* |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT
* | | | | | |
* v + v + v +
* +----------------------------+ DELAY +--------------------------+ +-------------------------------+
* |RESPONDER_INACTIVE_PRESS_OUT|+------->|RESPONDER_ACTIVE_PRESS_OUT| |RESPONDER_ACTIVE_LONG_PRESS_OUT|
* +----------------------------+ +--------------------------+ +-------------------------------+
*
* T + DELAY => LONG_PRESS_DELAY_MS + DELAY
*
* Not drawn are the side effects of each transition. The most important side
* effect is the `touchableHandlePress` abstract method invocation that occurs
* when a responder is released while in either of the "Press" states.
*
* The other important side effects are the highlight abstract method
* invocations (internal callbacks) to be implemented by the mixer.
*
*
* @lends Touchable.prototype
*/
var TouchableMixin = {
// HACK (part 1): basic support for touchable interactions using a keyboard
componentDidMount: function componentDidMount() {
var _this = this;
this._touchableNode = findNodeHandle(this);
if (this._touchableNode && this._touchableNode.addEventListener) {
this._touchableBlurListener = function (e) {
if (_this._isTouchableKeyboardActive) {
if (_this.state.touchable.touchState && _this.state.touchable.touchState !== States.NOT_RESPONDER) {
_this.touchableHandleResponderTerminate({
nativeEvent: e
});
}
_this._isTouchableKeyboardActive = false;
}
};
this._touchableNode.addEventListener('blur', this._touchableBlurListener);
}
},
/**
* Clear all timeouts on unmount
*/
componentWillUnmount: function componentWillUnmount() {
if (this._touchableNode && this._touchableNode.addEventListener) {
this._touchableNode.removeEventListener('blur', this._touchableBlurListener);
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
},
/**
* It's prefer that mixins determine state in this way, having the class
* explicitly mix the state in the one and only `getInitialState` method.
*
* @return {object} State object to be placed inside of
* `this.state.touchable`.
*/
touchableGetInitialState: function touchableGetInitialState() {
return {
touchable: {
touchState: undefined,
responderID: null
}
};
},
// ==== Hooks to Gesture Responder system ====
/**
* Must return true if embedded in a native platform scroll view.
*/
touchableHandleResponderTerminationRequest: function touchableHandleResponderTerminationRequest() {
return !this.props.rejectResponderTermination;
},
/**
* Must return true to start the process of `Touchable`.
*/
touchableHandleStartShouldSetResponder: function touchableHandleStartShouldSetResponder() {
return !this.props.disabled;
},
/**
* Return true to cancel press on long press.
*/
touchableLongPressCancelsPress: function touchableLongPressCancelsPress() {
return true;
},
/**
* Place as callback for a DOM element's `onResponderGrant` event.
* @param {SyntheticEvent} e Synthetic event from event system.
*
*/
touchableHandleResponderGrant: function touchableHandleResponderGrant(e) {
var dispatchID = e.currentTarget; // Since e is used in a callback invoked on another event loop
// (as in setTimeout etc), we need to call e.persist() on the
// event to make sure it doesn't get reused in the event object pool.
e.persist();
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
this.pressOutDelayTimeout = null;
this.state.touchable.touchState = States.NOT_RESPONDER;
this.state.touchable.responderID = dispatchID;
this._receiveSignal(Signals.RESPONDER_GRANT, e);
var delayMS = this.touchableGetHighlightDelayMS !== undefined ? Math.max(this.touchableGetHighlightDelayMS(), 0) : HIGHLIGHT_DELAY_MS;
delayMS = isNaN(delayMS) ? HIGHLIGHT_DELAY_MS : delayMS;
if (delayMS !== 0) {
this.touchableDelayTimeout = setTimeout(this._handleDelay.bind(this, e), delayMS);
} else {
this._handleDelay(e);
}
var longDelayMS = this.touchableGetLongPressDelayMS !== undefined ? Math.max(this.touchableGetLongPressDelayMS(), 10) : LONG_PRESS_DELAY_MS;
longDelayMS = isNaN(longDelayMS) ? LONG_PRESS_DELAY_MS : longDelayMS;
this.longPressDelayTimeout = setTimeout(this._handleLongDelay.bind(this, e), longDelayMS + delayMS);
},
/**
* Place as callback for a DOM element's `onResponderRelease` event.
*/
touchableHandleResponderRelease: function touchableHandleResponderRelease(e) {
this.pressInLocation = null;
this._receiveSignal(Signals.RESPONDER_RELEASE, e);
},
/**
* Place as callback for a DOM element's `onResponderTerminate` event.
*/
touchableHandleResponderTerminate: function touchableHandleResponderTerminate(e) {
this.pressInLocation = null;
this._receiveSignal(Signals.RESPONDER_TERMINATED, e);
},
/**
* Place as callback for a DOM element's `onResponderMove` event.
*/
touchableHandleResponderMove: function touchableHandleResponderMove(e) {
// Measurement may not have returned yet.
if (!this.state.touchable.positionOnActivate) {
return;
}
var positionOnActivate = this.state.touchable.positionOnActivate;
var dimensionsOnActivate = this.state.touchable.dimensionsOnActivate;
var pressRectOffset = this.touchableGetPressRectOffset ? this.touchableGetPressRectOffset() : {
left: PRESS_EXPAND_PX,
right: PRESS_EXPAND_PX,
top: PRESS_EXPAND_PX,
bottom: PRESS_EXPAND_PX
};
var pressExpandLeft = pressRectOffset.left;
var pressExpandTop = pressRectOffset.top;
var pressExpandRight = pressRectOffset.right;
var pressExpandBottom = pressRectOffset.bottom;
var hitSlop = this.touchableGetHitSlop ? this.touchableGetHitSlop() : null;
if (hitSlop) {
pressExpandLeft += hitSlop.left || 0;
pressExpandTop += hitSlop.top || 0;
pressExpandRight += hitSlop.right || 0;
pressExpandBottom += hitSlop.bottom || 0;
}
var touch = extractSingleTouch(e.nativeEvent);
var pageX = touch && touch.pageX;
var pageY = touch && touch.pageY;
if (this.pressInLocation) {
var movedDistance = this._getDistanceBetweenPoints(pageX, pageY, this.pressInLocation.pageX, this.pressInLocation.pageY);
if (movedDistance > LONG_PRESS_ALLOWED_MOVEMENT) {
this._cancelLongPressDelayTimeout();
}
}
var isTouchWithinActive = pageX > positionOnActivate.left - pressExpandLeft && pageY > positionOnActivate.top - pressExpandTop && pageX < positionOnActivate.left + dimensionsOnActivate.width + pressExpandRight && pageY < positionOnActivate.top + dimensionsOnActivate.height + pressExpandBottom;
if (isTouchWithinActive) {
var prevState = this.state.touchable.touchState;
this._receiveSignal(Signals.ENTER_PRESS_RECT, e);
var curState = this.state.touchable.touchState;
if (curState === States.RESPONDER_INACTIVE_PRESS_IN && prevState !== States.RESPONDER_INACTIVE_PRESS_IN) {
// fix for t7967420
this._cancelLongPressDelayTimeout();
}
} else {
this._cancelLongPressDelayTimeout();
this._receiveSignal(Signals.LEAVE_PRESS_RECT, e);
}
},
/**
* Invoked when the item receives focus. Mixers might override this to
* visually distinguish the `VisualRect` so that the user knows that it
* currently has the focus. Most platforms only support a single element being
* focused at a time, in which case there may have been a previously focused
* element that was blurred just prior to this. This can be overridden when
* using `Touchable.Mixin.withoutDefaultFocusAndBlur`.
*/
touchableHandleFocus: function touchableHandleFocus(e) {
this.props.onFocus && this.props.onFocus(e);
},
/**
* Invoked when the item loses focus. Mixers might override this to
* visually distinguish the `VisualRect` so that the user knows that it
* no longer has focus. Most platforms only support a single element being
* focused at a time, in which case the focus may have moved to another.
* This can be overridden when using
* `Touchable.Mixin.withoutDefaultFocusAndBlur`.
*/
touchableHandleBlur: function touchableHandleBlur(e) {
this.props.onBlur && this.props.onBlur(e);
},
// ==== Abstract Application Callbacks ====
/**
* Invoked when the item should be highlighted. Mixers should implement this
* to visually distinguish the `VisualRect` so that the user knows that
* releasing a touch will result in a "selection" (analog to click).
*
* @abstract
* touchableHandleActivePressIn: function,
*/
/**
* Invoked when the item is "active" (in that it is still eligible to become
* a "select") but the touch has left the `PressRect`. Usually the mixer will
* want to unhighlight the `VisualRect`. If the user (while pressing) moves
* back into the `PressRect` `touchableHandleActivePressIn` will be invoked
* again and the mixer should probably highlight the `VisualRect` again. This
* event will not fire on an `touchEnd/mouseUp` event, only move events while
* the user is depressing the mouse/touch.
*
* @abstract
* touchableHandleActivePressOut: function
*/
/**
* Invoked when the item is "selected" - meaning the interaction ended by
* letting up while the item was either in the state
* `RESPONDER_ACTIVE_PRESS_IN` or `RESPONDER_INACTIVE_PRESS_IN`.
*
* @abstract
* touchableHandlePress: function
*/
/**
* Invoked when the item is long pressed - meaning the interaction ended by
* letting up while the item was in `RESPONDER_ACTIVE_LONG_PRESS_IN`. If
* `touchableHandleLongPress` is *not* provided, `touchableHandlePress` will
* be called as it normally is. If `touchableHandleLongPress` is provided, by
* default any `touchableHandlePress` callback will not be invoked. To
* override this default behavior, override `touchableLongPressCancelsPress`
* to return false. As a result, `touchableHandlePress` will be called when
* lifting up, even if `touchableHandleLongPress` has also been called.
*
* @abstract
* touchableHandleLongPress: function
*/
/**
* Returns the number of millis to wait before triggering a highlight.
*
* @abstract
* touchableGetHighlightDelayMS: function
*/
/**
* Returns the amount to extend the `HitRect` into the `PressRect`. Positive
* numbers mean the size expands outwards.
*
* @abstract
* touchableGetPressRectOffset: function
*/
// ==== Internal Logic ====
/**
* Measures the `HitRect` node on activation. The Bounding rectangle is with
* respect to viewport - not page, so adding the `pageXOffset/pageYOffset`
* should result in points that are in the same coordinate system as an
* event's `globalX/globalY` data values.
*
* - Consider caching this for the lifetime of the component, or possibly
* being able to share this cache between any `ScrollMap` view.
*
* @sideeffects
* @private
*/
_remeasureMetricsOnActivation: function _remeasureMetricsOnActivation() {
var tag = this.state.touchable.responderID;
if (tag == null) {
return;
}
UIManager.measure(tag, this._handleQueryLayout);
},
_handleQueryLayout: function _handleQueryLayout(l, t, w, h, globalX, globalY) {
//don't do anything UIManager failed to measure node
if (!l && !t && !w && !h && !globalX && !globalY) {
return;
}
this.state.touchable.positionOnActivate && Position.release(this.state.touchable.positionOnActivate);
this.state.touchable.dimensionsOnActivate && // $FlowFixMe
BoundingDimensions.release(this.state.touchable.dimensionsOnActivate);
this.state.touchable.positionOnActivate = Position.getPooled(globalX, globalY); // $FlowFixMe
this.state.touchable.dimensionsOnActivate = BoundingDimensions.getPooled(w, h);
},
_handleDelay: function _handleDelay(e) {
this.touchableDelayTimeout = null;
this._receiveSignal(Signals.DELAY, e);
},
_handleLongDelay: function _handleLongDelay(e) {
this.longPressDelayTimeout = null;
var curState = this.state.touchable.touchState;
if (curState !== States.RESPONDER_ACTIVE_PRESS_IN && curState !== States.RESPONDER_ACTIVE_LONG_PRESS_IN) {
console.error('Attempted to transition from state `' + curState + '` to `' + States.RESPONDER_ACTIVE_LONG_PRESS_IN + '`, which is not supported. This is ' + 'most likely due to `Touchable.longPressDelayTimeout` not being cancelled.');
} else {
this._receiveSignal(Signals.LONG_PRESS_DETECTED, e);
}
},
/**
* Receives a state machine signal, performs side effects of the transition
* and stores the new state. Validates the transition as well.
*
* @param {Signals} signal State machine signal.
* @throws Error if invalid state transition or unrecognized signal.
* @sideeffects
*/
_receiveSignal: function _receiveSignal(signal, e) {
var responderID = this.state.touchable.responderID;
var curState = this.state.touchable.touchState;
var nextState = Transitions[curState] && Transitions[curState][signal];
if (!responderID && signal === Signals.RESPONDER_RELEASE) {
return;
}
if (!nextState) {
throw new Error('Unrecognized signal `' + signal + '` or state `' + curState + '` for Touchable responder `' + responderID + '`');
}
if (nextState === States.ERROR) {
throw new Error('Touchable cannot transition from `' + curState + '` to `' + signal + '` for responder `' + responderID + '`');
}
if (curState !== nextState) {
this._performSideEffectsForTransition(curState, nextState, signal, e);
this.state.touchable.touchState = nextState;
}
},
_cancelLongPressDelayTimeout: function _cancelLongPressDelayTimeout() {
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.longPressDelayTimeout = null;
},
_isHighlight: function _isHighlight(state) {
return state === States.RESPONDER_ACTIVE_PRESS_IN || state === States.RESPONDER_ACTIVE_LONG_PRESS_IN;
},
_savePressInLocation: function _savePressInLocation(e) {
var touch = extractSingleTouch(e.nativeEvent);
var pageX = touch && touch.pageX;
var pageY = touch && touch.pageY;
var locationX = touch && touch.locationX;
var locationY = touch && touch.locationY;
this.pressInLocation = {
pageX: pageX,
pageY: pageY,
locationX: locationX,
locationY: locationY
};
},
_getDistanceBetweenPoints: function _getDistanceBetweenPoints(aX, aY, bX, bY) {
var deltaX = aX - bX;
var deltaY = aY - bY;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
},
/**
* Will perform a transition between touchable states, and identify any
* highlighting or unhighlighting that must be performed for this particular
* transition.
*
* @param {States} curState Current Touchable state.
* @param {States} nextState Next Touchable state.
* @param {Signal} signal Signal that triggered the transition.
* @param {Event} e Native event.
* @sideeffects
*/
_performSideEffectsForTransition: function _performSideEffectsForTransition(curState, nextState, signal, e) {
var curIsHighlight = this._isHighlight(curState);
var newIsHighlight = this._isHighlight(nextState);
var isFinalSignal = signal === Signals.RESPONDER_TERMINATED || signal === Signals.RESPONDER_RELEASE;
if (isFinalSignal) {
this._cancelLongPressDelayTimeout();
}
var isInitialTransition = curState === States.NOT_RESPONDER && nextState === States.RESPONDER_INACTIVE_PRESS_IN;
var isActiveTransition = !IsActive[curState] && IsActive[nextState];
if (isInitialTransition || isActiveTransition) {
this._remeasureMetricsOnActivation();
}
if (IsPressingIn[curState] && signal === Signals.LONG_PRESS_DETECTED) {
this.touchableHandleLongPress && this.touchableHandleLongPress(e);
}
if (newIsHighlight && !curIsHighlight) {
this._startHighlight(e);
} else if (!newIsHighlight && curIsHighlight) {
this._endHighlight(e);
}
if (IsPressingIn[curState] && signal === Signals.RESPONDER_RELEASE) {
var hasLongPressHandler = !!this.props.onLongPress;
var pressIsLongButStillCallOnPress = IsLongPressingIn[curState] && ( // We *are* long pressing.. // But either has no long handler
!hasLongPressHandler || !this.touchableLongPressCancelsPress()); // or we're told to ignore it.
var shouldInvokePress = !IsLongPressingIn[curState] || pressIsLongButStillCallOnPress;
if (shouldInvokePress && this.touchableHandlePress) {
if (!newIsHighlight && !curIsHighlight) {
// we never highlighted because of delay, but we should highlight now
this._startHighlight(e);
this._endHighlight(e);
}
this.touchableHandlePress(e);
}
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.touchableDelayTimeout = null;
},
_playTouchSound: function _playTouchSound() {
UIManager.playTouchSound();
},
_startHighlight: function _startHighlight(e) {
this._savePressInLocation(e);
this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e);
},
_endHighlight: function _endHighlight(e) {
var _this2 = this;
if (this.touchableHandleActivePressOut) {
if (this.touchableGetPressOutDelayMS && this.touchableGetPressOutDelayMS()) {
this.pressOutDelayTimeout = setTimeout(function () {
_this2.touchableHandleActivePressOut(e);
}, this.touchableGetPressOutDelayMS());
} else {
this.touchableHandleActivePressOut(e);
}
}
},
// HACK (part 2): basic support for touchable interactions using a keyboard (including
// delays and longPress)
touchableHandleKeyEvent: function touchableHandleKeyEvent(e) {
var type = e.type,
key = e.key;
if (key === 'Enter' || key === ' ') {
if (type === 'keydown') {
if (!this._isTouchableKeyboardActive) {
if (!this.state.touchable.touchState || this.state.touchable.touchState === States.NOT_RESPONDER) {
this.touchableHandleResponderGrant(e);
this._isTouchableKeyboardActive = true;
}
}
} else if (type === 'keyup') {
if (this._isTouchableKeyboardActive) {
if (this.state.touchable.touchState && this.state.touchable.touchState !== States.NOT_RESPONDER) {
this.touchableHandleResponderRelease(e);
this._isTouchableKeyboardActive = false;
}
}
}
e.stopPropagation(); // prevent the default behaviour unless the Touchable functions as a link
// and Enter is pressed
if (!(key === 'Enter' && AccessibilityUtil.propsToAriaRole(this.props) === 'link')) {
e.preventDefault();
}
}
},
withoutDefaultFocusAndBlur: {}
};
/**
* Provide an optional version of the mixin where `touchableHandleFocus` and
* `touchableHandleBlur` can be overridden. This allows appropriate defaults to
* be set on TV platforms, without breaking existing implementations of
* `Touchable`.
*/
var touchableHandleFocus = TouchableMixin.touchableHandleFocus,
touchableHandleBlur = TouchableMixin.touchableHandleBlur,
TouchableMixinWithoutDefaultFocusAndBlur = _objectWithoutPropertiesLoose(TouchableMixin, ["touchableHandleFocus", "touchableHandleBlur"]);
TouchableMixin.withoutDefaultFocusAndBlur = TouchableMixinWithoutDefaultFocusAndBlur;
var Touchable = {
Mixin: TouchableMixin,
TOUCH_TARGET_DEBUG: false,
// Highlights all touchable targets. Toggle with Inspector.
/**
* Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android).
*/
renderDebugView: function renderDebugView(_ref) {
var color = _ref.color,
hitSlop = _ref.hitSlop;
if (!Touchable.TOUCH_TARGET_DEBUG) {
return null;
}
if (process.env.NODE_ENV !== 'production') {
throw Error('Touchable.TOUCH_TARGET_DEBUG should not be enabled in prod!');
}
var debugHitSlopStyle = {};
hitSlop = hitSlop || {
top: 0,
bottom: 0,
left: 0,
right: 0
};
for (var key in hitSlop) {
debugHitSlopStyle[key] = -hitSlop[key];
}
var normalizedColor = normalizeColor(color);
if (typeof normalizedColor !== 'number') {
return null;
}
var hexColor = '#' + ('00000000' + normalizedColor.toString(16)).substr(-8);
return React.createElement(View, {
pointerEvents: "none",
style: _objectSpread({
position: 'absolute',
borderColor: hexColor.slice(0, -2) + '55',
// More opaque
borderWidth: 1,
borderStyle: 'dashed',
backgroundColor: hexColor.slice(0, -2) + '0F'
}, debugHitSlopStyle)
});
}
};
export default Touchable; |
ajax/libs/material-ui/4.9.8/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/primereact/7.0.0-rc.2/tieredmenu/tieredmenu.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, classNames, Ripple, ObjectUtils, OverlayService, ZIndexUtils, ConnectedOverlayScrollHandler, CSSTransition, Portal } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper$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 TieredMenuSub = /*#__PURE__*/function (_Component) {
_inherits(TieredMenuSub, _Component);
var _super = _createSuper$1(TieredMenuSub);
function TieredMenuSub(props) {
var _this;
_classCallCheck(this, TieredMenuSub);
_this = _super.call(this, props);
_this.state = {
activeItem: null
};
_this.onLeafClick = _this.onLeafClick.bind(_assertThisInitialized(_this));
_this.onChildItemKeyDown = _this.onChildItemKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(TieredMenuSub, [{
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.parentActive && !this.props.parentActive) {
this.setState({
activeItem: null
});
}
if (this.props.parentActive && !this.props.root) {
this.position();
}
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
if (!this.documentClickListener) {
this.documentClickListener = function (event) {
if (_this2.element && !_this2.element.contains(event.target)) {
_this2.setState({
activeItem: null
});
}
};
document.addEventListener('click', this.documentClickListener);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.documentClickListener) {
document.removeEventListener('click', this.documentClickListener);
this.documentClickListener = null;
}
}
}, {
key: "position",
value: function position() {
if (this.element) {
var parentItem = this.element.parentElement;
var containerOffset = DomHandler.getOffset(parentItem);
var viewport = DomHandler.getViewport();
var sublistWidth = this.element.offsetParent ? this.element.offsetWidth : DomHandler.getHiddenElementOuterWidth(this.element);
var itemOuterWidth = DomHandler.getOuterWidth(parentItem.children[0]);
if (parseInt(containerOffset.left, 10) + itemOuterWidth + sublistWidth > viewport.width - DomHandler.calculateScrollbarWidth()) {
DomHandler.addClass(this.element, 'p-submenu-list-flipped');
}
}
}
}, {
key: "onItemMouseEnter",
value: function onItemMouseEnter(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (this.props.root) {
if (this.state.activeItem || this.props.popup) {
this.setState({
activeItem: item
});
}
} else {
this.setState({
activeItem: item
});
}
}
}, {
key: "onItemClick",
value: function onItemClick(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (!item.url) {
event.preventDefault();
}
if (item.command) {
item.command({
originalEvent: event,
item: item
});
}
if (this.props.root) {
if (item.items) {
if (this.state.activeItem && item === this.state.activeItem) {
this.setState({
activeItem: null
});
} else {
this.setState({
activeItem: item
});
}
}
}
if (!item.items) {
this.onLeafClick();
}
}
}, {
key: "onItemKeyDown",
value: function onItemKeyDown(event, item) {
var listItem = event.currentTarget.parentElement;
switch (event.which) {
//down
case 40:
var nextItem = this.findNextItem(listItem);
if (nextItem) {
nextItem.children[0].focus();
}
event.preventDefault();
break;
//up
case 38:
var prevItem = this.findPrevItem(listItem);
if (prevItem) {
prevItem.children[0].focus();
}
event.preventDefault();
break;
//right
case 39:
if (item.items) {
this.setState({
activeItem: item
});
setTimeout(function () {
listItem.children[1].children[0].children[0].focus();
}, 50);
}
event.preventDefault();
break;
}
if (this.props.onKeyDown) {
this.props.onKeyDown(event, listItem);
}
}
}, {
key: "onChildItemKeyDown",
value: function onChildItemKeyDown(event, childListItem) {
//left
if (event.which === 37) {
this.setState({
activeItem: null
});
childListItem.parentElement.previousElementSibling.focus();
}
}
}, {
key: "findNextItem",
value: function findNextItem(item) {
var nextItem = item.nextElementSibling;
if (nextItem) return DomHandler.hasClass(nextItem, 'p-disabled') || !DomHandler.hasClass(nextItem, 'p-menuitem') ? this.findNextItem(nextItem) : nextItem;else return null;
}
}, {
key: "findPrevItem",
value: function findPrevItem(item) {
var prevItem = item.previousElementSibling;
if (prevItem) return DomHandler.hasClass(prevItem, 'p-disabled') || !DomHandler.hasClass(prevItem, 'p-menuitem') ? this.findPrevItem(prevItem) : prevItem;else return null;
}
}, {
key: "onLeafClick",
value: function onLeafClick() {
this.setState({
activeItem: null
});
if (this.props.onLeafClick) {
this.props.onLeafClick();
}
}
}, {
key: "renderSeparator",
value: function renderSeparator(index) {
return /*#__PURE__*/React.createElement("li", {
key: 'separator_' + index,
className: "p-menu-separator",
role: "separator"
});
}
}, {
key: "renderSubmenu",
value: function renderSubmenu(item) {
if (item.items) {
return /*#__PURE__*/React.createElement(TieredMenuSub, {
model: item.items,
onLeafClick: this.onLeafClick,
popup: this.props.popup,
onKeyDown: this.onChildItemKeyDown,
parentActive: item === this.state.activeItem
});
}
return null;
}
}, {
key: "renderMenuitem",
value: function renderMenuitem(item, index) {
var _this3 = this;
var active = this.state.activeItem === item;
var className = classNames('p-menuitem', {
'p-menuitem-active': active
}, item.className);
var linkClassName = classNames('p-menuitem-link', {
'p-disabled': item.disabled
});
var iconClassName = classNames('p-menuitem-icon', item.icon);
var submenuIconClassName = 'p-submenu-icon pi pi-angle-right';
var icon = item.icon && /*#__PURE__*/React.createElement("span", {
className: iconClassName
});
var label = item.label && /*#__PURE__*/React.createElement("span", {
className: "p-menuitem-text"
}, item.label);
var submenuIcon = item.items && /*#__PURE__*/React.createElement("span", {
className: submenuIconClassName
});
var submenu = this.renderSubmenu(item);
var content = /*#__PURE__*/React.createElement("a", {
href: item.url || '#',
className: linkClassName,
target: item.target,
role: "menuitem",
"aria-haspopup": item.items != null,
onClick: function onClick(event) {
return _this3.onItemClick(event, item);
},
onKeyDown: function onKeyDown(event) {
return _this3.onItemKeyDown(event, item);
},
"aria-disabled": item.disabled
}, icon, label, submenuIcon, /*#__PURE__*/React.createElement(Ripple, null));
if (item.template) {
var defaultContentOptions = {
onClick: function onClick(event) {
return _this3.onItemClick(event, item);
},
onKeyDown: function onKeyDown(event) {
return _this3.onItemKeyDown(event, item);
},
className: linkClassName,
labelClassName: 'p-menuitem-text',
iconClassName: iconClassName,
submenuIconClassName: submenuIconClassName,
element: content,
props: this.props,
active: active
};
content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions);
}
return /*#__PURE__*/React.createElement("li", {
key: item.label + '_' + index,
className: className,
style: item.style,
onMouseEnter: function onMouseEnter(event) {
return _this3.onItemMouseEnter(event, item);
},
role: "none"
}, content, submenu);
}
}, {
key: "renderItem",
value: function renderItem(item, index) {
if (item.separator) return this.renderSeparator(index);else return this.renderMenuitem(item, index);
}
}, {
key: "renderMenu",
value: function renderMenu() {
var _this4 = this;
if (this.props.model) {
return this.props.model.map(function (item, index) {
return _this4.renderItem(item, index);
});
}
return null;
}
}, {
key: "render",
value: function render() {
var _this5 = this;
var className = classNames({
'p-submenu-list': !this.props.root
});
var submenu = this.renderMenu();
return /*#__PURE__*/React.createElement("ul", {
ref: function ref(el) {
return _this5.element = el;
},
className: className,
role: this.props.root ? 'menubar' : 'menu',
"aria-orientation": "horizontal"
}, submenu);
}
}]);
return TieredMenuSub;
}(Component);
_defineProperty(TieredMenuSub, "defaultProps", {
model: null,
root: false,
className: null,
popup: false,
onLeafClick: null,
onKeyDown: null,
parentActive: false
});
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 TieredMenu = /*#__PURE__*/function (_Component) {
_inherits(TieredMenu, _Component);
var _super = _createSuper(TieredMenu);
function TieredMenu(props) {
var _this;
_classCallCheck(this, TieredMenu);
_this = _super.call(this, props);
_this.state = {
visible: !props.popup
};
_this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this));
_this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this));
_this.onExit = _this.onExit.bind(_assertThisInitialized(_this));
_this.onExited = _this.onExited.bind(_assertThisInitialized(_this));
_this.onPanelClick = _this.onPanelClick.bind(_assertThisInitialized(_this));
_this.menuRef = /*#__PURE__*/React.createRef();
return _this;
}
_createClass(TieredMenu, [{
key: "onPanelClick",
value: function onPanelClick(event) {
if (this.props.popup) {
OverlayService.emit('overlay-click', {
originalEvent: event,
target: this.target
});
}
}
}, {
key: "toggle",
value: function toggle(event) {
if (this.props.popup) {
if (this.state.visible) this.hide(event);else this.show(event);
}
}
}, {
key: "show",
value: function show(event) {
var _this2 = this;
this.target = event.currentTarget;
var currentEvent = event;
this.setState({
visible: true
}, function () {
if (_this2.props.onShow) {
_this2.props.onShow(currentEvent);
}
});
}
}, {
key: "hide",
value: function hide(event) {
var _this3 = this;
var currentEvent = event;
this.setState({
visible: false
}, function () {
if (_this3.props.onHide) {
_this3.props.onHide(currentEvent);
}
});
}
}, {
key: "onEnter",
value: function onEnter() {
if (this.props.autoZIndex) {
ZIndexUtils.set('menu', this.menuRef.current, this.props.baseZIndex);
}
DomHandler.absolutePosition(this.menuRef.current, this.target);
}
}, {
key: "onEntered",
value: function onEntered() {
this.bindDocumentListeners();
this.bindScrollListener();
}
}, {
key: "onExit",
value: function onExit() {
this.target = null;
this.unbindDocumentListeners();
this.unbindScrollListener();
}
}, {
key: "onExited",
value: function onExited() {
ZIndexUtils.clear(this.menuRef.current);
}
}, {
key: "bindDocumentListeners",
value: function bindDocumentListeners() {
this.bindDocumentClickListener();
this.bindDocumentResizeListener();
}
}, {
key: "unbindDocumentListeners",
value: function unbindDocumentListeners() {
this.unbindDocumentClickListener();
this.unbindDocumentResizeListener();
}
}, {
key: "bindDocumentClickListener",
value: function bindDocumentClickListener() {
var _this4 = this;
if (!this.documentClickListener) {
this.documentClickListener = function (event) {
if (_this4.props.popup && _this4.state.visible && _this4.menuRef.current && !_this4.menuRef.current.contains(event.target)) {
_this4.hide(event);
}
};
document.addEventListener('click', this.documentClickListener);
}
}
}, {
key: "unbindDocumentClickListener",
value: function unbindDocumentClickListener() {
if (this.documentClickListener) {
document.removeEventListener('click', this.documentClickListener);
this.documentClickListener = null;
}
}
}, {
key: "bindDocumentResizeListener",
value: function bindDocumentResizeListener() {
var _this5 = this;
if (!this.documentResizeListener) {
this.documentResizeListener = function (event) {
if (_this5.state.visible && !DomHandler.isAndroid()) {
_this5.hide(event);
}
};
window.addEventListener('resize', this.documentResizeListener);
}
}
}, {
key: "unbindDocumentResizeListener",
value: function unbindDocumentResizeListener() {
if (this.documentResizeListener) {
window.removeEventListener('resize', this.documentResizeListener);
this.documentResizeListener = null;
}
}
}, {
key: "bindScrollListener",
value: function bindScrollListener() {
var _this6 = this;
if (!this.scrollHandler) {
this.scrollHandler = new ConnectedOverlayScrollHandler(this.target, function (event) {
if (_this6.state.visible) {
_this6.hide(event);
}
});
}
this.scrollHandler.bindScrollListener();
}
}, {
key: "unbindScrollListener",
value: function unbindScrollListener() {
if (this.scrollHandler) {
this.scrollHandler.unbindScrollListener();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.unbindDocumentListeners();
if (this.scrollHandler) {
this.scrollHandler.destroy();
this.scrollHandler = null;
}
ZIndexUtils.clear(this.menuRef.current);
}
}, {
key: "renderElement",
value: function renderElement() {
var className = classNames('p-tieredmenu p-component', {
'p-tieredmenu-overlay': this.props.popup
}, this.props.className);
return /*#__PURE__*/React.createElement(CSSTransition, {
nodeRef: this.menuRef,
classNames: "p-connected-overlay",
in: this.state.visible,
timeout: {
enter: 120,
exit: 100
},
options: this.props.transitionOptions,
unmountOnExit: true,
onEnter: this.onEnter,
onEntered: this.onEntered,
onExit: this.onExit,
onExited: this.onExited
}, /*#__PURE__*/React.createElement("div", {
ref: this.menuRef,
id: this.props.id,
className: className,
style: this.props.style,
onClick: this.onPanelClick
}, /*#__PURE__*/React.createElement(TieredMenuSub, {
model: this.props.model,
root: true,
popup: this.props.popup
})));
}
}, {
key: "render",
value: function render() {
var element = this.renderElement();
return this.props.popup ? /*#__PURE__*/React.createElement(Portal, {
element: element,
appendTo: this.props.appendTo
}) : element;
}
}]);
return TieredMenu;
}(Component);
_defineProperty(TieredMenu, "defaultProps", {
id: null,
model: null,
popup: false,
style: null,
className: null,
autoZIndex: true,
baseZIndex: 0,
appendTo: null,
transitionOptions: null,
onShow: null,
onHide: null
});
export { TieredMenu };
|
ajax/libs/material-ui/4.9.4/es/Slide/Slide.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 ReactDOM from 'react-dom';
import debounce from '../utils/debounce';
import { Transition } from 'react-transition-group';
import { elementAcceptingRef } from '@material-ui/utils';
import useForkRef from '../utils/useForkRef';
import useTheme from '../styles/useTheme';
import { duration } from '../styles/transitions';
import { reflow, getTransitionProps } from '../transitions/utils'; // Translate the node so he can't be seen on the screen.
// Later, we gonna translate back the node to his original location
// with `none`.`
function getTranslateValue(direction, node) {
const rect = node.getBoundingClientRect();
let transform;
if (node.fakeTransform) {
transform = node.fakeTransform;
} else {
const computedStyle = window.getComputedStyle(node);
transform = computedStyle.getPropertyValue('-webkit-transform') || computedStyle.getPropertyValue('transform');
}
let offsetX = 0;
let offsetY = 0;
if (transform && transform !== 'none' && typeof transform === 'string') {
const transformValues = transform.split('(')[1].split(')')[0].split(',');
offsetX = parseInt(transformValues[4], 10);
offsetY = parseInt(transformValues[5], 10);
}
if (direction === 'left') {
return `translateX(${window.innerWidth}px) translateX(-${rect.left - offsetX}px)`;
}
if (direction === 'right') {
return `translateX(-${rect.left + rect.width - offsetX}px)`;
}
if (direction === 'up') {
return `translateY(${window.innerHeight}px) translateY(-${rect.top - offsetY}px)`;
} // direction === 'down'
return `translateY(-${rect.top + rect.height - offsetY}px)`;
}
export function setTranslateValue(direction, node) {
const transform = getTranslateValue(direction, node);
if (transform) {
node.style.webkitTransform = transform;
node.style.transform = transform;
}
}
const defaultTimeout = {
enter: duration.enteringScreen,
exit: duration.leavingScreen
};
/**
* The Slide transition is used by the [Drawer](/components/drawers/) component.
* It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
*/
const Slide = React.forwardRef(function Slide(props, ref) {
const {
children,
direction = 'down',
in: inProp,
onEnter,
onEntering,
onExit,
onExited,
style,
timeout = defaultTimeout
} = props,
other = _objectWithoutPropertiesLoose(props, ["children", "direction", "in", "onEnter", "onEntering", "onExit", "onExited", "style", "timeout"]);
const theme = useTheme();
const childrenRef = React.useRef(null);
/**
* used in cloneElement(children, { ref: handleRef })
*/
const handleOwnRef = React.useCallback(instance => {
// #StrictMode ready
childrenRef.current = ReactDOM.findDOMNode(instance);
}, []);
const handleRefIntermediary = useForkRef(children.ref, handleOwnRef);
const handleRef = useForkRef(handleRefIntermediary, ref);
const handleEnter = (_, isAppearing) => {
const node = childrenRef.current;
setTranslateValue(direction, node);
reflow(node);
if (onEnter) {
onEnter(node, isAppearing);
}
};
const handleEntering = (_, isAppearing) => {
const node = childrenRef.current;
const transitionProps = getTransitionProps({
timeout,
style
}, {
mode: 'enter'
});
node.style.webkitTransition = theme.transitions.create('-webkit-transform', _extends({}, transitionProps, {
easing: theme.transitions.easing.easeOut
}));
node.style.transition = theme.transitions.create('transform', _extends({}, transitionProps, {
easing: theme.transitions.easing.easeOut
}));
node.style.webkitTransform = 'none';
node.style.transform = 'none';
if (onEntering) {
onEntering(node, isAppearing);
}
};
const handleExit = () => {
const node = childrenRef.current;
const transitionProps = getTransitionProps({
timeout,
style
}, {
mode: 'exit'
});
node.style.webkitTransition = theme.transitions.create('-webkit-transform', _extends({}, transitionProps, {
easing: theme.transitions.easing.sharp
}));
node.style.transition = theme.transitions.create('transform', _extends({}, transitionProps, {
easing: theme.transitions.easing.sharp
}));
setTranslateValue(direction, node);
if (onExit) {
onExit(node);
}
};
const handleExited = () => {
const node = childrenRef.current; // No need for transitions when the component is hidden
node.style.webkitTransition = '';
node.style.transition = '';
if (onExited) {
onExited(node);
}
};
const updatePosition = React.useCallback(() => {
if (childrenRef.current) {
setTranslateValue(direction, childrenRef.current);
}
}, [direction]);
React.useEffect(() => {
// Skip configuration where the position is screen size invariant.
if (inProp || direction === 'down' || direction === 'right') {
return undefined;
}
const handleResize = debounce(() => {
if (childrenRef.current) {
setTranslateValue(direction, childrenRef.current);
}
});
window.addEventListener('resize', handleResize);
return () => {
handleResize.clear();
window.removeEventListener('resize', handleResize);
};
}, [direction, inProp]);
React.useEffect(() => {
if (!inProp) {
// We need to update the position of the drawer when the direction change and
// when it's hidden.
updatePosition();
}
}, [inProp, updatePosition]);
return React.createElement(Transition, _extends({
onEnter: handleEnter,
onEntering: handleEntering,
onExit: handleExit,
onExited: handleExited,
appear: true,
in: inProp,
timeout: timeout
}, other), (state, childProps) => {
return React.cloneElement(children, _extends({
ref: handleRef,
style: _extends({
visibility: state === 'exited' && !inProp ? 'hidden' : undefined
}, style, {}, children.props.style)
}, childProps));
});
});
process.env.NODE_ENV !== "production" ? Slide.propTypes = {
/**
* A single child content element.
*/
children: elementAcceptingRef,
/**
* Direction the child node will enter from.
*/
direction: PropTypes.oneOf(['left', 'right', 'up', 'down']),
/**
* If `true`, show the component; triggers the enter or exit animation.
*/
in: PropTypes.bool,
/**
* @ignore
*/
onEnter: PropTypes.func,
/**
* @ignore
*/
onEntering: PropTypes.func,
/**
* @ignore
*/
onExit: PropTypes.func,
/**
* @ignore
*/
onExited: PropTypes.func,
/**
* @ignore
*/
style: PropTypes.object,
/**
* The duration for the transition, in milliseconds.
* You may specify a single timeout for all transitions, or individually with an object.
*/
timeout: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
enter: PropTypes.number,
exit: PropTypes.number
})])
} : void 0;
export default Slide; |
ajax/libs/material-ui/5.0.0-alpha.22/modern/utils/createSvgIcon.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import SvgIcon from '../SvgIcon';
/**
* Private module reserved for @material-ui packages.
*/
export default function createSvgIcon(path, displayName) {
const Component = (props, ref) => /*#__PURE__*/React.createElement(SvgIcon, _extends({
"data-testid": `${displayName}Icon`,
ref: ref
}, props), path);
if (process.env.NODE_ENV !== 'production') {
// Need to set `displayName` on the inner component for React.memo.
// React prior to 16.14 ignores `displayName` on the wrapper.
Component.displayName = `${displayName}Icon`;
}
Component.muiName = SvgIcon.muiName;
return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component));
} |
ajax/libs/react-native-web/0.16.0/exports/YellowBox/index.js | cdnjs/cdnjs | /**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import React from 'react';
import UnimplementedView from '../../modules/UnimplementedView';
function YellowBox(props) {
return /*#__PURE__*/React.createElement(UnimplementedView, props);
}
YellowBox.ignoreWarnings = function () {};
export default YellowBox; |
ajax/libs/material-ui/4.9.4/es/Switch/Switch.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
// @inheritedComponent IconButton
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { refType } from '@material-ui/utils';
import withStyles from '../styles/withStyles';
import { fade } from '../styles/colorManipulator';
import capitalize from '../utils/capitalize';
import SwitchBase from '../internal/SwitchBase';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
display: 'inline-flex',
width: 34 + 12 * 2,
height: 14 + 12 * 2,
overflow: 'hidden',
padding: 12,
boxSizing: 'border-box',
position: 'relative',
flexShrink: 0,
zIndex: 0,
// Reset the stacking context.
verticalAlign: 'middle' // For correct alignment with the text.
},
/* Styles applied to the root element if `edge="start"`. */
edgeStart: {
marginLeft: -8
},
/* Styles applied to the root element if `edge="end"`. */
edgeEnd: {
marginRight: -8
},
/* Styles applied to the internal `SwitchBase` component's `root` class. */
switchBase: {
position: 'absolute',
top: 0,
left: 0,
zIndex: 1,
// Render above the focus ripple.
color: theme.palette.type === 'light' ? theme.palette.grey[50] : theme.palette.grey[400],
transition: theme.transitions.create(['left', 'transform'], {
duration: theme.transitions.duration.shortest
}),
'&$checked': {
transform: 'translateX(20px)'
},
'&$disabled': {
color: theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[800]
},
'&$checked + $track': {
opacity: 0.5
},
'&$disabled + $track': {
opacity: theme.palette.type === 'light' ? 0.12 : 0.1
}
},
/* Styles applied to the internal SwitchBase component's root element if `color="primary"`. */
colorPrimary: {
'&$checked': {
color: theme.palette.primary.main,
'&:hover': {
backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity),
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
},
'&$disabled': {
color: theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[800]
},
'&$checked + $track': {
backgroundColor: theme.palette.primary.main
},
'&$disabled + $track': {
backgroundColor: theme.palette.type === 'light' ? theme.palette.common.black : theme.palette.common.white
}
},
/* Styles applied to the internal SwitchBase component's root element if `color="secondary"`. */
colorSecondary: {
'&$checked': {
color: theme.palette.secondary.main,
'&:hover': {
backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
},
'&$disabled': {
color: theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[800]
},
'&$checked + $track': {
backgroundColor: theme.palette.secondary.main
},
'&$disabled + $track': {
backgroundColor: theme.palette.type === 'light' ? theme.palette.common.black : theme.palette.common.white
}
},
/* Styles applied to the root element if `size="small"`. */
sizeSmall: {
width: 40,
height: 24,
padding: 7,
'& $thumb': {
width: 16,
height: 16
},
'& $switchBase': {
padding: 4,
'&$checked': {
transform: 'translateX(16px)'
}
}
},
/* Pseudo-class applied to the internal `SwitchBase` component's `checked` class. */
checked: {},
/* Pseudo-class applied to the internal SwitchBase component's disabled class. */
disabled: {},
/* Styles applied to the internal SwitchBase component's input element. */
input: {
left: '-100%',
width: '300%'
},
/* Styles used to create the thumb passed to the internal `SwitchBase` component `icon` prop. */
thumb: {
boxShadow: theme.shadows[1],
backgroundColor: 'currentColor',
width: 20,
height: 20,
borderRadius: '50%'
},
/* Styles applied to the track element. */
track: {
height: '100%',
width: '100%',
borderRadius: 14 / 2,
zIndex: -1,
transition: theme.transitions.create(['opacity', 'background-color'], {
duration: theme.transitions.duration.shortest
}),
backgroundColor: theme.palette.type === 'light' ? theme.palette.common.black : theme.palette.common.white,
opacity: theme.palette.type === 'light' ? 0.38 : 0.3
}
});
const Switch = React.forwardRef(function Switch(props, ref) {
const {
classes,
className,
color = 'secondary',
edge = false,
size = 'medium'
} = props,
other = _objectWithoutPropertiesLoose(props, ["classes", "className", "color", "edge", "size"]);
const icon = React.createElement("span", {
className: classes.thumb
});
return React.createElement("span", {
className: clsx(classes.root, className, {
'start': classes.edgeStart,
'end': classes.edgeEnd
}[edge], size === "small" && classes[`size${capitalize(size)}`])
}, React.createElement(SwitchBase, _extends({
type: "checkbox",
icon: icon,
checkedIcon: icon,
classes: {
root: clsx(classes.switchBase, classes[`color${capitalize(color)}`]),
input: classes.input,
checked: classes.checked,
disabled: classes.disabled
},
ref: ref
}, other)), React.createElement("span", {
className: classes.track
}));
});
process.env.NODE_ENV !== "production" ? Switch.propTypes = {
/**
* If `true`, the component is checked.
*/
checked: PropTypes.bool,
/**
* The icon to display when the component is checked.
*/
checkedIcon: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @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', 'default']),
/**
* @ignore
*/
defaultChecked: PropTypes.bool,
/**
* If `true`, the switch will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the ripple effect will be disabled.
*/
disableRipple: PropTypes.bool,
/**
* If given, uses a negative margin to counteract the padding on one
* side (this is often helpful for aligning the left or right
* side of the icon with content above or below, without ruining the border
* size and shape).
*/
edge: PropTypes.oneOf(['start', 'end', false]),
/**
* The icon to display when the component is unchecked.
*/
icon: PropTypes.node,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
*/
inputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* Callback fired when the state is changed.
*
* @param {object} event The event source of the callback.
* You can pull out the new checked state by accessing `event.target.checked` (boolean).
*/
onChange: PropTypes.func,
/**
* If `true`, the `input` element will be required.
*/
required: PropTypes.bool,
/**
* The size of the switch.
* `small` is equivalent to the dense switch styling.
*/
size: PropTypes.oneOf(['small', 'medium']),
/**
* The input component prop `type`.
*/
type: PropTypes.string,
/**
* The value of the component. The DOM API casts this to a string.
*/
value: PropTypes.any
} : void 0;
export default withStyles(styles, {
name: 'MuiSwitch'
})(Switch); |
ajax/libs/material-ui/5.0.0-alpha.17/modern/utils/createSvgIcon.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import SvgIcon from '../SvgIcon';
/**
* Private module reserved for @material-ui packages.
*/
export default function createSvgIcon(path, displayName) {
const Component = (props, ref) => /*#__PURE__*/React.createElement(SvgIcon, _extends({
"data-testid": `${displayName}Icon`,
ref: ref
}, props), path);
if (process.env.NODE_ENV !== 'production') {
// Need to set `displayName` on the inner component for React.memo.
// React prior to 16.14 ignores `displayName` on the wrapper.
Component.displayName = `${displayName}Icon`;
}
Component.muiName = SvgIcon.muiName;
return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component));
} |
ajax/libs/react-native-web/0.14.0/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/boardgame-io/0.50.0-alpha.1/esm/react-native.js | cdnjs/cdnjs | import 'nanoid/non-secure';
import { _ as _inherits, a as _createSuper, b as _createClass, c as _defineProperty, d as _classCallCheck, e as _objectWithoutProperties, f as _objectSpread2 } from './Debug-cc60d8e3.js';
import 'redux';
import './turn-order-8cc4909b.js';
import 'immer';
import './plugin-random-087f861e.js';
import 'lodash.isplainobject';
import './reducer-9b2fe64d.js';
import 'rfc6902';
import './initialize-cd2104ba.js';
import './transport-ce07b771.js';
import { C as Client$1 } from './client-44b09176.js';
import 'flatted';
import 'setimmediate';
import './ai-f5285565.js';
import React from 'react';
import PropTypes from 'prop-types';
var _excluded = ["matchID", "playerID"];
/**
* Client
*
* boardgame.io React Native client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React Native component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE.
*/
function Client(opts) {
var _class, _temp;
var game = opts.game,
numPlayers = opts.numPlayers,
board = opts.board,
multiplayer = opts.multiplayer,
enhancer = opts.enhancer;
var loading = opts.loading; // Component that is displayed before the client has synced
// with the game master.
if (loading === undefined) {
var Loading = function Loading() {
return /*#__PURE__*/React.createElement(React.Fragment, null);
};
loading = Loading;
}
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _temp = _class = /*#__PURE__*/function (_React$Component) {
_inherits(WrappedBoard, _React$Component);
var _super = _createSuper(WrappedBoard);
function WrappedBoard(props) {
var _this;
_classCallCheck(this, WrappedBoard);
_this = _super.call(this, props);
_this.client = Client$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();
if (state === null) {
return /*#__PURE__*/React.createElement(loading);
}
var _this$props = this.props,
matchID = _this$props.matchID,
playerID = _this$props.playerID,
rest = _objectWithoutProperties(_this$props, _excluded);
if (board) {
_board = /*#__PURE__*/React.createElement(board, _objectSpread2(_objectSpread2(_objectSpread2({}, state), rest), {}, {
matchID: matchID,
playerID: playerID,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
step: this.client.step,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages
}));
}
return _board;
}
}]);
return WrappedBoard;
}(React.Component), _defineProperty(_class, "propTypes", {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string
}), _defineProperty(_class, "defaultProps", {
matchID: 'default',
playerID: null,
credentials: null
}), _temp;
}
export { Client };
|
ajax/libs/react-native-web/0.0.0-3326aab2/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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import createReactClass from 'create-react-class';
import dismissKeyboard from '../../modules/dismissKeyboard';
import invariant from 'fbjs/lib/invariant';
import mergeRefs from '../../modules/mergeRefs';
import ScrollResponder from '../../modules/ScrollResponder';
import ScrollViewBase from './ScrollViewBase';
import StyleSheet from '../StyleSheet';
import View from '../View';
import React from 'react';
var emptyObject = {};
/* eslint-disable react/prefer-es6-class */
var ScrollView = createReactClass({
displayName: "ScrollView",
mixins: [ScrollResponder.Mixin],
getInitialState: function getInitialState() {
return this.scrollResponderMixinGetInitialState();
},
flashScrollIndicators: function flashScrollIndicators() {
this.scrollResponderFlashScrollIndicators();
},
/**
* Returns a reference to the underlying scroll responder, which supports
* operations like `scrollTo`. All ScrollView-like components should
* implement this method so that they can be composed while providing access
* to the underlying scroll responder's methods.
*/
getScrollResponder: function getScrollResponder() {
return this;
},
getScrollableNode: function getScrollableNode() {
return this._scrollNodeRef;
},
getInnerViewRef: function getInnerViewRef() {
return this._innerViewRef;
},
getInnerViewNode: function getInnerViewNode() {
return this._innerViewRef;
},
getNativeScrollRef: function getNativeScrollRef() {
return this._scrollNodeRef;
},
/**
* Scrolls to a given x, y offset, either immediately or with a smooth animation.
* Syntax:
*
* scrollTo(options: {x: number = 0; y: number = 0; animated: boolean = true})
*
* Note: The weird argument signature is due to the fact that, for historical reasons,
* the function also accepts separate arguments as as alternative to the options object.
* This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.
*/
scrollTo: function scrollTo(y, x, animated) {
if (typeof y === 'number') {
console.warn('`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, animated: true})` instead.');
} else {
var _ref = y || emptyObject;
x = _ref.x;
y = _ref.y;
animated = _ref.animated;
}
this.getScrollResponder().scrollResponderScrollTo({
x: x || 0,
y: y || 0,
animated: animated !== false
});
},
/**
* If this is a vertical ScrollView scrolls to the bottom.
* If this is a horizontal ScrollView scrolls to the right.
*
* Use `scrollToEnd({ animated: true })` for smooth animated scrolling,
* `scrollToEnd({ animated: false })` for immediate scrolling.
* If no options are passed, `animated` defaults to true.
*/
scrollToEnd: function scrollToEnd(options) {
// Default to true
var animated = (options && options.animated) !== false;
var horizontal = this.props.horizontal;
var scrollResponder = this.getScrollResponder();
var scrollResponderNode = scrollResponder.scrollResponderGetScrollableNode();
var x = horizontal ? scrollResponderNode.scrollWidth : 0;
var y = horizontal ? 0 : scrollResponderNode.scrollHeight;
scrollResponder.scrollResponderScrollTo({
x: x,
y: y,
animated: animated
});
},
render: function render() {
var _this$props = this.props,
contentContainerStyle = _this$props.contentContainerStyle,
horizontal = _this$props.horizontal,
onContentSizeChange = _this$props.onContentSizeChange,
refreshControl = _this$props.refreshControl,
stickyHeaderIndices = _this$props.stickyHeaderIndices,
pagingEnabled = _this$props.pagingEnabled,
forwardedRef = _this$props.forwardedRef,
keyboardDismissMode = _this$props.keyboardDismissMode,
onScroll = _this$props.onScroll,
other = _objectWithoutPropertiesLoose(_this$props, ["contentContainerStyle", "horizontal", "onContentSizeChange", "refreshControl", "stickyHeaderIndices", "pagingEnabled", "forwardedRef", "keyboardDismissMode", "onScroll"]);
if (process.env.NODE_ENV !== 'production' && this.props.style) {
var style = StyleSheet.flatten(this.props.style);
var childLayoutProps = ['alignItems', 'justifyContent'].filter(function (prop) {
return style && style[prop] !== undefined;
});
invariant(childLayoutProps.length === 0, "ScrollView child layout (" + JSON.stringify(childLayoutProps) + ") " + 'must be applied through the contentContainerStyle prop.');
}
var contentSizeChangeProps = {};
if (onContentSizeChange) {
contentSizeChangeProps = {
onLayout: this._handleContentOnLayout
};
}
var hasStickyHeaderIndices = !horizontal && Array.isArray(stickyHeaderIndices);
var children = hasStickyHeaderIndices || pagingEnabled ? React.Children.map(this.props.children, function (child, i) {
var isSticky = hasStickyHeaderIndices && stickyHeaderIndices.indexOf(i) > -1;
if (child != null && (isSticky || pagingEnabled)) {
return /*#__PURE__*/React.createElement(View, {
style: StyleSheet.compose(isSticky && styles.stickyHeader, pagingEnabled && styles.pagingEnabledChild)
}, child);
} else {
return child;
}
}) : this.props.children;
var contentContainer = /*#__PURE__*/React.createElement(View, _extends({}, contentSizeChangeProps, {
children: children,
collapsable: false,
ref: this._setInnerViewRef,
style: StyleSheet.compose(horizontal && styles.contentContainerHorizontal, contentContainerStyle)
}));
var baseStyle = horizontal ? styles.baseHorizontal : styles.baseVertical;
var pagingEnabledStyle = horizontal ? styles.pagingEnabledHorizontal : styles.pagingEnabledVertical;
var props = _objectSpread(_objectSpread({}, other), {}, {
style: [baseStyle, pagingEnabled && pagingEnabledStyle, this.props.style],
onTouchStart: this.scrollResponderHandleTouchStart,
onTouchMove: this.scrollResponderHandleTouchMove,
onTouchEnd: this.scrollResponderHandleTouchEnd,
onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag,
onScrollEndDrag: this.scrollResponderHandleScrollEndDrag,
onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin,
onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd,
onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder,
onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture,
onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder,
onScroll: this._handleScroll,
onResponderGrant: this.scrollResponderHandleResponderGrant,
onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest,
onResponderTerminate: this.scrollResponderHandleTerminate,
onResponderRelease: this.scrollResponderHandleResponderRelease,
onResponderReject: this.scrollResponderHandleResponderReject
});
var ScrollViewClass = ScrollViewBase;
invariant(ScrollViewClass !== undefined, 'ScrollViewClass must not be undefined');
var scrollView = /*#__PURE__*/React.createElement(ScrollViewClass, _extends({}, props, {
ref: this._setScrollNodeRef
}), contentContainer);
if (refreshControl) {
return /*#__PURE__*/React.cloneElement(refreshControl, {
style: props.style
}, scrollView);
}
return scrollView;
},
_handleContentOnLayout: function _handleContentOnLayout(e) {
var _e$nativeEvent$layout = e.nativeEvent.layout,
width = _e$nativeEvent$layout.width,
height = _e$nativeEvent$layout.height;
this.props.onContentSizeChange(width, height);
},
_handleScroll: function _handleScroll(e) {
if (process.env.NODE_ENV !== 'production') {
if (this.props.onScroll && this.props.scrollEventThrottle == null) {
console.log('You specified `onScroll` on a <ScrollView> but not ' + '`scrollEventThrottle`. You will only receive one event. ' + 'Using `16` you get all the events but be aware that it may ' + "cause frame drops, use a bigger number if you don't need as " + 'much precision.');
}
}
if (this.props.keyboardDismissMode === 'on-drag') {
dismissKeyboard();
}
this.scrollResponderHandleScroll(e);
},
_setInnerViewRef: function _setInnerViewRef(node) {
this._innerViewRef = node;
},
_setScrollNodeRef: function _setScrollNodeRef(node) {
this._scrollNodeRef = node; // ScrollView needs to add more methods to the hostNode in addition to those
// added by `usePlatformMethods`. This is temporarily until an API like
// `ScrollView.scrollTo(hostNode, { x, y })` is added to React Native.
if (node != null) {
node.getScrollResponder = this.getScrollResponder;
node.getInnerViewNode = this.getInnerViewNode;
node.getInnerViewRef = this.getInnerViewRef;
node.getNativeScrollRef = this.getNativeScrollRef;
node.getScrollableNode = this.getScrollableNode;
node.scrollTo = this.scrollTo;
node.scrollToEnd = this.scrollToEnd;
node.flashScrollIndicators = this.flashScrollIndicators;
node.scrollResponderZoomTo = this.scrollResponderZoomTo;
node.scrollResponderScrollNativeHandleToKeyboard = this.scrollResponderScrollNativeHandleToKeyboard;
}
var ref = mergeRefs(this.props.forwardedRef);
ref(node);
}
});
var commonStyle = {
flexGrow: 1,
flexShrink: 1,
// Enable hardware compositing in modern browsers.
// Creates a new layer with its own backing surface that can significantly
// improve scroll performance.
transform: [{
translateZ: 0
}],
// iOS native scrolling
WebkitOverflowScrolling: 'touch'
};
var styles = StyleSheet.create({
baseVertical: _objectSpread(_objectSpread({}, commonStyle), {}, {
flexDirection: 'column',
overflowX: 'hidden',
overflowY: 'auto'
}),
baseHorizontal: _objectSpread(_objectSpread({}, commonStyle), {}, {
flexDirection: 'row',
overflowX: 'auto',
overflowY: 'hidden'
}),
contentContainerHorizontal: {
flexDirection: 'row'
},
stickyHeader: {
position: 'sticky',
top: 0,
zIndex: 10
},
pagingEnabledHorizontal: {
scrollSnapType: 'x mandatory'
},
pagingEnabledVertical: {
scrollSnapType: 'y mandatory'
},
pagingEnabledChild: {
scrollSnapAlign: 'start'
}
});
var ForwardedScrollView = /*#__PURE__*/React.forwardRef(function (props, forwardedRef) {
return /*#__PURE__*/React.createElement(ScrollView, _extends({}, props, {
forwardedRef: forwardedRef
}));
});
ForwardedScrollView.displayName = 'ScrollView';
export default ForwardedScrollView; |
ajax/libs/primereact/6.6.0-rc.1/speeddial/speeddial.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { Button } from 'primereact/button';
import { DomHandler, classNames, ObjectUtils, Ripple } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
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 SpeedDial = /*#__PURE__*/function (_Component) {
_inherits(SpeedDial, _Component);
var _super = _createSuper(SpeedDial);
function SpeedDial(props) {
var _this;
_classCallCheck(this, SpeedDial);
_this = _super.call(this, props);
_this.state = {
visible: false
};
_this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
_this.onItemClick = _this.onItemClick.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(SpeedDial, [{
key: "isVisible",
value: function isVisible() {
return this.props.onVisibleChange ? this.props.visible : this.state.visible;
}
}, {
key: "show",
value: function show() {
if (this.props.onVisibleChange) {
this.props.onVisibleChange(true);
} else {
this.setState({
visible: true
});
}
this.props.onShow && this.props.onShow();
}
}, {
key: "hide",
value: function hide() {
if (this.props.onVisibleChange) {
this.props.onVisibleChange(false);
} else {
this.setState({
visible: false
});
}
this.props.onHide && this.props.onHide();
}
}, {
key: "onClick",
value: function onClick(e) {
this.isVisible() ? this.hide() : this.show();
this.props.onClick && this.props.onClick(e);
this.isItemClicked = true;
}
}, {
key: "onItemClick",
value: function onItemClick(e, item) {
if (item.command) {
item.command({
originalEvent: e,
item: item
});
}
this.hide();
this.isItemClicked = true;
e.preventDefault();
}
}, {
key: "bindDocumentClickListener",
value: function bindDocumentClickListener() {
var _this2 = this;
if (!this.documentClickListener) {
this.documentClickListener = function (event) {
if (_this2.isVisible() && _this2.isOutsideClicked(event)) {
_this2.hide();
}
_this2.isItemClicked = false;
};
document.addEventListener('click', this.documentClickListener);
}
}
}, {
key: "unbindDocumentClickListener",
value: function unbindDocumentClickListener() {
if (this.documentClickListener) {
document.removeEventListener('click', this.documentClickListener);
this.documentClickListener = null;
}
}
}, {
key: "isOutsideClicked",
value: function isOutsideClicked(event) {
return this.container && !(this.container.isSameNode(event.target) || this.container.contains(event.target) || this.isItemClicked);
}
}, {
key: "calculateTransitionDelay",
value: function calculateTransitionDelay(index) {
var length = this.props.model.length;
var visible = this.isVisible();
return (visible ? index : length - index - 1) * this.props.transitionDelay;
}
}, {
key: "calculatePointStyle",
value: function calculatePointStyle(index) {
var type = this.props.type;
if (type !== 'linear') {
var length = this.props.model.length;
var radius = this.props.radius || length * 20;
if (type === 'circle') {
var step = 2 * Math.PI / length;
return {
left: "calc(".concat(radius * Math.cos(step * index), "px + var(--item-diff-x, 0px))"),
top: "calc(".concat(radius * Math.sin(step * index), "px + var(--item-diff-y, 0px))")
};
} else if (type === 'semi-circle') {
var direction = this.props.direction;
var _step = Math.PI / (length - 1);
var x = "calc(".concat(radius * Math.cos(_step * index), "px + var(--item-diff-x, 0px))");
var y = "calc(".concat(radius * Math.sin(_step * index), "px + var(--item-diff-y, 0px))");
if (direction === 'up') {
return {
left: x,
bottom: y
};
} else if (direction === 'down') {
return {
left: x,
top: y
};
} else if (direction === 'left') {
return {
right: y,
top: x
};
} else if (direction === 'right') {
return {
left: y,
top: x
};
}
} else if (type === 'quarter-circle') {
var _direction = this.props.direction;
var _step2 = Math.PI / (2 * (length - 1));
var _x = "calc(".concat(radius * Math.cos(_step2 * index), "px + var(--item-diff-x, 0px))");
var _y = "calc(".concat(radius * Math.sin(_step2 * index), "px + var(--item-diff-y, 0px))");
if (_direction === 'up-left') {
return {
right: _x,
bottom: _y
};
} else if (_direction === 'up-right') {
return {
left: _x,
bottom: _y
};
} else if (_direction === 'down-left') {
return {
right: _y,
top: _x
};
} else if (_direction === 'down-right') {
return {
left: _y,
top: _x
};
}
}
}
return {};
}
}, {
key: "getItemStyle",
value: function getItemStyle(index) {
var transitionDelay = this.calculateTransitionDelay(index);
var pointStyle = this.calculatePointStyle(index);
return _objectSpread({
transitionDelay: "".concat(transitionDelay, "ms")
}, pointStyle);
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.props.type !== 'linear') {
var button = DomHandler.findSingle(this.container, '.p-speeddial-button');
var firstItem = DomHandler.findSingle(this.list, '.p-speeddial-item');
if (button && firstItem) {
var wDiff = Math.abs(button.offsetWidth - firstItem.offsetWidth);
var hDiff = Math.abs(button.offsetHeight - firstItem.offsetHeight);
this.list.style.setProperty('--item-diff-x', "".concat(wDiff / 2, "px"));
this.list.style.setProperty('--item-diff-y', "".concat(hDiff / 2, "px"));
}
}
if (this.props.hideOnClickOutside) {
this.bindDocumentClickListener();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.props.hideOnClickOutside) {
this.unbindDocumentClickListener();
}
}
}, {
key: "renderItem",
value: function renderItem(item, index) {
var _this3 = this;
var style = this.getItemStyle(index);
var disabled = item.disabled,
_icon = item.icon,
label = item.label,
template = item.template,
url = item.url,
target = item.target;
var contentClassName = classNames('p-speeddial-action', {
'p-disabled': disabled
});
var iconClassName = classNames('p-speeddial-action-icon', _icon);
var icon = _icon && /*#__PURE__*/React.createElement("span", {
className: iconClassName
});
var content = /*#__PURE__*/React.createElement("a", {
href: url || '#',
role: "menuitem",
className: contentClassName,
target: target,
"data-pr-tooltip": label,
onClick: function onClick(e) {
return _this3.onItemClick(e, item);
}
}, icon, /*#__PURE__*/React.createElement(Ripple, null));
if (template) {
var defaultContentOptions = {
onClick: function onClick(e) {
return _this3.onItemClick(e, item);
},
className: contentClassName,
iconClassName: iconClassName,
element: content,
props: this.props,
visible: this.isVisible()
};
content = ObjectUtils.getJSXElement(template, item, defaultContentOptions);
}
return /*#__PURE__*/React.createElement("li", {
key: index,
className: "p-speeddial-item",
style: style,
role: "none"
}, content);
}
}, {
key: "renderItems",
value: function renderItems() {
var _this4 = this;
if (this.props.model) {
return this.props.model.map(function (item, index) {
return _this4.renderItem(item, index);
});
}
return null;
}
}, {
key: "renderList",
value: function renderList() {
var _this5 = this;
var items = this.renderItems();
return /*#__PURE__*/React.createElement("ul", {
ref: function ref(el) {
return _this5.list = el;
},
className: "p-speeddial-list",
role: "menu"
}, items);
}
}, {
key: "renderButton",
value: function renderButton() {
var _classNames,
_this6 = this;
var visible = this.isVisible();
var className = classNames('p-speeddial-button p-button-rounded', {
'p-speeddial-rotate': this.props.rotateAnimation && !this.props.hideIcon
}, this.props.buttonClassName);
var iconClassName = classNames((_classNames = {}, _defineProperty(_classNames, "".concat(this.props.showIcon), !visible && !!this.props.showIcon || !this.props.hideIcon), _defineProperty(_classNames, "".concat(this.props.hideIcon), visible && !!this.props.hideIcon), _classNames));
var content = /*#__PURE__*/React.createElement(Button, {
type: "button",
style: this.props.buttonStyle,
className: className,
icon: iconClassName,
onClick: this.onClick,
disabled: this.props.disabled
});
if (this.props.buttonTemplate) {
var defaultContentOptions = {
onClick: function onClick(event) {
return _this6.onClick(event);
},
className: className,
iconClassName: iconClassName,
element: content,
props: this.props,
visible: visible
};
return ObjectUtils.getJSXElement(this.props.buttonTemplate, defaultContentOptions);
}
return content;
}
}, {
key: "renderMask",
value: function renderMask() {
if (this.props.mask) {
var visible = this.isVisible();
var className = classNames('p-speeddial-mask', {
'p-speeddial-mask-visible': visible
}, this.props.maskClassName);
return /*#__PURE__*/React.createElement("div", {
className: className,
style: this.props.maskStyle
});
}
return null;
}
}, {
key: "render",
value: function render() {
var _classNames2,
_this7 = this;
var className = classNames("p-speeddial p-component p-speeddial-".concat(this.props.type), (_classNames2 = {}, _defineProperty(_classNames2, "p-speeddial-direction-".concat(this.props.direction), this.props.type !== 'circle'), _defineProperty(_classNames2, 'p-speeddial-opened', this.isVisible()), _defineProperty(_classNames2, 'p-disabled', this.props.disabled), _classNames2), this.props.className);
var button = this.renderButton();
var list = this.renderList();
var mask = this.renderMask();
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this7.container = el;
},
id: this.props.id,
className: className,
style: this.props.style
}, button, list), mask);
}
}]);
return SpeedDial;
}(Component);
_defineProperty(SpeedDial, "defaultProps", {
id: null,
model: null,
visible: false,
style: null,
className: null,
direction: 'up',
transitionDelay: 30,
type: 'linear',
radius: 0,
mask: false,
disabled: false,
hideOnClickOutside: true,
buttonStyle: null,
buttonClassName: null,
buttonTemplate: null,
maskStyle: null,
maskClassName: null,
showIcon: 'pi pi-plus',
hideIcon: null,
rotateAnimation: true,
onVisibleChange: null,
onClick: null,
onShow: null,
onHide: null
});
export { SpeedDial };
|
ajax/libs/react-instantsearch/6.3.0/Connectors.js | cdnjs/cdnjs | /*! React InstantSearch 6.3.0 | © Algolia, inc. | https://github.com/algolia/react-instantsearch */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(global = global || self, factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Connectors = {}), global.React));
}(this, function (exports, React) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
function _typeof(obj) {
if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
_typeof = function _typeof(obj) {
return _typeof2(obj);
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
var isArray = Array.isArray;
var keyList = Object.keys;
var hasProp = Object.prototype.hasOwnProperty;
var fastDeepEqual = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
var arrA = isArray(a)
, arrB = isArray(b)
, i
, length
, key;
if (arrA && arrB) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if (arrA != arrB) return false;
var dateA = a instanceof Date
, dateB = b instanceof Date;
if (dateA != dateB) return false;
if (dateA && dateB) return a.getTime() == b.getTime();
var regexpA = a instanceof RegExp
, regexpB = b instanceof RegExp;
if (regexpA != regexpB) return false;
if (regexpA && regexpB) return a.toString() == b.toString();
var keys = keyList(a);
length = keys.length;
if (length !== keyList(b).length)
return false;
for (i = length; i-- !== 0;)
if (!hasProp.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
return a!==a && b!==b;
};
var shallowEqual = function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
} // Test for A's keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
};
var getDisplayName = function getDisplayName(Component) {
return Component.displayName || Component.name || 'UnknownComponent';
};
var isPlainObject = function isPlainObject(value) {
return _typeof(value) === 'object' && value !== null && !Array.isArray(value);
};
var removeEmptyKey = function removeEmptyKey(obj) {
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (!isPlainObject(value)) {
return;
}
if (!objectHasKeys(value)) {
delete obj[key];
} else {
removeEmptyKey(value);
}
});
return obj;
};
var removeEmptyArraysFromObject = function removeEmptyArraysFromObject(obj) {
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (Array.isArray(value) && value.length === 0) {
delete obj[key];
}
});
return obj;
};
function addAbsolutePositions(hits, hitsPerPage, page) {
return hits.map(function (hit, index) {
return _objectSpread({}, hit, {
__position: hitsPerPage * page + index + 1
});
});
}
function addQueryID(hits, queryID) {
if (!queryID) {
return hits;
}
return hits.map(function (hit) {
return _objectSpread({}, hit, {
__queryID: queryID
});
});
}
function find(array, comparator) {
if (!Array.isArray(array)) {
return undefined;
}
for (var i = 0; i < array.length; i++) {
if (comparator(array[i])) {
return array[i];
}
}
return undefined;
}
function objectHasKeys(object) {
return object && Object.keys(object).length > 0;
} // https://github.com/babel/babel/blob/3aaafae053fa75febb3aa45d45b6f00646e30ba4/packages/babel-helpers/src/helpers.js#L604-L620
function omit(source, excluded) {
if (source === null || source === undefined) {
return {};
}
var target = {};
var sourceKeys = Object.keys(source);
for (var i = 0; i < sourceKeys.length; i++) {
var _key = sourceKeys[i];
if (excluded.indexOf(_key) >= 0) {
// eslint-disable-next-line no-continue
continue;
}
target[_key] = source[_key];
}
return target;
}
/**
* Retrieve the value at a path of the object:
*
* @example
* getPropertyByPath(
* { test: { this: { function: [{ now: { everyone: true } }] } } },
* 'test.this.function[0].now.everyone'
* ); // true
*
* getPropertyByPath(
* { test: { this: { function: [{ now: { everyone: true } }] } } },
* ['test', 'this', 'function', 0, 'now', 'everyone']
* ); // true
*
* @param object Source object to query
* @param path either an array of properties, or a string form of the properties, separated by .
*/
var getPropertyByPath = function getPropertyByPath(object, path) {
return (Array.isArray(path) ? path : path.replace(/\[(\d+)]/g, '.$1').split('.')).reduce(function (current, key) {
return current ? current[key] : undefined;
}, object);
};
var _createContext = React.createContext({
onInternalStateUpdate: function onInternalStateUpdate() {
return undefined;
},
createHrefForState: function createHrefForState() {
return '#';
},
onSearchForFacetValues: function onSearchForFacetValues() {
return undefined;
},
onSearchStateChange: function onSearchStateChange() {
return undefined;
},
onSearchParameters: function onSearchParameters() {
return undefined;
},
store: {},
widgetsManager: {},
mainTargetedIndex: ''
}),
InstantSearchConsumer = _createContext.Consumer,
InstantSearchProvider = _createContext.Provider;
var _createContext2 = React.createContext(undefined),
IndexConsumer = _createContext2.Consumer,
IndexProvider = _createContext2.Provider;
/**
* Connectors are the HOC used to transform React components
* into InstantSearch widgets.
* In order to simplify the construction of such connectors
* `createConnector` takes a description and transform it into
* a connector.
* @param {ConnectorDescription} connectorDesc the description of the connector
* @return {Connector} a function that wraps a component into
* an instantsearch connected one.
*/
function createConnectorWithoutContext(connectorDesc) {
if (!connectorDesc.displayName) {
throw new Error('`createConnector` requires you to provide a `displayName` property.');
}
var isWidget = typeof connectorDesc.getSearchParameters === 'function' || typeof connectorDesc.getMetadata === 'function' || typeof connectorDesc.transitionState === 'function';
return function (Composed) {
var Connector =
/*#__PURE__*/
function (_Component) {
_inherits(Connector, _Component);
function Connector(props) {
var _this;
_classCallCheck(this, Connector);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Connector).call(this, props));
_defineProperty(_assertThisInitialized(_this), "unsubscribe", void 0);
_defineProperty(_assertThisInitialized(_this), "unregisterWidget", void 0);
_defineProperty(_assertThisInitialized(_this), "isUnmounting", false);
_defineProperty(_assertThisInitialized(_this), "state", {
providedProps: _this.getProvidedProps(_this.props)
});
_defineProperty(_assertThisInitialized(_this), "refine", function () {
var _ref;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this.props.contextValue.onInternalStateUpdate( // refine will always be defined here because the prop is only given conditionally
(_ref = connectorDesc.refine).call.apply(_ref, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args)));
});
_defineProperty(_assertThisInitialized(_this), "createURL", function () {
var _ref2;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _this.props.contextValue.createHrefForState( // refine will always be defined here because the prop is only given conditionally
(_ref2 = connectorDesc.refine).call.apply(_ref2, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args)));
});
_defineProperty(_assertThisInitialized(_this), "searchForFacetValues", function () {
var _ref3;
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
_this.props.contextValue.onSearchForFacetValues( // searchForFacetValues will always be defined here because the prop is only given conditionally
(_ref3 = connectorDesc.searchForFacetValues).call.apply(_ref3, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args)));
});
if (connectorDesc.getSearchParameters) {
_this.props.contextValue.onSearchParameters(connectorDesc.getSearchParameters.bind(_assertThisInitialized(_this)), {
ais: _this.props.contextValue,
multiIndexContext: _this.props.indexContextValue
}, _this.props);
}
return _this;
}
_createClass(Connector, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
this.unsubscribe = this.props.contextValue.store.subscribe(function () {
if (!_this2.isUnmounting) {
_this2.setState({
providedProps: _this2.getProvidedProps(_this2.props)
});
}
});
if (isWidget) {
this.unregisterWidget = this.props.contextValue.widgetsManager.registerWidget(this);
}
}
}, {
key: "shouldComponentUpdate",
value: function shouldComponentUpdate(nextProps, nextState) {
if (typeof connectorDesc.shouldComponentUpdate === 'function') {
return connectorDesc.shouldComponentUpdate.call(this, this.props, nextProps, this.state, nextState);
}
var propsEqual = shallowEqual(this.props, nextProps);
if (this.state.providedProps === null || nextState.providedProps === null) {
if (this.state.providedProps === nextState.providedProps) {
return !propsEqual;
}
return true;
}
return !propsEqual || !shallowEqual(this.state.providedProps, nextState.providedProps);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (!fastDeepEqual(prevProps, this.props)) {
this.setState({
providedProps: this.getProvidedProps(this.props)
});
if (isWidget) {
this.props.contextValue.widgetsManager.update();
if (typeof connectorDesc.transitionState === 'function') {
this.props.contextValue.onSearchStateChange(connectorDesc.transitionState.call(this, this.props, this.props.contextValue.store.getState().widgets, this.props.contextValue.store.getState().widgets));
}
}
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.isUnmounting = true;
if (this.unsubscribe) {
this.unsubscribe();
}
if (this.unregisterWidget) {
this.unregisterWidget();
if (typeof connectorDesc.cleanUp === 'function') {
var nextState = connectorDesc.cleanUp.call(this, this.props, this.props.contextValue.store.getState().widgets);
this.props.contextValue.store.setState(_objectSpread({}, this.props.contextValue.store.getState(), {
widgets: nextState
}));
this.props.contextValue.onSearchStateChange(removeEmptyKey(nextState));
}
}
}
}, {
key: "getProvidedProps",
value: function getProvidedProps(props) {
var _this$props$contextVa = this.props.contextValue.store.getState(),
widgets = _this$props$contextVa.widgets,
results = _this$props$contextVa.results,
resultsFacetValues = _this$props$contextVa.resultsFacetValues,
searching = _this$props$contextVa.searching,
searchingForFacetValues = _this$props$contextVa.searchingForFacetValues,
isSearchStalled = _this$props$contextVa.isSearchStalled,
metadata = _this$props$contextVa.metadata,
error = _this$props$contextVa.error;
var searchResults = {
results: results,
searching: searching,
searchingForFacetValues: searchingForFacetValues,
isSearchStalled: isSearchStalled,
error: error
};
return connectorDesc.getProvidedProps.call(this, props, widgets, searchResults, metadata, // @MAJOR: move this attribute on the `searchResults` it doesn't
// makes sense to have it into a separate argument. The search
// flags are on the object why not the results?
resultsFacetValues);
}
}, {
key: "getSearchParameters",
value: function getSearchParameters(searchParameters) {
if (typeof connectorDesc.getSearchParameters === 'function') {
return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.props.contextValue.store.getState().widgets);
}
return null;
}
}, {
key: "getMetadata",
value: function getMetadata(nextWidgetsState) {
if (typeof connectorDesc.getMetadata === 'function') {
return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState);
}
return {};
}
}, {
key: "transitionState",
value: function transitionState(prevWidgetsState, nextWidgetsState) {
if (typeof connectorDesc.transitionState === 'function') {
return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState);
}
return nextWidgetsState;
}
}, {
key: "render",
value: function render() {
var _this$props = this.props,
contextValue = _this$props.contextValue,
props = _objectWithoutProperties(_this$props, ["contextValue"]);
var providedProps = this.state.providedProps;
if (providedProps === null) {
return null;
}
var refineProps = typeof connectorDesc.refine === 'function' ? {
refine: this.refine,
createURL: this.createURL
} : {};
var searchForFacetValuesProps = typeof connectorDesc.searchForFacetValues === 'function' ? {
searchForItems: this.searchForFacetValues
} : {};
return React__default.createElement(Composed, _extends({}, props, providedProps, refineProps, searchForFacetValuesProps));
}
}]);
return Connector;
}(React.Component);
_defineProperty(Connector, "displayName", "".concat(connectorDesc.displayName, "(").concat(getDisplayName(Composed), ")"));
_defineProperty(Connector, "propTypes", connectorDesc.propTypes);
_defineProperty(Connector, "defaultProps", connectorDesc.defaultProps);
return Connector;
};
}
var createConnectorWithContext = function createConnectorWithContext(connectorDesc) {
return function (Composed) {
var Connector = createConnectorWithoutContext(connectorDesc)(Composed);
var ConnectorWrapper = function ConnectorWrapper(props) {
return React__default.createElement(InstantSearchConsumer, null, function (contextValue) {
return React__default.createElement(IndexConsumer, null, function (indexContextValue) {
return React__default.createElement(Connector, _extends({
contextValue: contextValue,
indexContextValue: indexContextValue
}, props));
});
});
};
return ConnectorWrapper;
};
};
var HIGHLIGHT_TAGS = {
highlightPreTag: "<ais-highlight-0000000000>",
highlightPostTag: "</ais-highlight-0000000000>"
};
/**
* Parses an highlighted attribute into an array of objects with the string value, and
* a boolean that indicated if this part is highlighted.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature
* @return {object[]} - An array of {value: string, isHighlighted: boolean}.
*/
function parseHighlightedAttribute(_ref) {
var preTag = _ref.preTag,
postTag = _ref.postTag,
_ref$highlightedValue = _ref.highlightedValue,
highlightedValue = _ref$highlightedValue === void 0 ? '' : _ref$highlightedValue;
var splitByPreTag = highlightedValue.split(preTag);
var firstValue = splitByPreTag.shift();
var elements = firstValue === '' ? [] : [{
value: firstValue,
isHighlighted: false
}];
if (postTag === preTag) {
var isHighlighted = true;
splitByPreTag.forEach(function (split) {
elements.push({
value: split,
isHighlighted: isHighlighted
});
isHighlighted = !isHighlighted;
});
} else {
splitByPreTag.forEach(function (split) {
var splitByPostTag = split.split(postTag);
elements.push({
value: splitByPostTag[0],
isHighlighted: true
});
if (splitByPostTag[1] !== '') {
elements.push({
value: splitByPostTag[1],
isHighlighted: false
});
}
});
}
return elements;
}
/**
* Find an highlighted attribute given an `attribute` and an `highlightProperty`, parses it,
* and provided an array of objects with the string value and a boolean if this
* value is highlighted.
*
* In order to use this feature, highlight must be activated in the configuration of
* the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and
* highlightPostTag in Algolia configuration.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightProperty - the property that contains the highlight structure in the results
* @param {string} attribute - the highlighted attribute to look for
* @param {object} hit - the actual hit returned by Algolia.
* @return {object[]} - An array of {value: string, isHighlighted: boolean}.
*/
function parseAlgoliaHit(_ref2) {
var _ref2$preTag = _ref2.preTag,
preTag = _ref2$preTag === void 0 ? '<em>' : _ref2$preTag,
_ref2$postTag = _ref2.postTag,
postTag = _ref2$postTag === void 0 ? '</em>' : _ref2$postTag,
highlightProperty = _ref2.highlightProperty,
attribute = _ref2.attribute,
hit = _ref2.hit;
if (!hit) throw new Error('`hit`, the matching record, must be provided');
var highlightObject = getPropertyByPath(hit[highlightProperty], attribute) || {};
if (Array.isArray(highlightObject)) {
return highlightObject.map(function (item) {
return parseHighlightedAttribute({
preTag: preTag,
postTag: postTag,
highlightedValue: item.value
});
});
}
return parseHighlightedAttribute({
preTag: preTag,
postTag: postTag,
highlightedValue: highlightObject.value
});
}
function getIndexId(context) {
return hasMultipleIndices(context) ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex;
}
function getResults(searchResults, context) {
if (searchResults.results) {
if (searchResults.results.hits) {
return searchResults.results;
}
var indexId = getIndexId(context);
if (searchResults.results[indexId]) {
return searchResults.results[indexId];
}
}
return null;
}
function hasMultipleIndices(context) {
return context && context.multiIndexContext;
} // eslint-disable-next-line max-params
function refineValue(searchState, nextRefinement, context, resetPage, namespace) {
if (hasMultipleIndices(context)) {
var indexId = getIndexId(context);
return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, indexId, resetPage);
} else {
// When we have a multi index page with shared widgets we should also
// reset their page to 1 if the resetPage is provided. Otherwise the
// indices will always be reset
// see: https://github.com/algolia/react-instantsearch/issues/310
// see: https://github.com/algolia/react-instantsearch/issues/637
if (searchState.indices && resetPage) {
Object.keys(searchState.indices).forEach(function (targetedIndex) {
searchState = refineValue(searchState, {
page: 1
}, {
multiIndexContext: {
targetedIndex: targetedIndex
}
}, true, namespace);
});
}
return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage);
}
}
function refineMultiIndex(searchState, nextRefinement, indexId, resetPage) {
var page = resetPage ? {
page: 1
} : undefined;
var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], nextRefinement, page))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, nextRefinement, page)));
return _objectSpread({}, searchState, {
indices: state
});
}
function refineSingleIndex(searchState, nextRefinement, resetPage) {
var page = resetPage ? {
page: 1
} : undefined;
return _objectSpread({}, searchState, nextRefinement, page);
} // eslint-disable-next-line max-params
function refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) {
var _objectSpread4;
var page = resetPage ? {
page: 1
} : undefined;
var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], (_objectSpread4 = {}, _defineProperty(_objectSpread4, namespace, _objectSpread({}, searchState.indices[indexId][namespace], nextRefinement)), _defineProperty(_objectSpread4, "page", 1), _objectSpread4)))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread(_defineProperty({}, namespace, nextRefinement), page)));
return _objectSpread({}, searchState, {
indices: state
});
}
function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) {
var page = resetPage ? {
page: 1
} : undefined;
return _objectSpread({}, searchState, _defineProperty({}, namespace, _objectSpread({}, searchState[namespace], nextRefinement)), page);
}
function getNamespaceAndAttributeName(id) {
var parts = id.match(/^([^.]*)\.(.*)/);
var namespace = parts && parts[1];
var attributeName = parts && parts[2];
return {
namespace: namespace,
attributeName: attributeName
};
}
function hasRefinements(_ref) {
var multiIndex = _ref.multiIndex,
indexId = _ref.indexId,
namespace = _ref.namespace,
attributeName = _ref.attributeName,
id = _ref.id,
searchState = _ref.searchState;
if (multiIndex && namespace) {
return searchState.indices && searchState.indices[indexId] && searchState.indices[indexId][namespace] && Object.hasOwnProperty.call(searchState.indices[indexId][namespace], attributeName);
}
if (multiIndex) {
return searchState.indices && searchState.indices[indexId] && Object.hasOwnProperty.call(searchState.indices[indexId], id);
}
if (namespace) {
return searchState[namespace] && Object.hasOwnProperty.call(searchState[namespace], attributeName);
}
return Object.hasOwnProperty.call(searchState, id);
}
function getRefinements(_ref2) {
var multiIndex = _ref2.multiIndex,
indexId = _ref2.indexId,
namespace = _ref2.namespace,
attributeName = _ref2.attributeName,
id = _ref2.id,
searchState = _ref2.searchState;
if (multiIndex && namespace) {
return searchState.indices[indexId][namespace][attributeName];
}
if (multiIndex) {
return searchState.indices[indexId][id];
}
if (namespace) {
return searchState[namespace][attributeName];
}
return searchState[id];
}
function getCurrentRefinementValue(props, searchState, context, id, defaultValue) {
var indexId = getIndexId(context);
var _getNamespaceAndAttri = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri.namespace,
attributeName = _getNamespaceAndAttri.attributeName;
var multiIndex = hasMultipleIndices(context);
var args = {
multiIndex: multiIndex,
indexId: indexId,
namespace: namespace,
attributeName: attributeName,
id: id,
searchState: searchState
};
var hasRefinementsValue = hasRefinements(args);
if (hasRefinementsValue) {
return getRefinements(args);
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return defaultValue;
}
function cleanUpValue(searchState, context, id) {
var indexId = getIndexId(context);
var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri2.namespace,
attributeName = _getNamespaceAndAttri2.attributeName;
if (hasMultipleIndices(context) && Boolean(searchState.indices)) {
return cleanUpValueWithMultiIndex({
attribute: attributeName,
searchState: searchState,
indexId: indexId,
id: id,
namespace: namespace
});
}
return cleanUpValueWithSingleIndex({
attribute: attributeName,
searchState: searchState,
id: id,
namespace: namespace
});
}
function cleanUpValueWithSingleIndex(_ref3) {
var searchState = _ref3.searchState,
id = _ref3.id,
namespace = _ref3.namespace,
attribute = _ref3.attribute;
if (namespace) {
return _objectSpread({}, searchState, _defineProperty({}, namespace, omit(searchState[namespace], [attribute])));
}
return omit(searchState, [id]);
}
function cleanUpValueWithMultiIndex(_ref4) {
var searchState = _ref4.searchState,
indexId = _ref4.indexId,
id = _ref4.id,
namespace = _ref4.namespace,
attribute = _ref4.attribute;
var indexSearchState = searchState.indices[indexId];
if (namespace && indexSearchState) {
return _objectSpread({}, searchState, {
indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, indexSearchState, _defineProperty({}, namespace, omit(indexSearchState[namespace], [attribute])))))
});
}
if (indexSearchState) {
return _objectSpread({}, searchState, {
indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, omit(indexSearchState, [id])))
});
}
return searchState;
}
function getId() {
return 'configure';
}
var connectConfigure = createConnectorWithContext({
displayName: 'AlgoliaConfigure',
getProvidedProps: function getProvidedProps() {
return {};
},
getSearchParameters: function getSearchParameters(searchParameters, props) {
var children = props.children,
contextValue = props.contextValue,
indexContextValue = props.indexContextValue,
items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]);
return searchParameters.setQueryParameters(items);
},
transitionState: function transitionState(props, prevSearchState, nextSearchState) {
var id = getId();
var children = props.children,
contextValue = props.contextValue,
indexContextValue = props.indexContextValue,
items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]);
var propKeys = Object.keys(props);
var nonPresentKeys = this._props ? Object.keys(this._props).filter(function (prop) {
return propKeys.indexOf(prop) === -1;
}) : [];
this._props = props;
var nextValue = _defineProperty({}, id, _objectSpread({}, omit(nextSearchState[id], nonPresentKeys), items));
return refineValue(nextSearchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
var id = getId();
var indexId = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var subState = hasMultipleIndices({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) && searchState.indices ? searchState.indices[indexId] : searchState;
var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : [];
var configureState = configureKeys.reduce(function (acc, item) {
if (!props[item]) {
acc[item] = subState[id][item];
}
return acc;
}, {});
var nextValue = _defineProperty({}, id, configureState);
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
var global$1 = (typeof global !== "undefined" ? global :
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window : {});
if (typeof global$1.setTimeout === 'function') ;
if (typeof global$1.clearTimeout === 'function') ;
// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
var performance = global$1.performance || {};
var performanceNow =
performance.now ||
performance.mozNow ||
performance.msNow ||
performance.oNow ||
performance.webkitNow ||
function(){ return (new Date()).getTime() };
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
}
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function clone(value) {
if (typeof value === 'object' && value !== null) {
return _merge(Array.isArray(value) ? [] : {}, value);
}
return value;
}
function isObjectOrArrayOrFunction(value) {
return (
typeof value === 'function' ||
Array.isArray(value) ||
Object.prototype.toString.call(value) === '[object Object]'
);
}
function _merge(target, source) {
if (target === source) {
return target;
}
for (var key in source) {
if (!Object.prototype.hasOwnProperty.call(source, key)) {
continue;
}
var sourceVal = source[key];
var targetVal = target[key];
if (typeof targetVal !== 'undefined' && typeof sourceVal === 'undefined') {
continue;
}
if (isObjectOrArrayOrFunction(targetVal) && isObjectOrArrayOrFunction(sourceVal)) {
target[key] = _merge(targetVal, sourceVal);
} else {
target[key] = clone(sourceVal);
}
}
return target;
}
/**
* This method is like Object.assign, but recursively merges own and inherited
* enumerable keyed properties of source objects into the destination object.
*
* NOTE: this behaves like lodash/merge, but:
* - does mutate functions if they are a source
* - treats non-plain objects as plain
* - does not work for circular objects
* - treats sparse arrays as sparse
* - does not convert Array-like objects (Arguments, NodeLists, etc.) to arrays
*
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
*/
function merge(target) {
if (!isObjectOrArrayOrFunction(target)) {
target = {};
}
for (var i = 1, l = arguments.length; i < l; i++) {
var source = arguments[i];
if (isObjectOrArrayOrFunction(source)) {
_merge(target, source);
}
}
return target;
}
var merge_1 = merge;
// NOTE: this behaves like lodash/defaults, but doesn't mutate the target
var defaultsPure = function defaultsPure() {
var sources = Array.prototype.slice.call(arguments);
return sources.reduceRight(function(acc, source) {
Object.keys(Object(source)).forEach(function(key) {
if (source[key] !== undefined) {
acc[key] = source[key];
}
});
return acc;
}, {});
};
function intersection(arr1, arr2) {
return arr1.filter(function(value, index) {
return (
arr2.indexOf(value) > -1 &&
arr1.indexOf(value) === index /* skips duplicates */
);
});
}
var intersection_1 = intersection;
// @MAJOR can be replaced by native Array#find when we change support
var find$1 = function find(array, comparator) {
if (!Array.isArray(array)) {
return undefined;
}
for (var i = 0; i < array.length; i++) {
if (comparator(array[i])) {
return array[i];
}
}
};
function valToNumber(v) {
if (typeof v === 'number') {
return v;
} else if (typeof v === 'string') {
return parseFloat(v);
} else if (Array.isArray(v)) {
return v.map(valToNumber);
}
throw new Error('The value should be a number, a parsable string or an array of those.');
}
var valToNumber_1 = valToNumber;
// https://github.com/babel/babel/blob/3aaafae053fa75febb3aa45d45b6f00646e30ba4/packages/babel-helpers/src/helpers.js#L604-L620
function _objectWithoutPropertiesLoose$1(source, excluded) {
if (source === null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key;
var i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var omit$1 = _objectWithoutPropertiesLoose$1;
function objectHasKeys$1(obj) {
return obj && Object.keys(obj).length > 0;
}
var objectHasKeys_1 = objectHasKeys$1;
/**
* Functions to manipulate refinement lists
*
* The RefinementList is not formally defined through a prototype but is based
* on a specific structure.
*
* @module SearchParameters.refinementList
*
* @typedef {string[]} SearchParameters.refinementList.Refinements
* @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList
*/
var lib = {
/**
* Adds a refinement to a RefinementList
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement, if the value is not a string it will be converted
* @return {RefinementList} a new and updated refinement list
*/
addRefinement: function addRefinement(refinementList, attribute, value) {
if (lib.isRefined(refinementList, attribute, value)) {
return refinementList;
}
var valueAsString = '' + value;
var facetRefinement = !refinementList[attribute] ?
[valueAsString] :
refinementList[attribute].concat(valueAsString);
var mod = {};
mod[attribute] = facetRefinement;
return defaultsPure({}, mod, refinementList);
},
/**
* Removes refinement(s) for an attribute:
* - if the value is specified removes the refinement for the value on the attribute
* - if no value is specified removes all the refinements for this attribute
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} [value] the value of the refinement
* @return {RefinementList} a new and updated refinement lst
*/
removeRefinement: function removeRefinement(refinementList, attribute, value) {
if (value === undefined) {
// we use the "filter" form of clearRefinement, since it leaves empty values as-is
// the form with a string will remove the attribute completely
return lib.clearRefinement(refinementList, function(v, f) {
return attribute === f;
});
}
var valueAsString = '' + value;
return lib.clearRefinement(refinementList, function(v, f) {
return attribute === f && valueAsString === v;
});
},
/**
* Toggles the refinement value for an attribute.
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement
* @return {RefinementList} a new and updated list
*/
toggleRefinement: function toggleRefinement(refinementList, attribute, value) {
if (value === undefined) throw new Error('toggleRefinement should be used with a value');
if (lib.isRefined(refinementList, attribute, value)) {
return lib.removeRefinement(refinementList, attribute, value);
}
return lib.addRefinement(refinementList, attribute, value);
},
/**
* Clear all or parts of a RefinementList. Depending on the arguments, three
* kinds of behavior can happen:
* - if no attribute is provided: clears the whole list
* - if an attribute is provided as a string: clears the list for the specific attribute
* - if an attribute is provided as a function: discards the elements for which the function returns true
* @param {RefinementList} refinementList the initial list
* @param {string} [attribute] the attribute or function to discard
* @param {string} [refinementType] optional parameter to give more context to the attribute function
* @return {RefinementList} a new and updated refinement list
*/
clearRefinement: function clearRefinement(refinementList, attribute, refinementType) {
if (attribute === undefined) {
if (!objectHasKeys_1(refinementList)) {
return refinementList;
}
return {};
} else if (typeof attribute === 'string') {
return omit$1(refinementList, attribute);
} else if (typeof attribute === 'function') {
var hasChanged = false;
var newRefinementList = Object.keys(refinementList).reduce(function(memo, key) {
var values = refinementList[key] || [];
var facetList = values.filter(function(value) {
return !attribute(value, key, refinementType);
});
if (facetList.length !== values.length) {
hasChanged = true;
}
memo[key] = facetList;
return memo;
}, {});
if (hasChanged) return newRefinementList;
return refinementList;
}
},
/**
* Test if the refinement value is used for the attribute. If no refinement value
* is provided, test if the refinementList contains any refinement for the
* given attribute.
* @param {RefinementList} refinementList the list of refinement
* @param {string} attribute name of the attribute
* @param {string} [refinementValue] value of the filter/refinement
* @return {boolean}
*/
isRefined: function isRefined(refinementList, attribute, refinementValue) {
var containsRefinements = !!refinementList[attribute] &&
refinementList[attribute].length > 0;
if (refinementValue === undefined || !containsRefinements) {
return containsRefinements;
}
var refinementValueAsString = '' + refinementValue;
return refinementList[attribute].indexOf(refinementValueAsString) !== -1;
}
};
var RefinementList = lib;
/**
* isEqual, but only for numeric refinement values, possible values:
* - 5
* - [5]
* - [[5]]
* - [[5,5],[4]]
*/
function isEqualNumericRefinement(a, b) {
if (Array.isArray(a) && Array.isArray(b)) {
return (
a.length === b.length &&
a.every(function(el, i) {
return isEqualNumericRefinement(b[i], el);
})
);
}
return a === b;
}
/**
* like _.find but using deep equality to be able to use it
* to find arrays.
* @private
* @param {any[]} array array to search into (elements are base or array of base)
* @param {any} searchedValue the value we're looking for (base or array of base)
* @return {any} the searched value or undefined
*/
function findArray(array, searchedValue) {
return find$1(array, function(currentValue) {
return isEqualNumericRefinement(currentValue, searchedValue);
});
}
/**
* The facet list is the structure used to store the list of values used to
* filter a single attribute.
* @typedef {string[]} SearchParameters.FacetList
*/
/**
* Structure to store numeric filters with the operator as the key. The supported operators
* are `=`, `>`, `<`, `>=`, `<=` and `!=`.
* @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList
*/
/**
* SearchParameters is the data structure that contains all the information
* usable for making a search to Algolia API. It doesn't do the search itself,
* nor does it contains logic about the parameters.
* It is an immutable object, therefore it has been created in a way that each
* changes does not change the object itself but returns a copy with the
* modification.
* This object should probably not be instantiated outside of the helper. It will
* be provided when needed. This object is documented for reference as you'll
* get it from events generated by the {@link AlgoliaSearchHelper}.
* If need be, instantiate the Helper from the factory function {@link SearchParameters.make}
* @constructor
* @classdesc contains all the parameters of a search
* @param {object|SearchParameters} newParameters existing parameters or partial object
* for the properties of a new SearchParameters
* @see SearchParameters.make
* @example <caption>SearchParameters of the first query in
* <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption>
{
"query": "",
"disjunctiveFacets": [
"customerReviewCount",
"category",
"salePrice_range",
"manufacturer"
],
"maxValuesPerFacet": 30,
"page": 0,
"hitsPerPage": 10,
"facets": [
"type",
"shipping"
]
}
*/
function SearchParameters(newParameters) {
var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {};
/**
* This attribute contains the list of all the conjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.facets = params.facets || [];
/**
* This attribute contains the list of all the disjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.disjunctiveFacets = params.disjunctiveFacets || [];
/**
* This attribute contains the list of all the hierarchical facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* Hierarchical facets are a sub type of disjunctive facets that
* let you filter faceted attributes hierarchically.
* @member {string[]|object[]}
*/
this.hierarchicalFacets = params.hierarchicalFacets || [];
// Refinements
/**
* This attribute contains all the filters that need to be
* applied on the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsRefinements = params.facetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* excluded from the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters excluded for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsExcludes = params.facetsExcludes || {};
/**
* This attribute contains all the filters that need to be
* applied on the disjunctive facets. Each facet must be properly
* defined in the `disjunctiveFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* applied on the numeric attributes.
*
* The key is the name of the attribute, and the value is the
* filters to apply to this attribute.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `numericFilters` attribute.
* @member {Object.<string, SearchParameters.OperatorList>}
*/
this.numericRefinements = params.numericRefinements || {};
/**
* This attribute contains all the tags used to refine the query.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `tagFilters` attribute.
* @member {string[]}
*/
this.tagRefinements = params.tagRefinements || [];
/**
* This attribute contains all the filters that need to be
* applied on the hierarchical facets. Each facet must be properly
* defined in the `hierarchicalFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name. The FacetList values
* are structured as a string that contain the values for each level
* separated by the configured separator.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {};
var self = this;
Object.keys(params).forEach(function(paramName) {
var isKeyKnown = SearchParameters.PARAMETERS.indexOf(paramName) !== -1;
var isValueDefined = params[paramName] !== undefined;
if (!isKeyKnown && isValueDefined) {
self[paramName] = params[paramName];
}
});
}
/**
* List all the properties in SearchParameters and therefore all the known Algolia properties
* This doesn't contain any beta/hidden features.
* @private
*/
SearchParameters.PARAMETERS = Object.keys(new SearchParameters());
/**
* @private
* @param {object} partialState full or part of a state
* @return {object} a new object with the number keys as number
*/
SearchParameters._parseNumbers = function(partialState) {
// Do not reparse numbers in SearchParameters, they ought to be parsed already
if (partialState instanceof SearchParameters) return partialState;
var numbers = {};
var numberKeys = [
'aroundPrecision',
'aroundRadius',
'getRankingInfo',
'minWordSizefor2Typos',
'minWordSizefor1Typo',
'page',
'maxValuesPerFacet',
'distinct',
'minimumAroundRadius',
'hitsPerPage',
'minProximity'
];
numberKeys.forEach(function(k) {
var value = partialState[k];
if (typeof value === 'string') {
var parsedValue = parseFloat(value);
// global isNaN is ok to use here, value is only number or NaN
numbers[k] = isNaN(parsedValue) ? value : parsedValue;
}
});
// there's two formats of insideBoundingBox, we need to parse
// the one which is an array of float geo rectangles
if (Array.isArray(partialState.insideBoundingBox)) {
numbers.insideBoundingBox = partialState.insideBoundingBox.map(function(geoRect) {
return geoRect.map(function(value) {
return parseFloat(value);
});
});
}
if (partialState.numericRefinements) {
var numericRefinements = {};
Object.keys(partialState.numericRefinements).forEach(function(attribute) {
var operators = partialState.numericRefinements[attribute] || {};
numericRefinements[attribute] = {};
Object.keys(operators).forEach(function(operator) {
var values = operators[operator];
var parsedValues = values.map(function(v) {
if (Array.isArray(v)) {
return v.map(function(vPrime) {
if (typeof vPrime === 'string') {
return parseFloat(vPrime);
}
return vPrime;
});
} else if (typeof v === 'string') {
return parseFloat(v);
}
return v;
});
numericRefinements[attribute][operator] = parsedValues;
});
});
numbers.numericRefinements = numericRefinements;
}
return merge_1({}, partialState, numbers);
};
/**
* Factory for SearchParameters
* @param {object|SearchParameters} newParameters existing parameters or partial
* object for the properties of a new SearchParameters
* @return {SearchParameters} frozen instance of SearchParameters
*/
SearchParameters.make = function makeSearchParameters(newParameters) {
var instance = new SearchParameters(newParameters);
var hierarchicalFacets = newParameters.hierarchicalFacets || [];
hierarchicalFacets.forEach(function(facet) {
if (facet.rootPath) {
var currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) {
instance = instance.clearRefinements(facet.name);
}
// get it again in case it has been cleared
currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length === 0) {
instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath);
}
}
});
return instance;
};
/**
* Validates the new parameters based on the previous state
* @param {SearchParameters} currentState the current state
* @param {object|SearchParameters} parameters the new parameters to set
* @return {Error|null} Error if the modification is invalid, null otherwise
*/
SearchParameters.validate = function(currentState, parameters) {
var params = parameters || {};
if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) {
return new Error(
'[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' +
'an error, if it is really what you want, you should first clear the tags with clearTags method.');
}
if (currentState.tagRefinements.length > 0 && params.tagFilters) {
return new Error(
'[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' +
'an error, if it is not, you should first clear the tags with clearTags method.');
}
if (
currentState.numericFilters &&
params.numericRefinements &&
objectHasKeys_1(params.numericRefinements)
) {
return new Error(
"[Numeric filters] Can't switch from the advanced to the managed API. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.'
);
}
if (objectHasKeys_1(currentState.numericRefinements) && params.numericFilters) {
return new Error(
"[Numeric filters] Can't switch from the managed API to the advanced. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
return null;
};
SearchParameters.prototype = {
constructor: SearchParameters,
/**
* Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)
* @method
* @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {SearchParameters}
*/
clearRefinements: function clearRefinements(attribute) {
var patch = {
numericRefinements: this._clearNumericRefinements(attribute),
facetsRefinements: RefinementList.clearRefinement(
this.facetsRefinements,
attribute,
'conjunctiveFacet'
),
facetsExcludes: RefinementList.clearRefinement(
this.facetsExcludes,
attribute,
'exclude'
),
disjunctiveFacetsRefinements: RefinementList.clearRefinement(
this.disjunctiveFacetsRefinements,
attribute,
'disjunctiveFacet'
),
hierarchicalFacetsRefinements: RefinementList.clearRefinement(
this.hierarchicalFacetsRefinements,
attribute,
'hierarchicalFacet'
)
};
if (
patch.numericRefinements === this.numericRefinements &&
patch.facetsRefinements === this.facetsRefinements &&
patch.facetsExcludes === this.facetsExcludes &&
patch.disjunctiveFacetsRefinements === this.disjunctiveFacetsRefinements &&
patch.hierarchicalFacetsRefinements === this.hierarchicalFacetsRefinements
) {
return this;
}
return this.setQueryParameters(patch);
},
/**
* Remove all the refined tags from the SearchParameters
* @method
* @return {SearchParameters}
*/
clearTags: function clearTags() {
if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this;
return this.setQueryParameters({
tagFilters: undefined,
tagRefinements: []
});
},
/**
* Set the index.
* @method
* @param {string} index the index name
* @return {SearchParameters}
*/
setIndex: function setIndex(index) {
if (index === this.index) return this;
return this.setQueryParameters({
index: index
});
},
/**
* Query setter
* @method
* @param {string} newQuery value for the new query
* @return {SearchParameters}
*/
setQuery: function setQuery(newQuery) {
if (newQuery === this.query) return this;
return this.setQueryParameters({
query: newQuery
});
},
/**
* Page setter
* @method
* @param {number} newPage new page number
* @return {SearchParameters}
*/
setPage: function setPage(newPage) {
if (newPage === this.page) return this;
return this.setQueryParameters({
page: newPage
});
},
/**
* Facets setter
* The facets are the simple facets, used for conjunctive (and) faceting.
* @method
* @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting
* @return {SearchParameters}
*/
setFacets: function setFacets(facets) {
return this.setQueryParameters({
facets: facets
});
},
/**
* Disjunctive facets setter
* Change the list of disjunctive (or) facets the helper chan handle.
* @method
* @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting
* @return {SearchParameters}
*/
setDisjunctiveFacets: function setDisjunctiveFacets(facets) {
return this.setQueryParameters({
disjunctiveFacets: facets
});
},
/**
* HitsPerPage setter
* Hits per page represents the number of hits retrieved for this query
* @method
* @param {number} n number of hits retrieved per page of results
* @return {SearchParameters}
*/
setHitsPerPage: function setHitsPerPage(n) {
if (this.hitsPerPage === n) return this;
return this.setQueryParameters({
hitsPerPage: n
});
},
/**
* typoTolerance setter
* Set the value of typoTolerance
* @method
* @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict")
* @return {SearchParameters}
*/
setTypoTolerance: function setTypoTolerance(typoTolerance) {
if (this.typoTolerance === typoTolerance) return this;
return this.setQueryParameters({
typoTolerance: typoTolerance
});
},
/**
* Add a numeric filter for a given attribute
* When value is an array, they are combined with OR
* When value is a single value, it will combined with AND
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number | number[]} value value of the filter
* @return {SearchParameters}
* @example
* // for price = 50 or 40
* searchparameter.addNumericRefinement('price', '=', [50, 40]);
* @example
* // for size = 38 and 40
* searchparameter.addNumericRefinement('size', '=', 38);
* searchparameter.addNumericRefinement('size', '=', 40);
*/
addNumericRefinement: function(attribute, operator, v) {
var value = valToNumber_1(v);
if (this.isNumericRefined(attribute, operator, value)) return this;
var mod = merge_1({}, this.numericRefinements);
mod[attribute] = merge_1({}, mod[attribute]);
if (mod[attribute][operator]) {
// Array copy
mod[attribute][operator] = mod[attribute][operator].slice();
// Add the element. Concat can't be used here because value can be an array.
mod[attribute][operator].push(value);
} else {
mod[attribute][operator] = [value];
}
return this.setQueryParameters({
numericRefinements: mod
});
},
/**
* Get the list of conjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getConjunctiveRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
return [];
}
return this.facetsRefinements[facetName] || [];
},
/**
* Get the list of disjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getDisjunctiveRefinements: function(facetName) {
if (!this.isDisjunctiveFacet(facetName)) {
return [];
}
return this.disjunctiveFacetsRefinements[facetName] || [];
},
/**
* Get the list of hierarchical refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getHierarchicalRefinement: function(facetName) {
// we send an array but we currently do not support multiple
// hierarchicalRefinements for a hierarchicalFacet
return this.hierarchicalFacetsRefinements[facetName] || [];
},
/**
* Get the list of exclude refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getExcludeRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
return [];
}
return this.facetsExcludes[facetName] || [];
},
/**
* Remove all the numeric filter for a given (attribute, operator)
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number} [number] the value to be removed
* @return {SearchParameters}
*/
removeNumericRefinement: function(attribute, operator, paramValue) {
if (paramValue !== undefined) {
if (!this.isNumericRefined(attribute, operator, paramValue)) {
return this;
}
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return (
key === attribute &&
value.op === operator &&
isEqualNumericRefinement(value.val, valToNumber_1(paramValue))
);
})
});
} else if (operator !== undefined) {
if (!this.isNumericRefined(attribute, operator)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator;
})
});
}
if (!this.isNumericRefined(attribute)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute;
})
});
},
/**
* Get the list of numeric refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {SearchParameters.OperatorList[]} list of refinements
*/
getNumericRefinements: function(facetName) {
return this.numericRefinements[facetName] || {};
},
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute attribute in the record
* @param {string} operator operator applied on the refined values
* @return {Array.<number|number[]>} refined values
*/
getNumericRefinement: function(attribute, operator) {
return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator];
},
/**
* Clear numeric filters.
* @method
* @private
* @param {string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {Object.<string, OperatorList>}
*/
_clearNumericRefinements: function _clearNumericRefinements(attribute) {
if (attribute === undefined) {
if (!objectHasKeys_1(this.numericRefinements)) {
return this.numericRefinements;
}
return {};
} else if (typeof attribute === 'string') {
if (!objectHasKeys_1(this.numericRefinements[attribute])) {
return this.numericRefinements;
}
return omit$1(this.numericRefinements, attribute);
} else if (typeof attribute === 'function') {
var hasChanged = false;
var numericRefinements = this.numericRefinements;
var newNumericRefinements = Object.keys(numericRefinements).reduce(function(memo, key) {
var operators = numericRefinements[key];
var operatorList = {};
operators = operators || {};
Object.keys(operators).forEach(function(operator) {
var values = operators[operator] || [];
var outValues = [];
values.forEach(function(value) {
var predicateResult = attribute({val: value, op: operator}, key, 'numeric');
if (!predicateResult) outValues.push(value);
});
if (outValues.length !== values.length) {
hasChanged = true;
}
operatorList[operator] = outValues;
});
memo[key] = operatorList;
return memo;
}, {});
if (hasChanged) return newNumericRefinements;
return this.numericRefinements;
}
},
/**
* Add a facet to the facets attribute of the helper configuration, if it
* isn't already present.
* @method
* @param {string} facet facet name to add
* @return {SearchParameters}
*/
addFacet: function addFacet(facet) {
if (this.isConjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
facets: this.facets.concat([facet])
});
},
/**
* Add a disjunctive facet to the disjunctiveFacets attribute of the helper
* configuration, if it isn't already present.
* @method
* @param {string} facet disjunctive facet name to add
* @return {SearchParameters}
*/
addDisjunctiveFacet: function addDisjunctiveFacet(facet) {
if (this.isDisjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
disjunctiveFacets: this.disjunctiveFacets.concat([facet])
});
},
/**
* Add a hierarchical facet to the hierarchicalFacets attribute of the helper
* configuration.
* @method
* @param {object} hierarchicalFacet hierarchical facet to add
* @return {SearchParameters}
* @throws will throw an error if a hierarchical facet with the same name was already declared
*/
addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) {
if (this.isHierarchicalFacet(hierarchicalFacet.name)) {
throw new Error(
'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`');
}
return this.setQueryParameters({
hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet])
});
},
/**
* Add a refinement on a "normal" facet
* @method
* @param {string} facet attribute to apply the faceting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addFacetRefinement: function addFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Exclude a value from a "normal" facet
* @method
* @param {string} facet attribute to apply the exclusion on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addExcludeRefinement: function addExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Adds a refinement on a disjunctive facet.
* @method
* @param {string} facet attribute to apply the faceting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.addRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* addTagRefinement adds a tag to the list used to filter the results
* @param {string} tag tag to be added
* @return {SearchParameters}
*/
addTagRefinement: function addTagRefinement(tag) {
if (this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: this.tagRefinements.concat(tag)
};
return this.setQueryParameters(modification);
},
/**
* Remove a facet from the facets attribute of the helper configuration, if it
* is present.
* @method
* @param {string} facet facet name to remove
* @return {SearchParameters}
*/
removeFacet: function removeFacet(facet) {
if (!this.isConjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
facets: this.facets.filter(function(f) {
return f !== facet;
})
});
},
/**
* Remove a disjunctive facet from the disjunctiveFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet disjunctive facet name to remove
* @return {SearchParameters}
*/
removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) {
if (!this.isDisjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
disjunctiveFacets: this.disjunctiveFacets.filter(function(f) {
return f !== facet;
})
});
},
/**
* Remove a hierarchical facet from the hierarchicalFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet hierarchical facet name to remove
* @return {SearchParameters}
*/
removeHierarchicalFacet: function removeHierarchicalFacet(facet) {
if (!this.isHierarchicalFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
hierarchicalFacets: this.hierarchicalFacets.filter(function(f) {
return f.name !== facet;
})
});
},
/**
* Remove a refinement set on facet. If a value is provided, it will clear the
* refinement for the given value, otherwise it will clear all the refinement
* values for the faceted attribute.
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} [value] value used to filter
* @return {SearchParameters}
*/
removeFacetRefinement: function removeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Remove a negative refinement on a facet
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeExcludeRefinement: function removeExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Remove a refinement on a disjunctive facet
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.removeRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Remove a tag from the list of tag refinements
* @method
* @param {string} tag the tag to remove
* @return {SearchParameters}
*/
removeTagRefinement: function removeTagRefinement(tag) {
if (!this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: this.tagRefinements.filter(function(t) {
return t !== tag;
})
};
return this.setQueryParameters(modification);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
* @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement}
*/
toggleRefinement: function toggleRefinement(facet, value) {
return this.toggleFacetRefinement(facet, value);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
*/
toggleFacetRefinement: function toggleFacetRefinement(facet, value) {
if (this.isHierarchicalFacet(facet)) {
return this.toggleHierarchicalFacetRefinement(facet, value);
} else if (this.isConjunctiveFacet(facet)) {
return this.toggleConjunctiveFacetRefinement(facet, value);
} else if (this.isDisjunctiveFacet(facet)) {
return this.toggleDisjunctiveFacetRefinement(facet, value);
}
throw new Error('Cannot refine the undeclared facet ' + facet +
'; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets');
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.toggleRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet));
var mod = {};
var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined &&
this.hierarchicalFacetsRefinements[facet].length > 0 && (
// remove current refinement:
// refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0] === value ||
// remove a parent refinement of the current refinement:
// - refinement was 'beer > IPA > Flying dog'
// - call is toggleRefine('beer > IPA')
// - refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0
);
if (upOneOrMultipleLevel) {
if (value.indexOf(separator) === -1) {
// go back to root level
mod[facet] = [];
} else {
mod[facet] = [value.slice(0, value.lastIndexOf(separator))];
}
} else {
mod[facet] = [value];
}
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaultsPure({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Adds a refinement on a hierarchical facet.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is refined
*/
addHierarchicalFacetRefinement: function(facet, path) {
if (this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is already refined.');
}
if (!this.isHierarchicalFacet(facet)) {
throw new Error(facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration.');
}
var mod = {};
mod[facet] = [path];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaultsPure({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is not refined
*/
removeHierarchicalFacetRefinement: function(facet) {
if (!this.isHierarchicalFacetRefined(facet)) {
return this;
}
var mod = {};
mod[facet] = [];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaultsPure({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Switch the tag refinement
* @method
* @param {string} tag the tag to remove or add
* @return {SearchParameters}
*/
toggleTagRefinement: function toggleTagRefinement(tag) {
if (this.isTagRefined(tag)) {
return this.removeTagRefinement(tag);
}
return this.addTagRefinement(tag);
},
/**
* Test if the facet name is from one of the disjunctive facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isDisjunctiveFacet: function(facet) {
return this.disjunctiveFacets.indexOf(facet) > -1;
},
/**
* Test if the facet name is from one of the hierarchical facets
* @method
* @param {string} facetName facet name to test
* @return {boolean}
*/
isHierarchicalFacet: function(facetName) {
return this.getHierarchicalFacetByName(facetName) !== undefined;
},
/**
* Test if the facet name is from one of the conjunctive/normal facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isConjunctiveFacet: function(facet) {
return this.facets.indexOf(facet) > -1;
},
/**
* Returns true if the facet is refined, either for a specific value or in
* general.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value, optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isFacetRefined: function isFacetRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
return false;
}
return RefinementList.isRefined(this.facetsRefinements, facet, value);
},
/**
* Returns true if the facet contains exclusions or if a specific value is
* excluded.
*
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isExcludeRefined: function isExcludeRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
return false;
}
return RefinementList.isRefined(this.facetsExcludes, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value optional, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
return false;
}
return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value optional, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
return false;
}
var refinements = this.getHierarchicalRefinement(facet);
if (!value) {
return refinements.length > 0;
}
return refinements.indexOf(value) !== -1;
},
/**
* Test if the triple (attribute, operator, value) is already refined.
* If only the attribute and the operator are provided, it tests if the
* contains any refinement value.
* @method
* @param {string} attribute attribute for which the refinement is applied
* @param {string} [operator] operator of the refinement
* @param {string} [value] value of the refinement
* @return {boolean} true if it is refined
*/
isNumericRefined: function isNumericRefined(attribute, operator, value) {
if (value === undefined && operator === undefined) {
return !!this.numericRefinements[attribute];
}
var isOperatorDefined =
this.numericRefinements[attribute] &&
this.numericRefinements[attribute][operator] !== undefined;
if (value === undefined || !isOperatorDefined) {
return isOperatorDefined;
}
var parsedValue = valToNumber_1(value);
var isAttributeValueDefined =
findArray(this.numericRefinements[attribute][operator], parsedValue) !==
undefined;
return isOperatorDefined && isAttributeValueDefined;
},
/**
* Returns true if the tag refined, false otherwise
* @method
* @param {string} tag the tag to check
* @return {boolean}
*/
isTagRefined: function isTagRefined(tag) {
return this.tagRefinements.indexOf(tag) !== -1;
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() {
var self = this;
// attributes used for numeric filter can also be disjunctive
var disjunctiveNumericRefinedFacets = intersection_1(
Object.keys(this.numericRefinements).filter(function(facet) {
return Object.keys(self.numericRefinements[facet]).length > 0;
}),
this.disjunctiveFacets
);
return Object.keys(this.disjunctiveFacetsRefinements).filter(function(facet) {
return self.disjunctiveFacetsRefinements[facet].length > 0;
})
.concat(disjunctiveNumericRefinedFacets)
.concat(this.getRefinedHierarchicalFacets());
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() {
var self = this;
return intersection_1(
// enforce the order between the two arrays,
// so that refinement name index === hierarchical facet index
this.hierarchicalFacets.map(function(facet) { return facet.name; }),
Object.keys(this.hierarchicalFacetsRefinements).filter(function(facet) {
return self.hierarchicalFacetsRefinements[facet].length > 0;
})
);
},
/**
* Returned the list of all disjunctive facets not refined
* @method
* @return {string[]}
*/
getUnrefinedDisjunctiveFacets: function() {
var refinedFacets = this.getRefinedDisjunctiveFacets();
return this.disjunctiveFacets.filter(function(f) {
return refinedFacets.indexOf(f) === -1;
});
},
managedParameters: [
'index',
'facets', 'disjunctiveFacets', 'facetsRefinements',
'facetsExcludes', 'disjunctiveFacetsRefinements',
'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'
],
getQueryParams: function getQueryParams() {
var managedParameters = this.managedParameters;
var queryParams = {};
var self = this;
Object.keys(this).forEach(function(paramName) {
var paramValue = self[paramName];
if (managedParameters.indexOf(paramName) === -1 && paramValue !== undefined) {
queryParams[paramName] = paramValue;
}
});
return queryParams;
},
/**
* Let the user set a specific value for a given parameter. Will return the
* same instance if the parameter is invalid or if the value is the same as the
* previous one.
* @method
* @param {string} parameter the parameter name
* @param {any} value the value to be set, must be compliant with the definition
* of the attribute on the object
* @return {SearchParameters} the updated state
*/
setQueryParameter: function setParameter(parameter, value) {
if (this[parameter] === value) return this;
var modification = {};
modification[parameter] = value;
return this.setQueryParameters(modification);
},
/**
* Let the user set any of the parameters with a plain object.
* @method
* @param {object} params all the keys and the values to be updated
* @return {SearchParameters} a new updated instance
*/
setQueryParameters: function setQueryParameters(params) {
if (!params) return this;
var error = SearchParameters.validate(this, params);
if (error) {
throw error;
}
var self = this;
var nextWithNumbers = SearchParameters._parseNumbers(params);
var previousPlainObject = Object.keys(this).reduce(function(acc, key) {
acc[key] = self[key];
return acc;
}, {});
var nextPlainObject = Object.keys(nextWithNumbers).reduce(
function(previous, key) {
var isPreviousValueDefined = previous[key] !== undefined;
var isNextValueDefined = nextWithNumbers[key] !== undefined;
if (isPreviousValueDefined && !isNextValueDefined) {
return omit$1(previous, [key]);
}
if (isNextValueDefined) {
previous[key] = nextWithNumbers[key];
}
return previous;
},
previousPlainObject
);
return new this.constructor(nextPlainObject);
},
/**
* Returns a new instance with the page reset. Two scenarios possible:
* the page is omitted -> return the given instance
* the page is set -> return a new instance with a page of 0
* @return {SearchParameters} a new updated instance
*/
resetPage: function() {
if (this.page === undefined) {
return this;
}
return this.setPage(0);
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSortBy: function(hierarchicalFacet) {
return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc'];
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSeparator: function(hierarchicalFacet) {
return hierarchicalFacet.separator || ' > ';
},
/**
* Helper function to get the hierarchicalFacet prefix path or null
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.rootPath or null as default
*/
_getHierarchicalRootPath: function(hierarchicalFacet) {
return hierarchicalFacet.rootPath || null;
},
/**
* Helper function to check if we show the parent level of the hierarchicalFacet
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.showParentLevel or true as default
*/
_getHierarchicalShowParentLevel: function(hierarchicalFacet) {
if (typeof hierarchicalFacet.showParentLevel === 'boolean') {
return hierarchicalFacet.showParentLevel;
}
return true;
},
/**
* Helper function to get the hierarchicalFacet by it's name
* @param {string} hierarchicalFacetName
* @return {object} a hierarchicalFacet
*/
getHierarchicalFacetByName: function(hierarchicalFacetName) {
return find$1(
this.hierarchicalFacets,
function(f) {
return f.name === hierarchicalFacetName;
}
);
},
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
getHierarchicalFacetBreadcrumb: function(facetName) {
if (!this.isHierarchicalFacet(facetName)) {
return [];
}
var refinement = this.getHierarchicalRefinement(facetName)[0];
if (!refinement) return [];
var separator = this._getHierarchicalFacetSeparator(
this.getHierarchicalFacetByName(facetName)
);
var path = refinement.split(separator);
return path.map(function(part) {
return part.trim();
});
},
toString: function() {
return JSON.stringify(this, null, 2);
}
};
/**
* Callback used for clearRefinement method
* @callback SearchParameters.clearCallback
* @param {OperatorList|FacetList} value the value of the filter
* @param {string} key the current attribute name
* @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude`
* depending on the type of facet
* @return {boolean} `true` if the element should be removed. `false` otherwise.
*/
var SearchParameters_1 = SearchParameters;
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined;
var valIsNull = value === null;
var othIsDefined = other !== undefined;
var othIsNull = other === null;
if (
(!othIsNull && value > other) ||
(valIsNull && othIsDefined) ||
!valIsDefined
) {
return 1;
}
if (
(!valIsNull && value < other) ||
(othIsNull && valIsDefined) ||
!othIsDefined
) {
return -1;
}
}
return 0;
}
/**
* @param {Array<object>} collection object with keys in attributes
* @param {Array<string>} iteratees attributes
* @param {Array<string>} orders asc | desc
*/
function orderBy(collection, iteratees, orders) {
if (!Array.isArray(collection)) {
return [];
}
if (!Array.isArray(orders)) {
orders = [];
}
var result = collection.map(function(value, index) {
return {
criteria: iteratees.map(function(iteratee) {
return value[iteratee];
}),
index: index,
value: value
};
});
result.sort(function comparer(object, other) {
var index = -1;
while (++index < object.criteria.length) {
var res = compareAscending(object.criteria[index], other.criteria[index]);
if (res) {
if (index >= orders.length) {
return res;
}
if (orders[index] === 'desc') {
return -res;
}
return res;
}
}
// This ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
});
return result.map(function(res) {
return res.value;
});
}
var orderBy_1 = orderBy;
var compact = function compact(array) {
if (!Array.isArray(array)) {
return [];
}
return array.filter(Boolean);
};
// @MAJOR can be replaced by native Array#findIndex when we change support
var findIndex = function find(array, comparator) {
if (!Array.isArray(array)) {
return -1;
}
for (var i = 0; i < array.length; i++) {
if (comparator(array[i])) {
return i;
}
}
return -1;
};
/**
* Transform sort format from user friendly notation to lodash format
* @param {string[]} sortBy array of predicate of the form "attribute:order"
* @param {string[]} [defaults] array of predicate of the form "attribute:order"
* @return {array.<string[]>} array containing 2 elements : attributes, orders
*/
var formatSort = function formatSort(sortBy, defaults) {
var defaultInstructions = (defaults || []).map(function(sort) {
return sort.split(':');
});
return sortBy.reduce(
function preparePredicate(out, sort) {
var sortInstruction = sort.split(':');
var matchingDefault = find$1(defaultInstructions, function(
defaultInstruction
) {
return defaultInstruction[0] === sortInstruction[0];
});
if (sortInstruction.length > 1 || !matchingDefault) {
out[0].push(sortInstruction[0]);
out[1].push(sortInstruction[1]);
return out;
}
out[0].push(matchingDefault[0]);
out[1].push(matchingDefault[1]);
return out;
},
[[], []]
);
};
var generateHierarchicalTree_1 = generateTrees;
function generateTrees(state) {
return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) {
var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex];
var hierarchicalFacetRefinement =
(state.hierarchicalFacetsRefinements[hierarchicalFacet.name] &&
state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0]) ||
'';
var hierarchicalSeparator = state._getHierarchicalFacetSeparator(
hierarchicalFacet
);
var hierarchicalRootPath = state._getHierarchicalRootPath(
hierarchicalFacet
);
var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(
hierarchicalFacet
);
var sortBy = formatSort(
state._getHierarchicalFacetSortBy(hierarchicalFacet)
);
var rootExhaustive = hierarchicalFacetResult.every(function(facetResult) {
return facetResult.exhaustive;
});
var generateTreeFn = generateHierarchicalTree(
sortBy,
hierarchicalSeparator,
hierarchicalRootPath,
hierarchicalShowParentLevel,
hierarchicalFacetRefinement
);
var results = hierarchicalFacetResult;
if (hierarchicalRootPath) {
results = hierarchicalFacetResult.slice(
hierarchicalRootPath.split(hierarchicalSeparator).length
);
}
return results.reduce(generateTreeFn, {
name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
count: null, // root level, no count
isRefined: true, // root level, always refined
path: null, // root level, no path
exhaustive: rootExhaustive,
data: null
});
};
}
function generateHierarchicalTree(
sortBy,
hierarchicalSeparator,
hierarchicalRootPath,
hierarchicalShowParentLevel,
currentRefinement
) {
return function generateTree(
hierarchicalTree,
hierarchicalFacetResult,
currentHierarchicalLevel
) {
var parent = hierarchicalTree;
if (currentHierarchicalLevel > 0) {
var level = 0;
parent = hierarchicalTree;
while (level < currentHierarchicalLevel) {
/**
* @type {object[]]} hierarchical data
*/
var data = parent && Array.isArray(parent.data) ? parent.data : [];
parent = find$1(data, function(subtree) {
return subtree.isRefined;
});
level++;
}
}
// we found a refined parent, let's add current level data under it
if (parent) {
// filter values in case an object has multiple categories:
// {
// categories: {
// level0: ['beers', 'bières'],
// level1: ['beers > IPA', 'bières > Belges']
// }
// }
//
// If parent refinement is `beers`, then we do not want to have `bières > Belges`
// showing up
var picked = Object.keys(hierarchicalFacetResult.data)
.map(function(facetValue) {
return [facetValue, hierarchicalFacetResult.data[facetValue]];
})
.filter(function(tuple) {
var facetValue = tuple[0];
return onlyMatchingTree(
facetValue,
parent.path || hierarchicalRootPath,
currentRefinement,
hierarchicalSeparator,
hierarchicalRootPath,
hierarchicalShowParentLevel
);
});
parent.data = orderBy_1(
picked.map(function(tuple) {
var facetValue = tuple[0];
var facetCount = tuple[1];
return format(
facetCount,
facetValue,
hierarchicalSeparator,
currentRefinement,
hierarchicalFacetResult.exhaustive
);
}),
sortBy[0],
sortBy[1]
);
}
return hierarchicalTree;
};
}
function onlyMatchingTree(
facetValue,
parentPath,
currentRefinement,
hierarchicalSeparator,
hierarchicalRootPath,
hierarchicalShowParentLevel
) {
// we want the facetValue is a child of hierarchicalRootPath
if (
hierarchicalRootPath &&
(facetValue.indexOf(hierarchicalRootPath) !== 0 ||
hierarchicalRootPath === facetValue)
) {
return false;
}
// we always want root levels (only when there is no prefix path)
return (
(!hierarchicalRootPath &&
facetValue.indexOf(hierarchicalSeparator) === -1) ||
// if there is a rootPath, being root level mean 1 level under rootPath
(hierarchicalRootPath &&
facetValue.split(hierarchicalSeparator).length -
hierarchicalRootPath.split(hierarchicalSeparator).length ===
1) ||
// if current refinement is a root level and current facetValue is a root level,
// keep the facetValue
(facetValue.indexOf(hierarchicalSeparator) === -1 &&
currentRefinement.indexOf(hierarchicalSeparator) === -1) ||
// currentRefinement is a child of the facet value
currentRefinement.indexOf(facetValue) === 0 ||
// facetValue is a child of the current parent, add it
(facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 &&
(hierarchicalShowParentLevel ||
facetValue.indexOf(currentRefinement) === 0))
);
}
function format(
facetCount,
facetValue,
hierarchicalSeparator,
currentRefinement,
exhaustive
) {
var parts = facetValue.split(hierarchicalSeparator);
return {
name: parts[parts.length - 1].trim(),
path: facetValue,
count: facetCount,
isRefined:
currentRefinement === facetValue ||
currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0,
exhaustive: exhaustive,
data: null
};
}
/**
* @typedef SearchResults.Facet
* @type {object}
* @property {string} name name of the attribute in the record
* @property {object} data the faceting data: value, number of entries
* @property {object} stats undefined unless facet_stats is retrieved from algolia
*/
/**
* @typedef SearchResults.HierarchicalFacet
* @type {object}
* @property {string} name name of the current value given the hierarchical level, trimmed.
* If root node, you get the facet name
* @property {number} count number of objects matching this hierarchical value
* @property {string} path the current hierarchical value full path
* @property {boolean} isRefined `true` if the current value was refined, `false` otherwise
* @property {HierarchicalFacet[]} data sub values for the current level
*/
/**
* @typedef SearchResults.FacetValue
* @type {object}
* @property {string} name the facet value itself
* @property {number} count times this facet appears in the results
* @property {boolean} isRefined is the facet currently selected
* @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets)
*/
/**
* @typedef Refinement
* @type {object}
* @property {string} type the type of filter used:
* `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical`
* @property {string} attributeName name of the attribute used for filtering
* @property {string} name the value of the filter
* @property {number} numericValue the value as a number. Only for numeric filters.
* @property {string} operator the operator used. Only for numeric filters.
* @property {number} count the number of computed hits for this filter. Only on facets.
* @property {boolean} exhaustive if the count is exhaustive
*/
/**
* @param {string[]} attributes
*/
function getIndices(attributes) {
var indices = {};
attributes.forEach(function(val, idx) {
indices[val] = idx;
});
return indices;
}
function assignFacetStats(dest, facetStats, key) {
if (facetStats && facetStats[key]) {
dest.stats = facetStats[key];
}
}
/**
* @typedef {Object} HierarchicalFacet
* @property {string} name
* @property {string[]} attributes
*/
/**
* @param {HierarchicalFacet[]} hierarchicalFacets
* @param {string} hierarchicalAttributeName
*/
function findMatchingHierarchicalFacetFromAttributeName(
hierarchicalFacets,
hierarchicalAttributeName
) {
return find$1(hierarchicalFacets, function facetKeyMatchesAttribute(
hierarchicalFacet
) {
var facetNames = hierarchicalFacet.attributes || [];
return facetNames.indexOf(hierarchicalAttributeName) > -1;
});
}
/*eslint-disable */
/**
* Constructor for SearchResults
* @class
* @classdesc SearchResults contains the results of a query to Algolia using the
* {@link AlgoliaSearchHelper}.
* @param {SearchParameters} state state that led to the response
* @param {array.<object>} results the results from algolia client
* @example <caption>SearchResults of the first query in
* <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption>
{
"hitsPerPage": 10,
"processingTimeMS": 2,
"facets": [
{
"name": "type",
"data": {
"HardGood": 6627,
"BlackTie": 550,
"Music": 665,
"Software": 131,
"Game": 456,
"Movie": 1571
},
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"Free shipping": 5507
},
"name": "shipping"
}
],
"hits": [
{
"thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
"_highlightResult": {
"shortDescription": {
"matchLevel": "none",
"value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"matchedWords": []
},
"category": {
"matchLevel": "none",
"value": "Computer Security Software",
"matchedWords": []
},
"manufacturer": {
"matchedWords": [],
"value": "Webroot",
"matchLevel": "none"
},
"name": {
"value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"matchedWords": [],
"matchLevel": "none"
}
},
"image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
"shipping": "Free shipping",
"bestSellingRank": 4,
"shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
"name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"category": "Computer Security Software",
"salePrice_range": "1 - 50",
"objectID": "1688832",
"type": "Software",
"customerReviewCount": 5980,
"salePrice": 49.99,
"manufacturer": "Webroot"
},
....
],
"nbHits": 10000,
"disjunctiveFacets": [
{
"exhaustive": false,
"data": {
"5": 183,
"12": 112,
"7": 149,
...
},
"name": "customerReviewCount",
"stats": {
"max": 7461,
"avg": 157.939,
"min": 1
}
},
{
"data": {
"Printer Ink": 142,
"Wireless Speakers": 60,
"Point & Shoot Cameras": 48,
...
},
"name": "category",
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"> 5000": 2,
"1 - 50": 6524,
"501 - 2000": 566,
"201 - 500": 1501,
"101 - 200": 1360,
"2001 - 5000": 47
},
"name": "salePrice_range"
},
{
"data": {
"Dynex™": 202,
"Insignia™": 230,
"PNY": 72,
...
},
"name": "manufacturer",
"exhaustive": false
}
],
"query": "",
"nbPages": 100,
"page": 0,
"index": "bestbuy"
}
**/
/*eslint-enable */
function SearchResults(state, results) {
var mainSubResponse = results[0];
this._rawResults = results;
/**
* query used to generate the results
* @member {string}
*/
this.query = mainSubResponse.query;
/**
* The query as parsed by the engine given all the rules.
* @member {string}
*/
this.parsedQuery = mainSubResponse.parsedQuery;
/**
* all the records that match the search parameters. Each record is
* augmented with a new attribute `_highlightResult`
* which is an object keyed by attribute and with the following properties:
* - `value` : the value of the facet highlighted (html)
* - `matchLevel`: full, partial or none depending on how the query terms match
* @member {object[]}
*/
this.hits = mainSubResponse.hits;
/**
* index where the results come from
* @member {string}
*/
this.index = mainSubResponse.index;
/**
* number of hits per page requested
* @member {number}
*/
this.hitsPerPage = mainSubResponse.hitsPerPage;
/**
* total number of hits of this query on the index
* @member {number}
*/
this.nbHits = mainSubResponse.nbHits;
/**
* total number of pages with respect to the number of hits per page and the total number of hits
* @member {number}
*/
this.nbPages = mainSubResponse.nbPages;
/**
* current page
* @member {number}
*/
this.page = mainSubResponse.page;
/**
* sum of the processing time of all the queries
* @member {number}
*/
this.processingTimeMS = results.reduce(function(sum, result) {
return result.processingTimeMS === undefined
? sum
: sum + result.processingTimeMS;
}, 0);
/**
* The position if the position was guessed by IP.
* @member {string}
* @example "48.8637,2.3615",
*/
this.aroundLatLng = mainSubResponse.aroundLatLng;
/**
* The radius computed by Algolia.
* @member {string}
* @example "126792922",
*/
this.automaticRadius = mainSubResponse.automaticRadius;
/**
* String identifying the server used to serve this request.
*
* getRankingInfo needs to be set to `true` for this to be returned
*
* @member {string}
* @example "c7-use-2.algolia.net",
*/
this.serverUsed = mainSubResponse.serverUsed;
/**
* Boolean that indicates if the computation of the counts did time out.
* @deprecated
* @member {boolean}
*/
this.timeoutCounts = mainSubResponse.timeoutCounts;
/**
* Boolean that indicates if the computation of the hits did time out.
* @deprecated
* @member {boolean}
*/
this.timeoutHits = mainSubResponse.timeoutHits;
/**
* True if the counts of the facets is exhaustive
* @member {boolean}
*/
this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount;
/**
* True if the number of hits is exhaustive
* @member {boolean}
*/
this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits;
/**
* Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/).
* @member {object[]}
*/
this.userData = mainSubResponse.userData;
/**
* queryID is the unique identifier of the query used to generate the current search results.
* This value is only available if the `clickAnalytics` search parameter is set to `true`.
* @member {string}
*/
this.queryID = mainSubResponse.queryID;
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
this.disjunctiveFacets = [];
/**
* disjunctive facets results
* @member {SearchResults.HierarchicalFacet[]}
*/
this.hierarchicalFacets = state.hierarchicalFacets.map(function initFutureTree() {
return [];
});
/**
* other facets results
* @member {SearchResults.Facet[]}
*/
this.facets = [];
var disjunctiveFacets = state.getRefinedDisjunctiveFacets();
var facetsIndices = getIndices(state.facets);
var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets);
var nextDisjunctiveResult = 1;
var self = this;
// Since we send request only for disjunctive facets that have been refined,
// we get the facets information from the first, general, response.
var mainFacets = mainSubResponse.facets || {};
Object.keys(mainFacets).forEach(function(facetKey) {
var facetValueObject = mainFacets[facetKey];
var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName(
state.hierarchicalFacets,
facetKey
);
if (hierarchicalFacet) {
// Place the hierarchicalFacet data at the correct index depending on
// the attributes order that was defined at the helper initialization
var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey);
var idxAttributeName = findIndex(state.hierarchicalFacets, function(f) {
return f.name === hierarchicalFacet.name;
});
self.hierarchicalFacets[idxAttributeName][facetIndex] = {
attribute: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
} else {
var isFacetDisjunctive = state.disjunctiveFacets.indexOf(facetKey) !== -1;
var isFacetConjunctive = state.facets.indexOf(facetKey) !== -1;
var position;
if (isFacetDisjunctive) {
position = disjunctiveFacetsIndices[facetKey];
self.disjunctiveFacets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey);
}
if (isFacetConjunctive) {
position = facetsIndices[facetKey];
self.facets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey);
}
}
});
// Make sure we do not keep holes within the hierarchical facets
this.hierarchicalFacets = compact(this.hierarchicalFacets);
// aggregate the refined disjunctive facets
disjunctiveFacets.forEach(function(disjunctiveFacet) {
var result = results[nextDisjunctiveResult];
var facets = result && result.facets ? result.facets : {};
var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet);
// There should be only item in facets.
Object.keys(facets).forEach(function(dfacet) {
var facetResults = facets[dfacet];
var position;
if (hierarchicalFacet) {
position = findIndex(state.hierarchicalFacets, function(f) {
return f.name === hierarchicalFacet.name;
});
var attributeIndex = findIndex(self.hierarchicalFacets[position], function(f) {
return f.attribute === dfacet;
});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
self.hierarchicalFacets[position][attributeIndex].data = merge_1(
{},
self.hierarchicalFacets[position][attributeIndex].data,
facetResults
);
} else {
position = disjunctiveFacetsIndices[dfacet];
var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {};
self.disjunctiveFacets[position] = {
name: dfacet,
data: defaultsPure({}, facetResults, dataFromMainRequest),
exhaustive: result.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet);
if (state.disjunctiveFacetsRefinements[dfacet]) {
state.disjunctiveFacetsRefinements[dfacet].forEach(function(refinementValue) {
// add the disjunctive refinements if it is no more retrieved
if (!self.disjunctiveFacets[position].data[refinementValue] &&
state.disjunctiveFacetsRefinements[dfacet].indexOf(refinementValue) > -1) {
self.disjunctiveFacets[position].data[refinementValue] = 0;
}
});
}
}
});
nextDisjunctiveResult++;
});
// if we have some root level values for hierarchical facets, merge them
state.getRefinedHierarchicalFacets().forEach(function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are already at a root refinement (or no refinement at all), there is no
// root level values request
if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) {
return;
}
var result = results[nextDisjunctiveResult];
var facets = result && result.facets
? result.facets
: {};
Object.keys(facets).forEach(function(dfacet) {
var facetResults = facets[dfacet];
var position = findIndex(state.hierarchicalFacets, function(f) {
return f.name === hierarchicalFacet.name;
});
var attributeIndex = findIndex(self.hierarchicalFacets[position], function(f) {
return f.attribute === dfacet;
});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
// when we always get root levels, if the hits refinement is `beers > IPA` (count: 5),
// then the disjunctive values will be `beers` (count: 100),
// but we do not want to display
// | beers (100)
// > IPA (5)
// We want
// | beers (5)
// > IPA (5)
var defaultData = {};
if (currentRefinement.length > 0) {
var root = currentRefinement[0].split(separator)[0];
defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root];
}
self.hierarchicalFacets[position][attributeIndex].data = defaultsPure(
defaultData,
facetResults,
self.hierarchicalFacets[position][attributeIndex].data
);
});
nextDisjunctiveResult++;
});
// add the excludes
Object.keys(state.facetsExcludes).forEach(function(facetName) {
var excludes = state.facetsExcludes[facetName];
var position = facetsIndices[facetName];
self.facets[position] = {
name: facetName,
data: mainSubResponse.facets[facetName],
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
excludes.forEach(function(facetValue) {
self.facets[position] = self.facets[position] || {name: facetName};
self.facets[position].data = self.facets[position].data || {};
self.facets[position].data[facetValue] = 0;
});
});
/**
* @type {Array}
*/
this.hierarchicalFacets = this.hierarchicalFacets.map(generateHierarchicalTree_1(state));
/**
* @type {Array}
*/
this.facets = compact(this.facets);
/**
* @type {Array}
*/
this.disjunctiveFacets = compact(this.disjunctiveFacets);
this._state = state;
}
/**
* Get a facet object with its name
* @deprecated
* @param {string} name name of the faceted attribute
* @return {SearchResults.Facet} the facet object
*/
SearchResults.prototype.getFacetByName = function(name) {
function predicate(facet) {
return facet.name === name;
}
return find$1(this.facets, predicate) ||
find$1(this.disjunctiveFacets, predicate) ||
find$1(this.hierarchicalFacets, predicate);
};
/**
* Get the facet values of a specified attribute from a SearchResults object.
* @private
* @param {SearchResults} results the search results to search in
* @param {string} attribute name of the faceted attribute to search for
* @return {array|object} facet values. For the hierarchical facets it is an object.
*/
function extractNormalizedFacetValues(results, attribute) {
function predicate(facet) {
return facet.name === attribute;
}
if (results._state.isConjunctiveFacet(attribute)) {
var facet = find$1(results.facets, predicate);
if (!facet) return [];
return Object.keys(facet.data).map(function(name) {
return {
name: name,
count: facet.data[name],
isRefined: results._state.isFacetRefined(attribute, name),
isExcluded: results._state.isExcludeRefined(attribute, name)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find$1(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return Object.keys(disjunctiveFacet.data).map(function(name) {
return {
name: name,
count: disjunctiveFacet.data[name],
isRefined: results._state.isDisjunctiveFacetRefined(attribute, name)
};
});
} else if (results._state.isHierarchicalFacet(attribute)) {
return find$1(results.hierarchicalFacets, predicate);
}
}
/**
* Sort nodes of a hierarchical facet results
* @private
* @param {HierarchicalFacet} node node to upon which we want to apply the sort
*/
function recSort(sortFn, node) {
if (!node.data || node.data.length === 0) {
return node;
}
var children = node.data.map(function(childNode) {
return recSort(sortFn, childNode);
});
var sortedChildren = sortFn(children);
var newNode = merge_1({}, node, {data: sortedChildren});
return newNode;
}
SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc'];
function vanillaSortFn(order, data) {
return data.sort(order);
}
/**
* Get a the list of values for a given facet attribute. Those values are sorted
* refinement first, descending count (bigger value on top), and name ascending
* (alphabetical order). The sort formula can overridden using either string based
* predicates or a function.
*
* This method will return all the values returned by the Algolia engine plus all
* the values already refined. This means that it can happen that the
* `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet)
* might not be respected if you have facet values that are already refined.
* @param {string} attribute attribute name
* @param {object} opts configuration options.
* @param {Array.<string> | function} opts.sortBy
* When using strings, it consists of
* the name of the [FacetValue](#SearchResults.FacetValue) or the
* [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the
* order (`asc` or `desc`). For example to order the value by count, the
* argument would be `['count:asc']`.
*
* If only the attribute name is specified, the ordering defaults to the one
* specified in the default value for this attribute.
*
* When not specified, the order is
* ascending. This parameter can also be a function which takes two facet
* values and should return a number, 0 if equal, 1 if the first argument is
* bigger or -1 otherwise.
*
* The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']`
* @return {FacetValue[]|HierarchicalFacet|undefined} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('result', function(event){
* //get values ordered only by name ascending using the string predicate
* event.results.getFacetValues('city', {sortBy: ['name:asc']});
* //get values ordered only by count ascending using a function
* event.results.getFacetValues('city', {
* // this is equivalent to ['count:asc']
* sortBy: function(a, b) {
* if (a.count === b.count) return 0;
* if (a.count > b.count) return 1;
* if (b.count > a.count) return -1;
* }
* });
* });
*/
SearchResults.prototype.getFacetValues = function(attribute, opts) {
var facetValues = extractNormalizedFacetValues(this, attribute);
if (!facetValues) {
return undefined;
}
var options = defaultsPure({}, opts, {sortBy: SearchResults.DEFAULT_SORT});
if (Array.isArray(options.sortBy)) {
var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT);
if (Array.isArray(facetValues)) {
return orderBy_1(facetValues, order[0], order[1]);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(function(hierarchicalFacetValues) {
return orderBy_1(hierarchicalFacetValues, order[0], order[1]);
}, facetValues);
} else if (typeof options.sortBy === 'function') {
if (Array.isArray(facetValues)) {
return facetValues.sort(options.sortBy);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(function(data) {
return vanillaSortFn(options.sortBy, data);
}, facetValues);
}
throw new Error(
'options.sortBy is optional but if defined it must be ' +
'either an array of string (predicates) or a sorting function'
);
};
/**
* Returns the facet stats if attribute is defined and the facet contains some.
* Otherwise returns undefined.
* @param {string} attribute name of the faceted attribute
* @return {object} The stats of the facet
*/
SearchResults.prototype.getFacetStats = function(attribute) {
if (this._state.isConjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.facets, attribute);
} else if (this._state.isDisjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute);
}
return undefined;
};
/**
* @typedef {Object} FacetListItem
* @property {string} name
*/
/**
* @param {FacetListItem[]} facetList (has more items, but enough for here)
* @param {string} facetName
*/
function getFacetStatsIfAvailable(facetList, facetName) {
var data = find$1(facetList, function(facet) {
return facet.name === facetName;
});
return data && data.stats;
}
/**
* Returns all refinements for all filters + tags. It also provides
* additional information: count and exhaustiveness for each filter.
*
* See the [refinement type](#Refinement) for an exhaustive view of the available
* data.
*
* Note that for a numeric refinement, results are grouped per operator, this
* means that it will return responses for operators which are empty.
*
* @return {Array.<Refinement>} all the refinements
*/
SearchResults.prototype.getRefinements = function() {
var state = this._state;
var results = this;
var res = [];
Object.keys(state.facetsRefinements).forEach(function(attributeName) {
state.facetsRefinements[attributeName].forEach(function(name) {
res.push(getRefinement(state, 'facet', attributeName, name, results.facets));
});
});
Object.keys(state.facetsExcludes).forEach(function(attributeName) {
state.facetsExcludes[attributeName].forEach(function(name) {
res.push(getRefinement(state, 'exclude', attributeName, name, results.facets));
});
});
Object.keys(state.disjunctiveFacetsRefinements).forEach(function(attributeName) {
state.disjunctiveFacetsRefinements[attributeName].forEach(function(name) {
res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets));
});
});
Object.keys(state.hierarchicalFacetsRefinements).forEach(function(attributeName) {
state.hierarchicalFacetsRefinements[attributeName].forEach(function(name) {
res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets));
});
});
Object.keys(state.numericRefinements).forEach(function(attributeName) {
var operators = state.numericRefinements[attributeName];
Object.keys(operators).forEach(function(operator) {
operators[operator].forEach(function(value) {
res.push({
type: 'numeric',
attributeName: attributeName,
name: value,
numericValue: value,
operator: operator
});
});
});
});
state.tagRefinements.forEach(function(name) {
res.push({type: 'tag', attributeName: '_tags', name: name});
});
return res;
};
/**
* @typedef {Object} Facet
* @property {string} name
* @property {Object} data
* @property {boolean} exhaustive
*/
/**
* @param {*} state
* @param {*} type
* @param {string} attributeName
* @param {*} name
* @param {Facet[]} resultsFacets
*/
function getRefinement(state, type, attributeName, name, resultsFacets) {
var facet = find$1(resultsFacets, function(f) {
return f.name === attributeName;
});
var count = facet && facet.data && facet.data[name] ? facet.data[name] : 0;
var exhaustive = (facet && facet.exhaustive) || false;
return {
type: type,
attributeName: attributeName,
name: name,
count: count,
exhaustive: exhaustive
};
}
/**
* @param {*} state
* @param {string} attributeName
* @param {*} name
* @param {Facet[]} resultsFacets
*/
function getHierarchicalRefinement(state, attributeName, name, resultsFacets) {
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var separator = state._getHierarchicalFacetSeparator(facetDeclaration);
var split = name.split(separator);
var rootFacet = find$1(resultsFacets, function(facet) {
return facet.name === attributeName;
});
var facet = split.reduce(function(intermediateFacet, part) {
var newFacet =
intermediateFacet && find$1(intermediateFacet.data, function(f) {
return f.name === part;
});
return newFacet !== undefined ? newFacet : intermediateFacet;
}, rootFacet);
var count = (facet && facet.count) || 0;
var exhaustive = (facet && facet.exhaustive) || false;
var path = (facet && facet.path) || '';
return {
type: 'hierarchical',
attributeName: attributeName,
name: path,
count: count,
exhaustive: exhaustive
};
}
var SearchResults_1 = SearchResults;
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
var events = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
function inherits(ctor, superCtor) {
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
var inherits_1 = inherits;
/**
* A DerivedHelper is a way to create sub requests to
* Algolia from a main helper.
* @class
* @classdesc The DerivedHelper provides an event based interface for search callbacks:
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
*/
function DerivedHelper(mainHelper, fn) {
this.main = mainHelper;
this.fn = fn;
this.lastResults = null;
}
inherits_1(DerivedHelper, events.EventEmitter);
/**
* Detach this helper from the main helper
* @return {undefined}
* @throws Error if the derived helper is already detached
*/
DerivedHelper.prototype.detach = function() {
this.removeAllListeners();
this.main.detachDerivedHelper(this);
};
DerivedHelper.prototype.getModifiedState = function(parameters) {
return this.fn(parameters);
};
var DerivedHelper_1 = DerivedHelper;
var requestBuilder = {
/**
* Get all the queries to send to the client, those queries can used directly
* with the Algolia client.
* @private
* @return {object[]} The queries
*/
_getQueries: function getQueries(index, state) {
var queries = [];
// One query for the hits
queries.push({
indexName: index,
params: requestBuilder._getHitsSearchParams(state)
});
// One for each disjunctive facets
state.getRefinedDisjunctiveFacets().forEach(function(refinedFacet) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet)
});
});
// maybe more to get the root level of hierarchical facets when activated
state.getRefinedHierarchicalFacets().forEach(function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are deeper than level 0 (starting from `beer > IPA`)
// we want to get the root values
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true)
});
}
});
return queries;
},
/**
* Build search parameters used to fetch hits
* @private
* @return {object.<string, any>}
*/
_getHitsSearchParams: function(state) {
var facets = state.facets
.concat(state.disjunctiveFacets)
.concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state));
var facetFilters = requestBuilder._getFacetFilters(state);
var numericFilters = requestBuilder._getNumericFilters(state);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
facets: facets,
tagFilters: tagFilters
};
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
return merge_1({}, state.getQueryParams(), additionalParams);
},
/**
* Build search parameters used to fetch a disjunctive facet
* @private
* @param {string} facet the associated facet name
* @param {boolean} hierarchicalRootLevel ?? FIXME
* @return {object}
*/
_getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) {
var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel);
var numericFilters = requestBuilder._getNumericFilters(state, facet);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
hitsPerPage: 1,
page: 0,
attributesToRetrieve: [],
attributesToHighlight: [],
attributesToSnippet: [],
tagFilters: tagFilters,
analytics: false,
clickAnalytics: false
};
var hierarchicalFacet = state.getHierarchicalFacetByName(facet);
if (hierarchicalFacet) {
additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute(
state,
hierarchicalFacet,
hierarchicalRootLevel
);
} else {
additionalParams.facets = facet;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
return merge_1({}, state.getQueryParams(), additionalParams);
},
/**
* Return the numeric filters in an algolia request fashion
* @private
* @param {string} [facetName] the name of the attribute for which the filters should be excluded
* @return {string[]} the numeric filters in the algolia format
*/
_getNumericFilters: function(state, facetName) {
if (state.numericFilters) {
return state.numericFilters;
}
var numericFilters = [];
Object.keys(state.numericRefinements).forEach(function(attribute) {
var operators = state.numericRefinements[attribute] || {};
Object.keys(operators).forEach(function(operator) {
var values = operators[operator] || [];
if (facetName !== attribute) {
values.forEach(function(value) {
if (Array.isArray(value)) {
var vs = value.map(function(v) {
return attribute + operator + v;
});
numericFilters.push(vs);
} else {
numericFilters.push(attribute + operator + value);
}
});
}
});
});
return numericFilters;
},
/**
* Return the tags filters depending
* @private
* @return {string}
*/
_getTagFilters: function(state) {
if (state.tagFilters) {
return state.tagFilters;
}
return state.tagRefinements.join(',');
},
/**
* Build facetFilters parameter based on current refinements. The array returned
* contains strings representing the facet filters in the algolia format.
* @private
* @param {string} [facet] if set, the current disjunctive facet
* @return {array.<string>}
*/
_getFacetFilters: function(state, facet, hierarchicalRootLevel) {
var facetFilters = [];
var facetsRefinements = state.facetsRefinements || {};
Object.keys(facetsRefinements).forEach(function(facetName) {
var facetValues = facetsRefinements[facetName] || [];
facetValues.forEach(function(facetValue) {
facetFilters.push(facetName + ':' + facetValue);
});
});
var facetsExcludes = state.facetsExcludes || {};
Object.keys(facetsExcludes).forEach(function(facetName) {
var facetValues = facetsExcludes[facetName] || [];
facetValues.forEach(function(facetValue) {
facetFilters.push(facetName + ':-' + facetValue);
});
});
var disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements || {};
Object.keys(disjunctiveFacetsRefinements).forEach(function(facetName) {
var facetValues = disjunctiveFacetsRefinements[facetName] || [];
if (facetName === facet || !facetValues || facetValues.length === 0) {
return;
}
var orFilters = [];
facetValues.forEach(function(facetValue) {
orFilters.push(facetName + ':' + facetValue);
});
facetFilters.push(orFilters);
});
var hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements || {};
Object.keys(hierarchicalFacetsRefinements).forEach(function(facetName) {
var facetValues = hierarchicalFacetsRefinements[facetName] || [];
var facetValue = facetValues[0];
if (facetValue === undefined) {
return;
}
var hierarchicalFacet = state.getHierarchicalFacetByName(facetName);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeToRefine;
var attributesIndex;
// we ask for parent facet values only when the `facet` is the current hierarchical facet
if (facet === facetName) {
// if we are at the root level already, no need to ask for facet values, we get them from
// the hits query
if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) ||
(rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) {
return;
}
if (!rootPath) {
attributesIndex = facetValue.split(separator).length - 2;
facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator));
} else {
attributesIndex = rootPath.split(separator).length - 1;
facetValue = rootPath;
}
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
} else {
attributesIndex = facetValue.split(separator).length - 1;
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
}
if (attributeToRefine) {
facetFilters.push([attributeToRefine + ':' + facetValue]);
}
});
return facetFilters;
},
_getHitsHierarchicalFacetsAttributes: function(state) {
var out = [];
return state.hierarchicalFacets.reduce(
// ask for as much levels as there's hierarchical refinements
function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) {
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0];
// if no refinement, ask for root level
if (!hierarchicalRefinement) {
allAttributes.push(hierarchicalFacet.attributes[0]);
return allAttributes;
}
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var level = hierarchicalRefinement.split(separator).length;
var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1);
return allAttributes.concat(newAttributes);
}, out);
},
_getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) {
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (rootLevel === true) {
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeIndex = 0;
if (rootPath) {
attributeIndex = rootPath.split(separator).length;
}
return [hierarchicalFacet.attributes[attributeIndex]];
}
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || '';
// if refinement is 'beers > IPA > Flying dog',
// then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values)
var parentLevel = hierarchicalRefinement.split(separator).length - 1;
return hierarchicalFacet.attributes.slice(0, parentLevel + 1);
},
getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) {
var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ?
state.clearRefinements(facetName) :
state;
var searchForFacetSearchParameters = {
facetQuery: query,
facetName: facetName
};
if (typeof maxFacetHits === 'number') {
searchForFacetSearchParameters.maxFacetHits = maxFacetHits;
}
return merge_1(
{},
requestBuilder._getHitsSearchParams(stateForSearchForFacetValues),
searchForFacetSearchParameters
);
}
};
var requestBuilder_1 = requestBuilder;
var version = '3.1.0';
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {object} event
* @property {SearchParameters} event.state the current parameters with the latest changes applied
* @property {SearchResults} event.results the previous results received from Algolia. `null` before the first request
* @example
* helper.on('change', function(event) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when a main search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search
* @property {SearchResults} event.results the results from the previous search. `null` if it is the first search.
* @example
* helper.on('search', function(event) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when a search using `searchForFacetValues` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchForFacetValues
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search it is the first search.
* @property {string} event.facet the facet searched into
* @property {string} event.query the query used to search in the facets
* @example
* helper.on('searchForFacetValues', function(event) {
* console.log('searchForFacetValues sent');
* });
*/
/**
* Event triggered when a search using `searchOnce` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchOnce
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search it is the first search.
* @example
* helper.on('searchOnce', function(event) {
* console.log('searchOnce sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {object} event
* @property {SearchResults} event.results the results received from Algolia
* @property {SearchParameters} event.state the parameters used to query Algolia. Those might be different from the one in the helper instance (for example if the network is unreliable).
* @example
* helper.on('result', function(event) {
* console.log('Search results received');
* });
*/
/**
* Event triggered when Algolia sends back an error. For example, if an unknown parameter is
* used, the error can be caught using this event.
* @event AlgoliaSearchHelper#event:error
* @property {object} event
* @property {Error} event.error the error returned by the Algolia.
* @example
* helper.on('error', function(event) {
* console.log('Houston we got a problem.');
* });
*/
/**
* Event triggered when the queue of queries have been depleted (with any result or outdated queries)
* @event AlgoliaSearchHelper#event:searchQueueEmpty
* @example
* helper.on('searchQueueEmpty', function() {
* console.log('No more search pending');
* // This is received before the result event if we're not expecting new results
* });
*
* helper.search();
*/
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
* search. It provides an event based interface for search callbacks:
* - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the
* {@link SearchResults} of the last result if any.
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial
* config of the search. It doesn't have to be a {SearchParameters},
* just an object containing the properties you need from it.
*/
function AlgoliaSearchHelper(client, index, options) {
if (typeof client.addAlgoliaAgent === 'function') {
client.addAlgoliaAgent('JS Helper (' + version + ')');
}
this.setClient(client);
var opts = options || {};
opts.index = index;
this.state = SearchParameters_1.make(opts);
this.lastResults = null;
this._queryId = 0;
this._lastQueryIdReceived = -1;
this.derivedHelpers = [];
this._currentNbQueries = 0;
}
inherits_1(AlgoliaSearchHelper, events.EventEmitter);
/**
* Start the search with the parameters set in the state. When the
* method is called, it triggers a `search` event. The results will
* be available through the `result` event. If an error occurs, an
* `error` will be fired instead.
* @return {AlgoliaSearchHelper}
* @fires search
* @fires result
* @fires error
* @chainable
*/
AlgoliaSearchHelper.prototype.search = function() {
this._search({onlyWithDerivedHelpers: false});
return this;
};
AlgoliaSearchHelper.prototype.searchOnlyWithDerivedHelpers = function() {
this._search({onlyWithDerivedHelpers: true});
return this;
};
/**
* Gets the search query parameters that would be sent to the Algolia Client
* for the hits
* @return {object} Query Parameters
*/
AlgoliaSearchHelper.prototype.getQuery = function() {
var state = this.state;
return requestBuilder_1._getHitsSearchParams(state);
};
/**
* Start a search using a modified version of the current state. This method does
* not trigger the helper lifecycle and does not modify the state kept internally
* by the helper. This second aspect means that the next search call will be the
* same as a search call before calling searchOnce.
* @param {object} options can contain all the parameters that can be set to SearchParameters
* plus the index
* @param {function} [callback] optional callback executed when the response from the
* server is back.
* @return {promise|undefined} if a callback is passed the method returns undefined
* otherwise it returns a promise containing an object with two keys :
* - content with a SearchResults
* - state with the state used for the query as a SearchParameters
* @example
* // Changing the number of records returned per page to 1
* // This example uses the callback API
* var state = helper.searchOnce({hitsPerPage: 1},
* function(error, content, state) {
* // if an error occurred it will be passed in error, otherwise its value is null
* // content contains the results formatted as a SearchResults
* // state is the instance of SearchParameters used for this search
* });
* @example
* // Changing the number of records returned per page to 1
* // This example uses the promise API
* var state1 = helper.searchOnce({hitsPerPage: 1})
* .then(promiseHandler);
*
* function promiseHandler(res) {
* // res contains
* // {
* // content : SearchResults
* // state : SearchParameters (the one used for this specific search)
* // }
* }
*/
AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) {
var tempState = !options ? this.state : this.state.setQueryParameters(options);
var queries = requestBuilder_1._getQueries(tempState.index, tempState);
var self = this;
this._currentNbQueries++;
this.emit('searchOnce', {
state: tempState
});
if (cb) {
this.client
.search(queries)
.then(function(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) {
self.emit('searchQueueEmpty');
}
cb(null, new SearchResults_1(tempState, content.results), tempState);
})
.catch(function(err) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) {
self.emit('searchQueueEmpty');
}
cb(err, null, tempState);
});
return undefined;
}
return this.client.search(queries).then(function(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
return {
content: new SearchResults_1(tempState, content.results),
state: tempState,
_originalResponse: content
};
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Structure of each result when using
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* @typedef FacetSearchHit
* @type {object}
* @property {string} value the facet value
* @property {string} highlighted the facet value highlighted with the query string
* @property {number} count number of occurrence of this facet value
* @property {boolean} isRefined true if the value is already refined
*/
/**
* Structure of the data resolved by the
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* promise.
* @typedef FacetSearchResult
* @type {object}
* @property {FacetSearchHit} facetHits the results for this search for facet values
* @property {number} processingTimeMS time taken by the query inside the engine
*/
/**
* Search for facet values based on an query and the name of a faceted attribute. This
* triggers a search and will return a promise. On top of using the query, it also sends
* the parameters from the state so that the search is narrowed down to only the possible values.
*
* See the description of [FacetSearchResult](reference.html#FacetSearchResult)
* @param {string} facet the name of the faceted attribute
* @param {string} query the string query for the search
* @param {number} [maxFacetHits] the maximum number values returned. Should be > 0 and <= 100
* @param {object} [userState] the set of custom parameters to use on top of the current state. Setting a property to `undefined` removes
* it in the generated query.
* @return {promise.<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits, userState) {
var clientHasSFFV = typeof this.client.searchForFacetValues === 'function';
if (
!clientHasSFFV &&
typeof this.client.initIndex !== 'function'
) {
throw new Error(
'search for facet values (searchable) was called, but this client does not have a function client.searchForFacetValues or client.initIndex(index).searchForFacetValues'
);
}
var state = this.state.setQueryParameters(userState || {});
var isDisjunctive = state.isDisjunctiveFacet(facet);
var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, state);
this._currentNbQueries++;
var self = this;
this.emit('searchForFacetValues', {
state: state,
facet: facet,
query: query
});
var searchForFacetValuesPromise = clientHasSFFV
? this.client.searchForFacetValues([{indexName: state.index, params: algoliaQuery}])
: this.client.initIndex(state.index).searchForFacetValues(algoliaQuery);
return searchForFacetValuesPromise.then(function addIsRefined(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
content = Array.isArray(content) ? content[0] : content;
content.facetHits.forEach(function(f) {
f.isRefined = isDisjunctive
? state.isDisjunctiveFacetRefined(facet, f.value)
: state.isFacetRefined(facet, f.value);
});
return content;
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Sets the text query used for the search.
*
* This method resets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setQuery = function(q) {
this._change({
state: this.state.resetPage().setQuery(q),
isPageReset: true
});
return this;
};
/**
* Remove all the types of refinements except tags. A string can be provided to remove
* only the refinements of a specific attribute. For more advanced use case, you can
* provide a function instead. This function should follow the
* [clearCallback definition](#SearchParameters.clearCallback).
*
* This method resets the current page to 0.
* @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* // Removing all the refinements
* helper.clearRefinements().search();
* @example
* // Removing all the filters on a the category attribute.
* helper.clearRefinements('category').search();
* @example
* // Removing only the exclude filters on the category facet.
* helper.clearRefinements(function(value, attribute, type) {
* return type === 'exclude' && attribute === 'category';
* }).search();
*/
AlgoliaSearchHelper.prototype.clearRefinements = function(name) {
this._change({
state: this.state.resetPage().clearRefinements(name),
isPageReset: true
});
return this;
};
/**
* Remove all the tag filters.
*
* This method resets the current page to 0.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.clearTags = function() {
this._change({
state: this.state.resetPage().clearTags(),
isPageReset: true
});
return this;
};
/**
* Adds a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().addDisjunctiveFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() {
return this.addDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Adds a refinement on a hierarchical facet. It will throw
* an exception if the facet is not defined or if the facet
* is already refined.
*
* This method resets the current page to 0.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is refined
* @chainable
* @fires change
*/
AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().addHierarchicalFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} operator the operator of the filter
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) {
this._change({
state: this.state.resetPage().addNumericRefinement(attribute, operator, value),
isPageReset: true
});
return this;
};
/**
* Adds a filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().addFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addRefine = function() {
return this.addFacetRefinement.apply(this, arguments);
};
/**
* Adds a an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) {
this._change({
state: this.state.resetPage().addExcludeRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion}
*/
AlgoliaSearchHelper.prototype.addExclude = function() {
return this.addFacetExclusion.apply(this, arguments);
};
/**
* Adds a tag filter with the `tag` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addTag = function(tag) {
this._change({
state: this.state.resetPage().addTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Removes an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* Some parameters are optional, triggering different behavior:
* - if the value is not provided, then all the numeric value will be removed for the
* specified attribute/operator couple.
* - if the operator is not provided either, then all the numeric filter on this attribute
* will be removed.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} [operator] the operator of the filter
* @param {number} [value] the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) {
this._change({
state: this.state.resetPage().removeNumericRefinement(attribute, operator, value),
isPageReset: true
});
return this;
};
/**
* Removes a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().removeDisjunctiveFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() {
return this.removeDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is not refined
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) {
this._change({
state: this.state.resetPage().removeHierarchicalFacetRefinement(facet),
isPageReset: true
});
return this;
};
/**
* Removes a filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().removeFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeRefine = function() {
return this.removeFacetRefinement.apply(this, arguments);
};
/**
* Removes an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) {
this._change({
state: this.state.resetPage().removeExcludeRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion}
*/
AlgoliaSearchHelper.prototype.removeExclude = function() {
return this.removeFacetExclusion.apply(this, arguments);
};
/**
* Removes a tag filter with the `tag` provided. If the
* filter is not set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeTag = function(tag) {
this._change({
state: this.state.resetPage().removeTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) {
this._change({
state: this.state.resetPage().toggleExcludeFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion}
*/
AlgoliaSearchHelper.prototype.toggleExclude = function() {
return this.toggleFacetExclusion.apply(this, arguments);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
* @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) {
return this.toggleFacetRefinement(facet, value);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) {
this._change({
state: this.state.resetPage().toggleFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefine = function() {
return this.toggleFacetRefinement.apply(this, arguments);
};
/**
* Adds or removes a tag filter with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleTag = function(tag) {
this._change({
state: this.state.resetPage().toggleTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Increments the page number by one.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setPage(0).nextPage().getPage();
* // returns 1
*/
AlgoliaSearchHelper.prototype.nextPage = function() {
var page = this.state.page || 0;
return this.setPage(page + 1);
};
/**
* Decrements the page number by one.
* @fires change
* @return {AlgoliaSearchHelper}
* @chainable
* @example
* helper.setPage(1).previousPage().getPage();
* // returns 0
*/
AlgoliaSearchHelper.prototype.previousPage = function() {
var page = this.state.page || 0;
return this.setPage(page - 1);
};
/**
* @private
*/
function setCurrentPage(page) {
if (page < 0) throw new Error('Page requested below 0.');
this._change({
state: this.state.setPage(page),
isPageReset: false
});
return this;
}
/**
* Change the current page
* @deprecated
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage;
/**
* Updates the current page.
* @function
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setPage = setCurrentPage;
/**
* Updates the name of the index that will be targeted by the query.
*
* This method resets the current page to 0.
* @param {string} name the index name
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setIndex = function(name) {
this._change({
state: this.state.resetPage().setIndex(name),
isPageReset: true
});
return this;
};
/**
* Update a parameter of the search. This method reset the page
*
* The complete list of parameters is available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters and facets have their own API)
*
* This method resets the current page to 0.
* @param {string} parameter name of the parameter to update
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setQueryParameter('hitsPerPage', 20).search();
*/
AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) {
this._change({
state: this.state.resetPage().setQueryParameter(parameter, value),
isPageReset: true
});
return this;
};
/**
* Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setState = function(newState) {
this._change({
state: SearchParameters_1.make(newState),
isPageReset: false
});
return this;
};
/**
* Override the current state without triggering a change event.
* Do not use this method unless you know what you are doing. (see the example
* for a legit use case)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @example
* helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
* updateYourURL(state)
* })
* window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
* helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
* @chainable
*/
AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) {
this.state = new SearchParameters_1(newState);
return this;
};
/**
* Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
* @example
* // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
* helper.hasRefinements('price'); // false
* helper.addNumericRefinement('price', '>', 100);
* helper.hasRefinements('price'); // true
*
* helper.hasRefinements('color'); // false
* helper.addFacetRefinement('color', 'blue');
* helper.hasRefinements('color'); // true
*
* helper.hasRefinements('material'); // false
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* helper.hasRefinements('material'); // true
*
* helper.hasRefinements('categories'); // false
* helper.toggleFacetRefinement('categories', 'kitchen > knife');
* helper.hasRefinements('categories'); // true
*
*/
AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) {
if (objectHasKeys_1(this.state.getNumericRefinements(attribute))) {
return true;
} else if (this.state.isConjunctiveFacet(attribute)) {
return this.state.isFacetRefined(attribute);
} else if (this.state.isDisjunctiveFacet(attribute)) {
return this.state.isDisjunctiveFacetRefined(attribute);
} else if (this.state.isHierarchicalFacet(attribute)) {
return this.state.isHierarchicalFacetRefined(attribute);
}
// there's currently no way to know that the user did call `addNumericRefinement` at some point
// thus we cannot distinguish if there once was a numeric refinement that was cleared
// so we will return false in every other situations to be consistent
// while what we should do here is throw because we did not find the attribute in any type
// of refinement
return false;
};
/**
* Check if a value is excluded for a specific faceted attribute. If the value
* is omitted then the function checks if there is any excluding refinements.
*
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} true if refined
* @example
* helper.isExcludeRefined('color'); // false
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // false
*
* helper.addFacetExclusion('color', 'red');
*
* helper.isExcludeRefined('color'); // true
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // true
*/
AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) {
return this.state.isExcludeRefined(facet, value);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) {
return this.state.isDisjunctiveFacetRefined(facet, value);
};
/**
* Check if the string is a currently filtering tag.
* @param {string} tag tag to check
* @return {boolean}
*/
AlgoliaSearchHelper.prototype.hasTag = function(tag) {
return this.state.isTagRefined(tag);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag}
*/
AlgoliaSearchHelper.prototype.isTagRefined = function() {
return this.hasTagRefinements.apply(this, arguments);
};
/**
* Get the name of the currently used index.
* @return {string}
* @example
* helper.setIndex('highestPrice_products').getIndex();
* // returns 'highestPrice_products'
*/
AlgoliaSearchHelper.prototype.getIndex = function() {
return this.state.index;
};
function getCurrentPage() {
return this.state.page;
}
/**
* Get the currently selected page
* @deprecated
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage;
/**
* Get the currently selected page
* @function
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getPage = getCurrentPage;
/**
* Get all the tags currently set to filters the results.
*
* @return {string[]} The list of tags currently set.
*/
AlgoliaSearchHelper.prototype.getTags = function() {
return this.state.tagRefinements;
};
/**
* Get the list of refinements for a given attribute. This method works with
* conjunctive, disjunctive, excluding and numerical filters.
*
* See also SearchResults#getRefinements
*
* @param {string} facetName attribute name used for faceting
* @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and
* a type. Numeric also contains an operator.
* @example
* helper.addNumericRefinement('price', '>', 100);
* helper.getRefinements('price');
* // [
* // {
* // "value": [
* // 100
* // ],
* // "operator": ">",
* // "type": "numeric"
* // }
* // ]
* @example
* helper.addFacetRefinement('color', 'blue');
* helper.addFacetExclusion('color', 'red');
* helper.getRefinements('color');
* // [
* // {
* // "value": "blue",
* // "type": "conjunctive"
* // },
* // {
* // "value": "red",
* // "type": "exclude"
* // }
* // ]
* @example
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* // [
* // {
* // "value": "plastic",
* // "type": "disjunctive"
* // }
* // ]
*/
AlgoliaSearchHelper.prototype.getRefinements = function(facetName) {
var refinements = [];
if (this.state.isConjunctiveFacet(facetName)) {
var conjRefinements = this.state.getConjunctiveRefinements(facetName);
conjRefinements.forEach(function(r) {
refinements.push({
value: r,
type: 'conjunctive'
});
});
var excludeRefinements = this.state.getExcludeRefinements(facetName);
excludeRefinements.forEach(function(r) {
refinements.push({
value: r,
type: 'exclude'
});
});
} else if (this.state.isDisjunctiveFacet(facetName)) {
var disjRefinements = this.state.getDisjunctiveRefinements(facetName);
disjRefinements.forEach(function(r) {
refinements.push({
value: r,
type: 'disjunctive'
});
});
}
var numericRefinements = this.state.getNumericRefinements(facetName);
Object.keys(numericRefinements).forEach(function(operator) {
var value = numericRefinements[operator];
refinements.push({
value: value,
operator: operator,
type: 'numeric'
});
});
return refinements;
};
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute attribute in the record
* @param {string} operator operator applied on the refined values
* @return {Array.<number|number[]>} refined values
*/
AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) {
return this.state.getNumericRefinement(attribute, operator);
};
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) {
return this.state.getHierarchicalFacetBreadcrumb(facetName);
};
// /////////// PRIVATE
/**
* Perform the underlying queries
* @private
* @return {undefined}
* @fires search
* @fires result
* @fires error
*/
AlgoliaSearchHelper.prototype._search = function(options) {
var state = this.state;
var states = [];
var mainQueries = [];
if (!options.onlyWithDerivedHelpers) {
mainQueries = requestBuilder_1._getQueries(state.index, state);
states.push({
state: state,
queriesCount: mainQueries.length,
helper: this
});
this.emit('search', {
state: state,
results: this.lastResults
});
}
var derivedQueries = this.derivedHelpers.map(function(derivedHelper) {
var derivedState = derivedHelper.getModifiedState(state);
var derivedStateQueries = requestBuilder_1._getQueries(derivedState.index, derivedState);
states.push({
state: derivedState,
queriesCount: derivedStateQueries.length,
helper: derivedHelper
});
derivedHelper.emit('search', {
state: derivedState,
results: derivedHelper.lastResults
});
return derivedStateQueries;
});
var queries = Array.prototype.concat.apply(mainQueries, derivedQueries);
var queryId = this._queryId++;
this._currentNbQueries++;
try {
this.client.search(queries)
.then(this._dispatchAlgoliaResponse.bind(this, states, queryId))
.catch(this._dispatchAlgoliaError.bind(this, queryId));
} catch (error) {
// If we reach this part, we're in an internal error state
this.emit('error', {
error: error
});
}
};
/**
* Transform the responses as sent by the server and transform them into a user
* usable object that merge the results of all the batch requests. It will dispatch
* over the different helper + derived helpers (when there are some).
* @private
* @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>}
* state state used for to generate the request
* @param {number} queryId id of the current request
* @param {object} content content of the response
* @return {undefined}
*/
AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, content) {
// FIXME remove the number of outdated queries discarded instead of just one
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._currentNbQueries -= (queryId - this._lastQueryIdReceived);
this._lastQueryIdReceived = queryId;
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
var results = content.results.slice();
states.forEach(function(s) {
var state = s.state;
var queriesCount = s.queriesCount;
var helper = s.helper;
var specificResults = results.splice(0, queriesCount);
var formattedResponse = helper.lastResults = new SearchResults_1(state, specificResults);
helper.emit('result', {
results: formattedResponse,
state: state
});
});
};
AlgoliaSearchHelper.prototype._dispatchAlgoliaError = function(queryId, error) {
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._currentNbQueries -= queryId - this._lastQueryIdReceived;
this._lastQueryIdReceived = queryId;
this.emit('error', {
error: error
});
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
};
AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) {
return query ||
facetFilters.length !== 0 ||
numericFilters.length !== 0 ||
tagFilters.length !== 0;
};
/**
* Test if there are some disjunctive refinements on the facet
* @private
* @param {string} facet the attribute to test
* @return {boolean}
*/
AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) {
return this.state.disjunctiveRefinements[facet] &&
this.state.disjunctiveRefinements[facet].length > 0;
};
AlgoliaSearchHelper.prototype._change = function(event) {
var state = event.state;
var isPageReset = event.isPageReset;
if (state !== this.state) {
this.state = state;
this.emit('change', {
state: this.state,
results: this.lastResults,
isPageReset: isPageReset
});
}
};
/**
* Clears the cache of the underlying Algolia client.
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.clearCache = function() {
this.client.clearCache && this.client.clearCache();
return this;
};
/**
* Updates the internal client instance. If the reference of the clients
* are equal then no update is actually done.
* @param {AlgoliaSearch} newClient an AlgoliaSearch client
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.setClient = function(newClient) {
if (this.client === newClient) return this;
if (typeof newClient.addAlgoliaAgent === 'function') {
newClient.addAlgoliaAgent('JS Helper (' + version + ')');
}
this.client = newClient;
return this;
};
/**
* Gets the instance of the currently used client.
* @return {AlgoliaSearch}
*/
AlgoliaSearchHelper.prototype.getClient = function() {
return this.client;
};
/**
* Creates an derived instance of the Helper. A derived helper
* is a way to request other indices synchronised with the lifecycle
* of the main Helper. This mechanism uses the multiqueries feature
* of Algolia to aggregate all the requests in a single network call.
*
* This method takes a function that is used to create a new SearchParameter
* that will be used to create requests to Algolia. Those new requests
* are created just before the `search` event. The signature of the function
* is `SearchParameters -> SearchParameters`.
*
* This method returns a new DerivedHelper which is an EventEmitter
* that fires the same `search`, `result` and `error` events. Those
* events, however, will receive data specific to this DerivedHelper
* and the SearchParameters that is returned by the call of the
* parameter function.
* @param {function} fn SearchParameters -> SearchParameters
* @return {DerivedHelper}
*/
AlgoliaSearchHelper.prototype.derive = function(fn) {
var derivedHelper = new DerivedHelper_1(this, fn);
this.derivedHelpers.push(derivedHelper);
return derivedHelper;
};
/**
* This method detaches a derived Helper from the main one. Prefer using the one from the
* derived helper itself, to remove the event listeners too.
* @private
* @return {undefined}
* @throws Error
*/
AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) {
var pos = this.derivedHelpers.indexOf(derivedHelper);
if (pos === -1) throw new Error('Derived helper already detached');
this.derivedHelpers.splice(pos, 1);
};
/**
* This method returns true if there is currently at least one on-going search.
* @return {boolean} true if there is a search pending
*/
AlgoliaSearchHelper.prototype.hasPendingRequests = function() {
return this._currentNbQueries > 0;
};
/**
* @typedef AlgoliaSearchHelper.NumericRefinement
* @type {object}
* @property {number[]} value the numbers that are used for filtering this attribute with
* the operator specified.
* @property {string} operator the faceting data: value, number of entries
* @property {string} type will be 'numeric'
*/
/**
* @typedef AlgoliaSearchHelper.FacetRefinement
* @type {object}
* @property {string} value the string use to filter the attribute
* @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude'
*/
var algoliasearch_helper = AlgoliaSearchHelper;
/**
* The algoliasearchHelper module is the function that will let its
* contains everything needed to use the Algoliasearch
* Helper. It is a also a function that instanciate the helper.
* To use the helper, you also need the Algolia JS client v3.
* @example
* //using the UMD build
* var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
* var helper = algoliasearchHelper(client, 'bestbuy', {
* facets: ['shipping'],
* disjunctiveFacets: ['category']
* });
* helper.on('result', function(event) {
* console.log(event.results);
* });
* helper
* .toggleFacetRefinement('category', 'Movies & TV Shows')
* .toggleFacetRefinement('shipping', 'Free shipping')
* .search();
* @example
* // The helper is an event emitter using the node API
* helper.on('result', updateTheResults);
* helper.once('result', updateTheResults);
* helper.removeListener('result', updateTheResults);
* helper.removeAllListeners('result');
* @module algoliasearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the name of the index to query
* @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
* @return {AlgoliaSearchHelper}
*/
function algoliasearchHelper(client, index, opts) {
return new algoliasearch_helper(client, index, opts);
}
/**
* The version currently used
* @member module:algoliasearchHelper.version
* @type {number}
*/
algoliasearchHelper.version = version;
/**
* Constructor for the Helper.
* @member module:algoliasearchHelper.AlgoliaSearchHelper
* @type {AlgoliaSearchHelper}
*/
algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper;
/**
* Constructor for the object containing all the parameters of the search.
* @member module:algoliasearchHelper.SearchParameters
* @type {SearchParameters}
*/
algoliasearchHelper.SearchParameters = SearchParameters_1;
/**
* Constructor for the object containing the results of the search.
* @member module:algoliasearchHelper.SearchResults
* @type {SearchResults}
*/
algoliasearchHelper.SearchResults = SearchResults_1;
var algoliasearchHelper_1 = algoliasearchHelper;
function createOptionalFilter(_ref) {
var attributeName = _ref.attributeName,
attributeValue = _ref.attributeValue,
attributeScore = _ref.attributeScore;
return "".concat(attributeName, ":").concat(attributeValue, "<score=").concat(attributeScore || 1, ">");
}
var defaultProps = {
transformSearchParameters: function transformSearchParameters(x) {
return _objectSpread({}, x);
}
};
function getId$1() {
// We store the search state of this widget in `configure`.
return 'configure';
}
function getSearchParametersFromProps(props) {
var optionalFilters = Object.keys(props.matchingPatterns).reduce(function (acc, attributeName) {
var attributePattern = props.matchingPatterns[attributeName];
var attributeValue = props.hit[attributeName];
var attributeScore = attributePattern.score;
if (Array.isArray(attributeValue)) {
return [].concat(_toConsumableArray(acc), [attributeValue.map(function (attributeSubValue) {
return createOptionalFilter({
attributeName: attributeName,
attributeValue: attributeSubValue,
attributeScore: attributeScore
});
})]);
}
if (typeof attributeValue === 'string') {
return [].concat(_toConsumableArray(acc), [createOptionalFilter({
attributeName: attributeName,
attributeValue: attributeValue,
attributeScore: attributeScore
})]);
}
return acc;
}, []);
return props.transformSearchParameters(new algoliasearchHelper_1.SearchParameters({
// @ts-ignore @TODO algoliasearch-helper@3.0.1 will contain the type
// `sumOrFiltersScores`.
// See https://github.com/algolia/algoliasearch-helper-js/pull/753
sumOrFiltersScores: true,
facetFilters: ["objectID:-".concat(props.hit.objectID)],
optionalFilters: optionalFilters
}));
}
var connectConfigureRelatedItems = createConnectorWithContext({
displayName: 'AlgoliaConfigureRelatedItems',
defaultProps: defaultProps,
getProvidedProps: function getProvidedProps() {
return {};
},
getSearchParameters: function getSearchParameters(searchParameters, props) {
return searchParameters.setQueryParameters(getSearchParametersFromProps(props));
},
transitionState: function transitionState(props, _prevSearchState, nextSearchState) {
var id = getId$1(); // We need to transform the exhaustive search parameters back to clean
// search parameters without the empty default keys so we don't pollute the
// `configure` search state.
var searchParameters = removeEmptyArraysFromObject(removeEmptyKey(getSearchParametersFromProps(props)));
var searchParametersKeys = Object.keys(searchParameters);
var nonPresentKeys = this._searchParameters ? Object.keys(this._searchParameters).filter(function (prop) {
return searchParametersKeys.indexOf(prop) === -1;
}) : [];
this._searchParameters = searchParameters;
var nextValue = _defineProperty({}, id, _objectSpread({}, omit(nextSearchState[id], nonPresentKeys), searchParameters));
return refineValue(nextSearchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
var _this = this;
var id = getId$1();
var indexId = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var subState = hasMultipleIndices({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) && searchState.indices ? searchState.indices[indexId] : searchState;
var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : [];
var configureState = configureKeys.reduce(function (acc, item) {
if (!_this._searchParameters[item]) {
acc[item] = subState[id][item];
}
return acc;
}, {});
var nextValue = _defineProperty({}, id, configureState);
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
function emptyFunction() {}
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret_1) {
// It is still safe when called from React.
return;
}
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} shim.isRequired = shim;
function getShim() {
return shim;
} // Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim
};
ReactPropTypes.checkPropTypes = emptyFunction;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = factoryWithThrowingShims();
}
});
var getId$2 = function getId() {
return 'query';
};
function getCurrentRefinement(props, searchState, context) {
var id = getId$2();
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, '');
if (currentRefinement) {
return currentRefinement;
}
return '';
}
function getHits(searchResults) {
if (searchResults.results) {
if (searchResults.results.hits && Array.isArray(searchResults.results.hits)) {
return addAbsolutePositions(addQueryID(searchResults.results.hits, searchResults.results.queryID), searchResults.results.hitsPerPage, searchResults.results.page);
} else {
return Object.keys(searchResults.results).reduce(function (hits, index) {
return [].concat(_toConsumableArray(hits), [{
index: index,
hits: addAbsolutePositions(addQueryID(searchResults.results[index].hits, searchResults.results[index].queryID), searchResults.results[index].hitsPerPage, searchResults.results[index].page)
}]);
}, []);
}
} else {
return [];
}
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId$2();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage);
}
function _cleanUp(props, searchState, context) {
return cleanUpValue(searchState, context, getId$2());
}
/**
* connectAutoComplete connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* prop to a [Configure](guide/Search_parameters.html) widget.
* @name connectAutoComplete
* @kind connector
* @propType {string} [defaultRefinement] - Provide a default value for the query
* @providedPropType {array.<object>} hits - the records that matched the search state
* @providedPropType {function} refine - a function to change the query
* @providedPropType {string} currentRefinement - the query to search for
*/
var connectAutoComplete = createConnectorWithContext({
displayName: 'AlgoliaAutoComplete',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
return {
hits: getHits(searchResults),
currentRefinement: getCurrentRefinement(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
})
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
/**
* AutoComplete needs to be considered as a widget to trigger a search,
* even if no other widgets are used.
*
* To be considered as a widget you need either:
* - getSearchParameters
* - getMetadata
* - transitionState
*
* See: createConnector.tsx
*/
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}));
}
});
var getId$3 = function getId(props) {
return props.attributes[0];
};
var namespace = 'hierarchicalMenu';
function _refine$1(props, searchState, nextRefinement, context) {
var id = getId$3(props);
var nextValue = _defineProperty({}, id, nextRefinement || '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace);
}
function transformValue(values) {
return values.reduce(function (acc, item) {
if (item.isRefined) {
acc.push({
label: item.name,
// If dealing with a nested "items", "value" is equal to the previous value concatenated with the current label
// If dealing with the first level, "value" is equal to the current label
value: item.path
}); // Create a variable in order to keep the same acc for the recursion, otherwise "reduce" returns a new one
if (item.data) {
acc = acc.concat(transformValue(item.data));
}
}
return acc;
}, []);
}
/**
* The breadcrumb component is s a type of secondary navigation scheme that
* reveals the user’s location in a website or web application.
*
* @name connectBreadcrumb
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a Breadcrumb of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display.
*/
var connectBreadcrumb = createConnectorWithContext({
displayName: 'AlgoliaBreadcrumb',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error("Invalid prop ".concat(propName, " supplied to ").concat(componentName, ". Expected an Array of Strings"));
}
return undefined;
},
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var id = getId$3(props);
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
canRefine: false
};
}
var values = results.getFacetValues(id);
var items = values.data ? transformValue(values.data) : [];
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
canRefine: transformedItems.length > 0,
items: transformedItems
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$1(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
/**
* connectCurrentRefinements connector provides the logic to build a widget that will
* give the user the ability to remove all or some of the filters that were
* set.
* @name connectCurrentRefinements
* @kind connector
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {function} [clearsQuery=false] - Pass true to also clear the search query
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {array.<{label: string, attribute: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attribute` and `currentRefinement` are metadata containing row values.
* @providedPropType {string} query - the search query
*/
var connectCurrentRefinements = createConnectorWithContext({
displayName: 'AlgoliaCurrentRefinements',
propTypes: {
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) {
var items = metadata.reduce(function (res, meta) {
if (typeof meta.items !== 'undefined') {
if (!props.clearsQuery && meta.id === 'query') {
return res;
} else {
if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') {
return res;
}
return res.concat(meta.items.map(function (item) {
return _objectSpread({}, item, {
id: meta.id,
index: meta.index
});
}));
}
}
return res;
}, []);
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems,
canRefine: transformedItems.length > 0
};
},
refine: function refine(props, searchState, items) {
// `value` corresponds to our internal clear function computed in each connector metadata.
var refinementsToClear = items instanceof Array ? items.map(function (item) {
return item.value;
}) : [items];
return refinementsToClear.reduce(function (res, clear) {
return clear(res);
}, searchState);
}
});
/**
* The GeoSearch connector provides the logic to build a widget that will display the results on a map.
* It also provides a way to search for results based on their position. The connector provides function to manage the search experience (search on map interaction).
* @name connectGeoSearch
* @kind connector
* @requirements Note that the GeoSearch connector uses the [geosearch](https://www.algolia.com/doc/guides/searching/geo-search) capabilities of Algolia.
* Your hits **must** have a `_geoloc` attribute in order to be passed to the rendering function. Currently, the feature is not compatible with multiple values in the `_geoloc` attribute
* (e.g. a restaurant with multiple locations). In that case you can duplicate your records and use the [distinct](https://www.algolia.com/doc/guides/ranking/distinct) feature of Algolia to only retrieve unique results.
* @propType {{ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } }} [defaultRefinement] - Default search state of the widget containing the bounds for the map
* @providedPropType {function({ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } })} refine - a function to toggle the refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {array.<object>} hits - the records that matched the search
* @providedPropType {boolean} isRefinedWithMap - true if the current refinement is set with the map bounds
* @providedPropType {{ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } }} [currentRefinement] - the refinement currently applied
* @providedPropType {{ lat: number, lng: number }} [position] - the position of the search
*/
// To control the map with an external widget the other widget
// **must** write the value in the attribute `aroundLatLng`
var getBoundingBoxId = function getBoundingBoxId() {
return 'boundingBox';
};
var getAroundLatLngId = function getAroundLatLngId() {
return 'aroundLatLng';
};
var getConfigureAroundLatLngId = function getConfigureAroundLatLngId() {
return 'configure.aroundLatLng';
};
var currentRefinementToString = function currentRefinementToString(currentRefinement) {
return [currentRefinement.northEast.lat, currentRefinement.northEast.lng, currentRefinement.southWest.lat, currentRefinement.southWest.lng].join();
};
var stringToCurrentRefinement = function stringToCurrentRefinement(value) {
var values = value.split(',');
return {
northEast: {
lat: parseFloat(values[0]),
lng: parseFloat(values[1])
},
southWest: {
lat: parseFloat(values[2]),
lng: parseFloat(values[3])
}
};
};
var latLngRegExp = /^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/;
var stringToPosition = function stringToPosition(value) {
var pattern = value.match(latLngRegExp);
return {
lat: parseFloat(pattern[1]),
lng: parseFloat(pattern[2])
};
};
var getCurrentRefinement$1 = function getCurrentRefinement(props, searchState, context) {
var refinement = getCurrentRefinementValue(props, searchState, context, getBoundingBoxId(), {});
if (!objectHasKeys(refinement)) {
return;
} // eslint-disable-next-line consistent-return
return {
northEast: {
lat: parseFloat(refinement.northEast.lat),
lng: parseFloat(refinement.northEast.lng)
},
southWest: {
lat: parseFloat(refinement.southWest.lat),
lng: parseFloat(refinement.southWest.lng)
}
};
};
var getCurrentPosition = function getCurrentPosition(props, searchState, context) {
var defaultRefinement = props.defaultRefinement,
propsWithoutDefaultRefinement = _objectWithoutProperties(props, ["defaultRefinement"]);
var aroundLatLng = getCurrentRefinementValue(propsWithoutDefaultRefinement, searchState, context, getAroundLatLngId());
if (!aroundLatLng) {
// Fallback on `configure.aroundLatLng`
var configureAroundLatLng = getCurrentRefinementValue(propsWithoutDefaultRefinement, searchState, context, getConfigureAroundLatLngId());
return configureAroundLatLng && stringToPosition(configureAroundLatLng);
}
return aroundLatLng;
};
var _refine$2 = function refine(searchState, nextValue, context) {
var resetPage = true;
var nextRefinement = _defineProperty({}, getBoundingBoxId(), nextValue);
return refineValue(searchState, nextRefinement, context, resetPage);
};
var connectGeoSearch = createConnectorWithContext({
displayName: 'AlgoliaGeoSearch',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var context = {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
};
var results = getResults(searchResults, context); // We read it from both because the SearchParameters & the searchState are not always
// in sync. When we set the refinement the searchState is used but when we clear the refinement
// the SearchParameters is used. In the first case when we render, the results are not there
// so we can't find the value from the results. The most up to date value is the searchState.
// But when we clear the refinement the searchState is immediately cleared even when the items
// retrieved are still the one from the previous query with the bounding box. It leads to some
// issue with the position of the map. We should rely on 1 source of truth or at least always
// be sync.
var currentRefinementFromSearchState = getCurrentRefinement$1(props, searchState, context);
var currentRefinementFromSearchParameters = results && results._state.insideBoundingBox && stringToCurrentRefinement(results._state.insideBoundingBox) || undefined;
var currentPositionFromSearchState = getCurrentPosition(props, searchState, context);
var currentPositionFromSearchParameters = results && results._state.aroundLatLng && stringToPosition(results._state.aroundLatLng) || undefined;
var currentRefinement = currentRefinementFromSearchState || currentRefinementFromSearchParameters;
var position = currentPositionFromSearchState || currentPositionFromSearchParameters;
return {
hits: !results ? [] : results.hits.filter(function (_) {
return Boolean(_._geoloc);
}),
isRefinedWithMap: Boolean(currentRefinement),
currentRefinement: currentRefinement,
position: position
};
},
refine: function refine(props, searchState, nextValue) {
return _refine$2(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var currentRefinement = getCurrentRefinement$1(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (!currentRefinement) {
return searchParameters;
}
return searchParameters.setQueryParameter('insideBoundingBox', currentRefinementToString(currentRefinement));
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, getBoundingBoxId());
},
getMetadata: function getMetadata(props, searchState) {
var items = [];
var id = getBoundingBoxId();
var context = {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
};
var index = getIndexId(context);
var nextRefinement = {};
var currentRefinement = getCurrentRefinement$1(props, searchState, context);
if (currentRefinement) {
items.push({
label: "".concat(id, ": ").concat(currentRefinementToString(currentRefinement)),
value: function value(nextState) {
return _refine$2(nextState, nextRefinement, context);
},
currentRefinement: currentRefinement
});
}
return {
id: id,
index: index,
items: items
};
},
shouldComponentUpdate: function shouldComponentUpdate() {
return true;
}
});
var getId$4 = function getId(props) {
return props.attributes[0];
};
var namespace$1 = 'hierarchicalMenu';
function getCurrentRefinement$2(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$1, ".").concat(getId$4(props)), null);
if (currentRefinement === '') {
return null;
}
return currentRefinement;
}
function getValue(path, props, searchState, context) {
var id = props.id,
attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel;
var currentRefinement = getCurrentRefinement$2(props, searchState, context);
var nextRefinement;
if (currentRefinement === null) {
nextRefinement = path;
} else {
var tmpSearchParameters = new algoliasearchHelper_1.SearchParameters({
hierarchicalFacets: [{
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}]
});
nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0];
}
return nextRefinement;
}
function transformValue$1(value, props, searchState, context) {
return value.map(function (v) {
return {
label: v.name,
value: getValue(v.path, props, searchState, context),
count: v.count,
isRefined: v.isRefined,
items: v.data && transformValue$1(v.data, props, searchState, context)
};
});
}
var truncate = function truncate() {
var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
return items.slice(0, limit).map(function () {
var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Array.isArray(item.items) ? _objectSpread({}, item, {
items: truncate(item.items, limit)
}) : item;
});
};
function _refine$3(props, searchState, nextRefinement, context) {
var id = getId$4(props);
var nextValue = _defineProperty({}, id, nextRefinement || '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$1);
}
function _cleanUp$1(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$1, ".").concat(getId$4(props)));
}
var sortBy = ['name:asc'];
/**
* connectHierarchicalMenu connector provides the logic to build a widget that will
* give the user the ability to explore a tree-like structure.
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
* @name connectHierarchicalMenu
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limit and showMoreLimit.
* @propType {number} [limit=10] - The maximum number of items displayed.
* @propType {number} [showMoreLimit=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string} [rootPath=null] - The path to use if the first level is not the root level.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items.
*/
var connectHierarchicalMenu = createConnectorWithContext({
displayName: 'AlgoliaHierarchicalMenu',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error("Invalid prop ".concat(propName, " supplied to ").concat(componentName, ". Expected an Array of Strings"));
}
return undefined;
},
separator: propTypes.string,
rootPath: propTypes.string,
showParentLevel: propTypes.bool,
defaultRefinement: propTypes.string,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
transformItems: propTypes.func
},
defaultProps: {
showMore: false,
limit: 10,
showMoreLimit: 20,
separator: ' > ',
rootPath: null,
showParentLevel: true
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var showMore = props.showMore,
limit = props.limit,
showMoreLimit = props.showMoreLimit;
var id = getId$4(props);
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
currentRefinement: getCurrentRefinement$2(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: false
};
}
var itemsLimit = showMore ? showMoreLimit : limit;
var value = results.getFacetValues(id, {
sortBy: sortBy
});
var items = value.data ? transformValue$1(value.data, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) : [];
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: truncate(transformedItems, itemsLimit),
currentRefinement: getCurrentRefinement$2(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: transformedItems.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$3(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$1(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel,
showMore = props.showMore,
limit = props.limit,
showMoreLimit = props.showMoreLimit,
contextValue = props.contextValue;
var id = getId$4(props);
var itemsLimit = showMore ? showMoreLimit : limit;
searchParameters = searchParameters.addHierarchicalFacet({
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}).setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, itemsLimit)
});
var currentRefinement = getCurrentRefinement$2(props, searchState, {
ais: contextValue,
multiIndexContext: props.indexContextValue
});
if (currentRefinement !== null) {
searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var rootAttribute = props.attributes[0];
var id = getId$4(props);
var currentRefinement = getCurrentRefinement$2(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = !currentRefinement ? [] : [{
label: "".concat(rootAttribute, ": ").concat(currentRefinement),
attribute: rootAttribute,
value: function value(nextState) {
return _refine$3(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: currentRefinement
}];
return {
id: id,
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: items
};
}
});
var highlight = function highlight(_ref) {
var attribute = _ref.attribute,
hit = _ref.hit,
highlightProperty = _ref.highlightProperty,
_ref$preTag = _ref.preTag,
preTag = _ref$preTag === void 0 ? HIGHLIGHT_TAGS.highlightPreTag : _ref$preTag,
_ref$postTag = _ref.postTag,
postTag = _ref$postTag === void 0 ? HIGHLIGHT_TAGS.highlightPostTag : _ref$postTag;
return parseAlgoliaHit({
attribute: attribute,
highlightProperty: highlightProperty,
hit: hit,
preTag: preTag,
postTag: postTag
});
};
/**
* connectHighlight connector provides the logic to create an highlighter
* component that will retrieve, parse and render an highlighted attribute
* from an Algolia hit.
* @name connectHighlight
* @kind connector
* @category connector
* @providedPropType {function} highlight - function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attributes: `highlightProperty` which is the property that contains the highlight structure from the records, `attribute` which is the name of the attribute (it can be either a string or an array of strings) to look for and `hit` which is the hit from Algolia. It returns an array of objects `{value: string, isHighlighted: boolean}`. If the element that corresponds to the attribute is an array of strings, it will return a nested array of objects.
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, SearchBox, Hits, connectHighlight } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const CustomHighlight = connectHighlight(
* ({ highlight, attribute, hit, highlightProperty }) => {
* const highlights = highlight({
* highlightProperty: '_highlightResult',
* attribute,
* hit
* });
*
* return highlights.map(part => part.isHighlighted ? (
* <mark>{part.value}</mark>
* ) : (
* <span>{part.value}</span>
* ));
* }
* );
*
* const Hit = ({ hit }) => (
* <p>
* <CustomHighlight attribute="name" hit={hit} />
* </p>
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <SearchBox defaultRefinement="pho" />
* <Hits hitComponent={Hit} />
* </InstantSearch>
* );
*/
var connectHighlight = createConnectorWithContext({
displayName: 'AlgoliaHighlighter',
propTypes: {},
getProvidedProps: function getProvidedProps() {
return {
highlight: highlight
};
}
});
/**
* connectHits connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* prop to a [Configure](guide/Search_parameters.html) widget.
*
* **Warning:** you will need to use the **objectID** property available on every hit as a key
* when iterating over them. This will ensure you have the best possible UI experience
* especially on slow networks.
* @name connectHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, Highlight, connectHits } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
* const CustomHits = connectHits(({ hits }) => (
* <div>
* {hits.map(hit =>
* <p key={hit.objectID}>
* <Highlight attribute="name" hit={hit} />
* </p>
* )}
* </div>
* ));
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <CustomHits />
* </InstantSearch>
* );
*/
var connectHits = createConnectorWithContext({
displayName: 'AlgoliaHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (!results) {
return {
hits: []
};
}
var hitsWithPositions = addAbsolutePositions(results.hits, results.hitsPerPage, results.page);
var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID);
return {
hits: hitsWithPositionsAndQueryID
};
},
/**
* Hits needs to be considered as a widget to trigger a search,
* even if no other widgets are used.
*
* To be considered as a widget you need either:
* - getSearchParameters
* - getMetadata
* - transitionState
*
* See: createConnector.tsx
*/
getSearchParameters: function getSearchParameters(searchParameters) {
return searchParameters;
}
});
function getId$5() {
return 'hitsPerPage';
}
function getCurrentRefinement$3(props, searchState, context) {
var id = getId$5();
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null);
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
}
/**
* connectHitsPerPage connector provides the logic to create connected
* components that will allow a user to choose to display more or less results from Algolia.
* @name connectHitsPerPage
* @kind connector
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {{value: number, label: string}[]} items - List of hits per page options.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
var connectHitsPerPage = createConnectorWithContext({
displayName: 'AlgoliaHitsPerPage',
propTypes: {
defaultRefinement: propTypes.number.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string,
value: propTypes.number.isRequired
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement$3(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _objectSpread({}, item, {
isRefined: true
}) : _objectSpread({}, item, {
isRefined: false
});
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId$5();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, getId$5());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setHitsPerPage(getCurrentRefinement$3(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}));
},
getMetadata: function getMetadata() {
return {
id: getId$5()
};
}
});
function getId$6() {
return 'page';
}
function getCurrentRefinement$4(props, searchState, context) {
var id = getId$6();
var page = 1;
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page);
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
}
/**
* InfiniteHits connector provides the logic to create connected
* components that will render an continuous list of results retrieved from
* Algolia. This connector provides a function to load more results.
* @name connectInfiniteHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @providedPropType {boolean} hasMore - indicates if there are more pages to load
* @providedPropType {function} refine - call to load more results
*/
var connectInfiniteHits = createConnectorWithContext({
displayName: 'AlgoliaInfiniteHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var _this = this;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
this._allResults = this._allResults || [];
this._prevState = this._prevState || {};
if (!results) {
return {
hits: [],
hasPrevious: false,
hasMore: false,
refine: function refine() {},
refinePrevious: function refinePrevious() {},
refineNext: function refineNext() {}
};
}
var page = results.page,
hits = results.hits,
hitsPerPage = results.hitsPerPage,
nbPages = results.nbPages,
_results$_state = results._state;
_results$_state = _results$_state === void 0 ? {} : _results$_state;
var p = _results$_state.page,
currentState = _objectWithoutProperties(_results$_state, ["page"]);
var hitsWithPositions = addAbsolutePositions(hits, hitsPerPage, page);
var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID);
if (this._firstReceivedPage === undefined || !fastDeepEqual(currentState, this._prevState)) {
this._allResults = _toConsumableArray(hitsWithPositionsAndQueryID);
this._firstReceivedPage = page;
this._lastReceivedPage = page;
} else if (this._lastReceivedPage < page) {
this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hitsWithPositionsAndQueryID));
this._lastReceivedPage = page;
} else if (this._firstReceivedPage > page) {
this._allResults = [].concat(_toConsumableArray(hitsWithPositionsAndQueryID), _toConsumableArray(this._allResults));
this._firstReceivedPage = page;
}
this._prevState = currentState;
var hasPrevious = this._firstReceivedPage > 0;
var lastPageIndex = nbPages - 1;
var hasMore = page < lastPageIndex;
var refinePrevious = function refinePrevious(event) {
return _this.refine(event, _this._firstReceivedPage - 1);
};
var refineNext = function refineNext(event) {
return _this.refine(event, _this._lastReceivedPage + 1);
};
return {
hits: this._allResults,
hasPrevious: hasPrevious,
hasMore: hasMore,
refinePrevious: refinePrevious,
refineNext: refineNext
};
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQueryParameters({
page: getCurrentRefinement$4(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) - 1
});
},
refine: function refine(props, searchState, event, index) {
if (index === undefined && this._lastReceivedPage !== undefined) {
index = this._lastReceivedPage + 1;
} else if (index === undefined) {
index = getCurrentRefinement$4(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
var id = getId$6();
var nextValue = _defineProperty({}, id, index + 1);
var resetPage = false;
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, resetPage);
}
});
var namespace$2 = 'menu';
function getId$7(props) {
return props.attribute;
}
function getCurrentRefinement$5(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$2, ".").concat(getId$7(props)), null);
if (currentRefinement === '') {
return null;
}
return currentRefinement;
}
function getValue$1(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement$5(props, searchState, context);
return name === currentRefinement ? '' : name;
}
function getLimit(_ref) {
var showMore = _ref.showMore,
limit = _ref.limit,
showMoreLimit = _ref.showMoreLimit;
return showMore ? showMoreLimit : limit;
}
function _refine$4(props, searchState, nextRefinement, context) {
var id = getId$7(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$2);
}
function _cleanUp$2(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$2, ".").concat(getId$7(props)));
}
var defaultSortBy = ['count:desc', 'name:asc'];
/**
* connectMenu connector provides the logic to build a widget that will
* give the user the ability to choose a single value for a specific facet.
* @name connectMenu
* @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @kind connector
* @propType {string} attribute - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limit=10] - the minimum number of diplayed items
* @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {boolean} [searchable=false] - allow search inside values
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
var connectMenu = createConnectorWithContext({
displayName: 'AlgoliaMenu',
propTypes: {
attribute: propTypes.string.isRequired,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
defaultRefinement: propTypes.string,
transformItems: propTypes.func,
searchable: propTypes.bool
},
defaultProps: {
showMore: false,
limit: 10,
showMoreLimit: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) {
var attribute = props.attribute,
searchable = props.searchable,
indexContextValue = props.indexContextValue;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search)
if (searchable && indexContextValue) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: canRefine
};
}
var items;
if (isFromSearch) {
items = searchForFacetValuesResults[attribute].map(function (v) {
return {
label: v.value,
value: getValue$1(v.value, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
_highlightResult: {
label: {
value: v.highlighted
}
},
count: v.count,
isRefined: v.isRefined
};
});
} else {
items = results.getFacetValues(attribute, {
sortBy: searchable ? undefined : defaultSortBy
}).map(function (v) {
return {
label: v.name,
value: getValue$1(v.name, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
count: v.count,
isRefined: v.isRefined
};
});
}
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, getLimit(props)),
currentRefinement: getCurrentRefinement$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: transformedItems.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$4(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return {
facetName: props.attribute,
query: nextRefinement,
maxFacetHits: getLimit(props)
};
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$2(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute;
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit(props))
});
searchParameters = searchParameters.addDisjunctiveFacet(attribute);
var currentRefinement = getCurrentRefinement$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (currentRefinement !== null) {
searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$7(props);
var currentRefinement = getCurrentRefinement$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return {
id: id,
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: currentRefinement === null ? [] : [{
label: "".concat(props.attribute, ": ").concat(currentRefinement),
attribute: props.attribute,
value: function value(nextState) {
return _refine$4(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: currentRefinement
}]
};
}
});
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function stringifyItem(item) {
if (typeof item.start === 'undefined' && typeof item.end === 'undefined') {
return '';
}
var start = typeof item.start !== 'undefined' ? item.start : '';
var end = typeof item.end !== 'undefined' ? item.end : '';
return "".concat(start, ":").concat(end);
}
function parseItem(value) {
if (value.length === 0) {
return {
start: null,
end: null
};
}
var _value$split = value.split(':'),
_value$split2 = _slicedToArray(_value$split, 2),
startStr = _value$split2[0],
endStr = _value$split2[1];
return {
start: startStr.length > 0 ? parseInt(startStr, 10) : null,
end: endStr.length > 0 ? parseInt(endStr, 10) : null
};
}
var namespace$3 = 'multiRange';
function getId$8(props) {
return props.attribute;
}
function getCurrentRefinement$6(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, "".concat(namespace$3, ".").concat(getId$8(props)), '');
}
function isRefinementsRangeIncludesInsideItemRange(stats, start, end) {
return stats.min > start && stats.min < end || stats.max > start && stats.max < end;
}
function isItemRangeIncludedInsideRefinementsRange(stats, start, end) {
return start > stats.min && start < stats.max || end > stats.min && end < stats.max;
}
function itemHasRefinement(attribute, results, value) {
var stats = results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null;
var range = value.split(':');
var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]);
var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]);
return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end)));
}
function _refine$5(props, searchState, nextRefinement, context) {
var nextValue = _defineProperty({}, getId$8(props), nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$3);
}
function _cleanUp$3(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$3, ".").concat(getId$8(props)));
}
/**
* connectNumericMenu connector provides the logic to build a widget that will
* give the user the ability to select a range value for a numeric attribute.
* Ranges are defined statically.
* @name connectNumericMenu
* @requirements The attribute passed to the `attribute` prop must be holding numerical values.
* @kind connector
* @propType {string} attribute - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string.
* @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the NumericMenu can display.
*/
var connectNumericMenu = createConnectorWithContext({
displayName: 'AlgoliaNumericMenu',
propTypes: {
id: propTypes.string,
attribute: propTypes.string.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.node,
start: propTypes.number,
end: propTypes.number
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attribute = props.attribute;
var currentRefinement = getCurrentRefinement$6(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = props.items.map(function (item) {
var value = stringifyItem(item);
return {
label: item.label,
value: value,
isRefined: value === currentRefinement,
noRefinement: results ? itemHasRefinement(getId$8(props), results, value) : false
};
});
var stats = results && results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null;
var refinedItem = find(items, function (item) {
return item.isRefined === true;
});
if (!items.some(function (item) {
return item.value === '';
})) {
items.push({
value: '',
isRefined: refinedItem === undefined,
noRefinement: !stats,
label: 'All'
});
}
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems,
currentRefinement: currentRefinement,
canRefine: transformedItems.length > 0 && transformedItems.some(function (item) {
return item.noRefinement === false;
})
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$5(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$3(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute;
var _parseItem = parseItem(getCurrentRefinement$6(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
})),
start = _parseItem.start,
end = _parseItem.end;
searchParameters = searchParameters.addDisjunctiveFacet(attribute);
if (typeof start === 'number') {
searchParameters = searchParameters.addNumericRefinement(attribute, '>=', start);
}
if (typeof end === 'number') {
searchParameters = searchParameters.addNumericRefinement(attribute, '<=', end);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$8(props);
var value = getCurrentRefinement$6(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = [];
var index = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (value !== '') {
var _find = find(props.items, function (item) {
return stringifyItem(item) === value;
}),
label = _find.label;
items.push({
label: "".concat(props.attribute, ": ").concat(label),
attribute: props.attribute,
currentRefinement: label,
value: function value(nextState) {
return _refine$5(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
}
return {
id: id,
index: index,
items: items
};
}
});
function getId$9() {
return 'page';
}
function getCurrentRefinement$7(props, searchState, context) {
var id = getId$9();
var page = 1;
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page);
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
}
function _refine$6(props, searchState, nextPage, context) {
var id = getId$9();
var nextValue = _defineProperty({}, id, nextPage);
var resetPage = false;
return refineValue(searchState, nextValue, context, resetPage);
}
/**
* connectPagination connector provides the logic to build a widget that will
* let the user displays hits corresponding to a certain page.
* @name connectPagination
* @kind connector
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [padding=3] - How many page links to display around the current page.
* @propType {number} [totalPages=Infinity] - Maximum number of pages to display.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {number} nbPages - the total of existing pages
* @providedPropType {number} currentRefinement - the page refinement currently applied
*/
var connectPagination = createConnectorWithContext({
displayName: 'AlgoliaPagination',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (!results) {
return null;
}
var nbPages = results.nbPages;
return {
nbPages: nbPages,
currentRefinement: getCurrentRefinement$7(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: nbPages > 1
};
},
refine: function refine(props, searchState, nextPage) {
return _refine$6(props, searchState, nextPage, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, getId$9());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setPage(getCurrentRefinement$7(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) - 1);
},
getMetadata: function getMetadata() {
return {
id: getId$9()
};
}
});
/**
* connectPoweredBy connector provides the logic to build a widget that
* will display a link to algolia.
* @name connectPoweredBy
* @kind connector
* @providedPropType {string} url - the url to redirect to algolia
*/
var connectPoweredBy = createConnectorWithContext({
displayName: 'AlgoliaPoweredBy',
getProvidedProps: function getProvidedProps() {
var hostname = typeof window === 'undefined' ? '' : window.location.hostname;
var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + "utm_content=".concat(hostname, "&") + 'utm_campaign=poweredby';
return {
url: url
};
}
});
/**
* connectRange connector provides the logic to create connected
* components that will give the ability for a user to refine results using
* a numeric range.
* @name connectRange
* @kind connector
* @requirements The attribute passed to the `attribute` prop must be present in “attributes for faceting”
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* The values inside the attribute must be JavaScript numbers (not strings).
* @propType {string} attribute - Name of the attribute for faceting
* @propType {{min?: number, max?: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [precision=0] - Number of digits after decimal point to use.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {number} min - the minimum value available.
* @providedPropType {number} max - the maximum value available.
* @providedPropType {number} precision - Number of digits after decimal point to use.
*/
function getId$a(props) {
return props.attribute;
}
var namespace$4 = 'range';
function getCurrentRange(boundaries, stats, precision) {
var pow = Math.pow(10, precision);
var min;
if (typeof boundaries.min === 'number' && isFinite(boundaries.min)) {
min = boundaries.min;
} else if (typeof stats.min === 'number' && isFinite(stats.min)) {
min = stats.min;
} else {
min = undefined;
}
var max;
if (typeof boundaries.max === 'number' && isFinite(boundaries.max)) {
max = boundaries.max;
} else if (typeof stats.max === 'number' && isFinite(stats.max)) {
max = stats.max;
} else {
max = undefined;
}
return {
min: min !== undefined ? Math.floor(min * pow) / pow : min,
max: max !== undefined ? Math.ceil(max * pow) / pow : max
};
}
function getCurrentRefinement$8(props, searchState, currentRange, context) {
var _getCurrentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$4, ".").concat(getId$a(props)), {}),
min = _getCurrentRefinement.min,
max = _getCurrentRefinement.max;
var isFloatPrecision = Boolean(props.precision);
var nextMin = min;
if (typeof nextMin === 'string') {
nextMin = isFloatPrecision ? parseFloat(nextMin) : parseInt(nextMin, 10);
}
var nextMax = max;
if (typeof nextMax === 'string') {
nextMax = isFloatPrecision ? parseFloat(nextMax) : parseInt(nextMax, 10);
}
var refinement = {
min: nextMin,
max: nextMax
};
var hasMinBound = props.min !== undefined;
var hasMaxBound = props.max !== undefined;
var hasMinRefinment = refinement.min !== undefined;
var hasMaxRefinment = refinement.max !== undefined;
if (hasMinBound && hasMinRefinment && refinement.min < currentRange.min) {
throw Error("You can't provide min value lower than range.");
}
if (hasMaxBound && hasMaxRefinment && refinement.max > currentRange.max) {
throw Error("You can't provide max value greater than range.");
}
if (hasMinBound && !hasMinRefinment) {
refinement.min = currentRange.min;
}
if (hasMaxBound && !hasMaxRefinment) {
refinement.max = currentRange.max;
}
return refinement;
}
function getCurrentRefinementWithRange(refinement, range) {
return {
min: refinement.min !== undefined ? refinement.min : range.min,
max: refinement.max !== undefined ? refinement.max : range.max
};
}
function nextValueForRefinement(hasBound, isReset, range, value) {
var next;
if (!hasBound && range === value) {
next = undefined;
} else if (hasBound && isReset) {
next = range;
} else {
next = value;
}
return next;
}
function _refine$7(props, searchState, nextRefinement, currentRange, context) {
var nextMin = nextRefinement.min,
nextMax = nextRefinement.max;
var currentMinRange = currentRange.min,
currentMaxRange = currentRange.max;
var isMinReset = nextMin === undefined || nextMin === '';
var isMaxReset = nextMax === undefined || nextMax === '';
var nextMinAsNumber = !isMinReset ? parseFloat(nextMin) : undefined;
var nextMaxAsNumber = !isMaxReset ? parseFloat(nextMax) : undefined;
var isNextMinValid = isMinReset || isFinite(nextMinAsNumber);
var isNextMaxValid = isMaxReset || isFinite(nextMaxAsNumber);
if (!isNextMinValid || !isNextMaxValid) {
throw Error("You can't provide non finite values to the range connector.");
}
if (nextMinAsNumber < currentMinRange) {
throw Error("You can't provide min value lower than range.");
}
if (nextMaxAsNumber > currentMaxRange) {
throw Error("You can't provide max value greater than range.");
}
var id = getId$a(props);
var resetPage = true;
var nextValue = _defineProperty({}, id, {
min: nextValueForRefinement(props.min !== undefined, isMinReset, currentMinRange, nextMinAsNumber),
max: nextValueForRefinement(props.max !== undefined, isMaxReset, currentMaxRange, nextMaxAsNumber)
});
return refineValue(searchState, nextValue, context, resetPage, namespace$4);
}
function _cleanUp$4(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$4, ".").concat(getId$a(props)));
}
var connectRange = createConnectorWithContext({
displayName: 'AlgoliaRange',
propTypes: {
id: propTypes.string,
attribute: propTypes.string.isRequired,
defaultRefinement: propTypes.shape({
min: propTypes.number,
max: propTypes.number
}),
min: propTypes.number,
max: propTypes.number,
precision: propTypes.number,
header: propTypes.node,
footer: propTypes.node
},
defaultProps: {
precision: 0
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attribute = props.attribute,
precision = props.precision,
minBound = props.min,
maxBound = props.max;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var hasFacet = results && results.getFacetByName(attribute);
var stats = hasFacet ? results.getFacetStats(attribute) || {} : {};
var facetValues = hasFacet ? results.getFacetValues(attribute) : [];
var count = facetValues.map(function (v) {
return {
value: v.name,
count: v.count
};
});
var _getCurrentRange = getCurrentRange({
min: minBound,
max: maxBound
}, stats, precision),
rangeMin = _getCurrentRange.min,
rangeMax = _getCurrentRange.max; // The searchState is not always in sync with the helper state. For example
// when we set boundaries on the first render the searchState don't have
// the correct refinement. If this behavior change in the upcoming version
// we could store the range inside the searchState instead of rely on `this`.
this._currentRange = {
min: rangeMin,
max: rangeMax
};
var currentRefinement = getCurrentRefinement$8(props, searchState, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return {
min: rangeMin,
max: rangeMax,
canRefine: count.length > 0,
currentRefinement: getCurrentRefinementWithRange(currentRefinement, this._currentRange),
count: count,
precision: precision
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$7(props, searchState, nextRefinement, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$4(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(params, props, searchState) {
var attribute = props.attribute;
var _getCurrentRefinement2 = getCurrentRefinement$8(props, searchState, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
min = _getCurrentRefinement2.min,
max = _getCurrentRefinement2.max;
params = params.addDisjunctiveFacet(attribute);
if (min !== undefined) {
params = params.addNumericRefinement(attribute, '>=', min);
}
if (max !== undefined) {
params = params.addNumericRefinement(attribute, '<=', max);
}
return params;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var _this$_currentRange = this._currentRange,
minRange = _this$_currentRange.min,
maxRange = _this$_currentRange.max;
var _getCurrentRefinement3 = getCurrentRefinement$8(props, searchState, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
minValue = _getCurrentRefinement3.min,
maxValue = _getCurrentRefinement3.max;
var items = [];
var hasMin = minValue !== undefined;
var hasMax = maxValue !== undefined;
var shouldDisplayMinLabel = hasMin && minValue !== minRange;
var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange;
if (shouldDisplayMinLabel || shouldDisplayMaxLabel) {
var fragments = [hasMin ? "".concat(minValue, " <= ") : '', props.attribute, hasMax ? " <= ".concat(maxValue) : ''];
items.push({
label: fragments.join(''),
attribute: props.attribute,
value: function value(nextState) {
return _refine$7(props, nextState, {}, _this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: getCurrentRefinementWithRange({
min: minValue,
max: maxValue
}, {
min: minRange,
max: maxRange
})
});
}
return {
id: getId$a(props),
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: items
};
}
});
var namespace$5 = 'refinementList';
function getId$b(props) {
return props.attribute;
}
function getCurrentRefinement$9(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$5, ".").concat(getId$b(props)), []);
if (typeof currentRefinement !== 'string') {
return currentRefinement;
}
if (currentRefinement) {
return [currentRefinement];
}
return [];
}
function getValue$2(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement$9(props, searchState, context);
var isAnewValue = currentRefinement.indexOf(name) === -1;
var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates
: currentRefinement.filter(function (selectedValue) {
return selectedValue !== name;
}); // cannot use .splice(), it mutates
return nextRefinement;
}
function getLimit$1(_ref) {
var showMore = _ref.showMore,
limit = _ref.limit,
showMoreLimit = _ref.showMoreLimit;
return showMore ? showMoreLimit : limit;
}
function _refine$8(props, searchState, nextRefinement, context) {
var id = getId$b(props); // Setting the value to an empty string ensures that it is persisted in
// the URL as an empty value.
// This is necessary in the case where `defaultRefinement` contains one
// item and we try to deselect it. `nextSelected` would be an empty array,
// which would not be persisted to the URL.
// {foo: ['bar']} => "foo[0]=bar"
// {foo: []} => ""
var nextValue = _defineProperty({}, id, nextRefinement.length > 0 ? nextRefinement : '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$5);
}
function _cleanUp$5(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$5, ".").concat(getId$b(props)));
}
/**
* connectRefinementList connector provides the logic to build a widget that will
* give the user the ability to choose multiple values for a specific facet.
* @name connectRefinementList
* @kind connector
* @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @propType {string} attribute - the name of the attribute in the record
* @propType {boolean} [searchable=false] - allow search inside values
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limit=10] - the minimum number of displayed items
* @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
* @providedPropType {boolean} canRefine - a boolean that says whether you can refine
*/
var sortBy$1 = ['isRefined', 'count:desc', 'name:asc'];
var connectRefinementList = createConnectorWithContext({
displayName: 'AlgoliaRefinementList',
propTypes: {
id: propTypes.string,
attribute: propTypes.string.isRequired,
operator: propTypes.oneOf(['and', 'or']),
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])),
searchable: propTypes.bool,
transformItems: propTypes.func
},
defaultProps: {
operator: 'or',
showMore: false,
limit: 10,
showMoreLimit: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) {
var attribute = props.attribute,
searchable = props.searchable,
indexContextValue = props.indexContextValue;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search)
if (searchable && indexContextValue) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement$9(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: canRefine,
isFromSearch: isFromSearch,
searchable: searchable
};
}
var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) {
return {
label: v.value,
value: getValue$2(v.value, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
_highlightResult: {
label: {
value: v.highlighted
}
},
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attribute, {
sortBy: sortBy$1
}).map(function (v) {
return {
label: v.name,
value: getValue$2(v.name, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
count: v.count,
isRefined: v.isRefined
};
});
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, getLimit$1(props)),
currentRefinement: getCurrentRefinement$9(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: transformedItems.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$8(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return {
facetName: props.attribute,
query: nextRefinement,
maxFacetHits: getLimit$1(props)
};
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute,
operator = props.operator;
var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet';
var addRefinementKey = "".concat(addKey, "Refinement");
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props))
});
searchParameters = searchParameters[addKey](attribute);
return getCurrentRefinement$9(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}).reduce(function (res, val) {
return res[addRefinementKey](attribute, val);
}, searchParameters);
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$b(props);
var context = {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
};
return {
id: id,
index: getIndexId(context),
items: getCurrentRefinement$9(props, searchState, context).length > 0 ? [{
attribute: props.attribute,
label: "".concat(props.attribute, ": "),
currentRefinement: getCurrentRefinement$9(props, searchState, context),
value: function value(nextState) {
return _refine$8(props, nextState, [], context);
},
items: getCurrentRefinement$9(props, searchState, context).map(function (item) {
return {
label: "".concat(item),
value: function value(nextState) {
var nextSelectedItems = getCurrentRefinement$9(props, nextState, context).filter(function (other) {
return other !== item;
});
return _refine$8(props, searchState, nextSelectedItems, context);
}
};
})
}] : []
};
}
});
/**
* connectScrollTo connector provides the logic to build a widget that will
* let the page scroll to a certain point.
* @name connectScrollTo
* @kind connector
* @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget.
* @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo
* @providedPropType {boolean} hasNotChanged - indicates whether the refinement came from the scrollOn argument (for instance page by default)
*/
var connectScrollTo = createConnectorWithContext({
displayName: 'AlgoliaScrollTo',
propTypes: {
scrollOn: propTypes.string
},
defaultProps: {
scrollOn: 'page'
},
getProvidedProps: function getProvidedProps(props, searchState) {
var id = props.scrollOn;
var value = getCurrentRefinementValue(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, id, null);
if (!this._prevSearchState) {
this._prevSearchState = {};
} // Get the subpart of the state that interest us
if (hasMultipleIndices({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
})) {
searchState = searchState.indices ? searchState.indices[getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
})] : {};
} // if there is a change in the app that has been triggered by another element
// than "props.scrollOn (id) or the Configure widget, we need to keep track of
// the search state to know if there's a change in the app that was not triggered
// by the props.scrollOn (id) or the Configure widget. This is useful when
// using ScrollTo in combination of Pagination. As pagination can be change
// by every widget, we want to scroll only if it cames from the pagination
// widget itself. We also remove the configure key from the search state to
// do this comparison because for now configure values are not present in the
// search state before a first refinement has been made and will false the results.
// See: https://github.com/algolia/react-instantsearch/issues/164
var cleanedSearchState = omit(searchState, ['configure', id]);
var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState);
this._prevSearchState = cleanedSearchState;
return {
value: value,
hasNotChanged: hasNotChanged
};
}
});
function getId$c() {
return 'query';
}
function getCurrentRefinement$a(props, searchState, context) {
var id = getId$c();
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, '');
if (currentRefinement) {
return currentRefinement;
}
return '';
}
function _refine$9(props, searchState, nextRefinement, context) {
var id = getId$c();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage);
}
function _cleanUp$6(props, searchState, context) {
return cleanUpValue(searchState, context, getId$c());
}
/**
* connectSearchBox connector provides the logic to build a widget that will
* let the user search for a query
* @name connectSearchBox
* @kind connector
* @propType {string} [defaultRefinement] - Provide a default value for the query
* @providedPropType {function} refine - a function to change the current query
* @providedPropType {string} currentRefinement - the current query used
* @providedPropType {boolean} isSearchStalled - a flag that indicates if InstantSearch has detected that searches are stalled
*/
var connectSearchBox = createConnectorWithContext({
displayName: 'AlgoliaSearchBox',
propTypes: {
defaultRefinement: propTypes.string
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
return {
currentRefinement: getCurrentRefinement$a(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isSearchStalled: searchResults.isSearchStalled
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$9(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$6(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement$a(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}));
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$c();
var currentRefinement = getCurrentRefinement$a(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return {
id: id,
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: currentRefinement === null ? [] : [{
label: "".concat(id, ": ").concat(currentRefinement),
value: function value(nextState) {
return _refine$9(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: currentRefinement
}]
};
}
});
function getId$d() {
return 'sortBy';
}
function getCurrentRefinement$b(props, searchState, context) {
var id = getId$d();
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null);
if (currentRefinement) {
return currentRefinement;
}
return null;
}
/**
* The connectSortBy connector provides the logic to build a widget that will
* display a list of indices. This allows a user to change how the hits are being sorted.
* @name connectSortBy
* @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on
* the Algolia website.
* @kind connector
* @propType {string} defaultRefinement - The default selected index.
* @propType {{value: string, label: string}[]} items - The list of indexes to search in.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
var connectSortBy = createConnectorWithContext({
displayName: 'AlgoliaSortBy',
propTypes: {
defaultRefinement: propTypes.string,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string,
value: propTypes.string.isRequired
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement$b(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _objectSpread({}, item, {
isRefined: true
}) : _objectSpread({}, item, {
isRefined: false
});
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId$d();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, getId$d());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var selectedIndex = getCurrentRefinement$b(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return searchParameters.setIndex(selectedIndex);
},
getMetadata: function getMetadata() {
return {
id: getId$d()
};
}
});
/**
* The `connectStateResults` connector provides a way to access the `searchState` and the `searchResults`
* of InstantSearch.
* For instance this connector allows you to create results/noResults or query/noQuery pages.
* @name connectStateResults
* @kind connector
* @providedPropType {object} searchState - The search state of the instant search component. <br/><br/> See: [Search state structure](https://community.algolia.com/react-instantsearch/guide/Search_state.html)
* @providedPropType {object} searchResults - The search results. <br/><br/> In case of multiple indices: if used under `<Index>`, results will be those of the corresponding index otherwise it'll be those of the root index See: [Search results structure](https://community.algolia.com/algoliasearch-helper-js/reference.html#searchresults)
* @providedPropType {object} allSearchResults - In case of multiple indices you can retrieve all the results
* @providedPropType {string} error - If the search failed, the error will be logged here.
* @providedPropType {boolean} searching - If there is a search in progress.
* @providedPropType {boolean} isSearchStalled - Flag that indicates if React InstantSearch has detected that searches are stalled.
* @providedPropType {boolean} searchingForFacetValues - If there is a search in a list in progress.
* @providedPropType {object} props - component props.
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, SearchBox, Hits, connectStateResults } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const Content = connectStateResults(({ searchState, searchResults }) => {
* const hasResults = searchResults && searchResults.nbHits !== 0;
*
* return (
* <div>
* <div hidden={!hasResults}>
* <Hits />
* </div>
* <div hidden={hasResults}>
* <div>No results has been found for {searchState.query}</div>
* </div>
* </div>
* );
* });
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <SearchBox />
* <Content />
* </InstantSearch>
* );
*/
var connectStateResults = createConnectorWithContext({
displayName: 'AlgoliaStateResults',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return {
searchState: searchState,
searchResults: results,
allSearchResults: searchResults.results,
searching: searchResults.searching,
isSearchStalled: searchResults.isSearchStalled,
error: searchResults.error,
searchingForFacetValues: searchResults.searchingForFacetValues,
props: props
};
}
});
/**
* connectStats connector provides the logic to build a widget that will
* displays algolia search statistics (hits number and processing time).
* @name connectStats
* @kind connector
* @providedPropType {number} nbHits - number of hits returned by Algolia.
* @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results.
*/
var connectStats = createConnectorWithContext({
displayName: 'AlgoliaStats',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (!results) {
return null;
}
return {
nbHits: results.nbHits,
processingTimeMS: results.processingTimeMS
};
}
});
function getId$e(props) {
return props.attribute;
}
var namespace$6 = 'toggle';
var falsyStrings = ['0', 'false', 'null', 'undefined'];
function getCurrentRefinement$c(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$6, ".").concat(getId$e(props)), false);
if (falsyStrings.indexOf(currentRefinement) !== -1) {
return false;
}
return Boolean(currentRefinement);
}
function _refine$a(props, searchState, nextRefinement, context) {
var id = getId$e(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : false);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$6);
}
function _cleanUp$7(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$6, ".").concat(getId$e(props)));
}
/**
* connectToggleRefinement connector provides the logic to build a widget that will
* provides an on/off filtering feature based on an attribute value.
* @name connectToggleRefinement
* @kind connector
* @requirements To use this widget, you'll need an attribute to toggle on.
*
* You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an
* extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details.
*
* @propType {string} attribute - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {string} value - Value of the refinement to apply on `attribute`.
* @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default?
* @providedPropType {boolean} currentRefinement - `true` when the refinement is applied, `false` otherwise
* @providedPropType {object} count - an object that contains the count for `checked` and `unchecked` state
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
*/
var connectToggleRefinement = createConnectorWithContext({
displayName: 'AlgoliaToggle',
propTypes: {
label: propTypes.string.isRequired,
attribute: propTypes.string.isRequired,
value: propTypes.any.isRequired,
filter: propTypes.func,
defaultRefinement: propTypes.bool
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attribute = props.attribute,
value = props.value;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var currentRefinement = getCurrentRefinement$c(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var allFacetValues = results && results.getFacetByName(attribute) ? results.getFacetValues(attribute) : null;
var facetValue = // Use null to always be consistent with type of the value
// count: number | null
allFacetValues && allFacetValues.length ? find(allFacetValues, function (item) {
return item.name === value.toString();
}) : null;
var facetValueCount = facetValue && facetValue.count;
var allFacetValuesCount = // Use null to always be consistent with type of the value
// count: number | null
allFacetValues && allFacetValues.length ? allFacetValues.reduce(function (acc, item) {
return acc + item.count;
}, 0) : null;
var canRefine = currentRefinement ? allFacetValuesCount !== null && allFacetValuesCount > 0 : facetValueCount !== null && facetValueCount > 0;
var count = {
checked: allFacetValuesCount,
unchecked: facetValueCount
};
return {
currentRefinement: currentRefinement,
canRefine: canRefine,
count: count
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$a(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$7(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute,
value = props.value,
filter = props.filter;
var checked = getCurrentRefinement$c(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var nextSearchParameters = searchParameters.addDisjunctiveFacet(attribute);
if (checked) {
nextSearchParameters = nextSearchParameters.addDisjunctiveFacetRefinement(attribute, value);
if (filter) {
nextSearchParameters = filter(nextSearchParameters);
}
}
return nextSearchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$e(props);
var checked = getCurrentRefinement$c(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = [];
var index = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (checked) {
items.push({
label: props.label,
currentRefinement: checked,
attribute: props.attribute,
value: function value(nextState) {
return _refine$a(props, nextState, false, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
}
return {
id: id,
index: index,
items: items
};
}
});
function inferPayload(_ref) {
var method = _ref.method,
results = _ref.results,
currentHit = _ref.currentHit;
var index = results.index;
var queryID = currentHit.__queryID;
var objectIDs = [currentHit.objectID];
if (!queryID) {
throw new Error("Could not infer `queryID`. Ensure `clickAnalytics: true` was added with the Configure widget.\nSee: https://alg.li/VpPpLt");
}
switch (method) {
case 'clickedObjectIDsAfterSearch':
{
var positions = [currentHit.__position];
return {
index: index,
queryID: queryID,
objectIDs: objectIDs,
positions: positions
};
}
case 'convertedObjectIDsAfterSearch':
return {
index: index,
queryID: queryID,
objectIDs: objectIDs
};
default:
throw new Error("Unsupported method \"".concat(method, "\" passed to the insights function. The supported methods are: \"clickedObjectIDsAfterSearch\", \"convertedObjectIDsAfterSearch\"."));
}
}
var wrapInsightsClient = function wrapInsightsClient(aa, results, currentHit) {
return function (method, payload) {
if (typeof aa !== 'function') {
throw new TypeError("Expected insightsClient to be a Function");
}
var inferredPayload = inferPayload({
method: method,
results: results,
currentHit: currentHit
});
aa(method, _objectSpread({}, inferredPayload, payload));
};
};
var connectHitInsights = (function (insightsClient) {
return createConnectorWithContext({
displayName: 'AlgoliaInsights',
getProvidedProps: function getProvidedProps(props, _, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var insights = wrapInsightsClient(insightsClient, results, props.hit);
return {
insights: insights
};
}
});
});
exports.EXPERIMENTAL_connectConfigureRelatedItems = connectConfigureRelatedItems;
exports.connectAutoComplete = connectAutoComplete;
exports.connectBreadcrumb = connectBreadcrumb;
exports.connectConfigure = connectConfigure;
exports.connectCurrentRefinements = connectCurrentRefinements;
exports.connectGeoSearch = connectGeoSearch;
exports.connectHierarchicalMenu = connectHierarchicalMenu;
exports.connectHighlight = connectHighlight;
exports.connectHitInsights = connectHitInsights;
exports.connectHits = connectHits;
exports.connectHitsPerPage = connectHitsPerPage;
exports.connectInfiniteHits = connectInfiniteHits;
exports.connectMenu = connectMenu;
exports.connectNumericMenu = connectNumericMenu;
exports.connectPagination = connectPagination;
exports.connectPoweredBy = connectPoweredBy;
exports.connectRange = connectRange;
exports.connectRefinementList = connectRefinementList;
exports.connectScrollTo = connectScrollTo;
exports.connectSearchBox = connectSearchBox;
exports.connectSortBy = connectSortBy;
exports.connectStateResults = connectStateResults;
exports.connectStats = connectStats;
exports.connectToggleRefinement = connectToggleRefinement;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=Connectors.js.map
|
ajax/libs/material-ui/4.9.4/esm/CircularProgress/CircularProgress.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { chainPropTypes } from '@material-ui/utils';
import withStyles from '../styles/withStyles';
import capitalize from '../utils/capitalize';
var 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 var styles = function styles(theme) {
return {
/* 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.
*/
var CircularProgress = React.forwardRef(function CircularProgress(props, ref) {
var classes = props.classes,
className = props.className,
_props$color = props.color,
color = _props$color === void 0 ? 'primary' : _props$color,
_props$disableShrink = props.disableShrink,
disableShrink = _props$disableShrink === void 0 ? false : _props$disableShrink,
_props$size = props.size,
size = _props$size === void 0 ? 40 : _props$size,
style = props.style,
_props$thickness = props.thickness,
thickness = _props$thickness === void 0 ? 3.6 : _props$thickness,
_props$value = props.value,
value = _props$value === void 0 ? 0 : _props$value,
_props$variant = props.variant,
variant = _props$variant === void 0 ? 'indeterminate' : _props$variant,
other = _objectWithoutProperties(props, ["classes", "className", "color", "disableShrink", "size", "style", "thickness", "value", "variant"]);
var circleStyle = {};
var rootStyle = {};
var rootProps = {};
if (variant === 'determinate' || variant === 'static') {
var circumference = 2 * Math.PI * ((SIZE - thickness) / 2);
circleStyle.strokeDasharray = circumference.toFixed(3);
rootProps['aria-valuenow'] = Math.round(value);
if (variant === 'static') {
circleStyle.strokeDashoffset = "".concat(((100 - value) / 100 * circumference).toFixed(3), "px");
rootStyle.transform = 'rotate(-90deg)';
} else {
circleStyle.strokeDashoffset = "".concat((easeIn((100 - value) / 100) * circumference).toFixed(3), "px");
rootStyle.transform = "rotate(".concat((easeOut(value / 70) * 270).toFixed(3), "deg)");
}
}
return React.createElement("div", _extends({
className: clsx(classes.root, className, color !== 'inherit' && classes["color".concat(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: "".concat(SIZE / 2, " ").concat(SIZE / 2, " ").concat(SIZE, " ").concat(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, function (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/material-ui/4.9.2/es/List/List.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import ListContext from './ListContext';
export const styles = {
/* Styles applied to the root element. */
root: {
listStyle: 'none',
margin: 0,
padding: 0,
position: 'relative'
},
/* Styles applied to the root element if `disablePadding={false}`. */
padding: {
paddingTop: 8,
paddingBottom: 8
},
/* Styles applied to the root element if dense. */
dense: {},
/* Styles applied to the root element if a `subheader` is provided. */
subheader: {
paddingTop: 0
}
};
const List = React.forwardRef(function List(props, ref) {
const {
children,
classes,
className,
component: Component = 'ul',
dense = false,
disablePadding = false,
subheader
} = props,
other = _objectWithoutPropertiesLoose(props, ["children", "classes", "className", "component", "dense", "disablePadding", "subheader"]);
const context = React.useMemo(() => ({
dense
}), [dense]);
return React.createElement(ListContext.Provider, {
value: context
}, React.createElement(Component, _extends({
className: clsx(classes.root, className, dense && classes.dense, !disablePadding && classes.padding, subheader && classes.subheader),
ref: ref
}, other), subheader, children));
});
process.env.NODE_ENV !== "production" ? List.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: PropTypes.elementType,
/**
* If `true`, compact vertical padding designed for keyboard and mouse input will be used for
* the list and list items.
* The prop is available to descendant components as the `dense` context.
*/
dense: PropTypes.bool,
/**
* If `true`, vertical padding will be removed from the list.
*/
disablePadding: PropTypes.bool,
/**
* The content of the subheader, normally `ListSubheader`.
*/
subheader: PropTypes.node
} : void 0;
export default withStyles(styles, {
name: 'MuiList'
})(List); |
ajax/libs/react-native-web/0.0.0-80dae21e2/exports/KeyboardAvoidingView/index.js | cdnjs/cdnjs | function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import View from '../View';
import React from 'react';
var KeyboardAvoidingView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(KeyboardAvoidingView, _React$Component);
function KeyboardAvoidingView() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
_this.frame = null;
_this.onLayout = function (event) {
_this.frame = event.nativeEvent.layout;
};
return _this;
}
var _proto = KeyboardAvoidingView.prototype;
_proto.relativeKeyboardHeight = function relativeKeyboardHeight(keyboardFrame) {
var frame = this.frame;
if (!frame || !keyboardFrame) {
return 0;
}
var keyboardY = keyboardFrame.screenY - (this.props.keyboardVerticalOffset || 0);
return Math.max(frame.y + frame.height - keyboardY, 0);
};
_proto.onKeyboardChange = function onKeyboardChange(event) {};
_proto.render = function render() {
var _this$props = this.props,
behavior = _this$props.behavior,
contentContainerStyle = _this$props.contentContainerStyle,
keyboardVerticalOffset = _this$props.keyboardVerticalOffset,
rest = _objectWithoutPropertiesLoose(_this$props, ["behavior", "contentContainerStyle", "keyboardVerticalOffset"]);
return React.createElement(View, _extends({
onLayout: this.onLayout
}, rest));
};
return KeyboardAvoidingView;
}(React.Component);
export default KeyboardAvoidingView; |
ajax/libs/primereact/6.6.0-rc.1/card/card.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { ObjectUtils, classNames } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Card = /*#__PURE__*/function (_Component) {
_inherits(Card, _Component);
var _super = _createSuper(Card);
function Card() {
_classCallCheck(this, Card);
return _super.apply(this, arguments);
}
_createClass(Card, [{
key: "renderHeader",
value: function renderHeader() {
if (this.props.header) {
return /*#__PURE__*/React.createElement("div", {
className: "p-card-header"
}, ObjectUtils.getJSXElement(this.props.header, this.props));
}
return null;
}
}, {
key: "renderBody",
value: function renderBody() {
var title = this.props.title && /*#__PURE__*/React.createElement("div", {
className: "p-card-title"
}, ObjectUtils.getJSXElement(this.props.title, this.props));
var subTitle = this.props.subTitle && /*#__PURE__*/React.createElement("div", {
className: "p-card-subtitle"
}, ObjectUtils.getJSXElement(this.props.subTitle, this.props));
var children = this.props.children && /*#__PURE__*/React.createElement("div", {
className: "p-card-content"
}, this.props.children);
var footer = this.props.footer && /*#__PURE__*/React.createElement("div", {
className: "p-card-footer"
}, ObjectUtils.getJSXElement(this.props.footer, this.props));
return /*#__PURE__*/React.createElement("div", {
className: "p-card-body"
}, title, subTitle, children, footer);
}
}, {
key: "render",
value: function render() {
var header = this.renderHeader();
var body = this.renderBody();
var className = classNames('p-card p-component', this.props.className);
return /*#__PURE__*/React.createElement("div", {
className: className,
style: this.props.style,
id: this.props.id
}, header, body);
}
}]);
return Card;
}(Component);
_defineProperty(Card, "defaultProps", {
id: null,
header: null,
footer: null,
title: null,
subTitle: null,
style: null,
className: null
});
export { Card };
|
ajax/libs/material-ui/5.0.0-alpha.9/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.2/esm/DialogContent/DialogContent.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
export var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: {
flex: '1 1 auto',
WebkitOverflowScrolling: 'touch',
// Add iOS momentum scrolling.
overflowY: 'auto',
padding: '8px 24px',
'&:first-child': {
// dialog without title
paddingTop: 20
}
},
/* Styles applied to the root element if `dividers={true}`. */
dividers: {
padding: '16px 24px',
borderTop: "1px solid ".concat(theme.palette.divider),
borderBottom: "1px solid ".concat(theme.palette.divider)
}
};
};
var DialogContent = React.forwardRef(function DialogContent(props, ref) {
var classes = props.classes,
className = props.className,
_props$dividers = props.dividers,
dividers = _props$dividers === void 0 ? false : _props$dividers,
other = _objectWithoutProperties(props, ["classes", "className", "dividers"]);
return React.createElement("div", _extends({
className: clsx(classes.root, className, dividers && classes.dividers),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? DialogContent.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Display the top and bottom dividers.
*/
dividers: PropTypes.bool
} : void 0;
export default withStyles(styles, {
name: 'MuiDialogContent'
})(DialogContent); |
ajax/libs/material-ui/4.10.2/RootRef/RootRef.js | cdnjs/cdnjs | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var React = _interopRequireWildcard(require("react"));
var ReactDOM = _interopRequireWildcard(require("react-dom"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _utils = require("@material-ui/utils");
var _setRef = _interopRequireDefault(require("../utils/setRef"));
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
/**
* ⚠️⚠️⚠️
* If you want the DOM element of a Material-UI component check out
* [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element)
* first.
*
* This component uses `findDOMNode` which is deprecated in React.StrictMode.
*
* Helper component to allow attaching a ref to a
* wrapped element to access the underlying DOM element.
*
* It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801.
* For example:
* ```jsx
* import React from 'react';
* import RootRef from '@material-ui/core/RootRef';
*
* function MyComponent() {
* const domRef = React.useRef();
*
* React.useEffect(() => {
* console.log(domRef.current); // DOM node
* }, []);
*
* return (
* <RootRef rootRef={domRef}>
* <SomeChildComponent />
* </RootRef>
* );
* }
* ```
*/
var RootRef = /*#__PURE__*/function (_React$Component) {
(0, _inherits2.default)(RootRef, _React$Component);
var _super = _createSuper(RootRef);
function RootRef() {
(0, _classCallCheck2.default)(this, RootRef);
return _super.apply(this, arguments);
}
(0, _createClass2.default)(RootRef, [{
key: "componentDidMount",
value: function componentDidMount() {
this.ref = ReactDOM.findDOMNode(this);
(0, _setRef.default)(this.props.rootRef, this.ref);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
var ref = ReactDOM.findDOMNode(this);
if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) {
if (prevProps.rootRef !== this.props.rootRef) {
(0, _setRef.default)(prevProps.rootRef, null);
}
this.ref = ref;
(0, _setRef.default)(this.props.rootRef, this.ref);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.ref = null;
(0, _setRef.default)(this.props.rootRef, null);
}
}, {
key: "render",
value: function render() {
return this.props.children;
}
}]);
return RootRef;
}(React.Component);
process.env.NODE_ENV !== "production" ? RootRef.propTypes = {
/**
* The wrapped element.
*/
children: _propTypes.default.element.isRequired,
/**
* A ref that points to the first DOM node of the wrapped element.
*/
rootRef: _utils.refType.isRequired
} : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== "production" ? RootRef.propTypes = (0, _utils.exactProp)(RootRef.propTypes) : void 0;
}
var _default = RootRef;
exports.default = _default; |
ajax/libs/react-native-web/0.17.1/exports/AppRegistry/renderApplication.js | cdnjs/cdnjs | function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import AppContainer from './AppContainer';
import invariant from 'fbjs/lib/invariant';
import render, { hydrate } from '../render';
import styleResolver from '../StyleSheet/styleResolver';
import React from 'react';
export default function renderApplication(RootComponent, WrapperComponent, callback, options) {
var shouldHydrate = options.hydrate,
initialProps = options.initialProps,
rootTag = options.rootTag;
var renderFn = shouldHydrate ? hydrate : render;
invariant(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag);
renderFn( /*#__PURE__*/React.createElement(AppContainer, {
WrapperComponent: WrapperComponent,
rootTag: rootTag
}, /*#__PURE__*/React.createElement(RootComponent, initialProps)), rootTag, callback);
}
export function getApplication(RootComponent, initialProps, WrapperComponent) {
var element = /*#__PURE__*/React.createElement(AppContainer, {
WrapperComponent: WrapperComponent,
rootTag: {}
}, /*#__PURE__*/React.createElement(RootComponent, initialProps)); // Don't escape CSS text
var getStyleElement = function getStyleElement(props) {
var sheet = styleResolver.getStyleSheet();
return /*#__PURE__*/React.createElement("style", _extends({}, props, {
dangerouslySetInnerHTML: {
__html: sheet.textContent
},
id: sheet.id
}));
};
return {
element: element,
getStyleElement: getStyleElement
};
} |
ajax/libs/zingchart-react/2.0.0/index.es.js | cdnjs/cdnjs | import React, { Component } from 'react';
/*
All of the code within the ZingChart software is developed and copyrighted by ZingChart, Inc., and may not be copied,
replicated, or used in any other software or application without prior permission from ZingChart. All usage must coincide with the
ZingChart End User License Agreement which can be requested by email at support@zingchart.com.
Build 2.8.7_ES6
*/
if(typeof(ZC)==="undefined"){eval(function(p,a,c,k,e,d){e=function(c){return (c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c);}k=[function(e){return d[e]}];e=function(){return '\\w+'};c=1;}while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);}}return p}('2w.ZC={AU:1n(e,t){if(e.1L)1l e.1L(t);1j(1a i=0,a=e.1f;i<a;i++)if(e[i]===t)1l i;1l-1},fF:"2.8.7",14O:"",Id:!1,wN:["1c","n8","1w","97","bj","1N","83","bv","2U","dN","5t","6O","6c","7k","6v","8r","5m","6V","3O","7e","9H","ql","8S","9u","aX","gO","7d","g7","8i","7R","qA","aA","aB","5V","xt","84","5z","qw","8D","b7"],mN:{Ib:["HP","Hz"],Hq:["Ht","Hr"],Ii:["Iv","IL"],Iw:["Iu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e=!!2g.4P("3a").9d,t=!1;e&&(t="1n"==1y 2g.4P("3a").9d("2d").rX);ZC.3a=e&&t,ZC.2F=2g.Nx.Nw("7h://8z.w3.dS/TR/Nv/Nt#Nh","1.1");1a i=2g.3s.2Z(2g.4P("3B")),a=2g.4P("7o:2T");a.7U="tW",a.4m("id","Ns"),a.4m("zk",1m 8W),i.2Z(a),a.1I.xP="3R(#2q#xG)",ZC.3K=!a||"4h"==1y a.zk,i.6o.b2(i);1a n=!1;8V.pS&&8V.pS["g8/x-zj-aJ"]?n=8V.pS["g8/x-zj-aJ"].Np:2g.4t&&-1===8V.Nm.1L("Nl")&&(n=1m bA(\'4J { 1a oC = 1m mr("zh.zh");if (oC) { oC = 1c; 1l gX; } } 4M (e) { 1l d5; }\')()),ZC.aJ=n?1:0},96:!(2g.zg&&"Nk"===2g.zg),6N:!!/zf (\\d+\\.\\d+);/.5U(8V.c3)&&5P(5y.$1)<8,cA:!!/zf (\\d+\\.\\d+);/.5U(8V.c3)&&5P(5y.$1)<9,2L:/Ni|Qf|zW Oh|Qg|Si CE|Td/.5U(8V.c3),wX:/Tc/.5U(8V.c3),wW:/Ta/.5U(8V.c3),hC:"pP"in 2w,oY:"SL"in 2w,RN:[],WU:[],DS:[0,0],Sz:1c,2E:1n(e,t,i,a,n,l){1c===ZC.1d(i)&&(i=!0),1c===ZC.1d(a)&&(a=!0),1c===ZC.1d(n)&&(n=!1);1a r=(l=l||[]).1f;1j(1a o in e)if(0===r||r>0&&-1===ZC.AU(l,o))if(e[o]3E 3M){if(a){(1c===ZC.1d(t[o])||"78"!==o&&!n)&&(t[o]=[]);1j(1a s=0,A=e[o].1f;s<A;s++)t[o].1h(e[o][s])}}1u e[o]3E 8W&&!(e[o]3E bA)?a&&(1c===ZC.1d(t[o])&&(t[o]={}),t[o]3E 8W&&!(t[o]3E bA)&&ZC.2E(e[o],t[o],i)):(1c===ZC.1d(t[o])||i)&&(t[o]=e[o])},so:1n(e,t){t||(t=[]);1j(1a i=0,a=e.1f;i<a;i++)t.1h(e[i])},Sy:1n(e,t){1a i={};ZC.2E(e,i),ZC.2E(t,e),ZC.2E(i,e)},6y:1n(e,t,i){if("gh"!==1o.oA){1y t===ZC.1b[31]&&(t=!0);1a a,n,l=(i=i||[]).1f;1j(1a r in e)if(e.8d(r)&&(0===l||l>0&&-1===ZC.AU(i,r))){1a o=r.2v(0,1);if("."!==o&&"#"!==o)if(e[r]3E 3M)if(ZC.V5(r)!==r){1j(e[ZC.V5(r)]=[],a=0,n=e[r].1f;a<n;a++)ZC.6y(e[r][a]),e[ZC.V5(r)].1h(e[r][a]);4v e[r]}1u 1j(a=0,n=e[r].1f;a<n;a++)ZC.6y(e[r][a]);1u e[r]3E 8W&&!(e[r]3E bA)?(ZC.V5(r)!==r&&(e[ZC.V5(r)]={},ZC.2E(e[r],e[ZC.V5(r)]),4v e[r]),t&&ZC.6y(e[ZC.V5(r)],t,i)):ZC.V5(r)!==r&&(e[ZC.V5(r)]=e[r],4v e[r])}}},gS:1n(e,t){1j(1a i in e){1a a;if(e.8d(i))if((a=i.1F(t+"-",""))!==i)if(e[a]=e[i],e[i]3E 3M)1j(1a n=0,l=e[i].1f;n<l;n++)ZC.gS(e[i][n],t);1u e[i]3E 8W&&!(e[i]3E bA)&&ZC.gS(e[i],t)}},sK:1n(e){1j(1a t="",i=0,a=e.1f;i<a;i++){1a n=i%2==0?i:e.1f-i;t+=e.2v(n,n+1)}1l t=t.1F(/\\./g,"d")},uh:1n(e){1a t=e;1l t=(t=(t=t.1F("*","&")).1F("9","3")).1F("l","1")},mj:1n(e){1l e.1F(/[a-zA-Z]/g,1n(e){1l 6d.d7((e<="Z"?90:122)>=(e=e.g1(0)+13)?e:e-26)})},ui:1n(e,t){1a i=ZC.XG(ZC.z6(e)),a=ZC.XG(ZC.ku(t)),n=i.1f;if(0===n)1l"";1j(1a l,r,o=i[n-1],s=i[0],A=z8,C=1B.4b(6+52/n)*A;0!==C;){r=C>>>2&3;1j(1a Z=n-1;Z>0;Z--)l=((o=i[Z-1])>>>5^s<<2)+(s>>>3^o<<4)^(C^s)+(a[3&Z^r]^o),s=i[Z]-=l;l=((o=i[n-1])>>>5^s<<2)+(s>>>3^o<<4)^(C^s)+(a[3&Z^r]^o),s=i[0]-=l,C-=A}1l Sx(ZC.z5(ZC.nh(i)))},Sw:1n(e,t){e=eQ(e);1a i=ZC.XG(ZC.ku(e)),a=ZC.XG(ZC.ku(t)),n=i.1f;if(0===n)1l"";1===n&&(i[n++]=0);1j(1a l,r,o=i[n-1],s=i[0],A=1B.4b(6+52/n),C=0;A-->0;){r=(C+=z8)>>>2&3;1j(1a Z=0;Z<n-1;Z++)l=(o>>>5^(s=i[Z+1])<<2)+(s>>>3^o<<4)^(C^s)+(a[3&Z^r]^o),o=i[Z]+=l;l=(o>>>5^(s=i[0])<<2)+(s>>>3^o<<4)^(C^s)+(a[3&Z^r]^o),o=i[n-1]+=l}1l ZC.z7(ZC.nh(i))},XG:1n(e){1j(1a t=1m 3M(1B.4l(e.1f/4)),i=0;i<t.1f;i++)t[i]=e[4*i]+(e[4*i+1]<<8)+(e[4*i+2]<<16)+(e[4*i+3]<<24);1l t},nh:1n(e){1j(1a t=[],i=0;i<e.1f;i++)t.1h(3U&e[i],e[i]>>>8&3U,e[i]>>>16&3U,e[i]>>>24&3U);1l t},z7:1n(e){1j(1a t="",i=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],a=0;a<e.1f;a++)t+=i[e[a]>>4]+i[15&e[a]];1l t},z6:1n(e){1j(1a t=[],i="zL"===e.5A(0,2)?2:0;i<e.1f;i+=2)t.1h(5v(e.5A(i,2),16));1l t},z5:1n(e){1j(1a t="",i=0;i<e.1f;i++)0!==e[i]&&(t+=6d.d7(e[i]));1l t},ku:1n(e){1j(1a t=[],i=0;i<e.1f;i++)t.1h(e.g1(i));1l t},1k:1n(e){1l-1!==6d(e).1L("e-")?0:""===(e=6d(e).1F(/[^0-9\\.\\-]/gi,""))?0:1B.43(e)},1W:1n(e){1l e=5P(e),7X(e)?0:e},4o:1n(e,t){1l 1y t===ZC.1b[31]&&(t=2),5P(4T(e).4A(t))},2l:1n(e){1l 1B.3l(e)},2s:1n(e){1l"d5"!==e&&"0"!==e&&("gX"===e||"1"===e||!!e&&!0)},8G:1n(e){1a t=(e=6d(e).1F(/[^0-9\\.\\%\\-]/gi,"")).1L("%");1l-1!==t&&(e=e.2v(0,t),e=ZC.1W(e)/100),e},j2:1n(e){1l 2w.z4?2w.z4(e):e},1d:1n(e){1l 1c===e||1y e===ZC.1b[31]?1c:e},9q:1n(e,t){1l 1c===e||1y e===ZC.1b[31]?t:e},gY:1n(e){1l(e%=2m)<0&&(e+=2m),e},IH:1n(e,t){1l ZC.1W(e)+""==e+""?t?ZC.1W(e):ZC.2l(e):-1!==(e+="").1L("%")?ZC.1W(e.1F("%",""))/100:-1!==e.1L("px")?ZC.1W(e.1F("px","")):ZC.1W(e)},R1:1n(e){1l 5v(e,16)},P2:1n(e){1l ZC.1k(e).a5(16)},hm:1n(e,t){1l 5v(e+(t-e)*1B.cb(),10)},5u:1n(e,t,i){1l e=(e=e<t?t:e)>i?i:e},E0:1n(e,t,i){1l t<=e&&e<=i||i<=e&&e<=t},BM:1n(e,t){1l 1B.1X(e,t)},CQ:1n(e,t){1l 1B.2j(e,t)},d4:1n(e){1j(1a t=0,i=e.1f,a=-4T.hH;t<i;t++)a=1B.1X(a,e[t]);1l a},dj:1n(e){1j(1a t=0,i=e.1f,a=4T.hH;t<i;t++)a=1B.2j(a,e[t]);1l a},Bu:1n(){1j(1a e=(Uf*1B.cb()+1<<0).a5(16);e.1f<6;)e="0"+e;1l"#"+e},qf:1n(e,t){1j(1a i,a=ZC.1W(t),n=4T.hH,l=0,r=0,o=e.1f;r<o;r++)(i=1B.3l(ZC.1W(e[r])-a))<n&&(l=r,n=i);1l l},So:1n(e){1a t=e.2n(".");1l t[t.1f-1]||""},GP:1n(e){1l e.1F(/^\\s\\s*/,"").1F(/\\s\\s*$/,"")},JN:1n(e,t){1l t=t||1B.E,dp(1B.3P(e)/1B.3P(t))?1B.3P(e)/1B.3P(t):0},UE:1n(e){1l 2m*e/(2*1B.PI)},TG:1n(e){1l 2*e*1B.PI/2m},EC:1n(e){1l 1B.dz(ZC.TG(e))},EH:1n(e){1l 1B.eb(ZC.TG(e))},PJ:1n(e){1l!7X(5P(e))&&dp(e)},EA:1n(e){1l-1!==e.1L("-")?e.1F(/(\\-[a-z0-9])/g,1n(e){1l e.5M().1F("-","")}):e},V5:1n(e){1l e.5M()!==e&&-1===e.1L("-")&&e.2v(0,1).aN()===e.2v(0,1)?e.1F(/([A-Z])/g,1n(e){1l"-"+e.aN()}).1F(/([0-9]+)/g,1n(e){1l"-"+e.aN()}).1F("-3d","3d"):e},Sn:1n(e){1l ZC.Y3.du(e)},AK:1n(e){1l 2g.cP(e)},lW:1n(e,t){1l e[0].1f<t[0].1f?1:e[0].1f>t[0].1f?-1:0},e3:1n(e){2w.5Q(e,1o.oo)},9y:1n(e,t){1l t>=0&&t<=20?e.4A(t):""+e},ll:1n(e,t,i,a){1a n=t.R[i].BW,l=t.R[a].BW;if(e==n)1l i;if(e==l)1l a;1a r=ZC.1k((i+a)/2);if(!t.R[r]){1j(;!t.R[r]&&r<a;)r++;if(r===a){1j(r=ZC.1k((i+a)/2);!t.R[r]&&r>i;)r--;if(r===i)1l 1c}}1a o=t.R[r].BW;1l r!==i&&r!==a?e==o?r:e>o?ZC.ll(e,t,r,a):ZC.ll(e,t,i,r):e==o?r:1c},aE:1n(e){1a t,i,a,n,l=[1,1,0,0];if(1o.3J.Ap&&!ZC.3K&&ZC.AK(e)){1a r=ZC.AK(e);1j(t="";r&&(""===t||"2b"===t);)t=ZC.A3(r).2O("5H")||"",r=r.6o;-1!==(i=t.1L("9v("))&&(a=t.1L(")",i),n=t.2v(i+7,a-i).2n(","),l=[ZC.1W(n[0]),ZC.1W(n[3]),ZC.1W(n[4]),ZC.1W(n[5])])}1l l}},ZC.sb=!1,ZC.aw=5x,ZC.aC=60*ZC.aw,ZC.HR=60*ZC.aC,ZC.9s=24*ZC.HR,ZC.dq=30*ZC.9s,ZC.YR=Ar*ZC.9s,ZC.3y=0,2w.3h=2w.3h||{},3h.5g=3h.5g||1n(e){1a t=1y e;if("4h"!==t||1c===e)1l"3e"===t&&(e=\'"\'+e.1F("\\\\","\\\\\\\\").1F(\'"\',\'"\')+\'"\'),6d(e);1a i,a,n=[],l=e&&e.2G===3M;1j(i in e)"1n"!=1y e[i]&&("3e"===(t=1y(a=e[i]))?a=\'"\'+a.1F("\\\\","\\\\\\\\").1F(\'"\',\'\\\\"\')+\'"\':"4h"===t&&1c!==a&&(a=3h.5g(a)),n.1h((l?"":\'"\'+i+\'":\')+6d(a)));1l(l?"[":"{")+6d(n)+(l?"]":"}")},3h.1q=3h.1q||1n(KY){1l""===KY&&(KY=\'""\'),7l("("+KY+")")},ZC.1b=["1U-1r","2f-4e","2f-6j","4w","1w-1s","6g","-2r-1N zc-2r-1N","6w","7z","1T","cC","dW","6K","m1-8E","6K-8E","-6I-c","aY","1T-3C","7i","1s","1M","2e","-2N-c","4U-2i","zc-3l zc-6p","ax-6K","3d-76","x-2f","y-2f","z-2f",\'" 9e="\',"mh","~9J(3U,3U,3U,0)","~9N(3U,3U,3U)","-2r-1N ","-ch-1A-","7h://8z.w3.dS/v9/2F","7h://8z.w3.dS/sQ/kn","Sl","Sk","Ud","Ub","Tz","Ty","Tx","If-Tu-Tt","cl, 1 ci dJ 6X:6X:6X dF","6F","7V","6k","1z-x","1z-y","1z-v","Ts","a9-93","4U-8x","4U-2z","2y-1v","2y-2A","2y-2a","2y-1K","1G-1r","1G-1s","Tr 4L","i3 dG 6A","6A.5i.6i-2C","-2C-1Q-iA","5H-5s-5I","5H-5s","bg-4d-1s","bg-4d-1M","2N-3X","1U-3X","dQ-3X"];1O ad{}if(ZC.uL=1n(e){1g.H=e,1g.ol=1n(e,t){1a i,a=1g,n=a.B8.6P;if(1c!==ZC.1d(t)&&1c!==ZC.1d(n[t])&&(n=n[t]),1c!==ZC.1d(n[e])){1a l=n[e];1l 1c===ZC.1d(l[2])&&(l[2]=ZC.AO.R2(l[1],10)),1c===ZC.1d(l[3])&&(l[3]=ZC.AO.R2(l[1],10)),l}1a r=["#Tq","#Tl","#Tk","#Tj","#Th","#Ri","#Rf"];i=1c!==ZC.1d(r[e-a.B8.6P.1f])?r[e-a.B8.6P.1f]:"#"+ZC.Y3.du(e).5A(e%20,6);1a o=ZC.AO.R2(i,10),s=ZC.AO.R2(i,20),A="#tf";1l a.B8.6P&&a.B8.6P[0]&&a.B8.6P[0][0]&&(A=a.B8.6P[0][0]),[A,i,o,s]},1g.ls=1n(e){e&&ZC.2E(e,1g.B8,!0)},1g.qv=1n(e){1a t=1g;1c!==ZC.1d(t.NU[e])&&(ZC.6y(t.NU[e]),ZC.2E(t.NU[e],t.B8))},1g.NU={},ZC.2E(1o.Az,1g.NU),1g.NU.cH={6P:[["#2S","#Rd","#Rc","#Qv"],["#2S","#Qr","#Qp","#Qn"],["#2S","#Qm","#Ql","#Qk"],["#2S","#Qj","#Rg","#Qu"],["#2S","#Rh","#Rv","#Sf"],["#2S","#Sd","#Sc","#Sb"]],2Y:{d0:{dk:{2o:.5,"1U-1r":"#4S",1r:"#4u","2t-2e":15,6x:1,1E:"o0..."}},"1U-1r":"#qW #Sa",5E:{"2t-2e":14,6x:1,1r:"#2S","1U-1r":"#S2 #Ry",3v:6},86:{"2t-2e":11,6x:1,1r:"#8M","2y-1v":30,3v:6},7g:{"2t-2e":10,1r:"#8M",1s:"100%",6x:1,"1E-3u":"2A",1M:20,2y:"3g 0 0 3g",3v:5},h7:{"2t-2e":12,1r:"#8M","1E-3u":"3F","9l-3u":"6n",1E:""},4z:{"2t-2e":11,"1w-1s":2,"1w-1r":"#fZ",1Q:{7J:!0},"3T-1w":{"1w-1s":1,"1w-1r":"#fZ"},2i:{2h:1,"1w-1s":1,"1w-1I":"2V","1w-1r":"#yp",2o:.2},"4Q-2i":{2h:1,"1w-1s":1,"1w-1I":"2V","1w-1r":"#Ay",2o:.1},3Z:{2h:1,2e:6,6w:ZC.1b[18],"1w-1s":2,"1w-1r":"#fZ"},"4Q-3Z":{2h:1,2e:4,"1w-1s":1,"1w-1r":"#fZ"},1H:{1r:"#yp",7J:!0}},"1Z-x":{2U:{1M:16},3q:{1M:16}},"1Z-y":{2U:{1s:16},3q:{1s:16}},1Y:{"1U-1r":"#2S","1G-1s":1,2o:.75,"1G-2o":.75,"1G-1r":"#cc","3I-6T":3,5K:{3v:"4 6",1r:"#2S","1G-1s":1,"1G-1r":"#fZ","1U-1r":"#fZ"},9U:{3v:"2 6","1U-1r":"#8c","1G-1s":1,"1G-1r":"#cc"},1R:{"1G-1r":"#8M","1G-1s":1}},1A:{"1T-3C":{7J:!0},1R:{3I:1,"1w-1s":1,"1G-1s":1},"2N-1R":{"1w-1s":1,"1G-1s":1}},2i:{"1w-1s":1,"1w-1r":"#4S",2o:1,"1z-1H":{1E:"%l",3v:"3 6"},"1A-1H":{3v:"3 6"}}},1w:{1A:{"3I-2o":.5,1R:{2e:4},"2N-1R":{2e:5}}},1N:{1A:{"3I-2o":.5,1R:{2e:4},"2N-1R":{2e:5}}},5t:{1A:{"3i-2f":90,3I:0}},6c:{1A:{"3i-2f":180,3I:0}},5V:{2u:{"4O-g2":[0,0]},1A:{3I:0}},84:{1A:{3I:0}},8i:{1A:{3I:0}},7R:{1A:{"3i-2f":0,3I:0}},6v:{1A:{1R:{2e:4},"2N-1R":{2e:5}}},8r:{1A:{1R:{2e:4},"2N-1R":{2e:5}}},5m:{1A:{1R:{"1G-1s":0},"2N-1R":{"1G-1s":0}}},6V:{1A:{1R:{"1G-1s":0},"2N-1R":{"1G-1s":0}}},3O:{1A:{"1G-1s":1}},8S:{1A:{"1G-1s":1}},7d:{1A:{1R:{2e:3},"2N-1R":{2e:4}},"1z-k":{2i:{2o:.5,"1U-1r":"#8X #74"}}},8D:{"1z-r":{"1U-1r":"-1",2i:{2o:.5,"1U-1r":"#8X #74"},1Q:{"2c-r":0},9H:{2e:1,2B:[{"1U-1r":"#4S",2o:.8},{"1U-1r":"#cc",2o:.8}]}}},aA:{2u:{2y:"50 100"},4z:{"1w-1s":0,3Z:{"1w-1s":0},"4Q-3Z":{"1w-1s":0},2i:{"1w-1s":0},"4Q-2i":{"1w-1s":0}},"1z-y":{2i:{2o:.25,"1U-1r":"-1 #8Q"}},"1z-y-n":{2i:{2o:.25,"1U-1r":"-1 #8Q"}},1A:{"1G-1s":1}},aB:{2u:{2y:"50 100"},"1z-x":{1H:{"2t-2f":3V}},"1z-x-n":{1H:{"2t-2f":90}},4z:{"1w-1s":0,3Z:{"1w-1s":0},"4Q-3Z":{"1w-1s":0},2i:{"1w-1s":0},"4Q-2i":{"1w-1s":0}},"1z-y":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"},2i:{2o:.25,"1U-1r":"#8Q -1"}},"1z-y-n":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"},2i:{2o:.25,"1U-1r":"#8Q -1"}},1A:{"1G-1s":1}},5z:{1A:{1R:{1J:"3z",2e:4},"2N-1R":{2e:5}}},97:{4z:{"1w-1r":"#74",3Z:{2h:!1}},1A:{"1G-1s":0,"1w-1s":1}},83:{4z:{"1w-1r":"#74",3Z:{2h:!1}},1A:{"1G-1s":0,"1w-1s":1}},aX:{4z:{"1w-1r":"#74",3Z:{2h:!1}},1A:{"1G-1s":1}},6O:{4z:{"1w-1r":"#74",3Z:{2h:!1}},1A:{"1G-1s":1}},7k:{4z:{"1w-1r":"#74",3Z:{2h:!1}},1A:{"1G-1s":1}},7e:{1A:{"1G-1s":1}},"-":""},1g.NU.8Y={6P:[["#2S","#yo","#yo","#Au"],["#2S","#yl","#yl","#Rs"],["#2S","#tV","#tV","#Rr"],["#2S","#y6","#y6","#Mf"],["#2S","#yc","#yc","#Rn"],["#2S","#yb","#yb","#Rm"],["#2S","#y9","#y9","#Rk"],["#2S","#zo","#zo","#Qh"],["#2S","#Bd","#Bd","#tV"]],2Y:{d0:{dk:{2o:.5,"1U-1r":"#4S",1r:"#4u","2t-2e":15,6x:1,1E:"o0..."}},"1U-1r":"#j4",5E:{"2t-2e":21,6x:1,1r:"#e5","1U-1r":"2b",3v:6},86:{"2t-2e":11,6x:1,1r:"#e5","2y-1v":30,3v:6},7g:{"2t-2e":10,1r:"#e5",1s:"100%",6x:1,"1E-3u":"2A",1M:20,2y:"3g 0 0 3g",3v:5},h7:{"2t-2e":12,1r:"#8M","1E-3u":"3F","9l-3u":"6n",1E:"No dG","1U-1r":"#Lr",2o:.8},4z:{"2t-2e":11,"1w-1s":1,"1w-1r":"#e2",1Q:{"2t-2e":12,7J:!0,1r:"#HS"},"3T-1w":{"1w-1s":1,"1w-1r":"#7M"},2i:{2h:1,"1w-1s":1,"1w-1I":"2V","1w-1r":"#Hu",2o:1},"4Q-2i":{2h:1,"1w-1s":1,"1w-1I":"2V","1w-1r":"#Ay",2o:.1},3Z:{2h:1,2e:5,6w:ZC.1b[18],"1w-1s":1,"1w-1r":"#e2"},"4Q-3Z":{2h:1,2e:3,"1w-1s":1,"1w-1r":"#cX"},1H:{1r:"#e5",7J:!0}},"1z-x":{fM:!0,2i:{2h:!1}},1Z:{2U:{"1U-1r":"#tL",2y:1},3q:{"1U-1r":"#cX","1G-9i":6}},"1Z-x":{2U:{1M:16,"1G-1v":"2b","1G-2A":"2b","1G-2a":"2b","1G-1K":"2b"},3q:{1M:10,"1G-1v":"2b","1G-2A":"2b","1G-2a":"2b","1G-1K":"2b"}},"1Z-y":{2U:{1s:16,"1G-1v":"2b","1G-2A":"2b","1G-2a":"2b","1G-1K":"2b"},3q:{1s:10,"1G-1v":"2b","1G-2A":"2b","1G-2a":"2b","1G-1K":"2b"}},"1Z-xi":{2U:{1s:16,"1G-1v":"2b","1G-2A":"2b","1G-2a":"2b","1G-1K":"2b"},3q:{1s:10,"1G-1v":"2b","1G-2A":"2b","1G-2a":"2b","1G-1K":"2b"}},"1Z-yi":{2U:{1M:16,"1G-1v":"2b","1G-2A":"2b","1G-2a":"2b","1G-1K":"2b"},3q:{1M:10,"1G-1v":"2b","1G-2A":"2b","1G-2a":"2b","1G-1K":"2b"}},2z:{"1U-1r":"#2S","1G-1s":1,"1G-1r":"#cX",4c:!0,4O:{"1U-1r":"#4S"},6C:{2o:0},3q:{1s:11,"1G-1s":2,"1G-9i":3,"1w-1r":"#tI","1G-1r":"#cX","1U-1r":"#tL"},"3q-1v":{1M:11},"3q-2a":{1M:11}},2H:{3I:1,"3I-2f":45,"3I-6T":1,"3I-2o":.25,"1G-1s":1,"1G-1r":"#2S","1G-2o":1},3G:{"dD-3G":1,"1U-1r":"#l8"},1Y:{"1U-1r":"#2S","1G-1s":1,3I:0,"3I-2o":.2,2o:1,"1G-2o":1,"1G-1r":"#e0",5K:{3v:"5 0 5 10",1r:"#Iy","1U-1r":"2b","1G-1s":0,"1G-1v":"gU 2V 2b","1G-2a":"7Y 2V #e0"},9U:{3v:"5 0 5 10","1G-1v":"7Y 2V #e0"},tz:{"1U-1r":"#tL","1w-1r":"#tI",2y:2,1M:8,"1w-1s":2,"1w-1I":"fo"},b0:{"1w-1r":"#tI","1w-1s":2,1I:"Ix"},1R:{"1G-1r":"#2S","1G-1s":1},"3f-on":{"1U-1r":"#l8"},"3f-6Q":{"1U-1r":"#tg"},1Z:{2U:{"1U-1r":"2b","2y-1v":3,"2y-2a":3},3q:{"1U-1r":"#tg","1G-1v":"2b","1G-2A":"2b","1G-2a":"2b","1G-1K":"2b","1G-9i":6,1s:12,1M:12}}},1A:{"1T-3C":{7J:!0},1R:{3I:0,"1w-1s":1,"1G-1s":1,"1G-1r":"#2S"},"2N-1R":{"1w-1s":1,"1G-1s":1},Cs:!0},2i:{"1w-1s":1,"1w-1r":"#e2",2o:1,"1z-1H":{1E:"%l",3v:"3 6"},"1A-1H":{3v:"3 6"}}},1w:{1A:{"1w-1s":2,3I:0,1R:{2e:4},"2N-3X":{},"2N-1R":{2e:5,"1G-1s":1,"1G-1r":"#2S"}}},1N:{1A:{"1w-1s":2,3I:0,"2o-1N":.25,"1U-1r-1I":"2V",1R:{2e:4},"2N-3X":{},"2N-1R":{2e:5,"1G-1s":1,"1G-1r":"#2S"}}},5t:{1A:{"3i-2f":90,3I:0}},6c:{1A:{"3i-2f":180,3I:0}},5V:{2u:{"4O-g2":[0,0]},1A:{3I:0},"1z-x":{2i:{2h:!0}}},84:{1A:{3I:0}},8i:{1A:{3I:0,7w:{"1G-1s":1,"1G-1r":"#2S",1M:8}}},7R:{1A:{"3i-2f":0,3I:0,7w:{"1G-1s":1,"1G-1r":"#2S",1s:8}}},6v:{1A:{"1w-1r":"%kY-0","1G-1r":"%kY-0",1R:{2e:5},"2N-1R":{2e:6}},"1z-x":{2i:{2h:!0}}},8r:{1A:{"1w-1r":"%kY-0","1G-1r":"%kY-0",1R:{2e:4},"2N-1R":{2e:5}},"1z-x":{2i:{2h:!0}}},5m:{1A:{1R:{"1G-1s":1,"1G-1r":"#2S"},"2N-1R":{"1G-1s":1,"1G-1r":"#2S"}},"1z-x":{2i:{2h:!0}}},6V:{1A:{1R:{"1G-1s":1,"1G-1r":"#2S"},"2N-1R":{"1G-1s":1,"1G-1r":"#2S"}},"1z-x":{2i:{2h:!0}}},3O:{1A:{3I:0,"1G-1s":1,"1T-3C":{6w:"in","2t-2e":16,1E:"%2r-8e-1T%"}}},8S:{1A:{"1G-1s":1}},7d:{1A:{3I:0,"1w-1s":2,"1U-1r":"%6P-1","6C-1N":!0,1R:{2e:4},"2N-1R":{2e:5,"1G-1r":"#2S"}},"1z-k":{2i:{"1w-1s":1,"1w-1I":"2V","1w-1r":"#e2","1w-fI-2e":6,"1w-h8-2e":6,2o:1,"1U-1r":"#2S #Ik"},3Z:{"1w-1r":"#e2","1w-1s":1,2e:10}},"1z-r":{},"1z-v":{"3T-1w":{"1w-1r":"#e2","1w-1s":1},3Z:{"1w-1r":"#e2","1w-1s":1},2i:{"1w-1r":"#hU","1w-1s":1}}},8D:{1A:{3I:0},1z:{"2e-7c":1},"1z-r":{ij:3V,3Z:{2e:11,"1w-1s":2},"1U-1r":-1,2i:{"1U-1r":"#2S"},9H:{2e:8,"1U-1r":"#hU"},3F:{2e:20,"1U-1r":"#2S","1G-1s":6,"1G-1r":"#Au"}}},aA:{2u:{2y:"50 100"},4z:{"1w-1s":0,3Z:{"1w-1s":0},"4Q-3Z":{"1w-1s":0},2i:{"1w-1s":1,"1w-1I":"2V","1w-1r":"#hU","1w-fI-2e":6,"1w-h8-2e":6,2o:1},"4Q-2i":{"1w-1s":0}},"1z-x":{2h:!1,2i:{2h:0}},"1z-y":{2i:{"1U-1r":"-1",2o:1}},"1z-y-n":{2i:{"1U-1r":"-1"}},1A:{"1G-1s":1,"1G-1r":"#2S",3I:0,"2N-3X":{"1w-1r":"-1","1G-1r":"-1"}}},aB:{2u:{2y:"50 100"},"1z-x":{2h:!1,2i:{2h:0},1H:{"2t-2f":3V}},"1z-x-n":{1H:{"2t-2f":90}},4z:{"1w-1s":0,3Z:{"1w-1s":0},"4Q-3Z":{"1w-1s":0},2i:{"1w-1s":1,"1w-1I":"2V","1w-1r":"#hU","1w-fI-2e":6,"1w-h8-2e":6,2o:1},"4Q-2i":{"1w-1s":0}},"1z-y":{2i:{"1U-1r":"-1",2o:1},1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-y-n":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"},2i:{"1U-1r":"-1"}},1A:{"1G-1s":1,"1G-1r":"#2S",3I:0,"2N-3X":{"1w-1r":"-1","1G-1r":"-1"}}},5z:{1A:{"1U-1r":"%6P-1",1R:{1J:"3z",2e:4},"2N-1R":{2e:5}}},97:{4z:{"1w-1r":"#74",3Z:{2h:!1}},1A:{"1G-1s":0,"1w-1s":1}},83:{4z:{"1w-1r":"#74",3Z:{2h:!1}},1A:{"1G-1s":0,"1w-1s":1}},aX:{4z:{"1w-1r":"#74",3Z:{2h:!1}},1A:{"1G-1s":1}},6O:{4z:{"1w-1r":"#74",3Z:{2h:!1}},1A:{"1G-1s":1}},7k:{4z:{"1w-1r":"#74",3Z:{2h:!1}},1A:{"1G-1s":1}},7e:{1A:{"1G-1s":1}},b7:{1A:{"1G-1s":0,3I:0,2o:.75,"1U-1r":"%6P-1"}},a3:{5i:{"6i-2C":{2h:!0,1s:"Ir",3v:"5 0","1U-1r":"#l4","1G-1s":0,"1G-1r":"#l4",2K:"1K",7K:{2h:ZC.2L,2o:0},b5:{"1U-1r":"#4u",1J:"pN",2o:1},1Q:{"1U-1r":"#l4","1E-3u":"1K",3v:"4 20 4 15","1G-1s":0,"1G-1r":"#l4","2t-2e":"y4",1r:"#2S","2N-3X":{"1U-1r":"#Ip"}},8E:{"1w-1s":1,"1w-1r":"#Ba"}},"6i-2C[2L]":{1Q:{3v:"6 10 6 6"}}}},"-":""},1g.NU.8Y.2Y["9j-x"]=1g.NU.8Y.2Y["9j-y"]=1g.NU.8Y.2Y.2i,1g.NU.b4={},ZC.2E(1g.NU.8Y,1g.NU.b4,!0,!0),ZC.2E({2Y:{"1U-1r":"#77",5E:{1r:"#2S"},86:{1r:"#2S"},7g:{1r:"#2S"},4z:{"1w-1r":"#7M",1Q:{1r:"#7M"},"3T-1w":{"1w-1r":"#7M"},2i:{"1w-1r":"#8Q"},"4Q-2i":{"1w-1r":"#8Q"},3Z:{"1w-1r":"#7M"},"4Q-3Z":{"1w-1r":"#7M"},1H:{1r:"#7M"}},1Z:{2U:{"1U-1r":"#Io"},3q:{"1U-1r":"#cX"}},"1Z-x":{2U:{"1G-1v":"gU 2V 2b","1G-2A":"5o 2V #7M","1G-2a":"5o 2V #7M","1G-1K":"5o 2V #7M"},3q:{"1G-1v":"2b","1G-2A":"2b","1G-2a":"2b","1G-1K":"2b"}},"1Z-y":{2U:{"1G-1v":"5o 2V #7M","1G-2A":"gU 2V 2b","1G-2a":"5o 2V #7M","1G-1K":"5o 2V #7M"}},2z:{"1U-1r":"#77"},2H:{"1G-1r":"#4u"},1Y:{"1U-1r":"#77",5K:{1r:"#2S",tz:{"1U-1r":"#e5","1w-1r":"#tq"}},9U:{1r:"#7M","1U-1r":"#e5","1G-1v":"gU 2V 2b","1G-2A":"5o 2V #cX","1G-2a":"5o 2V #cX","1G-1K":"5o 2V #cX"},tz:{"1U-1r":"#e5","1w-1r":"#tq"},b0:{"1w-1r":"#tq"},"3f-6M":{1r:"#7M"},"3f-on":{"1U-1r":"#tg"},"3f-6Q":{"1U-1r":"#l8"},1R:{"1G-1r":"#4u"},1Q:{1r:"#7M"}},1A:{1R:{"1G-1r":"#77"}},2i:{"1w-1r":"#7M","1z-1H":{"1U-1r":"#l8"},"1A-1H":{"1U-1r":"#77",1r:"#tf","1G-1r":"#Ij"}}},1w:{1A:{"2N-1R":{"1G-1r":"#77"}}},1N:{1A:{"2N-1R":{"1G-1r":"#77"}}},8i:{1A:{7w:{"1G-1r":"#77"}}},7R:{1A:{7w:{"1G-1r":"#77"}}},5m:{1A:{1R:{"1G-1r":"#77"},"2N-1R":{"1G-1r":"#77"}}},6V:{1A:{1R:{"1G-1r":"#77"},"2N-1R":{"1G-1r":"#77"}}},3O:{1A:{"1G-1r":"#77"}},7d:{1A:{"2N-1R":{"1G-1r":"#77"}},"1z-k":{2i:{"1w-1r":"#8Q","1U-1r":"#77 #Hh"},3Z:{"1w-1r":"#7M"}},"1z-v":{"3T-1w":{"1w-1r":"#8Q"},3Z:{"1w-1r":"#8Q"},2i:{"1w-1r":"#8Q"}}},8D:{"1z-r":{2i:{"1U-1r":"#77"},9H:{"1U-1r":"#Hn"}}},aA:{4z:{2i:{"1w-1r":"#8Q"}},1A:{"1G-1r":"#77","2N-3X":{"1w-1r":"#8Q","1G-1r":"#77"}}},aB:{4z:{2i:{"1w-1r":"#8Q"}},"1z-y":{2i:{2o:.25,"1U-1r":"#Aq -1"}},"1z-y-n":{2i:{2o:.25,"1U-1r":"#Aq -1"}},1A:{"1G-1r":"#77","2N-3X":{"1w-1r":"#8Q","1G-1r":"#77"}}},a3:{5i:{"6i-2C":{b5:{"1U-1r":"#tf"}}}},"-":""},1g.NU.b4,!0,!0),1g.NU.b4.2Y["9j-x"]=1g.NU.b4.2Y["9j-y"]=1g.NU.b4.2Y.2i,1g.NU.lX={2Y:{5E:{1s:"100%",3v:"1 2 2","2t-2e":10},86:{1s:"100%",3v:"1 2 2","2y-1v":14,"2t-2e":9},2u:{1s:"100%",1M:"100%",2y:"18 4 4 4"},4z:{2h:0},2H:{3I:0,"1G-9i":7},1Y:{2h:0},2z:{2h:0},2i:{"1w-1s":1,"1w-1r":"#8c",2o:1,"1z-1H":{1E:"%l",3v:"3 6"},"1A-1H":{"1G-1r":"#8c","1G-9i":5,3v:"3 6"}},1A:{3I:0,"1T-3C":{2h:0},"2N-3X":{2h:0},"2N-1R":{2h:0},"1X-oE":qY,"1X-cM":qY}},1w:{1A:{"1w-1s":1,1R:{1J:"2b"}}},97:{"3d-76":{5p:20,2f:45,"x-2f":-20,"y-2f":0,"z-2f":0,3G:.9}},1N:{1A:{"1w-1s":1,1R:{1J:"2b"}}},83:{"3d-76":{5p:20,2f:45,"x-2f":-20,"y-2f":0,"z-2f":0,3G:.9}},6v:{4z:{2c:5},1A:{1R:{2e:3,3I:!1,2o:.8}}},8r:{4z:{2c:5},1A:{1R:{2e:3,3I:!1,2o:.8}}},5m:{4z:{2c:15},1A:{1R:{"3i-1J":"2b",3I:!1,2o:.8},"2j-2e":3,"1X-2e":9}},6V:{4z:{2c:15},1A:{1R:{"3i-1J":"2b",3I:!1,2o:.8},"2j-2e":3,"1X-2e":9}},3O:{2u:{2y:"18 4 4 4"},1A:{"1T-3C":{2h:0}},1z:{"2e-7c":.95}},7e:{2u:{2y:"32 4 4 4"},1A:{"1T-3C":{2h:0}},1z:{"2e-7c":1}},8S:{2u:{2y:"18 4 4 4"},1A:{"1T-3C":{2h:0}},1z:{"2e-7c":.95}},7d:{2u:{2y:"18 4 4 4"},1A:{"1w-1s":1,1R:{3I:0,2e:2}},1z:{"2e-7c":.95}},6O:{"3d-76":{5p:20,2f:45,"x-2f":-20,"y-2f":0,"z-2f":0,3G:.9}},7k:{"3d-76":{5p:20,2f:45,"x-2f":0,"y-2f":-20,"z-2f":0,3G:.9}},b7:{2u:{2y:"18 4 4 4"},1A:{"1G-1s":0}},8D:{2u:{2y:"18 4 4 4"},1A:{yQ:[5]},4z:{2h:1},1z:{"2e-7c":.9},"1z-r":{"1U-1r":"-1",ij:3V,3Z:{2h:0},1Q:{2h:0},2i:{2h:0},9H:{2e:6,"1U-1r":"#hU",2B:[]},3F:{"1G-1s":0,2e:2,"1U-1r":"#2S"}}},aA:{2u:{2y:"18 4 4 4"}},aB:{2u:{2y:"18 4 4 4"}},8i:{1A:{"2U-8I":.5,7w:{"1G-1s":0,1M:4}}},7R:{1A:{"2U-8I":.5,7w:{"1G-1s":0,1s:4}}},5z:{1A:{"1w-1s":1,1R:{2h:0},"2N-3X":{2h:0}}},"-":""},1g.NU.Gq={6P:[["#4u","#Gk","#Ba","#Gi"],["#4u","#Gg","#Gu","#Gv"],["#4u","#Hf","#Hk","#Hi"],["#4u","#Hg","#Hd","#e0"],["#4u","#Hc","#Gz","#Gy"],["#4u","#Gf","#Bw","#Gx"],["#4u","#Bx","#Cd","#Hm"]],2Y:{"1U-1r":"#111",5E:{1r:"#2S"},86:{1r:"#8M"},4z:{"2t-2e":11,"1w-1s":2,"1w-1r":"#8c",2i:{2h:1,"1w-1s":1,"1w-1I":"2V","1w-1r":"#8c",2o:.2},"4Q-2i":{2h:1,"1w-1s":1,"1w-1I":"2V","1w-1r":"#8c",2o:.2},3Z:{2h:1,2e:6,6w:ZC.1b[18],"1w-1s":2,"1w-1r":"#8c"},"4Q-3Z":{2h:1,2e:4,"1w-1s":1,"1w-1r":"#8c"},1H:{1r:"#2S"},1Q:{1r:"#2S"}}},7d:{"1z-k":{2i:{2o:.5,"1U-1r":"#Gl #8M"}}},"-":""},1g.NU.Gm=1g.NU.lX,1g.B8={a3:{5i:{ac:[{id:"xr",46:"4t"},{id:"uN",46:"4t"},{id:"uz",46:"2b"},{id:"uT",46:"2b"},{id:"uU",46:"2b"},{id:"uG",46:"2b"},{id:"3D",46:"2b"},{id:"uj",46:"2b"},{id:"x6",46:"2b"},{id:"ua",46:ZC.cA?"2b":"4t"},{id:"pU",46:ZC.cA?"2b":"4t"}],ew:{1J:1,2K:"rb"},4Z:{2y:"10 3g 3g 10",1s:30,1M:22,3v:4,1Q:{"1U-1r":"#j3","1G-1s":1,"1G-1r":"#Gn"},"1Q-6Q":{"1U-1r":"#8X","1G-1r":"#74"}},7L:{"1U-1r":"#2S",1r:"#4u"},"6i-2C":{3v:0,"1G-1s":1,"1G-1r":"#4u",7K:{2h:ZC.2L,2y:"5 3g 3g 5",2o:.8,"1U-1r":"#8M #4S","1G-9i":8,1s:40,1M:40},b5:{"1U-1r":"#2S #Cd",1J:"uP",2o:.8},1Q:{"1U-1r":"#Ja","1E-3u":"1K",3v:"4 20 4 8","1G-1s":1,"1G-1r":"#4u",1r:"#2S","2N-3X":{"1U-1r":"#Lj"}},8E:{"1w-1s":1,"1w-1r":"#cs"}},"6i-2C[2L]":{1Q:{3v:"6 10 6 6"}}}},6P:[],2Y:{5E:{1s:"100%",6x:1,"2t-2e":13},86:{1s:"100%",6x:1,"2t-2e":11},1Z:{2U:{"1U-1r":"#qW","1G-1r":"#74"},3q:{"1U-1r":"#74","1G-1r":"#8c","1G-1s":2,"1G-1v":"5o 2V #8X","1G-1K":"5o 2V #8X","1G-2A":"5o 2V #4S","1G-2a":"5o 2V #4S"}},"1Z-x":{2U:{1M:16},3q:{1M:16}},"1Z-y":{2U:{1s:16},3q:{1s:16}},"1Z-xi":{2U:{1s:16},3q:{1s:16}},"1Z-yi":{2U:{1M:16},3q:{1M:16}},2z:{1s:"100%",1M:50,2y:"3g 50 20 50","1G-1s":1,3I:0,"1U-1r":"#Bx","1G-1r":"#4S",4O:{2o:.5,"1U-1r":"#8M"},6C:{2o:.1,"1U-1r":"#4S"},3q:{1s:9,1M:16,"1G-1s":1,"1w-1s":1,"1w-1r":"#111","1G-1r":"#Kt","1G-9i":2,"1U-1r":"#Bw"},"3q-1v":{1s:16,1M:9},"3q-2a":{1s:16,1M:9}},2u:{1s:"100%",1M:"100%",2y:"60 50 65 50"},"2u[2z]":{2y:"60 50 105 50"},4z:{"1w-1s":1,2i:{"1w-1s":1,"1w-1r":"#74"},3Z:{2e:6,"1w-1s":2},"4Q-2i":{"1w-1s":1,"1w-1r":"#74"},"4Q-3Z":{2e:4,"1w-1s":1},1H:{6x:1,3v:6,7J:!0},1Q:{3v:2,"3g-3u":!0,7J:!0},1R:{"1w-1s":1,"1w-1r":"#4u","1U-1r":"#8c"},"5H[5s]":{1Q:{"2t-2e":10,3v:2,1r:"#4u","1U-1r":"#2S"}}},"4z[3d]":{"1U-1r":"#8c"},"1z-y[2q]":{1H:{"2t-2f":3V},1Q:{"1E-3u":"2A"}},"1z-y[5w]":{1H:{"2t-2f":90},1Q:{"1E-3u":"1K"}},1A:{4L:{"1w-1s":1,"1w-1r":"#8M",2e:.5},"1T-3C":{7J:!0,1E:"%v",6x:1,6w:"3g",3I:1},"2H-1E":"%v",3I:1,"1w-1s":1,1R:{1J:"9r",3I:1},"6b-3X":{3I:!0,"3I-x3":2,"3I-6T":1,"3I-2o":.91}},2H:{3I:1,3v:"4 8","3I-6T":3,"2c-y":ZC.2L?-40:-20},"2H[4N]":{3v:"4 8","2c-y":0},2i:{1R:{1J:"3z"},"1A-1H[bO]":{1E:\'<b 1I="1r:%1r">%1A-1E:</b> %2r-1T\',3v:10,"1U-1r":"#2S #8X","1G-1s":1,"1G-1r":"#4S",1r:"#4u","1E-3u":"1K"},"1A-1H[ay]":{1E:\'<b 1I="1r:%1r">%1A-1E:</b> %2r-1T\',3v:5,"1U-1r":"#2S #8X","1G-1s":1,"1G-1r":"#4S",1r:"#4u","1E-3u":"1K"}},3G:{"dD-3G":1,"1G-1s":0,"1U-1r":"#j3",2o:.25,1H:{2h:!1,"1U-1r":"#2S","2t-2e":10,3v:2,"1G-1s":1,"1G-1r":"#4S"}},7I:{"1G-1s":1,"1G-1r":"#4u","1U-1r":"#cc",2e:4},"1Y[2K]":{2y:10},1Y:{"1U-1r":"#8X",2o:1,3I:1,2y:"10 10 3g 3g",3v:"4 2 4 2",1Q:{"1E-3u":"1K",2y:"2 6 2 4",3v:"2 4"},"1Q-6Q":{2o:.25},1R:{3I:0,2e:6,"1G-1r":"#4S","1G-1s":1},5K:{"2t-2e":12,"1E-3u":"1K",6x:1},9U:{"1E-3u":"1K"},b0:{"1w-1r":"#4u","1w-1s":1},"3f-6M":{1r:"#4u"},"3f-on":{"1U-1r":"#vr"},"3f-6Q":{"1U-1r":"#4S"},1Z:{2U:{1s:12,1M:12,"1U-1r":"#qW","1G-1r":"#74"},3q:{1s:12,1M:12,"1U-1r":"#74","1G-1r":"#8c","1G-1s":2,"1G-1v":"5o 2V #8X","1G-1K":"5o 2V #8X","1G-2A":"5o 2V #4S","1G-2a":"5o 2V #4S"}}}},5t:{1A:{"1T-3C":{6w:"1v-4R"}}},6O:{1A:{"1T-3C":{6w:"1v-4R"}},"3d-76":{5p:40,2f:45,"x-2f":-20,"y-2f":0,"z-2f":0}},aX:{"3d-76":{5p:40,2f:45,"x-2f":-20,"y-2f":0,"z-2f":0}},6c:{"1z-y":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-y-n":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-x[2q]":{1H:{"2t-2f":3V}},"1z-x[5w]":{1H:{"2t-2f":90}},1A:{"1T-3C":{6w:"1v-4R"}}},bj:{"1z-y":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-y-n":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-x[2q]":{1H:{"2t-2f":3V}},"1z-x[5w]":{1H:{"2t-2f":90}}},bv:{1A:{"3i-2f":0},"1z-y":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-y-n":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-x[2q]":{1H:{"2t-2f":3V}},"1z-x[5w]":{1H:{"2t-2f":90}}},7k:{"1z-y":{1H:{"2t-2f":0}},"1z-x":{1H:{"2t-2f":3V}},"1z-y-n":{1H:{"2t-2f":0}},"1z-x-n":{1H:{"2t-2f":90}},"3d-76":{5p:40,2f:45,"x-2f":0,"y-2f":-20,"z-2f":0},1A:{"1T-3C":{6w:"1v-4R"}}},7R:{"1z-y":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-x":{1H:{"2t-2f":3V}},"1z-y-n":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-x-n":{1H:{"2t-2f":90}}},1w:{1A:{"1w-1s":4,1R:{1J:"3z",2e:4}}},1N:{1A:{"1w-1s":4,1R:{1J:"3z",2e:4},"1T-3C":{6w:"1v"}}},97:{"3d-76":{5p:40,2f:45,"x-2f":-20,"y-2f":0,"z-2f":0},1A:{"1G-1s":1,"1w-1s":1,1R:{1J:"3z",2e:4,2o:1,2h:0}}},83:{"3d-76":{5p:40,2f:45,"x-2f":-20,"y-2f":0,"z-2f":0},1A:{"1G-1s":1,"1w-1s":1,1R:{1J:"3z",2e:4,2o:1,2h:0},"1T-3C":{6w:"1v"}}},6v:{4z:{2c:10},1A:{1R:{1J:"3z",2e:4},"1T-3C":{6w:"1v"}}},4C:{4z:{2c:10},1A:{"2o-1N":.4,1R:{1J:"2b"},"1T-3C":{6w:"1v"}}},8r:{4z:{2c:10},"1z-y":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-x":{1H:{"2t-2f":3V}},"1z-y-n":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-x-n":{1H:{"2t-2f":90}},1A:{1R:{1J:"3z",2e:4},"1T-3C":{6w:"1v"}}},5m:{4z:{2c:40},1A:{1R:{1J:"3z","3i-1J":"8K","3i-2c-x":-.2,"3i-2c-y":-.2},"2N-1R":{"3i-1J":"8K","3i-2c-x":-.2,"3i-2c-y":-.2},"1T-3C":{6w:"6n",1E:"%2r-2e-1T"},"2H-1E":"%2r-2e-1T"}},6V:{4z:{2c:40},"1z-y":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-x":{1H:{"2t-2f":3V}},"1z-y-n":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-x-n":{1H:{"2t-2f":90}},1A:{1R:{1J:"3z","3i-1J":"8K","3i-2c-x":-.2,"3i-2c-y":-.2},"2N-1R":{"3i-1J":"8K","3i-2c-x":-.2,"3i-2c-y":-.2},"1T-3C":{6w:"6n",1E:"%2r-2e-1T"},"2H-1E":"%2r-2e-1T"}},gO:{"1z-y":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-x":{1H:{"2t-2f":3V}},"1z-y-n":{1H:{"2t-2f":0},1Q:{"1E-3u":"3F"}},"1z-x-n":{1H:{"2t-2f":90}}},3O:{2u:{2y:"35 5 5 5"},1z:{"2e-7c":"3g","1w-1s":0,2i:{"1w-1s":0},"4Q-2i":{"1w-1s":0}},1A:{"3i-1J":"8K","1T-3C":{8O:{"1w-1s":1},6w:"4R",1E:"%t",2h:1}}},7e:{"3d-76":{"x-2f":38,"y-2f":0,"z-2f":0},2u:{2y:"25 5 5 5"},1z:{"2e-7c":"3g","1w-1s":0,2i:{"1w-1s":0},"4Q-2i":{"1w-1s":0}},1A:{"3i-1J":"9k","1T-3C":{8O:{"1w-1s":1},6w:"4R",1E:"%t",2h:1}}},8S:{2u:{2y:"40 5 15 5"},1z:{"2e-7c":.8,"1w-1s":0,2i:{"1w-1s":0},"4Q-2i":{"1w-1s":0}},1A:{"3i-1J":"8K","1T-3C":{8O:{"1w-1s":1},1E:"%t",2h:1}}},b7:{2u:{2y:"30 10 10 10"},1A:{2o:.5,"1G-1s":4},1z:{"2e-7c":.65,"1w-1s":0,2i:{"1w-1s":0},"4Q-2i":{"1w-1s":0}}},7d:{4z:{2i:{"1w-1s":1,"1w-1r":"#4S","1U-1r":"-1"},3Z:{"1w-1s":1},1Q:{"3g-3u":!1}},1z:{2h:0,"2e-7c":.7},"1z-k":{"3T-2f":3V},2u:{2y:"40 5 5 5"},1A:{"1w-1s":4,76:"1w",1R:{1J:"3z"}}},8D:{4z:{2i:{"1G-1s":1,"1G-1r":"#4S","1U-1r":"-1"}},1z:{"1w-1s":0,2i:{"1w-1s":0},"4Q-2i":{"1w-1s":0},"2e-7c":.7},"1z-r":{"3T-2f":3V,"1U-1r":"#2S",2i:{"1w-1s":0},3Z:{6w:"5N"},1Q:{"2c-r":"-45%"}},1A:{2e:"85%"},2u:{2y:"40 5 5 5"}},84:{1A:{"1w-1s":1,"1G-1s":1,"2H-1E":"Kz:&8u;$%bD<br>Ky:&8u;$%qp<br>Kx:&8u;$%qq<br>hl:&8u;$%7m"}},5z:{1A:{"1w-1s":2,"1T-3C":{1E:"%2r-2j-1T - %2r-1X-1T"},"2H-1E":"%2r-2j-1T - %2r-1X-1T"}},"-":""},1g.PT=1n(e,t){1a i,a=1g,n=!1;1l 1c!==ZC.1d(i=a.B8.2Y[e])&&1c!==ZC.1d(i.46)&&(n=n||ZC.2s(i.46)),1c!==ZC.1d(a.B8[t])&&1c!==ZC.1d(i=a.B8[t][e])&&1c!==ZC.1d(i.46)&&(n=n||ZC.2s(i.46)),n},1g.2x=1n(e,t,i,a){1a n,l,r,o=1g;i=1c===ZC.1d(i)||ZC.2s(i),a=1c!==ZC.1d(a)&&ZC.2s(a),t 3E 3M||(t=1m 3M(t));1a s=[],A="";1j(l=0,r=t.1f;l<r;l++)if(/(\\(\\w+\\))(.*)/.5U(t[l])){1a C=5y.$1;A=t[l].1F(C,"2Y"),-1===ZC.AU(s,A)&&s.1h(A),A=t[l].1F(C,C.2v(1,C.1f-1)),-1===ZC.AU(s,A)&&s.1h(A)}1u-1===ZC.AU(s,t[l])&&s.1h(t[l]),/a3(.*)/.5U(t[l])&&-1===ZC.AU(s,t[l].1F("a3","6A"))&&s.1h(t[l].1F("a3","6A")),/6A(.*)/.5U(t[l])&&-1===ZC.AU(s,t[l].1F("6A","a3"))&&s.1h(t[l].1F("6A","a3"));1a Z={};1j(l=0,r=s.1f;l<r;l++){1j(1a c=s[l].2n("."),p=o.B8,u=0,h=c.1f;u<h;u++)if(1c!==ZC.1d(n=p[c[u]]))p=n;1u if(1c!==ZC.1d(n=p[ZC.V5(c[u])]))p=n;1u{if(1c===ZC.1d(n=p[ZC.EA(c[u])])){p=1c;1p}p=n}if(p)1j(1a 1b in p)1c!==ZC.1d(p[1b])&&(a||"4h"!=1y p[1b]||p[1b].1f)&&(i||1c===ZC.1d(e[1b])?o.H.QN&&1c!==ZC.1d(o.H.QN[1b])||(Z[1b]=p[1b]):i&&"4h"==1y p[1b]&&(o.H.QN&&1c!==ZC.1d(o.H.QN[1b])||(Z[1b]=p[1b])))}ZC.2E(Z,e)}},ZC.AO={Kw:1n(e,t){1j(1a i=[],a=0,n=e.p.1f;a<n;a++)if(e.p[a]){1a l=(e.p[a][0]-e.x)/e.w,r=(e.p[a][1]-e.y)/e.h;i.1h([t.x+t.w*l,t.y+t.h*r])}1u i.1h(1c);1l{l:t.w*e.l/e.w,r:t.w*e.r/e.w,p:i}},Bj:1n(e,t,i){1a a=2g.dK("fb")[0],n=2g.4P("Kv");n.1J="1E/7u",n.5a=t+"?v"+ZC.fF;1a l=!1;n.hL=n.fD=1n(){if(!(l||1g.fE&&"Lk"!==1g.fE&&"ai"!==1g.fE)){l=!0,n.hL=n.fD=1c,a&&n.6o&&a.b2(n);1a e=1m 5y("1o-(.+?).2j.js","g").3n(t);e&&ZC.WU.1h(e[1]),i&&i(t)}},n.j0=1n(){!e&&1o.HY[0]&&(e=1o.HY[0]),e?e.NC({8C:ZC.1b[63],b8:"bB cR fG ("+n.5a+")"},"La 6A"):w7("bB cR fG ("+n.5a+")")},a.sT(n,a.Ll)},Bu:1n(){1l"#"+ZC.Y3.du(ZC.hm(0,qY)).5A(ZC.hm(0,20),6)},XA:1n(){},oM:1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||"";if("3e"!=1y o&&o.1f){""+ZC.1W(o[0])!==o[0]&&(o=[5x].4B(o));1j(1a s=1,A=o[0]||5x,C=o.7z(1),Z=1c,c=0;c<C.1f;c++)0===C[c].1L("#")&&(Z=c,C[c]=C[c].2v(1));if(C.1f){if(1c!==Z)s=Z;1u if(1c!==ZC.1d(t["1X-cW"]))s=t["1X-cW"];1u{1a p=ZC.JN(ZC.2l(4T(l)),A);s=1B.4b(p),s=ZC.CQ(s,C.1f-1)}n=C[s];1a u=(l=""+4T(l)/1B.6s(A,s)).2n(".");2===u.1f&&u[1].1f>=9&&(l=1c!==ZC.1d(t[ZC.1b[12]])&&-1!==t[ZC.1b[12]]?""+ZC.4o(l,t[ZC.1b[12]]):""+ZC.4o(l))}}1u{1a h=ZC.JN(ZC.2l(4T(l)))/1B.a6;1P(ZC.2l(4T(l))){1i 5x:h=3;1p;1i gy:h=6;1p;1i r8:h=9}if(1c!==ZC.1d(t["1X-cW"])&&(h=3*t["1X-cW"]),"KB"===o.5M())l=""+4T(l)/gL,n="KB";1u if("MB"===o.5M())l=""+4T(l)/Lz,n="MB";1u if("GB"===o.5M())l=""+4T(l)/Ly,n="GB";1u if("TB"===o.5M())l=""+4T(l)/Lw,n="TB";1u if("PB"===o.5M())l=""+4T(l)/Ln,n="PB";1u if(h>=0&&h<3)1P(o){2q:l=l,n="";1p;1i"K":l=""+4T(l)/5x,n="K";1p;1i"M":l=""+4T(l)/gy,n="M";1p;1i"B":l=""+4T(l)/r8,n="B"}1u h>=3&&h<6&&""===o||"K"===o.5M()?(l=""+4T(l)/5x,n="K"):h>=6&&h<9&&""===o||"M"===o.5M()?(l=""+4T(l)/gy,n="M"):(h>=9&&""===o||"B"===o.5M())&&(l=""+4T(l)/r8,n="B")}if(ZC.PJ(l))if(1c!==ZC.1d(t[ZC.1b[12]])&&-1!==t[ZC.1b[12]])l=ZC.9y(4T(l),ZC.BM(0,ZC.1k(t[ZC.1b[12]])));1u{1a 1b=l.2n(".")[1]||"";-1!==t["1X-6K"]&&t["1X-6K"]<1b.1f&&(l=ZC.9y(4T(l),ZC.BM(0,ZC.1k(t["1X-6K"]))))}1c!==ZC.1d(t[ZC.1b[14]])&&(l=l.1F(/\\./g,t[ZC.1b[14]]))}if(!7X(l)){if(1c!==ZC.1d(t[ZC.1b[12]])&&-1!==t[ZC.1b[12]]&&ZC.PJ(l)&&(1c!==ZC.1d(t.5G)&&t.5G||(l=ZC.9y(4T(l),ZC.BM(0,ZC.1k(t[ZC.1b[12]]))))),1c!==ZC.1d(t[ZC.1b[13]])||1c!==ZC.1d(t[ZC.1b[14]])){1j(1a d=l.2n("."),f="",g=0,B=d[0].1f;g<B;g++){1a v=d[0].2v(g,g+1);f+=v,-1===ZC.AU(["-","+"],v)&&(d[0].1f-g-1)%3==0&&d[0].1f-g-1!=0&&(f+=t[ZC.1b[13]])}l=f+(1c!==ZC.1d(d[1])?t[ZC.1b[14]]+d[1]:"")}1c!==ZC.1d(t.5G)&&t.5G&&(l+=n)}}1l l},oN:1n(e){1a t=e.1L("("),i="",a="";-1!==t?(i=ZC.GP(e.2v(0,t)),a=ZC.GP(e.2v(t+1,e.1f-1))):i=ZC.GP(e);1a n=[],l="";if(""!==a){1a r=!1,o=!1,s=!1;l="";1j(1a A=0,C=a.1f;A<C;A++){1a Z=a.2v(A,A+1);1P(Z){1i"\\\\":s?(l+="\\\\",s=!1):s=!0;1p;1i\'"\':s?(l+=\'"\',s=!1):o?(n.1h(l),l="",o=!1):r?l+=Z:o=!0;1p;1i"\'":s?(l+="\'",s=!1):r?(n.1h(l),l="",r=!1):o?l+=Z:r=!0;1p;1i" ":(r||o)&&(l+=Z);1p;1i",":r||o?l+=Z:(""!==l&&n.1h(l),l="");1p;2q:l+=Z}}}1l""!==l&&n.1h(l),[i,n]},ep:1n(e){1l e.a5().1F(/^([0-9])$/,"0$1")},YT:1n(e,t,i,a){t=t||ZC.HE["5s-rO"].hT,1y i===ZC.1b[31]&&(i=!1),1y a===ZC.1b[31]&&(a=0),i&&(e+=lA*a);1a n,l,r,o,s,A,C,Z,c=1m a1;c.Lq(e),i?(n=c.Lp(),l=c.Lm(),r=c.Kr(),o=c.Jw(),s=c.Jt(),A=c.Js(),C=c.Jr(),Z=c.Jq()):(n=c.Jo(),l=c.Jn(),r=c.Jm(),o=c.Jk(),s=c.Jb(),A=c.Ji(),C=c.Jh(),Z=c.vS());1j(1a p=[["mm",ZC.AO.ep(C+1)],["dd",ZC.AO.ep(A)],["Y",Z],["y",Z.a5().5A(2,2)],["F",ZC.HE["k9-fR"][C]],["m",C+1],["M",ZC.HE["k9-5G"][C]],["n",C],["d",A],["D",ZC.HE["jV-5G"][s]],["j",A],["l",ZC.HE["jV-fR"][s]],["N",s+1],["w",s],["S",1n(){1l A%10==1?"st":A%10==2?"nd":A%10==3?"rd":"th"}],["a",n<12?"am":"pm"],["A",n<12?"AM":"PM"],["g",n%12||12],["G",n],["h",ZC.AO.ep(n%12||12)],["H",ZC.AO.ep(n)],["i",ZC.AO.ep(l)],["s",ZC.AO.ep(r)],["q",o]],u=0;u<p.1f;u++)t=t.1F("%"+p[u][0],p[u][1]);1l t},jF:{},ZL:1n(e,t){1a i=1c;if(t&&t.BS?i=t.BS:t&&t.A&&t.A.BS&&(i=t.A.BS),"3e"==1y e&&-1!==e.1L("%1r-")&&ZC.aq.1f>0)1j(1a a=0;a<ZC.aq.1f;a++)-1===e.1L("(+")&&-1===e.1L("(-")||(e=e.1F(/%1r-(\\d+?)\\((\\+|\\-)(\\d+?)\\)/gi,1n(){1a e=ZC.AO.G7(ZC.aq[ZC.1k(8P[1])]);1l"+"===8P[2]?e=ZC.AO.R2(e,ZC.1k(8P[3])):"-"===8P[2]&&(e=ZC.AO.JK(e,ZC.1k(8P[3]))),e})),e=e.1F("%1r-"+a,ZC.aq[a]);1u"3e"==1y e&&i&&-1!==e.1L("%6P-")&&(e=i[ZC.1k(e.1F("%6P-",""))]);1l e},G7:1n(e,t){1a i,a,n,l;if(1c!==ZC.1d(ZC.AO.jF[e]))1l ZC.AO.jF[e];1a r=ZC.GP(6d(e)),o=1,s=!1;1l 0===r.1f?"":("9J("===(r=r.1F("zL","#")).2v(0,5)?(i=1m 5y("9J\\\\((\\\\d{1,3}),\\\\s*(\\\\d{1,3}),\\\\s*(\\\\d{1,3}),\\\\s*([0-9.]+)\\\\)","gi").3n(r))&&(1===(a=ZC.P2(i[1])).1f&&(a="0"+a),1===(n=ZC.P2(i[2])).1f&&(n="0"+n),1===(l=ZC.P2(i[3])).1f&&(l="0"+l),r="#"+a+n+l,o=ZC.BM(0,ZC.CQ(1,5P(i[4]))),s=!0):"9N("===r.2v(0,4)?(i=1m 5y("9N\\\\((\\\\d{1,3}),\\\\s*(\\\\d{1,3}),\\\\s*(\\\\d{1,3})\\\\)","gi").3n(r))&&(1===(a=ZC.P2(i[1])).1f&&(a="0"+a),1===(n=ZC.P2(i[2])).1f&&(n="0"+n),1===(l=ZC.P2(i[3])).1f&&(l="0"+l),r="#"+a+n+l):"#"===r.2v(0,1)?4===r.1f?r="#"+r.2v(1,2)+r.2v(1,2)+r.2v(2,3)+r.2v(2,3)+r.2v(3,4)+r.2v(3,4):7!==r.1f&&(r=""):1c!==ZC.1d(ZC.P.sN[r.5M()])&&(r="#"+ZC.P.sN[r.5M()]),"2b"!==r&&"aG"!==r||(r="-1"),t||(ZC.AO.jF[e]=r),t&&s?[r,o]:r)},jH:{},eq:1n(e,t){if(-1===e&&(e="#j4",t=0),1c!==ZC.1d(ZC.AO.jH[e+","+t]))1l ZC.AO.jH[e+","+t];4===e.1f&&(e=e.2v(0,1)+e.2v(1,2)+e.2v(1,2)+e.2v(2,3)+e.2v(2,3)+e.2v(3,4)+e.2v(3,4));1a i="9J("+[ZC.R1(e.2v(1,3)),ZC.R1(e.2v(3,5)),ZC.R1(e.2v(5,7)),t].2M(",")+")";1l ZC.AO.jH[e+","+t]=i,i},zK:1n(e,t,i){e/=3U,t/=3U,i/=3U;1a a,n,l,r=1B.1X(e,t,i),o=1B.2j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fd),ZC.bU=t}1u t=ZC.bU;if(t)1P(e){1i"7A":1i"6F":e="4H";1p;1i"7V":e="6f";1p;1i"7T":1i"6k":e="5R";1p;1i"3H":e="4H"}1l e},ny:1n(e,t){1a i,a,n,l=[],r=t.JR,o=t.OI,s=t.PB,A=r-s/2;if(e.1f>0){1a C=0,Z=0;1j(0!==r&&(C=ZC.1k(A*ZC.EC(o)+s),Z=ZC.1k(A*ZC.EH(o)+s)),i=0,a=e.1f;i<a;i++)if(1c!==ZC.1d(e[i])){1a c=[];1j(n=0;n<e[i].1f;n++)c[n]=e[i][n];1a p=c.1f;if(2===p||4===p)1j(n=0;n<p;n++)c[n]=e[i][n]+(n%2?Z+t.BB:C+t.BJ);l.1h(c)}1u l.1h(1c)}1l l},mM:1n(e,t,i,a,n){1y n===ZC.1b[31]&&(n=!1);1a l,r,o=[e[0],e[1]];1P(e.1f>=4&&(o[2]=e[2],o[3]=e[3]),e.1f>=6&&(o[4]=e[4],o[5]=e[5]),7===e.1f&&(o[6]=e[6]),t){1i"3a":1i"2F":1a s,A;if(i.CV)s=A=i.AX%2==1?.5:0,ZC.A3.6J.af&&ZC.96&&"2F"===t&&(s=i.AX%2==1?.5:0,A=i.AX%2==1?0:.5),o[0]=1B.43(o[0])-s,o[1]=1B.43(o[1])-A,4===o.1f&&(o[2]=1B.43(o[2])-s,o[3]=1B.43(o[3])-A);"2F"===t&&(o[0]=5P(o[0].4A(4)),o[1]=5P(o[1].4A(4)),4===o.1f&&(o[2]=5P(o[2].4A(4)),o[3]=5P(o[3].4A(4)))),"3a"!==t||a||1y i.BJ!==ZC.1b[31]&&1y i.BB!==ZC.1b[31]&&(o[0]+=i.BJ,o[1]+=i.BB,4===o.1f&&(o[2]+=i.BJ,o[3]+=i.BB));1p;1i"3K":i.AA%2m==0?(l=10,r=i.AX%2==1?0:l/2):(l=1,r=0),i.CV?(o[0]=l*ZC.1k(ZC.1k(l*o[0])/l)-r,o[1]=l*ZC.1k(ZC.1k(l*o[1])/l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[0]+" "+o[1]);1u if(u&&(p.1h(("2F"===t?"M ":"m ")+o[0]+" "+o[1]),u=!1),2===o.1f)p.1h(("2F"===t?"L ":"l ")+o[0]+" "+o[1]);1u if(4===o.1f)p.1h(("2F"===t?"Q ":"qb ")+o[0]+" "+o[1]+" "+o[2]+" "+o[3]),"3K"===t&&p.1h("l "+o[2]+" "+o[3]);1u if(6===o.1f)if("2F"===t){1a 1b=0;o[3]%2m==o[4]%2m&&(1b=o[4]>=o[3]?.Cl:-.Cl),s=ZC.AQ.BN(o[0],o[1],o[2],o[3]+1b),A=ZC.AQ.BN(o[0],o[1],o[2],o[4]-1b),C="0 0",0===o[5]?o[4]-o[3]>2m?(C="0 1",A[0]=s[0],A[1]=s[1]):C=o[4]-o[3]<=180?"0 1":"1 1":o[3]-o[4]>2m?(C="0 0",A[0]=s[0],A[1]=s[1]):C=o[3]-o[4]<=180?"0 0":"1 0",p.1h("a "+o[2]+","+o[2]+" 0 "+C+" "+(A[0]-s[0])+","+(A[1]-s[1]))}1u"3K"===t&&(o[2]*=10,s=ZC.AQ.BN(o[0],o[1],o[2],o[3]),A=ZC.AQ.BN(o[0],o[1],o[2],o[4]),C=1===o[5]?"at":"wa",p.1h(C+" "+ZC.1k(o[0]-o[2])+","+ZC.1k(o[1]-o[2])+","+ZC.1k(o[0]+o[2])+","+ZC.1k(o[1]+o[2])+" "+ZC.1k(s[0])+","+ZC.1k(s[1])+" "+ZC.1k(A[0])+","+ZC.1k(A[1])));1u 7===o.1f&&p.1h(("2F"===t?"C ":"c ")+o[0]+" "+o[1]+" "+o[2]+" "+o[3]+" "+o[4]+" "+o[5])}1u u=!0;1l i.E["8F-dC-2R"]||i.O9&&ZC.4f.2P("2R-2W-"+Z,p.2M("#")),i.H&&r<=20&&a&&(i.H.E[i.J+"-cK"]=c),p},MH:1n(e,t){1a i,a,n=e.117||e.Af;1l t=ZC.1k(t||"0"),n&&n.7x?n.7x.1f>0?(i=n.7x[t].bk,a=n.7x[t].c2):n.qC.1f>0&&(i=n.qC[t].bk,a=n.qC[t].c2):(i=e.bk,a=e.c2),[ZC.1k(i||"0"),ZC.1k(a||"0")]},F2:1n(e,t,i){1a a;1l i=i||2g,1c!==ZC.1d(t)?i.zQ?a=i.zQ(t,e):(a=i.4P(e)).4m("e4",t):a=i.4P(e),"7o:"===e.2v(0,4)&&(a.7U="tW"),a},ER:1n(e){1a t;e 3E 3M||(e=[e]);1j(1a i=0,a=e.1f;i<a;i++)"4h"!=1y(t=e[i])&&(t=ZC.AK(e[i])),t&&(1y t.gl!==ZC.1b[31]?t.gl.b2(t):1y t.6o!==ZC.1b[31]&&t.6o.b2(t))},G3:1n(e,t){1j(1a i in t)if("3e"==1y i&&"4h"!=1y t[i]&&"1n"!=1y t[i])4J{e.4m(i,t[i])}4M(a){}},PO:1n(e,t){1j(1a i in t)"3e"==1y i&&"4h"!=1y t[i]&&"1n"!=1y t[i]&&(e.1I[i]=t[i])},sp:1n(e){1a t;if(e===2g)1l!0;if(!e)1l!1;if(!e.6o)1l!1;if(e.1I){if("2b"===e.1I.3L)1l!1;if("8R"===e.1I.ds)1l!1}if(2w.g6){if("2b"===(t=2w.g6(e,"")).3L)1l!1;if("8R"===t.ds)1l!1}if(t=e.lU){if("2b"===t.3L)1l!1;if("8R"===t.ds)1l!1}1l ZC.P.sp(e.6o)},TF:1n(e){1a t=e.7U||ZC.A3(e).3Q("1O");1l 1c!==ZC.1d(t)&&"4h"==1y t&&(t=1y t.dg!==ZC.1b[31]?t.dg:""),t||""},II:1n(e,t,i,a,n,l,r,o){if(e)1P(r=r||"",t){1i"3a":o?e.9d("2d").n6(i,a,n,l):e.1s=e.1s;1p;1i"3K":1i"2F":1a s=e.6Y.1f;if(s>gL&&1y e.4q!==ZC.1b[31])1l 8j(e.4q="");if(s>0)1j(1a A=s-1;A>=0;A--)""===r?e.b2(e.6Y[A]):0===e.6Y[A].id.1L(r+"-")&&e.b2(e.6Y[A])}},E4:1n(e,t){1P("3e"==1y e&&(e=ZC.AK(e)),t){1i"3a":1l e.9d("2d");1i"2F":1i"3K":1l e}},K1:1n(e,t){1P(t){1i"2F":1l ZC.P.qF(e);1i"3K":1i"3a":1l ZC.P.HZ(e)}},HF:1n(e,t){1P(t){1i"2F":1l ZC.P.qF(e);1i"3K":1l ZC.P.HZ(e);1i"3a":1l ZC.P.zR(e)}},qF:1n(e){1a t;if(ZC.AK(e.id))1l ZC.AK(e.id);1a i=ZC.P.F2("g",ZC.1b[36]);1l 1c!==ZC.1d(t=e.id)&&i.4m("id",t),1c!==ZC.1d(t=e.2p)&&i.4m("1O",t),1c!==ZC.1d(t=e.8l)&&i.4m("z-3b",t),1c!==ZC.1d(t=e["3t-2R"])&&i.4m("3t-2R",t),e.p.2Z(i),i},XW:1n(e){1a t;ZC.P.ER(e.id);1a i=ZC.P.F2("xa",ZC.1b[36]);1l i.id=e.id,1c!==ZC.1d(e.cx)?((t=ZC.P.F2("3z",ZC.1b[36])).id=e.id+"-2T",ZC.P.G3(t,{cx:e.cx,cy:e.cy,r:e.r})):((t=ZC.P.F2("12t",ZC.1b[36])).id=e.id+"-2T",ZC.P.G3(t,{2W:e.2R})),i.2Z(t),i},zR:1n(e){1a t;if(ZC.AK(e.id))1l ZC.AK(e.id);1a i=2g.4P("3a"),a=i.1I;if(1c!==ZC.1d(t=e.id)&&(i.id=t),1c!==ZC.1d(t=e.2p)&&(i.7U=t),1c!==ZC.1d(t=e.wh)){1a n=(""+t).2n("/");e[ZC.1b[19]]=n[0],e[ZC.1b[20]]=n[1]}if(1c!==ZC.1d(t=e.tl)){1a l=(""+t).2n("/");e.1v=l[0],e.1K=l[1]}1l i.1s=e[ZC.1b[19]],i.1M=e[ZC.1b[20]],1c!==ZC.1d(t=e.1K)&&(a.1K=t+"px"),1c!==ZC.1d(t=e.1v)&&(a.1v=t+"px"),1c!==ZC.1d(t=e.3L)&&(a.3L=t),1c!==ZC.1d(t=e.2K)&&(a.2K=t),1c!==ZC.1d(t=e.8l)&&(a.a2=t),e.p.2Z(i),i},HZ:1n(e){1a t,i,a,n,l,r;if(ZC.AK(e.id))1l a=ZC.AK(e.id),1c!==ZC.1d(t=e.wh)&&(l=(""+t).2n("/"),a.1I.1s=l[0]+"px",a.1I.1M=l[1]+"px"),1c!==ZC.1d(t=e.tl)&&(r=(""+t).2n("/"),a.1I.1v=r[0]+"px",a.1I.1K=r[1]+"px"),a;(n=(a=2g.4P("3B")).1I).u8="mC",1c!==ZC.1d(t=e.wh)&&(l=(""+t).2n("/"),e[ZC.1b[19]]=l[0],e[ZC.1b[20]]=l[1]),1c!==ZC.1d(t=e.tl)&&(r=(""+t).2n("/"),e.1v=r[0],e.1K=r[1]),1c!==ZC.1d(t=e.id)&&(a.id=t),1c!==ZC.1d(t=e.2p)&&""!==t&&(a.7U=t);1j(1a o=[["1v","","px"],["1K","","px"],[ZC.1b[19],"","px"],[ZC.1b[20],"","px"],"2K","9L",["9c","qR|sc"],["8l","a2"],"3t","3L",["6S","","px"],"6W","6U","cO","dv","cT","sx","1r","1G","xc","lm","oa","lB","1U","4V",["2y","mT|ss|su|mG","px"],["mT","","px"],["ss","","px"],["su","","px"],["mG","","px"],["3v","ca|di|d6|d8","px"],["ca","","px"],["di","","px"],["d6","","px"],["d8","","px"],"bt","jU"],s=1c,A=1c,C=1c,Z=0,c=o.1f;Z<c;Z++)if("3e"==1y o[Z]&&(o[Z]=[o[Z]]),t=1c,1c!==ZC.1d(i=e[o[Z][0]])&&(t=i),1c!==ZC.1d(t)){1c!==ZC.1d(o[Z][1])&&""!==o[Z][1]||(o[Z][1]=o[Z][0]);1j(1a p=o[Z][1].2n("|"),u=0,h=p.1f;u<h;u++){1a 1b=t+(1c===ZC.1d(o[Z][2])?"":o[Z][2]);n[p[u]]=1b,"6W"===p[u]&&(s=1b),"6S"===p[u]&&(A=ZC.1k(1b)),"6U"===p[u]&&(C=1b)}}1l 1c!==ZC.1d(t=e.3o)&&(n.3o=t,1!==ZC.1W(t)&&(n.jU="2o(3o = "+ZC.1k(100*ZC.1W(t))+")",n.3o=t)),1c!==ZC.1d(t=e.p)&&t.2Z(a),1c!==ZC.1d(t=e.4g)&&(a.4q=ZC.j2(t),-1!==t.1L("<")&&-1!==t.1L(">")&&ZC.A3(a).9z().5d(1n(){1c!==ZC.1d(s)&&(1c!==ZC.1d(1g.1I.6W)&&""!==1g.1I.6W||(1g.1I.6W=s)),1c!==ZC.1d(A)&&(1c!==ZC.1d(1g.1I.6S)&&""!==1g.1I.6S||(1g.1I.6S=A+"px")),1c!==ZC.1d(C)&&(1c!==ZC.1d(1g.1I.6U)&&""!==1g.1I.6U||(1g.1I.6U=C))})),e.aH&&(a.1I.12s="dw-78",a.1I.c1="aH"),e.4V&&"iC"===e.4V&&(a.1I.4V="8q"),a},WB:1c,lz:1n(e,t,i,a,n,l,r){1a o,s,A,C;1c===ZC.1d(r)&&(r=!1);1a Z=!1;"[sf]"===t.2v(0,10)&&(Z=!0,t=t.2v(10)),C=e+"-1E-kJ",-1!==e.1L("-5X")&&(C="zc-1E-kJ");1a c="{{"+t+"}}"+i.1F(/[^a-z]/gi,"").aN()+a+l+n;if(ZC.4f.1V["1E-1s-"+c]&&!r)1l ZC.4f.1V["1E-1s-"+c];if(ZC.4f.1V["1E-1M-"+c]&&r)1l ZC.4f.1V["1E-1M-"+c];1a p,u=t;1l u=u.1F(/<hr>/g,\'<hr 1I="2y:0;3v:0">\'),(p=ZC.AK(C))?(ZC.P.WB&&ZC.P.WB===e+i+a+l+n||(p.1I.6W=i,p.1I.6S=a+"px",p.1I.6U=n,p.1I.bt=Z?"130%":-1!==l?ZC.1k(l)+"px":"130%",ZC.P.WB=e+i+a+l+n),p.4q=u):(p=ZC.P.HZ({id:C,p:2g.3s,tl:"-6H/-6H",4g:u,2K:"4D",6W:i,6S:a,2p:"zc-1E-kJ",6U:n})).1I.bt=Z?"130%":-1!==l?ZC.1k(l)+"px":"130%",-1===t.1L("<")||-1===t.1L(">")||Z||ZC.A3(p).9z().5d(1n(){"BR"!==1g.8h.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&c.1h(n[l]);n=c}1j(l=0,r=n.1f;l<r;l++)o.P6.1h(n[l])}1u{1a p=1m 5y("(^|\\\\s)"+C.2v(1)+"(\\\\s|$)","i"),u=o.MJ.dK("*"),h="";1j(l=0,r=u.1f;l<r;l++)"4h"==1y(h=u[l].7U)&&(h=1y h.dg!==ZC.1b[31]?h.dg:""),""!==h&&p.5U(h)&&o.P6.1h(u[l])}1u 1j(l=0,r=(n=o.MJ.dK(C)).1f;l<r;l++)o.P6.1h(n[l])}1l o.1f=o.P6.1f,1g},ZC.A3.5j={7t:1n(){1j(1a e,t=[],i=0,a=1g.P6.1f;i<a;i++){1a n=[1g.P6[i]];if((e=8P.1f)>1)1j(1a l=1;l<e;l++)n.1h(8P[l]);t.1h(8P[0].9A(1g,n))}1l t},5d:1n(){1j(1a e,t=0,i=1g.P6.1f;t<i;t++){1a a=[1g.P6[t]];if((e=8P.1f)>1)1j(1a n=1;n<e;n++)a.1h(8P[n]);8P[0].9A(1g.P6[t],a)}1l 1g},9z:1n(){1a e=[];1l 1g.5d(1n(){1j(1a t=0,i=1g.6Y.1f;t<i;t++)1===1g.6Y[t].eA&&e.1h(1g.6Y[t])}),1g.P6=e,1g},3p:1n(){1g.7t.4x(1g,1n(e){e&&e.6o&&e.6o.b2(e)})},jX:1n(){1g.7t.4x(1g,1n(e){if(e)1j(;e.6Y.1f;)e.b2(e.6Y[e.6Y.1f-1])})},lD:1n(e){1a t,i;1y e===ZC.1b[31]&&(e=!0);1a a=1g.7t.4x(1g,1n(a){if(!a)1l 1c;if(a===2w){1a n=2g.3s;1l a.zT?(t=a.zT,i=a.12q):n&&n.gl&&n.gl.lI?(t=n.gl.lI,i=n.gl.zV):n&&n.lI&&(t=n.lI,i=n.zV),{1s:t,1M:i}}1a l,r,o=e?"8y":ZC.A3(a).fY("3L");if(2w.g6){1a s=2w.g6(a,1c);l=s.sd(ZC.1b[19]).7z(0,-2),r=s.sd(ZC.1b[20]).7z(0,-2)}1u if(a.hY){1a A=a.hY();l=A.1s?A.1s:a.qM,r=A.1M?A.1M:a.qP}1u l=a.qM,r=a.qP;if("2b"===o||""===o||1y o===ZC.1b[31]){1a C=a.1I,Z=C.ds,c=C.2K,p=C.3L;C.ds="8R",C.2K="4D",C.3L="8y",t=l,i=r,C.3L=p,C.2K=c,C.ds=Z}1u t=l||0,i=r||0;1l{1s:t,1M:i}});1l 1===a.1f?a[0]:a},fY:1n(e){1a t=1g.7t.4x(1g,1n(e,t){if("3L"===t)1l e.1I.3L;1a i,a=2g;if(t=ZC.EA(t),!e||e===a)1l mh;if("3o"===t&&1y e.12p!==ZC.1b[31]){1a n=(ZC.A3(e).fY("jU")||"").m0(/2o\\(3o=(.*)\\)/);1l n&&n[1]?5P(n[1])/100:1}if(-1!==ZC.AU(["9c","qR","sc"],t))1l(i=e.1I.9c)?i:(i=e.1I.qR)?i:(i=e.1I.sc)?i:"2b";1a l=e.1I?e.1I[t]:1c;if(!l)if(a.lp&&a.lp.g6){1a r=a.lp.g6(e,1c);t=t.1F(/([A-Z])/g,"-$1").aN(),l=r?r.sd(t):1c}1u if(e.lU&&(l=e.lU[t],/^\\d/.5U(l)&&!/px$/.5U(l)&&"6U"!==t)){1a o=e.1I.1K,s=e.sm.1K;e.sm.1K=e.lU.1K,e.1I.1K=l||0,l=e.1I.12o+"px",e.1I.1K=o,e.sm.1K=s}1l"3o"===t&&(l=5P(l)),/zW/.5U(8V.c3)&&-1!==ZC.AU(["1K","1v","2A","2a"],t)&&"8L"===ZC.A3(e).fY("2K")&&(l="3g"),"3g"===l?1c:l},e);1l 1===t.1f?t[0]:t},wh:1n(){1a e;1l 1g.P6[0]?1c!==ZC.1d(e=ZC.A3(1g.P6[0]).lD())?[ZC.1k(e[ZC.1b[19]]),ZC.1k(e[ZC.1b[20]])]:[0,0]:1c},1s:1n(e){1a t;if(1y e===ZC.1b[31]){1a i=1g.7t.4x(1g,1n(e){1l 1c!==ZC.1d(t=ZC.A3(e).lD())?ZC.1k(t[ZC.1b[19]]):0});1l 1===i.1f?i[0]:i}1l 1g.7t.4x(1g,1n(e,t){e.1I.1s=t+"px"},e),1g},1M:1n(e){1a t;if(1y e===ZC.1b[31]){1a i=1g.7t.4x(1g,1n(e){1l 1c!==ZC.1d(t=ZC.A3(e).lD())?ZC.1k(t[ZC.1b[20]]):0});1l 1===i.1f?i[0]:i}1l 1g.7t.4x(1g,1n(e,t){e.1I.1M=t+"px"},e),1g},aK:1n(){1l ZC.A3.1Z().1K},aO:1n(){1l ZC.A3.1Z().1v},2O:1n(e,t){if(1y t===ZC.1b[31]){1a i=1g.7t.4x(1g,1n(t){1a i=ZC.A3(t).fY(e);1l-1!==(""+i).1L("px")?ZC.1k(i):i});1l 1===i.1f?i[0]:i}1l 1g.7t.4x(1g,1n(e,t,i){e.1I[t]=i},e,t),1g},3Q:1n(e,t){if(1y t===ZC.1b[31]){1a i=1g.7t.4x(1g,1n(t){1l t.bJ(e)});1l 1===i.1f?i[0]:i}1l 1g.7t.4x(1g,1n(e,t,i){e.4m(t,i)},e,t),1g},8t:1n(e){if(1y e===ZC.1b[31]){1a t=1g.7t.4x(1g,1n(e){1l e.1T});1l 1===t.1f?t[0]:t}1l 1g.7t.4x(1g,1n(e,t){e.1T=t},e),1g},4n:1n(){1l 1g.7t.4x(1g,1n(e){e.1I.3L="8y"}),1g},5b:1n(){1l 1g.7t.4x(1g,1n(e){e.1I.3L="2b"}),1g},2c:1n(){1a e=1g.7t.4x(1g,1n(e){if(!(e&&(e.x&&e.y||1c!==!e.6o&&"2b"!==ZC.A3(e).fY("3L"))))1l mh;1a t,i,a,n,l,r,o,s={1v:0,1K:0},A={1v:0,1K:0},C=e&&e.Ag;1l C&&((i=C.3s)===e&&(s={1v:i.12n,1K:i.12m}),t=C.fd,1y e.hY!==ZC.1b[31]&&(A=e.hY()),a=C.lp||C.12l,n=t.lV||i.lV||0,l=t.lC||i.lC||0,r=a.uZ||t.aO,o=a.v4||t.aK,s={1v:A.1v+r-n,1K:A.1K+o-l}),s});1l 1===e.1f?e[0]:e},3r:1n(e,t,i){if(""!==(e=ZC.A3.ic(e))){if(i||(i=!ZC.sb||{sy:!0}),-1!==e.1L(" ")){1j(1a a=e.2n(/\\s+/),n=0;n<a.1f;n++)1g.3r(a[n],t,i);1l 1g}1l 1g.7t.4x(1g,1n(e,t,a){1n n(e){1a t=(e=e||2w.Aa).2X||e.sE,i=ZC.A3.BZ(e);1c!==i&&a.4x(t,i)}ZC.A3.IW||(ZC.A3.IW=[]),ZC.A3.IW.1h([e,t,a,n]),e.ly?e.ly(t,n,i):e.mK("on"+t,n)},e,t),1g}},3k:1n(e,t){if(""!==(e=ZC.A3.ic(e))){if(-1!==e.1L(" ")){1j(1a i=e.2n(/\\s+/),a=0;a<i.1f;a++)1g.3k(i[a],t);1l 1g}1l 1g.7t.4x(1g,1n(e,t,i){if(1y ZC.A3.IW!==ZC.1b[31])1j(1a a=0,n=ZC.A3.IW.1f;a<n;a++)if((ZC.A3.IW[a][0]===e||e.8h&&"12k"===e.8h.5M()&&e.id===ZC.A3.IW[a][0].id)&&ZC.A3.IW[a][1]===t&&ZC.A3.IW[a][2]===i){e.zZ?e.zZ(t,ZC.A3.IW[a][3],!0):e.12j("on"+t,ZC.A3.IW[a][3]),ZC.A3.IW.6r(a,1);1p}},e,t),1g}},4c:1n(e,t,i){if(""!==(e=ZC.A3.ic(e))){if(i||(i=!ZC.sb||{sy:!0}),0===e.1L("en")&&(i={sy:!1}),-1!==e.1L(" ")){1j(1a a=e.2n(/\\s+/),n=0;n<a.1f;n++)1g.4c(a[n],t,i);1l 1g}1a l=1g.Q9;1l ZC.A3.9W||(ZC.A3.9W={}),ZC.A3.9W[e]||(ZC.A3.9W[e]=[],2g.ly?2g.ly(e,r,i):2g.mK("on"+e,r)),ZC.A3.9W[e].1h([l,t]),1g}1n r(t){1a i=(t=t||2w.Aa).2X||t.sE,a=i.7U||"";"4h"==1y a&&(a=1y a.dg!==ZC.1b[31]&&1c!==ZC.1d(a.dg)?a.dg:"");1a l,r,o=ZC.A3.9W[e],s=1c,A=1c,C=[];1j(l=0,r=o.1f;l<r;l++)("4h"==1y o[l][0]&&i===o[n][0]||"3e"==1y o[l][0]&&("."===o[l][0].2v(0,1)&&-1!==ZC.AU(a.2n(" "),o[l][0].1F(".",""))||"#"===o[l][0].2v(0,1)&&i.id===o[l][0].2v(1)))&&(s=o[l][1],A=ZC.A3.BZ(t),1c!==ZC.1d(s)&&1c!==ZC.1d(A)&&C.1h([s,i,A]));1j(l=0,r=C.1f;l<r;l++)C[l][0].4x(C[l][1],C[l][2])}},4j:1n(e,t){if(""!==(e=ZC.A3.ic(e))){1a i,a,n;if(-1!==e.1L(" ")){1j(a=0,n=(i=e.2n(/\\s+/)).1f;a<n;a++)1g.4j(i[a],t);1l 1g}1a l=1g.Q9;if(ZC.A3.9W||(ZC.A3.9W={}),i=ZC.A3.9W[e])1j(a=i.1f-1;a>=0;a--)i[a][0]!==l||t&&i[a][1]!==t||ZC.A3.9W[e].6r(a,1);1l 1g}}},ZC.A3.12h=1n(e){1j(1a t=[],i=0;i<ZC.A3.9W[e].1f;i++)t.1h(ZC.A3.9W[e][i][0]);1l t.2M(",")},ZC.A3.ic=1n(e){1l ZC.cA&&(e=ZC.GP(e.1F(/4H|5R|6f/,""))),e},ZC.A3.4f={},ZC.A3.6J={},1n(){1a e=/(7n)[ \\/]([\\w.]+)/,t=/(li)(?:.*a4)?[ \\/]([\\w.]+)/,i=/(af) ([\\w.]+)/,a=/(yI)(?:.*? rv:([\\w.]+))?/,n=/(Ad)(?:.*? rv:([\\w.]+))?/,l=1n(l){l=l.aN();1a r=e.3n(l)||t.3n(l)||i.3n(l)||n.3n(l)||l.1L("121")<0&&a.3n(l)||[];1l[r[1]||"",r[2]||"0"]}(8V.c3);l[0]&&("Ad"===l[0]&&(l[0]="af"),ZC.A3.6J[l[0]]=!0,ZC.A3.6J.a4=l[1])}(),ZC.A3.1Z=1n(){1a e={1v:0,1K:0},t=2g,i=t.fd,a=t.3s;1l i&&(i.aO||i.aK)?(e.1K=i.aK,e.1v=i.aO):a&&(e.1K=a.aK,e.1v=a.aO),e},ZC.A3.BZ=1n(e){if(e.Af=e,e.2X||(e.2X=e.sE||2g),3!==e.2X.eA&&8!==e.2X.eA||(e.2X=e.2X.6o),1c===ZC.1d(e.bk)&&1c!==ZC.1d(e.c8)){1a t=e.2X.Ag||2g,i=t.fd,a=t.3s;e.bk=e.c8+(i&&i.aK||a&&a.aK||0)-(i&&i.lC||a&&a.lC||0),e.c2=e.dt+(i&&i.aO||a&&a.aO||0)-(i&&i.lV||a&&a.lV||0)}1l!e.9f&&(e.7K,mh),e.6R||(e.6R=1n(){1g.12g=!1}),e.Ak||(e.Ak=1n(){1g.12f=!0}),e},ZC.A3.A4=1n(e,t){if(e===t)1l!0;1j(;e!==t&&e.6o;)if((e=e.6o)===t)1l!0;1l!1},ZC.A3.a8=1n(e){1a t=e.3R||"",i=e.1J||"bL",a=e.1V||"",n=!0;1y e.ag!==ZC.1b[31]&&(n=ZC.2s(e.ag)),""===a.1F(/\\&/g,"")&&(a="");1a l=e.ej||1c,r=e.4L||1c,o=e.aF||1c,s=1c;4J{2w.mr?s=1m mr("12e.12d"):2w.hP&&(s=1m hP)}4M(C){}1a A="s4:"===2w.89.hM;if(s){n&&(s.fD=1n(){4===s.fE&&((A||s.6M>=oG&&s.6M<eX)&&o&&o(s.zt,s.6M,s,t),s.6M>=sC&&r&&r(s,s.6M,s.rQ,t),s.fD=1m 2w.bA,s=1c)}),2w.mr||(s.j0=1n(){r&&r(s,0,"",t)}),"zN"===i.5M()?(s.bD("zN",t,n),s.cn("X-12c-12b","hP"),s.cn("12a-1J","g8/x-8z-4I-12T")):(""!==a&&(-1===t.1L("?")&&(t+="?"),t+="&"+a),s.bD("bL",t,n)),l&&l(s);4J{s.8f(a),n||((A||s.6M>=oG&&s.6M<eX)&&o&&o(s.zt,s.6M,s,t),s.6M>=sC&&r&&r(s,s.6M,s.rQ,t),s=1c)}4M(Z){A&&r&&(r(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b(.5*(l+r));1a o=e[n];if(o<i)l=n+1;1u{if(!(o>i))1l t[n];r=n-1}}a=1B.1X(0,r);1a s=i-e[a],A=s*s;1l t[a]+Z[a]*s+u[a]*A+h[a]*s*A}},YQ:1n(e,t,i,a){1c===ZC.1d(a)&&(a=1/(i/t.1f*4));1a n,l,r=[];if(e)if((n=[].4B(t))[1]&&n[2]){n[0]=n[0]||n[1]||n[2]||n[3],n[1]=n[1]||n[2]||n[0]||n[3],n[2]=n[2]||n[3]||n[1]||n[0],n[3]=n[3]||n[2]||n[1]||n[0];1a o=ZC.AQ.zv([0,1,2,3],n);1j(l=1;l<=2;l+=a)r.1h([l-1,o(l)])}1u r.1h([]);1u 1j(1a s=1;s<t.1f-2;s++)if(1!==a)if((n=[t[s-1],t[s],t[s+1],t[s+2]])[1]&&n[2])1j(n[0]=n[0]||n[1]||n[2]||n[3],n[1]=n[1]||n[2]||n[0]||n[3],n[2]=n[2]||n[3]||n[1]||n[0],n[3]=n[3]||n[2]||n[1]||n[0],l=0;l<=1;l+=a){1a A=s+l,C=ZC.AQ.zw(l,n);r.1h([A-1,C])}1u r.1h([]);1u r.1h([s-1,t[s]]);1l r},SN:1n(e){1j(1a t=1B.43(ZC.JN(ZC.2l(e))/1B.a6),i=[1,2,4,5,6,8,10],a=ZC.3w,n=1,l=0;l<i.1f;l++){1a r=i[l]*1B.6s(10,t)-e;ZC.2l(r)<a&&(n=i[l],a=ZC.2l(r))}1l n*1B.6s(10,t)},ZI:1n(e,t,i,a,n){1a l,r,o,s;1c!==ZC.1d(a)&&0!==a||(a=1);1a A=1B.4b(ZC.JN(ZC.2l(t))/1B.a6),C=1B.4b(ZC.JN(ZC.2l(e))/1B.a6);e===t&&(t+=1B.6s(10,A));1a Z=1B.1X(A,C);if(1c===ZC.1d(i)){(i=1B.6s(10,Z))>t-e&&(i=1B.6s(10,Z-1)),ZC.2l(t)/i<2&&ZC.2l(e)/i<2&&(Z--,i=1B.6s(10,Z));1a c=1B.4b(ZC.JN(t-e)/1B.a6),p=1B.6s(10,c);t-e>0&&i/p>=10&&(i=p,Z=c)}1a u=2===(r=(""+i).2n(".")).1f?r[1].1f:0;if(1!==a){1a h=2===(r=(""+(i*=a)).2n(".")).1f?r[1].1f:0;h>u&&h>=9&&(i=ZC.4o(i,9))}1a 1b=i;if(1c===n){1a d=[1,2,5],f=0;1j(Z=0;(t-e)/i>20;)i=1b*d[f]*1B.6s(10,Z),++f===d.1f&&(Z++,f=0)}s=t,s=1B.4l(t/i)*i,e<0?(o=-1B.4b(ZC.2l(e/i))*i)>e&&(o=-(1B.4b(ZC.2l(e/i))+1)*i):((o=1B.4b(ZC.2l(e/i))*i)>e&&(o=1B.4b(ZC.2l(e/i)-1)*i),o=o<0?0:o),Z<0&&(o=ZC.1W(ZC.9y(o,1-Z)),s=ZC.1W(ZC.9y(s,1-Z)),(l=ZC.1W(ZC.9y(i,1-Z)))>0&&(i=l));1a g=2===(r=(""+i).2n(".")).1f?r[1].1f:0,B=2===(r=(""+o).2n(".")).1f?r[1].1f:0,v=2===(r=(""+s).2n(".")).1f?r[1].1f:0;1l B>g&&B>=9&&(o=ZC.4o(o)),v>g&&v>=9&&(s=ZC.4o(s)),[o,s,1b,Z,i]}},ZC.Y3={du:1n(e){1l ZC.Y3.zy(ZC.Y3.zx(ZC.Y3.zq(e)))},zx:1n(e){1l ZC.Y3.zG(ZC.Y3.zH(ZC.Y3.zF(e),8*e.1f))},zy:1n(e){1j(1a t,i="",a=0,n=e.1f;a<n;a++)t=e.g1(a),i+="zz".fz(t>>>4&15)+"zz".fz(15&t);1l i},zq:1n(e){1j(1a t,i,a="",n=-1,l=e.1f;++n<l;)t=e.g1(n),i=n+1<l?e.g1(n+1):0,12x<=t&&t<=12H&&12F<=i&&i<=12E&&(t=12D+((zD&t)<<10)+(zD&i),n++),t<=127?a+=6d.d7(t):t<=12C?a+=6d.d7(12B|t>>>6&31,128|63&t):t<=m7?a+=6d.d7(12A|t>>>12&15,128|t>>>6&63,128|63&t):t<=12z&&(a+=6d.d7(12y|t>>>18&7,128|t>>>12&63,128|t>>>6&63,128|63&t));1l a},zF:1n(e){1a t,i=3M(e.1f>>2);1j(t=0;t<i.1f;t++)i[t]=0;1j(t=0;t<8*e.1f;t+=8)i[t>>5]|=(3U&e.g1(t/8))<<t%32;1l i},zG:1n(e){1j(1a t="",i=0;i<32*e.1f;i+=8)t+=6d.d7(e[i>>5]>>>i%32&3U);1l t},zH:1n(e,t){1n i(e,t,i,a,n,l){1l o((r=o(o(t,e),o(a,l)))<<(s=n)|r>>>32-s,i);1a r,s}1n a(e,t,a,n,l,r,o){1l i(t&a|~t&n,e,t,l,r,o)}1n n(e,t,a,n,l,r,o){1l i(t&n|a&~n,e,t,l,r,o)}1n l(e,t,a,n,l,r,o){1l i(t^a^n,e,t,l,r,o)}1n r(e,t,a,n,l,r,o){1l i(a^(t|~n),e,t,l,r,o)}1n o(e,t){1a i=(m7&e)+(m7&t);1l(e>>16)+(t>>16)+(i>>16)<<16|m7&i}e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;1j(1a s=11Y,A=-11y,C=-11t,Z=11r,c=0,p=e.1f;c<p;c+=16){1a u=s,h=A,1b=C,d=Z;A=r(A=r(A=r(A=r(A=l(A=l(A=l(A=l(A=n(A=n(A=n(A=n(A=a(A=a(A=a(A=a(A,C=a(C,Z=a(Z,s=a(s,A,C,Z,e[c],7,-11q),A,C,e[c+1],12,-11p),s,A,e[c+2],17,11o),Z,s,e[c+3],22,-11n),C=a(C,Z=a(Z,s=a(s,A,C,Z,e[c+4],7,-11m),A,C,e[c+5],12,11l),s,A,e[c+6],17,-11j),Z,s,e[c+7],22,-118),C=a(C,Z=a(Z,s=a(s,A,C,Z,e[c+8],7,11i),A,C,e[c+9],12,-11h),s,A,e[c+10],17,-11g),Z,s,e[c+11],22,-11f),C=a(C,Z=a(Z,s=a(s,A,C,Z,e[c+12],7,11e),A,C,e[c+13],12,-11d),s,A,e[c+14],17,-11c),Z,s,e[c+15],22,11b),C=n(C,Z=n(Z,s=n(s,A,C,Z,e[c+1],5,-11a),A,C,e[c+6],9,-Ug),s,A,e[c+11],14,119),Z,s,e[c],20,-11w),C=n(C,Z=n(Z,s=n(s,A,C,Z,e[c+5],5,-11k),A,C,e[c+10],9,11x),s,A,e[c+15],14,-11L),Z,s,e[c+4],20,-11W),C=n(C,Z=n(Z,s=n(s,A,C,Z,e[c+9],5,11V),A,C,e[c+14],9,-11U),s,A,e[c+3],14,-11T),Z,s,e[c+8],20,11S),C=n(C,Z=n(Z,s=n(s,A,C,Z,e[c+13],5,-11R),A,C,e[c+2],9,-11Q),s,A,e[c+7],14,11P),Z,s,e[c+12],20,-11O),C=l(C,Z=l(Z,s=l(s,A,C,Z,e[c+5],4,-11N),A,C,e[c+8],11,-11M),s,A,e[c+11],16,11K),Z,s,e[c+14],23,-11z),C=l(C,Z=l(Z,s=l(s,A,C,Z,e[c+1],4,-11I),A,C,e[c+4],11,11H),s,A,e[c+7],16,-11G),Z,s,e[c+10],23,-11F),C=l(C,Z=l(Z,s=l(s,A,C,Z,e[c+13],4,11E),A,C,e[c],11,-11D),s,A,e[c+3],16,-12W),Z,s,e[c+6],23,12X),C=l(C,Z=l(Z,s=l(s,A,C,Z,e[c+9],4,-14k),A,C,e[c+12],11,-14j),s,A,e[c+15],16,14i),Z,s,e[c+2],23,-14h),C=r(C,Z=r(Z,s=r(s,A,C,Z,e[c],6,-14g),A,C,e[c+7],10,14f),s,A,e[c+14],15,-14e),Z,s,e[c+5],21,-14d),C=r(C,Z=r(Z,s=r(s,A,C,Z,e[c+12],6,14c),A,C,e[c+3],10,-14b),s,A,e[c+10],15,-14a),Z,s,e[c+1],21,-148),C=r(C,Z=r(Z,s=r(s,A,C,Z,e[c+8],6,145),A,C,e[c+15],10,-144),s,A,e[c+6],15,-143),Z,s,e[c+13],21,142),C=r(C,Z=r(Z,s=r(s,A,C,Z,e[c+4],6,-13Z),A,C,e[c+11],10,-13X),s,A,e[c+2],15,13W),Z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H,1o.dL=1c,1o.hd=0,1o.wn=0,1o.q4=0,1o.oo=0,1o.tH={},1o.dI="5f",1o.oA="9u",1o.jQ=1c,1o.nq=("s4:"===2g.89.hM?"7h:":2g.89.hM)+"//8m.1o.bZ/",1o.hZ=!1,1o.lN="5f",1o.ga={1M:14G,1s:14F},1o.x4=0,1o.iF=11,1o.9T="mY qJ 14E,mY 14D,mY qJ,Bf,Bg,nX-nO",ZC.2L&&(1o.9T="mY qJ,Bf,Bg,nX-nO"),1o.qG=1n(e,t){1j(1a i=(""+e).2n(","),a=0,n=i.1f;a<n;a++){1a l=ZC.GP(i[a]);-1!==ZC.AU(["2U","dN","qA","g7"],l)&&(l="v"+l);1a r=1o.Bh[l];1c!==ZC.1d(r)&&1o.qG(r),-1===ZC.AU(ZC.RN,l)&&ZC.RN.1h(l)}t&&1o.ip(1c,ZC.RN,t)},1o.ip=1n(e,t,i){1a a=0;if(0===t.1f)i();1u{if(!2g.dK("fb")[0])1l 8j i();!1n n(){1a l,r=!0;1n o(){++a===t.1f?i():n()}1o.Bl(t[a])?l=1o.Bi+"1o-"+t[a]+".2j.js":r=!1,r?ZC.AO.Bj(e,l,o):o()}()}},1o.Bl=1n(e){1l-1!==ZC.AU(ZC.RN,e)&&-1===ZC.AU(ZC.WU,e)},1o.LN=[],ZC.6N||1n(){1j(1a e in ZC.c0)ZC.c0.8d(e)&&(1o.LN[e]=1m d2,1o.LN[e].5a=ZC.c0[e])}(),1y 14C!==ZC.1b[31]&&(1o.LN["zc.Ao"]=1m d2,1o.LN["zc.Ao"].5a=ZC.kw),1o.3n=1n(e,t,i){1l 1o.l9?1o.l9(e,t,i):1c},1o.yy=1n(O){1a QK=O.i5||"",F5="",G,MD=1c;1c!==ZC.1d(G=O.1V)&&("3e"==1y G?F5=G:MD=3h.1q(3h.5g(G)));1a DF=1c;if(""!==QK)ZC.A3.a8({1J:"bL",3R:QK,ag:!1,1V:1o.hd?"lx=14A":"",4L:1n(){1l!1},aF:1n(KH){1n 1W(e){ZC.4f.1V["1V-"+QK]=KH,O.bb="3g",ZC.2E(e.aW,O)}4J{DF=3h.1q(KH),1W(DF)}4M(J7){4J{DF=7l("("+KH+")"),1W(DF)}4M(J7){1l!1}}}});1u{if(""!==F5)4J{DF=3h.1q(F5)}4M(J7){1l!1}1u 1c!==MD&&(DF=MD);1c===ZC.1d(O.bb)&&(O.bb="3g"),ZC.2E(DF.aW,O)}1l 1o.aW(O)},1o.fN=1c,1o.aQ={},1o.aW=1n(e,t){if(1c===ZC.1d(t)&&(t=!1),t)1l 1o.yy(e);1c===ZC.1d(ZC.3a)&&ZC.zn();1a i=e.bb||"3g";"gV"===i&&(i="3g"),ZC.2L&&"3g"===i&&(i="2F");1a a=!1;if("!"===i.2v(0,1)&&(a=!0,i=i.2v(1)),a||("3g"===i||"3a"===i&&!ZC.3a||"2F"===i&&!ZC.2F||"3K"===i&&!ZC.3K||"aJ"===i&&!ZC.aJ)&&(ZC.2F?i="2F":ZC.3a?i="3a":ZC.3K?i="3K":ZC.aJ&&(i="aJ")),"3K"===i&&1c===ZC.1d(1o.fN)&&(1o.fN=!1),"aJ"!==i)1l 1o.rs(e,i);1o.14o(e)},2g.mK&&("ai"===2g.fE?1o.fN=!0:2g.mK("fD",1n(){"ai"===2g.fE&&(1o.fN=!0)})),1o.14z=1o.14y=1n(e,t){ZC.HE[e]=t},1o.HY=[],1o.YE={},1o.14x=0,1o.14w=0,1o.14v=!1,1o.tP=!1,1o.rr=!1,1o.14u=!1,1o.2O=1c,1o.XC=1n(e){if(e.2X.id){1j(1a t=1c,i=0,a=1o.HY.1f;i<a;i++)e.2X.id.5A(0,1o.HY[i].J.1f+1)===1o.HY[i].J+"-"&&(t=1o.HY[i]);1l t}},ZC.5h={id:1c,on:!1,ts:1c,1J:1c,eT:-1,mp:[-1,-1]},1y 1o.ML===ZC.1b[31]&&(1o.ML=1n(e){if("mX"===1o.lN)1P(ZC.bU=!1,e.1J){1i"4H":1j(1a t=!1,i=0;i<1o.HY.1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(1o.SM=1n(e){1j(1a t=0,i=1o.HY.1f;t<i;t++)1o.HY[t].9h();if(ZC.2L&&ZC.3m)ZC.3m=!1;1u if(ZC.2L||!(e.9f>1)){1a a=1o.XC(e);if(a){if("3H"===e.1J&&ZC.jj&&(ZC.2l(ZC.jj[0]-e.bk)>2||ZC.2l(ZC.jj[1]-e.c2)>2))1l;1o.4F.9O||ZC.AO.C8("9C"===e.1J?"9C":"3H",a,1o.hI(e,a)),1o.4F.9O=!1,e.2X.id!==a.J+"-2C-1N"?a.9h():1o.ZH(e)}}},ZC.2L?(ZC.A3(2g).3r("6f",1n(){ZC.3m=!0}),ZC.A3(2g).3r("5R",1n(){ZC.3m=!1})):(ZC.A3(2g).3r("3H",1o.SM),ZC.A3(2g).3r("9C",1o.SM))),1y 1o.qS===ZC.1b[31]&&(1o.qS=1n(e){e.7x.1f>0&&(ZC.bU=!0)},ZC.A3(2g).3r("4H",1o.qS)),1y 1o.ZH===ZC.1b[31]&&(1o.ZH=1n(e,t,i){if(!e||"14s"===e.2X.8h.5M()||"ud"===e.2X.8h.5M()||-1!==ZC.P.TF(e.2X).1L("zc-1Z")||-1!==e.2X.id.1L("-1Y-")||-1!==e.2X.id.1L("-2z-")||1o.3J.bC){1a a,n,l,r,o,s;i=i||{};1a A=1c===ZC.1d(t)?1o.XC(e):1o.6Z(t);if(A){if(-1!==ZC.AU(A.KP,ZC.1b[38]))1l!1;if(1c===ZC.1d(t)?(n=ZC.P.MH(e),a=A.mu(n[0],n[1])):a=1c!==ZC.1d(i[ZC.1b[3]])?A.OH(i[ZC.1b[3]]):A.AI[0],!a)1l!1;1a C=ZC.A3("#"+A.J+"-1v");1c===ZC.1d(t)?(l=n[0]-C.2c().1K,r=n[1]-C.2c().1v):(l=A.I/2,r=A.F/2);1a Z={};e&&(Z=1o.hI(e,A));1a c=ZC.AO.C8("f9",A,Z,!0);if(!c&&1y c!==ZC.1b[31]&&(!e&&!i["6m-7p"]||e&&e.2X.id!==A.J+"-2C-1N"))1l e.6R(),!1;1a p=ZC.aE(A.J);A.p7(a?a.L:-1,e);1a u=-1;if(0!==1o.qT)u=1o.qT;1u 1j(1a h=ZC.AK(A.J);-1===u&&1c!==h.6o;)"3g"!==(u=ZC.1k(ZC.A3(h).2O("a2")))&&""!==u&&1c!==ZC.1d(u)||(u=-1),h=h.6o;u&&-1!==u&&1c!==ZC.1d(u)||(u=1);1a 1b=ZC.A3("#"+A.J+"-2C");if(1b.2O("a2",1o.qB+u+1),1c===ZC.1d(t)){if(e.2X.id===A.J+"-6I-9K"||e.2X.id===A.J+"-6I-dX")1l!0;e.6R()}if(!ZC.AK(A.J+"-2C"))1l!1;l=C.2c().1K,r=C.2c().1v;1a d=C.1s(),f=C.1M();1c===ZC.1d(t)?(o=(n=ZC.P.MH(e))[0]||ZC.DS[0],s=n[1]||ZC.DS[1]):(o=l+A.I/2,s=r+5);1a g=!1;if(A.UF("c6",!1),A.NY>0&&(A.UF("c6",!0),g=!0),A.UF("c5",!1),A.NY<A.QS.1f-1&&(A.UF("c5",!0),g=!0),A.UF("4Z",g,!0),o>=l&&o<=l+d*p[0]&&s>=r&&s<=r+f*p[1]){ZC.A3(".zc-2C").5d(1n(){1g.id!==A.J+"-2C"&&A.9h()}),A.SY=[o,s,1c===ZC.1d(t)?e.2X.id:t],1b.2O("3o",0).4n();1a B,v,b=ZC.1k(1b.2O(ZC.1b[19]))+ZC.1k(1b.2O("d8"))+ZC.1k(1b.2O("di")),m=ZC.1k(1b.2O(ZC.1b[20]))+ZC.1k(1b.2O("ca"))+ZC.1k(1b.2O("d6")),E=1,D=!1;if(A.o.5i&&A.o.5i["6i-2C"]&&A.o.5i["6i-2C"]&&(E=A.o.5i["6i-2C"].2o?A.o.5i["6i-2C"].2o:1,D=A.o.5i["6i-2C"].14q),1b.2O("3o",E).5b(),"cH"!==A.LO&&D){if(D){1a J=A.B8.NU[A.LO].a3.5i["6i-2C"];ZC.2E(A.o.5i["6i-2C"],J),B="1K"!==A.o.5i["6i-2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1c!==ZC.1d(i.y)&&(B=l+ZC.1k(i.x),v=r+ZC.1k(i.y));if(1b.2O("1K",ZC.BM(1,B)+"px").2O("1v",ZC.BM(1,v)+"px").4n(),ZC.6N){1a Y=ZC.A3("#"+A.J+"-2C 3B").1s()[0]||120;1b.2O(ZC.1b[19],Y+"px")}}1l A.dZ=!0,!1}}}},ZC.A3(2g).3r("f9",1o.ZH)),1o.tE=1n(e,t){if(1o.2O)1l 1o.2O.yk?1o.2O.yk(e,t):1o.2O.13T(e+"{"+t+"}",0)},1o.wh=1n(e,t,i){"3g"===t&&(t="100%"),"3g"===i&&(i="100%");1a a=[0,0];1l-1===(""+t).1L("%")&&-1===(""+i).1L("%")||(a=e.wh()),[-1!==(""+t).1L("%")?a[0]*5v(t,10)/100:5v(t,10),-1!==(""+i).1L("%")?a[1]*5v(i,10)/100:5v(i,10)]},1o.IW={},1o.3r=1n(e,t,i){e=e||"1o-lk",1o.IW[e]||(1o.IW[e]={}),1o.IW[e][t]?1o.IW[e][t].1h({fn:i}):1o.IW[e][t]=[{fn:i}]},1o.3k=1n(e,t,i){if(e=e||"1o-lk",1o.IW[e]&&1o.IW[e][t])if(i){1j(1a a=0,n=1o.IW[e][t].1f;a<n;a++)if(1o.IW[e][t][a].fn===i){1o.IW[e][t].6r(a,1);1p}}1u 1o.IW[e][t]=1c},1o.h5=1n(e,t,i,a){if(e=e||"1o-lk",1o.IW[e]&&1o.IW[e][t]){1j(1a n=0,l=1o.IW[e][t].1f;n<l;n++)a?i[i.1f-1]=1o.IW[e][t][n].fn.9A(1o,i):1o.IW[e][t][n].fn.9A(1o,i);if(a)1l i[i.1f-1]}},1o.h4=1n(e,t){1l e=e||"1o-lk",1o.IW[e]&&1o.IW[e][t]},1o.rs=1n(e,t){ZC.6y(e,!1);1a i,a,n,l,r,o,s,A,C=[];if(1c!==ZC.1d(i=e.hc)&&(C=i.2n(",")),1c!==ZC.1d(i=e.4E))1P(i){1i"8L":C=[ZC.1b[38],ZC.1b[39],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r:#yt;2t-2e:r3;1w-1M:125%;",".zc-6t-2":"3v:88;1r:#2S;1E-3u:3F !7r;",".zc-6t-3":"3v:88;1E-3u:3F;1w-1M:125%;",".zc-6t-3 3B":"1U-1r:#yt;1w-1M:125%;1r:#2S;1G:7Y 2V #2S;3v:88 az;2t-79:6x;1s:13h;2y:0 3g;4V:8q;1E-3u:3F",".zc-6t-4":"1r:#2S;1w-1M:125%;",".zc-6t-4 3B":"9c:2A;1r:#2S;1w-1M:125%;",".zc-4K":"1G:88 2V #2S;1U:#4S",".zc-4L":"1G:88 2V #2S;1U:#x5",".zc-4r":"1G:88 2V #2S;1U:#4S",".zc-4I-5B-1H":"3v:dM az 5o;1E-3u:1K;1r:#2S",".zc-4I-5B-ao":"3v:5o ri",".zc-4I-5B-7Z":"3v:ri ri 5o !7r",".zc-4I-5B-ao bP":"1E-3u:1K;1U:#2S;1r:#4u;1G:7Y 2V #8M;",".zc-4I-5B-1H an":"1r:#4u;3v:5o;2y:0 88 0 0;1U-1r:#4S;",".zc-4I-5B-ao an":"1r:#4u;3v:5o;2y:0;1U-1r:#2S",".zc-4I-5B-7Z an":"3v:dM az !7r;2y:0 13d 0 0 !7r;1U-1r:#8X !7r;1G:5o 12Z #8c !7r",".zc-4I-s0":"2t-2e:13b !7r;13a-139:-7Y;1w-1M:125%",".zc-4I-s1":"2t-2e:r3 !7r;1w-1M:125%",".zc-4I-s1 a":"1r:#2S;3v:138 az;2K:k2;1v:dM;1G:7Y 2V #8M;1G-2a:gU 2V #8M",".zc-cS-6C":"1U-1r:#2S;1r:#8M !7r",".zc-cS-ez":"1U-1r:#4S;1r:#74 !7r",".zc-4r 1H":"3L:137-8y;2K:k2;1v:-5o",".zc-cj 3B":"2K:4D;1E-3u:3F;3v:88;1U:#4S;1r:#2S",".zc-eJ-6N":"3v:0;2K:4D;2t-2e:y4;2t-79:6x;2t-9B:"+1o.9T+";1r:#j3;1E-3u:1K",".zc-eJ":"3v:0;2K:4D;","#zc-5X":"3L:8y;2K:4D;1v:0;1K:0;1s:100%;1M:100%;2y:0;3v:0;1U:#2S;",".zc-2C":"2K:4D;3L:2b;1U-6B:no-6B !7r;1U-2K:50% 0% !7r;",".zc-2C-eu":"2t-2e:7Y;3v:0;1w-1M:7Y;1G-2a:7Y 2V #4u",".zc-2C-1Q":"4V:8q;xL-8I:mC",".zc-9b":"1U:#8X",".zc-9b 3B.zc-9b-w1":"2K:4D;1G:5o 2V #8c;3v:az 133;1U-1r:#8M;1r:#2S",".zc-f1":"1U-1r:#2S;1r:#4u;1G:5o 2V #4S",".zc-2i-1H-6q":"1G-gz:gz",".zc-2i-1H-6q td":"3v:dM az 5o 5o",".zc-1V-6q":"1G-gz:gz",".zc-1V-6q tJ":"2t-9B:"+1o.9T+";1E-3u:1K;2t-2e:r3;2t-79:qQ;3v:xH rB xH dM;1U-1r:#8c;1G-2a:5o 2V #cc",".zc-1V-6q th":"2t-9B:"+1o.9T+";1E-3u:1K;2t-2e:132;2t-79:qQ;3v:5o rB 5o dM;1U-1r:#74;1G-2a:7Y 2V #cc",".zc-1V-6q td":"2t-9B:"+1o.9T+";1E-3u:1K;2t-2e:uu;3v:7Y rB 7Y dM;1U-1r:#j4;1G-2a:7Y 2V #8X;xL-8I:mC",".zc-aS":"1v:0;1K:0;2K:k2",".zc-3l":"1v:0;1K:0;2K:4D"};ZC.cA||(h[".zc-1V-6q th:cR(:7Z-xM)"]="1G-2A:7Y fo #cc",h[".zc-1V-6q td:cR(:7Z-xM)"]="1G-2A:7Y 2V #8X");1a 1b=2g.dK("fb")[0],d=2g.4P("1I");if(d.1J="1E/2O",d.4m("1V-xO","1o"),1b.2Z(d),!1o.2O)1j(n=0,l=2g.fq.1f;n<l;n++)2g.fq[n].xN&&"1o"===2g.fq[n].xN.bJ("1V-xO")&&(1o.2O=2g.fq[n]);1j(1a f in 1o.2O||(1o.2O=2g.fq[2g.fq.1f-1]),h)1c!==ZC.1d(1o.tH[f])?1o.tE(f,1o.tH[f]):1o.tE(f,h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u.QM?1o.wh(w,""+w.1s(),""+w.1M()):1o.wh(w,u.FW,u.MW))[0]>10&&e[1]>10){1j(u.I=e[0],u.F=e[1],M=w.1s(),H=w.1M(),n=0,l=u.AI.1f;n<l;n++)u.AI[n].O5[0]=0;G()}}1u if(M=w.1s(),H=w.1M(),M>10&&H>10){1j(-1!==(""+u.FW).1L("%")?u.I=M*ZC.IH(u.FW):u.I=M,-1!==(""+u.MW).1L("%")?u.F=H*ZC.IH(u.MW):u.F=H,n=0,l=u.AI.1f;n<l;n++)u.AI[n].O5[0]=0;G()}P++}1u 2w.9S(u.YU)},1o.3J.xT)}1l u}1n N(){if(!u.E.wh||u.E.wh!==u.I+"/"+u.F){1j(1a e=!1,t=0;t<1o.HY.1f;t++)1o.HY[t].J===u.J&&(e=!0);e&&u.bT()}u.kT=!1}1n G(){u.kT?u.VV.1s!==u.I&&(iu(u.tn),u.VV.1s=u.I,u.VV.1M=u.F,u.tn=5Q(N,1o.3J.tk)):(u.kT=!0,u.VV={1s:u.I,1M:u.F},u.tn=5Q(N,1o.3J.tk))}},2w.1o=1o,ZC.A3.6J.af&&5P(ZC.A3.6J.a4)<9){1a t8=2w.xU;2w.xU=1n(){1j(;1o.HY.1f;)1o.3n(1o.HY[0].J,"a0");ZC.A3(2g).3k(ZC.P.BZ("7A"),1o.ML).3k(ZC.P.BZ("7T"),1o.ML).3k(ZC.P.BZ(ZC.1b[48]),1o.ML).3k(ZC.P.BZ(ZC.1b[47]),1o.ML).3k(ZC.P.BZ(ZC.1b[49]),1o.ML).3k("3H",1o.SM).3k("f9",1o.ZH),1o.HY=[],t8&&t8()}}1o.fT.s2={aH:!1,"6K-8E":".","m1-8E":"","2C-na":"13P nB xW","2C-nb":"13O nB xW","2C-f5":"xw","2C-6I":"uc 13N","2C-pQ":"gK As 13M","2C-pM":"gK As 13L","2C-u3":"kW 13I","2C-u5":"kW 13H","2C-tY":"kW 8n","2C-u6":"kW 13t","2C-sX":"gK dG y0","2C-t0":"yZ dG y0","2C-k8":"13C dG","2C-eG":"yv In","2C-f3":"yv 13z","2C-gd":"gK 13y","2C-4K":"gK 13x","2C-4r":"ng yD","2C-nI":"yX To 2D","2C-n9":"yX To 3D","2C-i0":"tO o1","2C-mx":"yZ o1","2C-nH":"tO 13w z1","2C-nn":"tO 13v z1","2C-5X":"z2 z3","2C-iA":"12Y z2 z3","2C-c6":"Go os","2C-c5":"Go Yf","5s-rO":{rN:"%d %M %Y<br>%g:%i:%s %A<br>%q ms",mA:"%d %M %Y<br>%g:%i:%s %A",hT:"%d %M %Y<br>%g:%i %A",mz:"%d %M %Y<br>%g %A",da:"%d %M %Y",ex:"%M %Y",mw:"%Y"},"jV-5G":["113","Xb","Xa","WF","cl","WA","Wz"],"jV-fR":["Wy","Wx","Ww","Wv","Wu","Wr","Wg"],"k9-5G":["ci","Wq","Wp","Wo","yV","Wn","Wm","Wk","Wi","Xc","Ws","Xt"],"k9-fR":["Yb","XX","Xz","Xy","yV","Xx","Xw","Xu","Xs","Xg","Xr","Xq"],"tm-b3":"nV...","8m-b3":"Xp...","7L-b3-fR":"nV. o0...","7L-b3-5G":"nV...","7L-b3-lX":"...","4L-5K":"An yB Xo Xn","4L-b8":"yB Xj:","4L-7m":"hl","4r-5K":"ng yD Xh","4r-wg":"yE 3h dG","4r-ux":"yE Wd Wc","4r-w9":"nf Vc:","4r-wc":"3h dG:","4r-wi":"nf yN Vb","4r-wk":"if yP Va to Ux Uw r4 13r Ut to Us Ur","4r-xf":"yN Up is Uo...","4r-fP":"ng","4r-iT":"Um","4r-wD":"nf Uk Uj Vd Vf.\\n\\Vt yP!","6t-7m":"hl","4K-fU":"wv 3h","4K-fV":"ww 3h","4K-7m":"hl","4K-9A":"Wa","cj-7m":"hl","1Y-vx":"nB %3f% of %9R%"},ZC.HE=1o.fT.s2,1o.6Z=1n(e){1j(1a t=0;t<1o.HY.1f;t++)if(1o.HY[t].J===e)1l 1o.HY[t];1l 1c},1o.pE=1n(e,t){1l e.OH(t)},1o.W9=1n(e){e.A6&&e.A6.fX();1j(1a t=0;t<e.AI.1f;t++)e.AI[t].L6()},1o.VU=1n(e,t,i){1l e.or(t,i)},1o.VB=1n(e){e&&e.qr(!0)},1o.yR=1n(e){ZC.WU.1h(e)},1o.yS=1n(e){1l e.jx.2n(",")},1o.Vz=1n(e,t,i){1P(1o.yR(e),t){1i"b9":1o.3r(1c,"fJ",1n(t,a){1j(1a n=a[ZC.1b[16]].1f,l=0;l<n;l++)if(a[ZC.1b[16]][l].1J===e){1a r=a[ZC.1b[16]][l];r.id?r.id=r.id:r.id=e.1F(/-/g,"")+l,a[ZC.1b[16]][l]=i(r)}1l a});1p;1i"Vx":1o.3r(1c,"fJ",1n(t,a){1a n=1o.6Z(t.id);if(-1!==1o.yS(n).1L(e))1j(1a l=a[ZC.1b[16]].1f,r=1c,o=0;o<l;o++)(r=a[ZC.1b[16]][o]).8d(e)&&(a[ZC.1b[16]][o]=i(r,t.id));1l a})}},1o.Vw=1n(e,t,i){1l i=i||"2U",e.B8.ol(t,i)},1o.Vv=1n(e,t,i){1a a,n;1P(i=i||"1H"){1i"2T":1j(a=0,n=e.FC.1f;a<n;a++)if(e.FC[a].H1===t||a===t)1l e.FC[a].BD;1p;1i"1H":1j(a=0,n=e.BV.1f;a<n;a++)if(e.BV[a].H1===t||a===t)1l e.BV[a]}1l 1c},1o.a7=1n(e,t){1P(t){1i"1I":1l 1m CX(e);1i"2T":1l 1m DT(e);1i"3C":1l 1m I1(e);1i"Vu":1l 1m DM(e)}1l 1c},1o.fM=1n(e){ZC.6y(e)},1o.1S=1n(e,t){ZC.2E(e,t)},1o.Vr=1n(e,t,i,a){1l ZC.AO.YT(e,t,i,a)},1o.Vq=1n(e,t){1l ZC.AO.GO(e,t)},1o.Vp=1n(e,t,i){ZC.AO.C8(e,t,i)},1o.gB=[],1o.ji=1n(e,t){1o.gB.1h({4x:e,7p:t})},1o.3n=1n(e,t,i){1l 1o.6Z(e)?1o.yU(e,t,i):1o.l9?1o.l9(e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!0;1p}l||i.DC["6i-2C"]["5D-2B"].1h(t)}),1o.pd=1n(e,t,i){1a a;2g.cP("zc-5X")&&(e="zc-5X"),"3e"==1y(i=i||{})&&(i=3h.1q(i));1a n,l,r,o,s,A,C,Z,c,p,u,h,1b,d,f,g,B,v,b,m,E=1o.6Z(e),D=!(1c!==ZC.1d(i.3S)&&!ZC.2s(i.3S)),J=1c!==ZC.1d(i.4Z)&&ZC.2s(i.4Z),F=1y i.fg!==ZC.1b[31]&&ZC.2s(i.fg);if(E){1P(-1===ZC.AU(["Ec","Fc","oF","Fj","Fb","Ev","Dh","aI"],t)&&((l=E.FO()).aQ=i,ZC.AO.C8(t,E,l)),t){1i"10d":if(!(n=E.C5(i[ZC.1b[3]])))1l 1c;n.I8&&n.I8.NR&&(n.I8.NR(),n.I8.3k()),n.I9&&n.I9.NR&&(n.I9.NR(),n.I9.3k());1p;1i"10A":1l(n=E.C5(i[ZC.1b[3]]))&&(r=n.I0(i.3W,i.4X))?r.j6(i[ZC.1b[9]]||1):1c;1i"10o":1l(n=E.C5(i[ZC.1b[3]]))&&(o=n.BK(i.8C||""))?1c!==ZC.1d(i[ZC.1b[9]])?o.B2?o.B2(i[ZC.1b[9]]):1c:1c!==ZC.1d(i.lP)&&o.KW?o.KW(i.lP):1c:1c;1i"m6":if(!(n=E.C5(i[ZC.1b[3]])))1l 1c;1a I={id:"J",x:"iX",y:"iY",1s:"I",1M:"F",1r:"C1",ir:"B9",cv:"AX",eU:"BU",eS:"AP",eP:"A0",f4:"AD"};1P(i.4h){1i"2Y":1j(p in l={},I)l[p]=n[I[p]];1l ZC.2E({1J:n.AF},l),l;1i"2u":1j(p in l={},I)l[p]=n.Q[I[p]];1l l;1i"1z":if(!(o=n.BK(i.8C||"")))1l 1c;1j(p in l={},I)l[p]=o[I[p]];1l ZC.2E({1J:o.AF,1E:o.M&&o.M.AN||"",10Q:1c!==o.FB&&"5s"===o.FB.o.1J,6z:o.CP,112:o.QU,110:o.A8,6g:o.Y,6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t.o&&(ZC.2E(Z,t.o),t.KK())}}1q(){1a e,t,i,a,n=1g;"gh"!==1o.oA&&ZC.6y(n.o);1a l="";if(1y n.H!==ZC.1b[31]&&(l=n.H.AB),ZC.gS(n.o,"gV"),""!==l&&ZC.gS(n.o,l),1o.3J.rZ&&n.o["ov-ak"]&&1y n.H!==ZC.1b[31])1j(t=0;t<n.o["ov-ak"].1f;t++)i=n.o["ov-ak"][t],a=!0,1c!==ZC.1d(i["2j-1s"])&&ZC.1k(i["2j-1s"])>n.H.I&&(a=!1),1c!==ZC.1d(i["1X-1s"])&&ZC.1k(i["1X-1s"])<n.H.I&&(a=!1),1c!==ZC.1d(i["2j-1M"])&&ZC.1k(i["2j-1M"])>n.H.F&&(a=!1),1c!==ZC.1d(i["1X-1M"])&&ZC.1k(i["1X-1M"])<n.H.F&&(a=!1),a&&ZC.2E(i,n.o);1j(n.o.ak&&(n.DY=n.o.ak),t=0;t<n.DY.1f;t++)if("*"===n.DY[t].cz&&n.DY[t].js){n.o["js-cz"]=n.DY[t].js,n.DY.6r(t,1);1p}if((e=n.o["js-cz"])&&("7u:"===e.2v(0,11)||e.1L("(")<e.1L(")")))4J{n.OL="";1a r=e.1F("7u:",""),o=e.1L("("),s=e.1L(")");-1!==o&&-1!==s&&(n.OL=r.5A(o+1,s-o-1),r=r.5A(0,o)),n.IE=ZC.iS(r,2w)}4M(C){}if(1y n.H!==ZC.1b[31]&&1c!==n.H.QN)1j(1a A in n.H.QN)n.H.QN.8d(A)&&1c===ZC.1d(n.o[A])&&(n.o[A]=n.H.QN[A])}7W(){1l{}}dE(e,t,i){1j(1a a=t.2n(","),n=i.2n(","),l=0,r=n.1f;l<r;l++)e[a[l]]=n[l]}Zy(){1l 1g.o}102(e){1g.o=e}py(){1l 1g.E}bJ(e){1l 1g.E[e]}4m(e,t){1g.E[e]=t}sV(e){1a t=1g.7W();1l t[e]?1g[t[e]]:1c}mZ(e,t){1a i=1g.7W();i[e]&&(1g[i[e]]=t)}1C(e,t,i){1c===t&&(t=!0);1a a=1g;e&&(a.I3||(a.I3={},ZC.2E(a.o,a.I3,!0,i)),a.JU||(a.JU={}),ZC.2E(e,a.JU,!0,i),ZC.2E(e,a.o,!0,i)),1y a.lS!==ZC.1b[31]&&a.lS()&&e&&ZC.2E(e,a.o)}lS(){}4y(e){1j(1a t=0,i=e.1f;t<i;t++)1g.o.8d(e[t][0])&&1g.YS(e[t][0],e[t][1],e[t][2],e[t][3],e[t][4])}YS(e,t,i,a,n){1a l,r=1g;if(1c!==(l=r.o[e])&&1y l!==ZC.1b[31]){if(i)1P(-1!==i.1L("p")&&(l=ZC.8G(l),i=i.1F("p","")),-1!==i.1L("a")&&(l=ZC.2l(l),i=i.1F("a","")),i){1i"i":l=ZC.1k(l);1p;1i"f":l=ZC.1W(l);1p;1i"b":l=ZC.2s(l);1p;1i"c":l=ZC.AO.ZL(l,r),(l=ZC.AO.G7(l,r))3E 3M&&("1r"===e||"2t-1r"===e?(r.o["1E-2o"]=l[1],r.WY=l[1],r.E["1E-2o"]=l[1]):e===ZC.1b[61]?(r.o["1G-2o"]=l[1],r.O2=l[1],r.E["b-2o"]=l[1]):("1w-1r"===e&&(r.E["l-2o"]=l[1]),1c===ZC.1d(r.o.2o)&&(r.C4=l[1])),l=l[0])}1c!==ZC.1d(a)&&1c!==ZC.1d(n)&&(l=ZC.5u(l,a,n)),r[t]=l}}DA(){1j(1a e=1g,t=!1,i=0,a=e.DY.1f;i<a;i++){1a n=!1;4J{n=1m bA("1l ("+e.IT(e.DY[i].cz)+")")()}4M(l){n=!1}n&&(t=!0,e.1C(e.DY[i]))}1l t}yH(e){1j(1a t="",i=0,a=e.1f;i<a;i++){1a n=!1;4J{n=1m bA("1l ("+1g.IT(e[i].cz)+")")()}4M(l){n=!1}n&&(t+="<"+e[i].cz+">")}1l""!==t?[t,ZC.Y3.du(t)]:1c}IT(){1l!0}1S(e){1a t=1g;ZC.2E(e.o,t.o),e.I3&&(t.I3=t.I3||{},ZC.2E(e.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=i.o.id)&&(t=i.H.N["#"+e])&&(a=!0,ZC.2E(t,i.o))}1l 1c!==i.OE&&(t=i.H.N[i.OE])&&(a=!0,ZC.2E(t,i.o)),a}KK(e){1a t,i=1g;1P(1c===ZC.1d(e)&&(e=i.AX),i.G8){1i"fo":i.EU=ZC.BM(1,.75*e),i.G4=1.75*e;1p;1i"gh":i.EU=4*e,i.G4=3*e;1p;1i"go":i.EU=4*e,i.G4=2*e;1p;2q:i.EU=0,i.G4=0}1c!==(t=ZC.1d(i.o["1w-fI-2e"]))&&(i.EU=5v(t,10)),1c!==(t=ZC.1d(i.o["1w-h8-2e"]))&&(i.G4=5v(t,10))}1q(){1a e,t,i,a,n,l,r,o,s;1D.1q();1a A=1g;if(1c!==(e=ZC.1d(A.o.78))&&!A.sP){1a C,Z,c,p=-1,u=-1;1j(1y A.E.7b!==ZC.1b[31]&&(p=ZC.1k(A.E.7b)),1y A.E.7s!==ZC.1b[31]&&(u=ZC.1k(A.E.7s)),r=0,o=e.1f;r<o;r++){if(C=-1,Z=-1,e[r].7q){if(1c!==(t=ZC.1d(e[r].7q["2r-3b"]))){if(Z=0,c=[],"4h"==1y t)c=t;1u if("3e"==1y t){if(-1!==t.1L(","))c=t.2n(",");1u if(-1!==t.1L("-"))1j(i=t.2n("-"),a=ZC.1k(i[0]);a<=ZC.1k(i[1]);a++)c.1h(a)}1u c=[t];-1!==ZC.AU(c,u)&&(Z=1)}if(1c!==(t=e[r].7q["1A-3b"])&&1y t!==ZC.1b[31]){if(C=0,c=[],"4h"==1y t)c=t;1u if("3e"==1y t){if(-1!==t.1L(","))c=t.2n(",");1u if(-1!==t.1L("-"))1j(i=t.2n("-"),a=ZC.1k(i[0]);a<ZC.1k(i[1]);a++)c.1h(a)}1u c=[t];-1!==ZC.AU(c,p)&&(C=1)}}0!==C&&0!==Z&&A.1C(e[r])}}if(1c!==(e=A.RK)&&A.1C(e),e=A.o[ZC.1b[0]]){if(e=ZC.AO.ZL(e,1g),"9N("===6d(e).2v(0,4))1j(n=1m 5y("9N\\\\((\\\\d{1,3}),\\\\s*(\\\\d{1,3}),\\\\s*(\\\\d{1,3})\\\\)");l=n.3n(e);)e=e.1F(l[0],ZC.AO.G7(l[0]));if("9J("===6d(e).2v(0,5))1j(n=1m 5y("9J\\\\((\\\\d{1,3}),\\\\s*(\\\\d{1,3}),\\\\s*(\\\\d{1,3})\\\\,\\\\s*([0-9.]+)\\\\)");l=n.3n(e);){1a h=ZC.AO.G7(l[0],A);e=e.1F(l[0],h[0]),A.o.2o=h[1],A.C4=h[1],A.E["bg-2o"]=h[1],1c===ZC.1d(A.E["b-2o"])&&(A.E["b-2o"]=1),1c===ZC.1d(A.E["l-2o"])&&(A.E["l-2o"]=1)}1a 1b=ZC.GP(6d(e)).2n(/\\s+|;|,/);A.A0=ZC.AO.G7(1b[0]),A.AD=1===1b.1f?A.A0:ZC.AO.G7(1b[1])}if(!(1c===ZC.1d(A.o[ZC.1b[62]])&&1c===ZC.1d(A.o[ZC.1b[61]])&&1c===ZC.1d(A.o["1w-1I"])||1c===ZC.1d(A.o["1G-1v"])&&1c===ZC.1d(A.o["1G-2A"])&&1c===ZC.1d(A.o["1G-2a"])&&1c===ZC.1d(A.o["1G-1K"])&&1c===ZC.1d(A.o.1G))){1a d=["1v","2A","2a","1K"],f={1v:[0,"2V","#4u"],2A:[0,"2V","#4u"],2a:[0,"2V","#4u"],1K:[0,"2V","#4u"]};if(A.I3=A.I3||{},e=A.I3.1G)1j(s=e.2n(/\\s/),r=0;r<4;r++)f[d[r]]=[ZC.1k(s[0]||"0"),ZC.GP(s[1]||"2V"),ZC.AO.G7(s[2]||"#cs")];if(1c!==ZC.1d(A.I3[ZC.1b[62]]))1j(r=0;r<4;r++)f[d[r]][0]=A.I3[ZC.1b[62]];if(1c!==ZC.1d(A.I3["1w-1I"]))1j(r=0;r<4;r++)f[d[r]][1]=A.I3["1w-1I"];if(1c!==ZC.1d(A.I3[ZC.1b[61]]))1j(r=0;r<4;r++)f[d[r]][2]=A.I3[ZC.1b[61]];1j(r=0;r<4;r++)(e=A.I3["1G-"+d[r]])&&(s=e.2n(/\\s/),f[d[r]]=[ZC.1k(s[0]||"0"),ZC.GP(s[1]||"2V"),ZC.AO.G7(s[2]||"#cs")]);if(A.JU=A.JU||{},e=A.JU.1G)1j(s=e.2n(/\\s/),r=0;r<4;r++)f[d[r]]=[ZC.1k(s[0]||"0"),ZC.GP(s[1]||"2V"),ZC.AO.G7(s[2]||"#cs")];if(1c!==ZC.1d(A.JU[ZC.1b[62]]))1j(r=0;r<4;r++)f[d[r]][0]=A.JU[ZC.1b[62]];if(1c!==ZC.1d(A.JU["1w-1I"]))1j(r=0;r<4;r++)f[d[r]][1]=A.JU["1w-1I"];if(1c!==ZC.1d(A.JU[ZC.1b[61]]))1j(r=0;r<4;r++)f[d[r]][2]=A.JU[ZC.1b[61]];1j(r=0;r<4;r++)(e=A.JU["1G-"+d[r]])&&(s=e.2n(/\\s/),f[d[r]]=[ZC.1k(s[0]||"0"),ZC.GP(s[1]||"2V"),ZC.AO.G7(s[2]||"#cs")]);1j(r=0;r<4;r++)1c===ZC.1d(A.o["1G-"+d[r]])&&(A.o["1G-"+d[r]]=f[d[r]].2M(" "))}A.4y([["2h","AM","b"],["1U-1r-1","A0","c"],["1U-1r-2","AD","c"],["5e-gR","GM"],["5e-tv","HL"],["1U-3t","W0","b"],["1U-4d","D6"],["1U-6B","M9"],["1U-2K","TI"],["1U-iB","WV"],["1U-1z","KV","f"],["3i-1J","NI"],["3i-2f","N7","i"],["3i-2c-x","W7","f"],["3i-2c-y","W6","f"],[ZC.1b[4],"AX","i"],["1w-1r","B9","c"],["1w-1I","G8",""],["1O","DG"],["2p","DG"],["1G","BF"]]),"2b"===A.NI&&(A.AD=A.A0,A.NI="9k"),""!==A.BF&&(s=A.BF.2n(/\\s/),A.AP=ZC.1k(s[0]||"0"),A.G8=ZC.GP(s[1]||"2V"),A.BU=ZC.AO.G7(s[2]||"#cs")),A.GM=ZC.AO.ZL(A.GM,1g),A.KK(),A.4y([["1w-fI-2e","EU","i"],["1w-h8-2e","G4","i"],[ZC.1b[62],"AP","i"],[ZC.1b[61],"BU","c"],["2o","C4","f",0,1],["3I","MC","b"],["3I-2f","OI","i",0,2m],["3I-6T","JR","i"],["3I-2o","T8","f",0,1],["3I-1r","S1","c"],["3I-x3","PB","i"]]),A.O2=A.C4,A.4y([["1G-2o","O2","f",0,1]])}}ZC.CN={iM:1n(e,t,i){1a a,n,l;if(e&&i&&0!==i.1f){if(!t.E["8F-dC-2R"])1j(a=0,n=i.1f;a<n;a++)i[a]&&(i[a][0]=5P(4T(i[a][0]).4A(2)),i[a][1]=5P(4T(i[a][1]).4A(2)));1a r=!1,o=i.1f;1j(a=0;a<o;a++)1c!==ZC.1d(i[a])&&(l=[i[a][0],i[a][1]],1c!==ZC.1d(i[a][2])&&l.1h(i[a][2],i[a][3]),1c!==ZC.1d(i[a][4])&&l.1h(i[a][4],i[a][5]),t.ON&&(l[0]=1B.43(l[0]),l[1]=1B.43(l[1]),4===l.1f&&(l[2]=1B.43(l[2]),l[3]=1B.43(l[3]))),t.CV&&t.AX%2==1&&(l[0]-=.5,l[1]-=.5,4===l.1f&&(l[2]-=.5,l[3]-=.5))),0===a?e.eo(l[0],l[1]):i[a]?(r&&(e.eo(l[0],l[1]),r=!1),2===l.1f?e.gN(l[0],l[1]):4===l.1f?e.wM(l[0],l[1],l[2],l[3]):6===l.1f&&e.6u(l[0],l[1],l[2],ZC.TG(l[3]),ZC.TG(l[4]),l[5])):r=!0}},2I:1n(e,t){1a i=t.H.AB;if(1!==t.C4&&t.L9&&(1c===ZC.1d(t.o[ZC.1b[61]])&&(t.BU=t.A0),1c===ZC.1d(t.o[ZC.1b[62]])))1P(i){1i"3a":t.AP=.2;1p;1i"2F":t.AP=.1;1p;1i"3K":t.AP=.2,t.E.ox=t.C4/10}},1t:1n(e,t,i,a,n,l){if(1c===ZC.1d(n)&&(n=2),1c===ZC.1d(a)&&(a=!1),1c===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f+=" gj("+g+")"}if(a&&-1!==t.E.3i?(c.3i=t.E.3i,c["3i-3o"]=t.C4):c.3i="2b",c["4a-10G"]=t.T7,c["4a-10H"]=t.gf,t.AX>0&&(c.4a=t.B9,c["4a-1s"]=t.AX,c["4a-3o"]=a?t.O2:t.C4,"2V"===t.G8||0===t.EU&&0===t.G4||("go"===t.G8?c["4a-t9"]=[t.EU,t.G4,t.AX,t.G4].2M(" "):c["4a-t9"]=t.EU+","+t.G4)),l.id=1b,""!==f&&(c.5H=f),t.o["8F-1w"]&&t.AX>0?(l.4m("4a",c.4a),l.4m("4a-1s",c["4a-1s"]),l.4m("4a-3o",c["4a-3o"]),l.4m("d",i)):ZC.P.G3(l,c),ZC.CN.jo(e,t,l),(!t.E.1G||"4t"===t.E.1G)&&1y t.E.5c!==ZC.1b[31])if("3e"==1y t.E.5c)ZC.AK(1b+"-5c")||(d=n?ZC.P.F2("5n",ZC.1b[36]):ZC.P.F2("2R",ZC.1b[36]),ZC.P.G3(d,{id:1b+"-5c",5H:f,3i:t.E.5c,"3i-3o":t.C4}),n?ZC.P.G3(d,{x:r,y:o,1s:ZC.BM(0,s),1M:ZC.BM(0,A),rx:C,ry:Z}):ZC.P.G3(d,{d:i}),ZC.CN.jo(e,t,d));1u if(!ZC.AK(1b+"-5c")){1a B=t.E.5c,v=ZC.P.F2("4d",ZC.1b[36]);v.aa?"zc."===t.D6.2v(0,3)?v.aa(ZC.1b[37],"7B",ZC.c0[t.D6]):v.aa(ZC.1b[37],"7B",t.D6):"zc."===t.D6.2v(0,3)?v.4m("5a",ZC.c0[t.D6]):v.4m("5a",t.D6),1c!==ZC.1d(t.E["3t-2R"])&&ZC.P.G3(v,{"3t-2R":"3R(#"+t.E["3t-2R"]+")"}),ZC.P.G3(v,{id:1b+"-5c",x:B[1],y:B[2],"3i-3o":t.C4,1s:t.E[ZC.1b[69]],1M:t.E[ZC.1b[70]],u7:"2b"}),ZC.CN.jo(e,t,v)}}},UA:1n(e,t,i,a){1a n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DN,KA,IO"),e}5S(){}1S(e){1D.1S(e);1a t,i,a=1g,n="BJ,BB,DP,AH,KZ,AA,DN,KA,IO".2n(",");1j(t=0,i=n.1f;t<i;t++)1y e[n[t]]!==ZC.1b[31]&&(a[n[t]]=e[n[t]]);if(e.C&&e.C.1f>0)1j(a.C=[],t=0,i=e.C.1f;t<i;t++)a.C.1h(e.C[t])}hb(e,t){1a i=1g;-1!==(""+e).1L("fh")&&(t="y"),-1!==(""+e).1L("eM")&&(t="x"),e=ZC.1W((""+e).1F("fh","").1F("eM",""));1a a=1o.4Y.4Y[i.eC];1l a&&(e=1o.4Y.10f(a.bF.x,a.bF.y,a.bF.1s,a.bF.1M,"x"===t?[e,0]:[0,e],a.bF.wf,{3c:i.eC,1Q:i.p9,3G:a.bF.3G,mO:a.bF.mO,mS:a.bF.mS},!0)),e=ZC.1k("x"===t?e[0]:e[1])}pI(e,t){1a i;-1!==(""+e).1L("8t")&&(t="y"),-1!==(""+e).1L("81")&&(t="x"),e=ZC.1W((""+e).1F("81","").1F("8t",""));1a a=1g.H||1o.HY[0];if(a){1a n=1g.A||a.AI[0];n&&("x"===t?1c!==(i=n.BT("k")[0])&&(e=ZC.1k(i.B2(e))):1c!==(i=n.BT("v")[0])&&(e=ZC.1k(i.B2(e))))}1l ZC.1k(e)}c4(e,t,i){1a a=1g;t=t||"x";1a n=""+e;if(-1!==n.1L("fh")||-1!==n.1L("eM"))1l a.hb(e,t);if(-1!==n.1L("8t")||-1!==n.1L("81"))1l a.pI(e,t);if(""+ZC.1W(e)!==n)1l-1!==(e+="").1L("%")?a.c4(5P(e.1F("%",""))/100,t,!0):-1!==e.1L("px")?a.c4(5P(e.1F("px","")),t):a.c4(5P(e),t);1a l=1y a.E["p-x"]!==ZC.1b[31]?a.E["p-x"]:a.A.iX,r=1y a.E["p-y"]!==ZC.1b[31]?a.E["p-y"]:a.A.iY,o=1y a.E["p-1s"]!==ZC.1b[31]?a.E["p-1s"]:a.A.I,s=1y a.E["p-1M"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C+A.BJ)+","+ZC.1k(A.iY+C+A.BB)+","+ZC.1k(A.AH)];1i"3z":1i"6u":1l["3z",ZC.1k(A.iX+C+A.BJ)+","+ZC.1k(A.iY+C+A.BB)+","+ZC.1k(A.AH+2)];1i"3O":1l["4C",A.EX()];2q:1a c,p=["4C"];1j(i=[],e=0,t=A.C.1f;e<t;e++)if(1c!==A.C[e])if(6===A.C[e].1f)1j(1a u=A.C[e][3];u<A.C[e][4];u+=1)i.1h(ZC.AQ.BN(A.C[e][0],A.C[e][1],A.C[e][2],u));1u if(4===A.C[e].1f&&i[e-1]){1a h={x:i[i.1f-1][0],y:i[i.1f-1][1]},1b={x:A.C[e][2],y:A.C[e][3]},d={x:A.C[e][0],y:A.C[e][1]};1j(c=0;c<=1;c+=.1)i.1h([(1-c)*(1-c)*h.x+2*c*(1-c)*d.x+c*c*1b.x,(1-c)*(1-c)*h.y+2*c*(1-c)*d.y+c*c*1b.y])}1u if(7===A.C[e].1f&&i[e-1]){1a f={x:i[i.1f-1][0],y:i[i.1f-1][1]},g={x:A.C[e][0],y:A.C[e][1]},B={x:A.C[e][2],y:A.C[e][3]},v={x:A.C[e][4],y:A.C[e][5]};1j(c=0;c<=1;c+=.1){1a b=(1-c)*(1-c)*(1-c),m=3*c*(1-c)*(1-c),E=3*c*c*(1-c),D=c*c*c;i.1h([b*f.x+m*g.x+E*B.x+D*v.x,b*f.y+m*g.y+E*B.y+D*v.y])}}1u i.1h(A.C[e]);1u i.1f>-1&&p.1h(ZC.AQ.Q0(i,1B.2j(5,A.AH/5),[A.BJ,A.BB])),i=[];if(0!==A.AA)1j(a=ZC.1k((A.CW[0]+A.CW[2])/2),n=ZC.1k((A.CW[1]+A.CW[3])/2),e=0,t=i.1f;e<t;e++)1c!==i[e]&&(l=i[e][0]-a,r=i[e][1]-n,o=l*ZC.EC(A.AA)-r*ZC.EH(A.AA),s=l*ZC.EH(A.AA)+r*ZC.EC(A.AA),i[e]=[o+a,s+n]);1l i.1f>-1&&p.1h(ZC.AQ.Q0(i,1B.2j(5,A.AH/5),[A.BJ,A.BB])),p}}1q(e){1a t,i,a,n,l,r,o;1c===ZC.1d(e)&&(e=!1),1g.o.cf||e||1D.1q();1a s=1g;if(!s.o.cf&&!e){s.4y([["3c","eC"]]),"3e"==1y s.o.1Q&&s.4y([["1Q","p9"]]),0!==s.eC&&(1c===ZC.1d(s.o["3c-1Q"])||s.o["3c-1Q"])&&(s.o["3c-1Q"]=!0,s.o["3c-aP-z-4i"]=!0);1a A=["2c-x","2c-y"];1j(i=0;i<2;i++){1a C=A[i],Z="2c-x"===C?"eM":"fh";if(1c!==(t=s.o[C])&&1y t!==ZC.1b[31]&&-1!==(t=""+t).1L(Z)){t=ZC.1W(t.1F(Z,""));1a c=1o.4Y.4Y[s.eC];c&&(t=1o.4Y.7f(C.1F("2c-"),t,s.A.I,s.A.F,c.bF.wf),s.o[C]=t)}}1j(s.4y([["3R","E1"],["2X","FA"],["4V","IO"],["id","H1"],["2f","AA","i"],["8L","KA","b"],["7J","KA","b"],[ZC.1b[1],"B0","f"],[ZC.1b[2],"BH","f"],[ZC.1b[8],"CJ","i"],[ZC.1b[21],"AH","f"],["2e-2","KZ","f"],["8F-dC-2R","QT","b"],["1J","DN"],["2W","C"],["2c-x","BJ"],["2c-y","BB"],["2c-z","rR","i"],["2c-r","DP","i"],["z-4i","lb","i"],["z-3b","JP","f"],["10v","h3"]]),s.BJ=ZC.IH(s.BJ,!0),s.BB=ZC.IH(s.BB,!0),s.BJ>-1&&s.BJ<1&&1y s.E["p-1s"]!==ZC.1b[31]&&(s.BJ*=s.E["p-1s"]),s.BB>-1&&s.BB<1&&1y s.E["p-1M"]!==ZC.1b[31]&&(s.BB*=s.E["p-1M"]),s.AH=ZC.BM(1,s.AH),s.KZ=ZC.BM(1,s.KZ),1c!==s.o["z-4i"]&&1y s.o["z-4i"]!==ZC.1b[31]||(s.lb=s.JP),"fi"!==s.DN&&"5n"!==s.DN||s.4y([[ZC.1b[19],"AH","f"],[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AQ.BN(Y,x,w,y),ZC.AQ.BN(Y,x,M,y),[Y,x,M,y,X,1])}s.C.1h([s.C[0][0],s.C[0][1]])}}s.9n(2)}1t(){1a e=1g;if("2b"!==e.DN&&("5D"===e.DN||"3z"===e.DN||"6u"===e.DN||0!==e.C.1f)){1a t,i,a={x:"iX",y:"iY",1s:"I",1M:"F",2e:"AH"};if(e.o["2a-3X"]&&!e.YN&&!e.WG&&!e.fS){1a n=1m DT(e.A);1j(t in n.1S(e),n.fS=!0,n.MC=!1,n.Z=e.Z,n.1C(e.o["2a-3X"]),n.J=e.J+"-2a",n.1q(),i=!1,a)1c===ZC.1d(n.o[t])||-1===(""+n.o[t]).1L("+")&&-1===(""+n.o[t]).1L("-")||(n.o[t]=n[a[t]]=e[a[t]]+ZC.1k(n.o[t])),i&&n.1q();n.1t()}1a l=e.H.AB;1P(e.MC&&e.C7&&e.kH(),l){1i"3a":e.WS();1p;1i"2F":e.UB();1p;1i"3K":e.UA()}if(e.o["1v-3X"]&&!e.YN&&!e.WG&&!e.fS){1a r=1m DT(e.A);1j(t in r.1S(e),r.WG=!0,r.MC=!1,r.Z=e.Z,r.1C(e.o["1v-3X"]),r.J=e.J+"-1v",r.1q(),i=!1,a)1c===ZC.1d(r.o[t])||-1===(""+r.o[t]).1L("+")&&-1===(""+r.o[t]).1L("-")||(r.o[t]=r[a[t]]=e[a[t]]+ZC.1k(r.o[t]),i=!0);i&&r.1q(),r.1t()}}}kH(){1a e,t=1g,i=1m DT(t.A);i.J=t.J+"-sh",i.1S(t),i.O9=t.O9,i.Z=t.C7,i.MC=!1,i.YN=!0,i.A0=i.AD=i.S1,i.GM=i.HL="",i.D6="",i.G8="2V",i.BU=i.S1,i.AX=0,i.C4=i.T8*t.C4,i.J=t.J+"-sh";1a a=(t.JR-t.PB)*ZC.EC(t.OI)+t.PB,n=(t.JR-t.PB)*ZC.EH(t.OI)+t.PB;if(i.iX=t.iX+5v(a,10),i.iY=t.iY+5v(n,10),i.AH=t.AH+t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="3C",t.I=0,t.F=0,t.rw="",t.E2=-1,t.E6=-1,t.DR=-1,t.DZ=-1,t.F1=0,t.FQ=0,t.EY=0,t.F9=0,t.qD=!1,t.KQ=!1,t.EP="2a",t.ET=0,t.MA=0,t.H3=8,t.G2=8,t.Y0=[1,1],t.DH=1c,t.OP=1c,t.Q2=!1,t.ON=!0,t.Q4="",t.OJ="",t.NT="",t.PF="",t.X4="tl",t.F8=!1}7W(){1a e=1D.7W();1l 1g.dE(e,"1s,1M,136,13c,13f,13g,6G,184,wL,13i,13j,13l,13p,13s,2K,xc,lm,oa,lB,14n","I,F,F1,FQ,EY,F9,KQ,EP,DH,H3,G2,ET,MA,rw,Q4,OJ,NT,PF,F8"),e}5S(){}jc(e,t,i){1a a=1g;if(t=t||"w",ZC.1W(e)+""!=e+"")1l-1!==(e+="").1L("%")?a.jc(ZC.1W(e.1F("%",""))/100,t,!0):-1!==e.1L("px")?a.jc(ZC.1W(e.1F("px","")),t):a.jc(ZC.1W(e),t);1a n=1y a.E["p-1s"]!==ZC.1b[31]?a.E["p-1s"]:a.A.I,l=1y a.E["p-1M"]!==ZC.1b[31]?a.E["p-1M"]:a.A.F;1l(e=ZC.2l(e))>1&&!i?ZC.1k(e):e<=1||i?"w"===t?ZC.1k(n*e):ZC.1k(l*e):8j 0}5Z(e,t,i,a,n){1a l,r,o=1g;if(i=i||0,a=a||0,t=t||"4t",n=n||"n","4t"===t){1a s=6d(e).2n(/\\s+|;|,/);1l 1===s.1f?[o.5Z(s[0],"tb",i,a,n),o.5Z(s[0],"lr",i,a,n),o.5Z(s[0],"tb",i,a,n),o.5Z(s[0],"lr",i,a,n)]:2===s.1f?[o.5Z(s[0],"tb",i,a,n),o.5Z(s[1],"lr",i,a,n),o.5Z(s[0],"tb",i,a,n),o.5Z(s[1],"lr",i,a,n)]:3===s.1f?[o.5Z(s[0],"tb",i,a,n),o.5Z(s[1],"lr",i,a,n),o.5Z(s[2],"tb",i,a,n),o.5Z(s[1],"lr",i,a,n)]:[o.5Z(s[0],"tb",i,a,n),o.5Z(s[1],"lr",i,a,n),o.5Z(s[2],"tb",i,a,n),o.5Z(s[3],"lr",i,a,n)]}1l e+""=="3g"?-2:e+""=="4N"&&"y"===n?"4N":ZC.1W(e)+""!=e+""?-1!==(e+="").1L("%")?o.5Z(ZC.1W(e.1F("%",""))/100,t):-1!==e.1L("px")?o.5Z(ZC.1W(e.1F("px","")),t):o.5Z(ZC.1W(e),t):((o.A||1y o.E["p-1s"]!==ZC.1b[31])&&(l=1y o.E["p-1s"]!==ZC.1b[31]?o.E["p-1s"]:o.A.I),(o.A||1y o.E["p-1M"]!==ZC.1b[31])&&(r=1y o.E["p-1M"]!==ZC.1b[31]?o.E["p-1M"]:o.A.F),(e=ZC.2l(e))>=1?ZC.1k(e):e<1?"lr"===t?ZC.1k((o.A?l:i)*e):ZC.1k((o.A?r:a)*e):8j 0)}1S(e){1D.1S(e);1j(1a t="I,F,E2,DR,DZ,E6,F1,FQ,EY,F9,KQ,EP,DH,Y0,H3,G2,ET,MA,rw,Q4,OJ,NT,PF,F8".2n(","),i=0,a=t.1f;i<a;i++)1y e[t[i]]!==ZC.1b[31]&&(1g[t[i]]=e[t[i]])}9n(e){1a t,i,a,n,l,r=1g;if(2!==(e=e||1))if(r.TW)r.4y([["x","iX"],["y","iY"],[ZC.1b[19],"I"],[ZC.1b[20],"F"]]);1u{1a o=1y r.E["p-x"]!==ZC.1b[31]?r.E["p-x"]:r.A.iX,s=1y r.E["p-y"]!==ZC.1b[31]?r.E["p-y"]:r.A.iY,A=1y r.E["p-1s"]!==ZC.1b[31]?r.E["p-1s"]:r.A.I,C=1y r.E["p-1M"]!==ZC.1b[31]?r.E["p-1M"]:r.A.F;if(!r.Q2){1a Z=0,c=0,p=0,u=0;if(1c!==ZC.1d(r.o.2y)){1a h=""+r.o.2y;if(-1!==h.1L("4N")){1a 1b=r.5Z(h,"4t",0,0,"y");"4N"===1b[0]&&(r.E["d-2y-1v"]=r.E["d-2y"]=!0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F):-2===Z&&-2===p?(r.E2=r.DR=(C-r.F)/2,r.iY=s+r.E2):-2===Z&&-2!==p?(r.DR=p,r.E2=C-r.DR-r.F,r.iY=s+r.E2):(r.E2=Z,r.iY=s+r.E2,r.DR=r 3E DM?p:C-r.E2-r.F)}1u-1!==r.iY?(r.E2=r.iY-s,r.DR=-2===p?0:p,r.F=C-r.E2-r.DR):-2===Z&&-2===Z?(r.E2=r.E2=0,r.iY=s+r.E2,r.F=C-r.E2-r.DR):-2===Z&&-2!==p?(r.DR=p,r.E2=0,r.iY=s+r.E2,r.F=C-r.E2-r.DR):-2===Z&&-2!==p?(r.E2=Z,r.DR=r 3E DM?p:0,r.iY=s+r.E2,r.F=C-r.E2-r.DR):(r.E2=Z,r.DR=p,r.iY=s+r.E2,r.F=C-r.E2-r.DR);if(1c!==(t=ZC.1d(r.o.2K))){if(r.A&&1y r.A.iX!==ZC.1b[31]&&1y r.A.iY!==ZC.1b[31]&&1y r.A.I!==ZC.1b[31]&&1y r.A.F!==ZC.1b[31]){1P(a=0,n=0,(l=6d(t).2n(/\\s+/))[0]){1i"1K":a=0;1p;1i"2A":a=1;1p;1i"3F":a=.5;1p;2q:(a=ZC.IH(l[0]))>1&&(a/=r.A.I)}1P(l[1]){1i"1v":n=0;1p;1i"2a":n=1;1p;1i"6n":n=.5;1p;2q:(n=ZC.IH(l[1]))>1&&(n/=r.A.F)}}r.E["2K-6E"]=[a,n],r.iX=r.A.iX+ZC.1k(a*(r.A.I-r.I-v[1]-v[3]))+v[3],r.iY=r.A.iY+ZC.1k(n*(r.A.F-r.F-v[0]-v[2]))+v[0]}r.CW=[r.iX,r.iY,r.iX+r.I,r.iY+r.F]}}}1q(){1D.1q();1a e,t=1g;if(!t.o.cf){if(t.4y([["bp","X4"],["5n-zp","F8","b"],["3F-3T","qD","b"],["6G","KQ","b"],["6G-1J","14r"],["6G-2K","EP"],["6G-7q","DH"],["6G-eD","Y0"],["6G-1s","H3","i"],["6G-1M","G2","i"],["6G-2c","ET","i"],["6G-rj","MA","i"],["1G-1v","Q4"],["1G-2A","OJ"],["1G-2a","NT"],["1G-1K","PF"]]),1c!==(e=ZC.1d(t.o["1G-9i"]))){1a i=6d(e).2n(/\\s+|;|,/);2===i.1f?(t.F1=t.FQ=ZC.1k(i[0]),t.EY=t.F9=ZC.1k(i[1])):4===i.1f?(t.F1=ZC.1k(i[0]),t.FQ=ZC.1k(i[1]),t.EY=ZC.1k(i[2]),t.F9=ZC.1k(i[3])):t.F1=t.FQ=t.EY=t.F9=ZC.1k(i[0])}1c!==ZC.1d(t.o["6G-mL"])&&(t.OP=1m DT(t.A)),t.4y([["1G-9i-1v-1K","F1","i"],["1G-9i-1v-2A","FQ","i"],["1G-9i-2a-2A","EY","i"],["1G-9i-2a-1K","F9","i"]])}}V8(e){1a t=e.2n(/\\s/);1l t[0]=ZC.1k(t[0]),t[2]=ZC.AO.G7(t[2]),t}1t(){1a e=1g;if(1c!==e.DH&&!(e.DH 3E 3M)&&"vG"===e.A.OD){1a t=e.A.OG(e.DH);e.DH=[t[0],t[1]],e.DH[0]-=e.BJ,e.DH[1]-=e.BB}if(e.qD&&(e.iX-=e.I/2,e.iY-=e.F/2),"-1"!==e.BU&&0!==e.AP||e.Q4+e.OJ+e.NT+e.PF!==""||"-1"!==e.A0||"-1"!==e.AD||""!==e.D6||""!==e.GM||""!==e.HL){1a i=e.H.AB;e.MC&&e.C7&&e.kH();1a a,n={x:"iX",y:"iY",1s:"I",1M:"F"};if(e.o["2a-3X"]&&!e.YN&&!e.fS&&!e.WG){1a l=1m I1(-1===e.A.iX&&-1===e.A.iY?e:e.A);1j(a in l.1S(e),l.fS=!0,l.MC=!1,l.Z=e.Z,l.X4=e.X4,l.1C(e.o["2a-3X"]),l.J=e.J+"-2a",l.1q(),l.gC(),n)1c===ZC.1d(l.o[a])||-1===(""+l.o[a]).1L("+")&&-1===(""+l.o[a]).1L("-")||(l[n[a]]=e[n[a]]+ZC.1k(l.o[a]));l.1t()}if(e.Q4+e.OJ+e.NT+e.PF===""){1P(i){1i"3a":e.WS();1p;1i"2F":e.UB();1p;1i"3K":e.UA()}if(e.KQ&&e.OP){1a r,o;if(e.DH&&2===e.DH.1f?(r=e.DH[0],o=e.DH[1]):e.E.cp&&(r=e.E.cp[0],o=e.E.cp[1]),e.OP.Z=e.OP.C7=e.Z,e.OP.1S(e),e.OP.1C(e.o["6G-mL"]),e.OP.J=e.J+"-6G-mL",e.OP.o.x=r,e.OP.o.y=o,e.E.cm){1a s=e.E.cm[0],A=e.E.cm[1],C=1B.sr(ZC.1k(A)-ZC.1k(o),ZC.1k(s)-ZC.1k(r));7X(C)&&(C=0),1c===ZC.1d(e.OP.o.2f)&&(e.OP.o.2f=ZC.UE(C))}e.OP.1q(),e.OP.1t()}}1u{1a Z=e.AP,c=e.BU,p=e.G8;1P(e.AP=0,i){1i"3a":e.WS();1p;1i"2F":e.UB();1p;1i"3K":e.UA()}e.AP=Z;1a u=e.A0,h=e.AD;e.A0=e.AD="-1";1j(1a 1b,d=["1v","2A","2a","1K"],f=["Q4","OJ","NT","PF"],g=0;g<d.1f;g++)if(""!==(1b=e[f[g]])&&"2b"!==1b){1a B=e.V8(1b);1P(e.AP=B[0],e.G8=B[1],e.BU=B[2],i){1i"3a":e.WS(d[g]);1p;1i"2F":e.UB(d[g]);1p;1i"3K":e.UA(d[g])}e.AP=Z,e.BU=c,e.G8=p}e.A0=u,e.AD=h}if(e.o["1v-3X"]&&!e.YN&&!e.WG&&!e.fS){1a v=1m I1(-1===e.A.iX&&-1===e.A.iY?e:e.A);1j(a in v.1S(e),v.WG=!0,v.MC=!1,v.Z=e.Z,v.X4=e.X4,v.1C(e.o["1v-3X"]),v.J=e.J+"-1v",v.1q(),v.gC(),n)1c===ZC.1d(v.o[a])||-1===(""+v.o[a]).1L("+")&&-1===(""+v.o[a]).1L("-")||(v[n[a]]=e[n[a]]+ZC.1k(v.o[a]));v.1t()}}}gC(){1a e=1g;1P(e.X4){1i"tl":1p;1i"tr":e.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6U,bH,hh,dv,ca,di,d6,d8,1E","OA,JW,DE,GC,C1,gJ,7C,N2,QO,KB,FM,FN,FY,EN,AN"),e}1S(e){1D.1S(e);1j(1a t="OA,JW,DE,GC,C1,gJ,7C,N2,KB,QO,FM,FN,FY,EN,AN".2n(","),i=0,a=t.1f;i<a;i++)1y e[t[i]]!==ZC.1b[31]&&(1g[t[i]]=e[t[i]])}EW(e){1l e}mi(e){1l"6x"===e||"14I"===e||"kj"===e||"qQ"===e||"14J"===e||"14K"===e||"x5"===e}eV(e){1a t=1g;if(t.WW)1l e.1F(/(<([^>]+)>)/gi,"").1f*t.DE/(t.qU*(t.mi(t.7C)?.87:1)*(t.N2?.95:1));1a i="";1l 1y t.o["4g-4E"]!==ZC.1b[31]&&ZC.2s(t.o["4g-4E"])&&(i="[sf]"),ZC.P.lz(1g.H.J,i+e,1g.GC,1g.DE,1g.7C,1g.FE)}1q(){1g.I=1g.F=1g.NM=1g.KO=0,1D.1q();1a e,t,i,a,n,l=1g;if(!l.o.cf){if(l.YS("1E","AN"),1c!==ZC.1d(l.AN)&&(l.AN=""+l.AN,l.AN=l.EW(l.AN),l.AN=l.AN.1F(/\\n/g,"<br>").1F(/\\\\n/g,"<br>"),"2F"===l.H.AB&&(l.AN=l.AN.1F(/&8u;/g," "))),l.4y([["iy","sn","b"],["8F-1s","WW","b"],["1X-1s","OR","i"],["1w-1M","FE","i"],["1s-eD","qU","f"],["14B-1E","iE","b"],["3t-1E","sF","b"],["6x","gJ","b"],["bH","N2","b"],["hh","QO","b"],["1E-bS","KB"],["aH","gF","b"],["1E-3u","OA"],["3u","OA"],["9l-3u","JW"],["2t-2e","DE","f"],["1X-qZ","YM","i"],["2t-9B","GC"],["2t-2f","AA","i"],["1r","C1","c"],["2t-1r","C1","c"],["1E-2o","WY","f",0,1],["14m-sa","VN","b"]]),l.DE=ZC.BM(1,l.DE),1c===ZC.1d(l.o["1E-2o"])&&(l.WY=l.C4),l.gJ&&(l.7C="6x"),1c!==(e=ZC.1d(l.o["2t-79"]))&&(l.7C=e),1c===ZC.1d(l.o["1E-bS"])&&(l.KB=l.QO?"hh":"2b"),1c!==(e=ZC.1d(l.o["2t-1I"]))&&(l.N2="bH"===e||"bQ"===e),1c!==(e=ZC.1d(l.o.3v))){1a r=6d(e).2n(/\\s+|;|,/);t=1===r.1f?[ZC.1k(r[0]),ZC.1k(r[0]),ZC.1k(r[0]),ZC.1k(r[0])]:2===r.1f?[ZC.1k(r[0]),ZC.1k(r[1]),ZC.1k(r[0]),ZC.1k(r[1])]:3===r.1f?[ZC.1k(r[0]),ZC.1k(r[1]),ZC.1k(r[2]),ZC.1k(r[0])]:[ZC.1k(r[0]),ZC.1k(r[1]),ZC.1k(r[2]),ZC.1k(r[3])],l.FM=t[0],l.FN=t[1],l.FY=t[2],l.EN=t[3]}if(l.4y([["3v-1v","FM","i"],["3v-2A","FN","i"],["3v-2a","FY","i"],["3v-1K","EN","i"]]),l.AN){l.YM>0&&l.AN.1f>l.YM&&(l.AN=l.AN.2v(0,l.YM)+"...");1a o=l.AN.2n(/<br>|<br\\/>|<br \\/>|\\n/),s="";1y l.o["4g-4E"]!==ZC.1b[31]&&ZC.2s(l.o["4g-4E"])&&(o=[l.AN],s="[sf]");o.1f;1j(l.KO=ZC.P.lz(1g.H.J,s+l.AN,1g.GC,1g.DE,1g.7C,1g.FE,!0)+l.FM+l.FY,i=0,a=o.1f;i<a;i++)l.NM=ZC.BM(l.NM,l.eV(o[i])+l.EN+l.FN)}1u l.AN="",l.NM=ZC.1k(1.25*l.DE),l.KO=-1===l.FE?ZC.1k(1.25*l.DE):l.FE;if((1c===ZC.1d(l.o[ZC.1b[19]])||7X(l.I)||0===l.I)&&(l.I=l.NM),(1c===ZC.1d(l.o[ZC.1b[20]])||7X(l.F)||0===l.F)&&(l.F=l.KO),l.I=ZC.CQ(l.I,l.OR),l.iE&&l.NM>l.I&&!l.E.si&&l.I>2*l.DE){1a A,C="",Z=0,c=l.AN.1F(/<br>/gi," [##] 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,t.kq=1,t.MI=1c,t.SI="",t.ug="F*11v$11X!",t.MF="",t.d9={},t.lG=!1,t.AB="",t.KI=1c,t.gT=!1,t.QQ=["",""],t.L8=0,t.KP=[],t.jr=0,t.jE=0,t.dZ=!1,t.jx="",t.uQ=!0,t.I7=1c,t.QS=[],t.NY=0,t.12w=!1,t.SJ={},t.lg=!1,t.FZ=1o.3J.kz?{}:1c,t.mb=!1,t.T1=[]}q0(e){1a t=1g;if(e)1j(1a i=t.T1.1f-1;i>=0;i--)t.T1[i].1J===e&&t.T1.6r(i,1);1u t.T1=[]}2Q(){1l-1!==ZC.AU(1g.KP,ZC.1b[44])}mc(e){1l e=e||"",ZC.AK(1g.J+"-3Y-c"+(""===e?e:"-"+e))}9h(){1a e;(e=ZC.AK(1g.J+"-2C"))&&(e.1I.3L="2b"),1g.dZ=!1}XV(){1j(1a e=1g,t=e.NW.1f,i=0;i<t;i++)if(1c!==ZC.1d(e.NW[i])){1P(e.AB){1i"2F":ZC.CN.UB(e.NW[i].bo,e.NW[i].1I,e.NW[i].2R.2M(" "),e.NW[i].ab);1p;1i"3K":ZC.CN.UA(e.NW[i].bo,e.NW[i].1I,e.NW[i].2R.2M(" "),e.NW[i].ab)}e.NW[i]=1c}}nN(){1a s=1g,i,A2,FG,fm;fm="s4:"===2g.89.hM?ZC.12G||"":2g.89.12I;1a cg=[fm],CU=fm.2n(".");1j("8z"===CU[0]?cg.1h(fm.1F("8z.","")):cg.1h("8z."+fm),i=0;i<=CU.1f-2;i++){1j(1a rV="*",j=i;j<CU.1f;j++)rV+="."+CU[j];cg.1h(rV)}1n XH(e){if(ZC.rU&&ZC.rU 3E 3M){1a t=ZC.Y3.du(ZC.sK(ZC.mj(e)));-1!==ZC.AU(ZC.rU,t)&&(s.vm=!0)}}if(-1!==ZC.AU(cg,"vz")||-1!==ZC.AU(cg,"127.0.0.1"))s.TX=!0,s.jC=!0,XH("vz");1u{1a mt=[["2w.AC.12L.12M","Q^12N]12O`12P^`12Q[12R"],["2w.12S.12U","12V/12K+12v/12i/12u/+123+124/129="]];1j(i=0,A2=mt.1f;i<A2;i++)4J{if(7l(mt[i][0])===ZC.mj(mt[i][1])){s.TX=!0;1p}}4M(e){}1j(i=0,A2=cg.1f;i<A2;i++){1a sA=ZC.Y3.du(ZC.sK(ZC.mj(cg[i])));ZC.un 3E 3M&&-1!==ZC.AU(ZC.un,sA)&&(s.TX=!0,XH(sA))}ZC.il 3E 3M&&2===ZC.il.1f&&(FG=ZC.uh(s.ug),FG=FG.1F("O","0"),s.SI=ZC.ui(ZC.il[0],FG),s.SI===ZC.il[1]&&(s.TX=!0,s.jC=!0,XH(ZC.il[0])))}}ls(){1a e=1g;if(1c!==e.MO)ZC.6y(e.MO),e.2x();1u if(1c===ZC.1d(ZC.4f.1V["cr-"+e.QL])){1a t=["g5-3e"===e.N3?"eK="+1B.cb():"",1o.hd?"lx="+e.AB:""].2M("&");ZC.A3.a8({1J:"bL",3R:e.QL,pK:"1E",ej:1n(t){e.S0.cr||"7h-f0"!==e.N3||t.cn(ZC.1b[45],"cl, 8H ci dJ 6X:6X:6X dF")},1V:t,4L:1n(t,i,a,n){1l e.NC({8C:ZC.1b[63],b8:"bB cR fG ("+n+")"},ZC.1b[64]),!1},aF:1n(t){1a i;4J{i=3h.1q(t),ZC.4f.1V["cr-"+e.QL]=t}4M(a){1l e.NC(a,"3h mQ"),!1}e.MO=i,ZC.6y(e.MO),e.2x()}})}1u{1a i;4J{i=3h.1q(ZC.4f.1V["cr-"+e.QL])}4M(a){1l e.NC(a,"3h mQ"),!1}e.MO=i,ZC.6y(e.MO),e.2x()}}2x(e,t){1a i=1g;if(i.MF="2x",""!==(t=t||i.QK)&&0!==t.1L("7u:"))if(1c===ZC.1d(ZC.4f.1V["1V-"+t])){1a a=["g5-3e"===i.N3?"eK="+1B.cb():"",1o.hd?"lx="+i.AB:""].2M("&");ZC.A3.a8({1J:"bL",3R:t,pK:"1E",ej:1n(e){i.S0.1V||"7h-f0"!==i.N3||e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ZC.AO.C8("Uh",s,{id:s.J}),1c===ZC.1d(JH))s.VQ(DF),s.o=DF,s.dR?(s.1q(),s.1t()):s.OQ(1n(){s.1q(),s.1t()});1u{1a e=s.OH(JH);if(1c!==e&&1c!==ZC.1d(G=DF[ZC.1b[16]])){1a t=G.1f>1?G[e.L]:G[0];t.id||(t.id=e.o.id||""),s.o[ZC.1b[16]][e.L]=t,s.OQ(1n(){s.1q(JH),s.AI[e.L].1t()})}}})})}VQ(DF){1a s=1g,G,i,A2,j,J8;1j(1c===ZC.1d(DF[ZC.1b[16]])&&(DF={aY:[DF]}),1===DF[ZC.1b[16]].1f&&1c===ZC.1d(DF[ZC.1b[16]][0])&&(DF[ZC.1b[16]]=[{1J:"1c"}]),i=0,A2=DF[ZC.1b[16]].1f;i<A2;i++)if(1c!==ZC.1d(DF[ZC.1b[16]][i])){if(1c!==ZC.1d(G=DF[ZC.1b[16]][i].5L)){1a FC=[];1j(DF[ZC.1b[16]][i][ZC.1b[10]]=DF[ZC.1b[16]][i][ZC.1b[10]]||[],j=0,J8=G.1f;j<J8;j++)if(G[j].fr&&G[j]["3c-1Q"]||FC.1h(G[j]),1c!==ZC.1d(G[j].1J)&&0===G[j].1J.1L("1o."))4J{1a M5=G[j].uq||{},EF=G[j].1J+"."+(M5.8C||"");M5[ZC.1b[3]]=i;1a ft=7l(EF).4x(s,M5,DF,G[j]);1j(1a ih in ft)ft.8d(ih)&&("1H"===ft[ih].mP?DF[ZC.1b[16]][i][ZC.1b[10]].1h(ft[ih]):FC.1h(ft[ih]))}4M(e){}DF[ZC.1b[16]][i].5L=FC}1a mI;if(1c!==ZC.1d(mI=DF[ZC.1b[16]][i].fH))1j(1a xC=s.or(DF,i),k=0;k<mI.1f;k++){1a fK=mI[k];if(1c!==ZC.1d(fK.1J)&&1c!==ZC.1d(1o.fH[fK.1J])&&"1n"==1y 1o.fH[fK.1J].1q)4J{1a BO={};ZC.2E(fK,BO),BO.2Y=xC.2Y,BO.6A={id:s.J,1s:s.I,1M:s.F};1a o=1o.fH[fK.1J].1q.4x(s,BO);if(1c!==ZC.1d(G=o.Gr))1j(j=0;j<G.1f;j++)DF[ZC.1b[16]].1h({}),ZC.2E(G[j],DF[ZC.1b[16]][DF[ZC.1b[16]].1f-1]);if(1c!==ZC.1d(G=o[ZC.1b[10]]))1j(1c===ZC.1d(DF[ZC.1b[16]][i][ZC.1b[10]])&&(DF[ZC.1b[16]][i][ZC.1b[10]]=[]),j=0;j<G.1f;j++)DF[ZC.1b[16]][i][ZC.1b[10]].1h(G[j]);if(1c!==ZC.1d(G=o.5L))1j(1c===ZC.1d(DF[ZC.1b[16]][i].5L)&&(DF[ZC.1b[16]][i].5L=[]),j=0;j<G.1f;j++)DF[ZC.1b[16]][i].5L.1h(G[j])}4M(e){}}}}w2(e,t){1a i=1g;1P(e){1i"1w":1l 1m qa(i);1i"1N":1l 1m q7(i);1i"bj":1l 1m Gc(i);1i"bv":1l 1m Fv(i);1i"2U":1i"5t":1i"8U":1l 1m lu(i);1i"6c":1l 1m lv(i);1i"9u":1i"gO":1i"aX":1j(1a a=!1,n=i.o[ZC.1b[16]][t][ZC.1b[11]],l=0,r=n.1f;l<r;l++)n[l]&&n[l].1J&&-1!==n[l].1J.1L("3d")&&(a=!0);1l a?1m nG(i):i.o[ZC.1b[16]][t].1A&&i.o[ZC.1b[16]][t].1J&&i.o[ZC.1b[16]][t].1A&&i.o[ZC.1b[16]][t].1A.1J&&-1!==i.o[ZC.1b[16]][t].1A.1J.1L("3d")?1m nG(i):"9u"===e?1m nD(i):1m Fq(i);1i"6v":1l 1m Fy(i);1i"8r":1l 1m Ga(i);1i"5m":1l 1m DO(i);1i"6V":1l 1m Fl(i);1i"9H":1i"3O":1l 1m qh(i);1i"8S":1l 1m Dj(i);1i"7d":1i"pR":1l 1m Dl(i);1i"b7":1l 1m Fh(i);1i"g7":1i"8i":1l 1m Dr(i);1i"7R":1l 1m Ds(i);1i"qA":1i"aA":1l 1m Dg(i);1i"aB":1l 1m Cw(i);1i"xt":1i"5V":1l 1m Dx(i);1i"84":1l 1m Cp(i);1i"5z":1l 1m Cu(i);1i"qw":1l 1m Cn(i);1i"8D":1l 1m Cr(i);1i"97":1l 1m Da(i);1i"83":1l 1m Dy(i);1i"ql":1i"7e":1l 1m Cx(i);1i"dN":1i"6O":1l 1m Cz(i);1i"7k":1l 1m Cy(i);1i"n8":1l 1m Gb(i);2q:1l 1m Fp(i)}}OH(e){1j(1a t=1g,i=0,a=t.AI.1f;i<a;i++)if(t.AI[i].J===t.J+"-2Y-"+e||t.AI[i].J===t.J+"-2Y-id"+e||t.AI[i].J===e||i===e)1l t.AI[i];1l 1c}mu(e,t){1a i=1g,a=ZC.A3("#"+i.J+("2F"===i.AB?"-1v":"-3Y")),n=ZC.aE(i.J);e-=a.2c().1K,t-=a.2c().1v;1j(1a l=1c,r=0,o=i.AI.1f;r<o;r++)ZC.E0(e,i.AI[r].iX,i.AI[r].iX+i.AI[r].I*n[0])&&ZC.E0(t,i.AI[r].iY,i.AI[r].iY+i.AI[r].F*n[1])&&(l=i.AI[r]);1l l}qr(e){1a t,i=1g;if(1y i.E.xo===ZC.1b[31]){1y e===ZC.1b[31]&&(e=!1),i.4y([["bx","LO"]]),i.o[ZC.1b[16]]&&1===i.o[ZC.1b[16]].1f&&1c!==ZC.1d(t=i.o[ZC.1b[16]][0].bx)&&(i.LO=t),""===i.LO&&(i.LO="8Y"),i.LO=6d(i.LO).1F("1o","cH");1j(1a a=i.LO.2n(/\\s+|;|,/),n=0,l=a.1f;n<l;n++)i.B8.qv(a[n]);i.B8.ls(i.MO),ZC.2L&&i.B8.qv("2L"),e||(i.E.xo=!0)}}1q(e){1a t,i,a,n,l,r,o=1g;o.NH="x",o.E.4G=ZC.GP(3h.5g(o.o)),ZC.2E(o.o.xm,o.O0),1===o.o[ZC.1b[16]].1f&&ZC.2E(o.o[ZC.1b[16]][0].xm,o.O0);1a s=o.FO();if(1c!==ZC.1d(e)&&(s[ZC.1b[3]]=e),ZC.AO.C8("Lv",o,s),o.MF="1q",o.QQ[1]=o.QQ[0],o.QQ[0]="",o.QQ[0]+=o.I+":"+o.F+":",1c!==ZC.1d(t=o.o[ZC.1b[16]]))1j(o.QQ[0]+=t.1f+":",n=0;n<t.1f;n++)o.QQ[0]+=(t[n].1J||"")+":",o.QQ[0]+=(t[n].x||"")+":"+(t[n].y||"")+":"+(t[n][ZC.1b[19]]||"")+":"+(t[n][ZC.1b[20]]||"")+":",1c!==ZC.1d(t[n][ZC.1b[11]])&&(o.QQ[0]+=t[n][ZC.1b[11]].1f+":");if(ZC.AK(o.J+"-3Y-c")&&o.3j(e,!1),1y mF!==ZC.1b[31]&&(o.H7=1m mF(o)),1c===ZC.1d(e)){o.qr(),o.B8.B8["2t-9B"]&&(1o.9T=o.B8.B8["2t-9B"]);1a A=!!o.o.5i;if(o.B8.2x(o.o,"6A",!1,!0),o.4y([["5i","DC"],["xk","QN"]]),o.o[ZC.1b[16]]&&1===o.o[ZC.1b[16]].1f&&(i=o.o[ZC.1b[16]][0],1c!==ZC.1d(t=i.5i)&&(o.DC=t),1c!==ZC.1d(t=i.xk)&&(o.QN=t)),ZC.6y(o.QN),ZC.2E(o.B8.B8.a3.5i,o.DC,!1,!0,!0),o.DC.ac)1j(n=o.DC.ac.1f-1;n>=0;n--)1j(r=0;r<n;r++)if(o.DC.ac[n].id===o.DC.ac[r].id){o.DC.ac.6r(n,1);1p}if(A||4v o.o.5i,ZC.6y(o.DC),o.N={},1c!==ZC.1d(t=o.o.1I))1j(a in t)"3R"!==a&&(o.N[a]=t[a]);if(o.o[ZC.1b[16]]&&1===o.o[ZC.1b[16]].1f&&(i=o.o[ZC.1b[16]][0],1c!==ZC.1d(t=i.1I)))1j(a in t)"3R"!==a&&(o.N[a]=t[a]);ZC.6y(o.N),o.O0[ZC.1b[16]]&&1D.1q(),o.4y([["iw","ed"],["mZ-iw","ed"],["3x","NH"],["h-8I","jr","i"],["v-8I","jE","i"],["7J","KA","b"],["4n-7L","lG","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==o.1L(".8J.")&&(!ZC.6N&&ZC.jy&&"vN"===e[a].2v(0,8)&&(e[a]=ZC.jy[e[a].2v(8)]),"!"===e[a].fz(0)&&(e[a]=e[a].2v(1),1g.E["bd-8J"]=1g.E["bd-8J"]||[],1g.E["bd-8J"].1h(e[a])),i.1h([e[a],"4d"])),".6L"===o.5A(o.1f-4,4)&&"3e"==1y e[a]&&i.1h([e[a],"6L"]),"3R"===a&&(-1!==o.1L(".1I.")&&i.1h([e[a],"2O"]),-1!==o.1L(".6L.")&&i.1h([e[a],"6L"]),-1!==o.1L(".1R.")&&i.1h([e[a],"4d"])),"3e"==1y e[a]&&"3R"!==a&&(0===e[a].1L("3R:")&&a===ZC.1b[5]||0===e[a].1L("7u:"))&&-1===ZC.AU(["5I","1E","Jp"],ZC.EA(a))&&i.1h([e[a],"1V"])}1l i}OQ(JA){1a s=1g;if(1o.3J.rg){1a J3=s.jv(s.o).4B(s.jv(s.MO));if(0!==J3.1f){1a UU=0,LN={},ra=0;s.E["bd-8J"]=s.E["bd-8J"]||[];1a C6=2w.eN(1n(){if(UU>=J3.1f){1j(1a e in 2w.9S(C6),s.ti(s.o),LN)if(0!==e.1L("1V:")&&-1===ZC.AU(s.E["bd-8J"],e))4J{1a t=2g.4P("3a");t.1s=LN[e].1s,t.1M=LN[e].1M,t.9d("2d").d3(LN[e],0,0);1a i=t.jT("4d/9K");LN[e].hL=1c,LN[e].j0=1c,LN[e].5a=i,ZC.4f.1V[e]=LN[e]}4M(a){}2w.5Q(1n(){1o.YE[s.J]&&JA()},1)}1u r5(++ra)},20);r5(ra)}1u 1o.YE[s.J]&&JA()}1u 1o.YE[s.J]&&JA();1n r5(i){if(!(i>=J3.1f)){1a F5,MB,KG=J3[i][0],kI=J3[i][1];if("3R:"===KG.2v(0,4)){1a QK=KG.2v(4);s.QP["3R:"+QK]="[]";4J{F5=["g5-3e"===s.N3?"eK="+1B.cb():""].2M("&"),ZC.A3.a8({1J:"bL",3R:QK,ej:1n(e){s.S0.1V||"7h-f0"!==s.N3||e.cn(ZC.1b[45],"cl, 8H ci dJ 6X:6X:6X dF")},1V:F5,4L:1n(e,t,i,a){1l s.NC({8C:ZC.1b[63],b8:"bB cR fG ("+a+")"},ZC.1b[64]),!1},aF:1n(e,t,i,a){s.QP["3R:"+a]=e,UU++}})}4M(J7){1l s.NC(J7,ZC.1b[64]),!1}}1u if("7u:"===KG.2v(0,11))if("zc.Ma.2x"===s.QP[KG]){s.QP[KG]="[]";1a EB=ZC.AO.oN(KG.2v(11)),O={id:s.J,pT:KG,5F:1n(e){s.QP[KG]=e,UU++}},wl=EB[0];O.8P=EB[1];4J{1a iL=7l(wl).4x(s,O);1c!==ZC.1d(iL)&&iL&&(s.QP[KG]=iL,UU++)}4M(J7){1l s.NC(J7,"oS 1V 6A"),!1}}1u UU++;1u"4d"===kI?(LN[KG]=1m d2,LN[KG].u0="xD",LN[KG].hL=1n(){UU++},LN[KG].j0=1n(){1a e=ZC.2s(s.o.KX);if(ZC.fu.1h(KG),e)1l s.NC({8C:ZC.1b[63],b8:"bB cR fG ("+1g.5a+")"},"bB 6A (4d)"),!1;1g.5a=ZC.kw,UU++},LN[KG].5a=KG,ZC.4f.1V[KG]=LN[KG]):"2O"===kI?(F5=["g5-3e"===s.N3?"eK="+1B.cb():""].2M("&"),ZC.A3.a8({1J:"bL",3R:KG,ej:1n(e){s.S0.2O||"7h-f0"!==s.N3||e.cn(ZC.1b[45],"cl, 8H ci dJ 6X:6X:6X dF")},1V:F5,4L:1n(e,t,i){1l s.NC(i,"bB 6A"),!1},aF:1n(e){1j(1a t={},i=e.m0(/[a-zA-Z0-9\\.\\#\\-](.+?)\\{((.|\\s)+?)\\}/gi),a=0,n=i.1f;a<n;a++){MB=i[a].2n("{");1a l=ZC.GP(MB[0]),r=l.2n(/\\s+/);if(1===r.1f||2===r.1f&&ZC.GP(r[0])==="#"+s.J){t[l=ZC.GP(1===r.1f?r[0]:r[1])]||(t[l]={});1j(1a o=0,A=(MB=MB[1].1F("}","").2n(";")).1f;o<A;o++){1a C=MB[o].2n(":");2===C.1f&&(t[l][ZC.GP(C[0])]=""+ZC.GP(C[1]))}}}1c!==ZC.1d(s.o.1I)?ZC.2E(t,s.o.1I):1c!==ZC.1d(s.o[ZC.1b[16]])&&1===s.o[ZC.1b[16]].1f&&s.o[ZC.1b[16]][0].1I&&ZC.2E(t,s.o[ZC.1b[16]][0].1I),UU++}})):"6L"===kI&&(F5=["g5-3e"===s.N3?"eK="+1B.cb():""].2M("&"),ZC.A3.a8({1J:"bL",3R:KG,ej:1n(e){s.S0.6L||"7h-f0"!==s.N3||e.cn(ZC.1b[45],"cl, 8H ci dJ 6X:6X:6X dF")},1V:F5,4L:1n(e,t,i){1l s.NC(i,"bB 6A"),!1},aF:1n(e,t,i,a){s.iN[a]=e,UU++}}))}}}ti(BX){1a s=1g;1j(1a p in BX)if("4h"==1y BX[p])s.ti(BX[p]);1u 1j(1a F5 in s.QP)F5===BX[p]&&(BX[p]=7l(s.QP[F5]))}bT(e){1a t,i,a,n,l=1g;if(l.E.bT=!0,l.E.wh=l.I+"/"+l.F,l.o[ZC.1b[16]])if(l.lg)1o.3n(l.J,"a0"),1o.aW(1o.aQ[l.J]);1u if(1y e===ZC.1b[31]&&(e=!1),ZC.AO.C8("bT",l,l.FO()),e=!1);1u{1j(i=0;i<l.AI.1f;i++)1j(n=0;n<l.AI[i].AZ.A9.1f;n++)l.E["g-"+i+"-p-"+n+".2h"]=l.AI[i].E["1A"+n+".2h"];1j(i=0;i<l.AI.1f;i++)l.E["g-"+l.AI[i].L+"-aL"]=3h.5g(l.AI[i].D9);1j(1a r=l.o[ZC.1b[16]],o=[ZC.1b[10],"5L"],s=0,A=r.1f;s<A;s++)1j(1a C=0;C<o.1f;C++){1a Z=o[C],c=[];if(1c!==ZC.1d(r[s][Z])){1j(i=0,a=r[s][Z].1f;i<a;i++)r[s][Z][i].fr||c.1h(r[s][Z][i]);r[s][Z]=c}}if(l.VQ(l.o),l.o=ZC.A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a=e.1f;i<a;i++)1j(1a n=0;n<t.1f;n++){1a l=t[n],r=[];if(1c!==ZC.1d(e[i][l])){1j(1a o=0,s=e[i][l].1f;o<s;o++)e[i][l][o].fr||r.1h(e[i][l][o]);e[i][l]=r}}}3j(e,t,i){1a a=1g;1j(1a n in a.E)-1!==n.1L("-1H-")&&-1!==n.1L("-cK")&&4v a.E[n];if(1y t===ZC.1b[31]&&(t=!0),ZC.A3("."+a.J+"-4Z-1N").4j("3H",a.rf),ZC.A3("."+a.J+"-4Z-1N").3p(),1c!==ZC.1d(e))a.OH(e).3j();1u{t&&a.po(),a.pn();1j(1a l=0,r=a.AI.1f;l<r;l++)"3K"===a.AB&&i?a.AI[l].a0():a.AI[l].3j();1a o,s,A;1c!==(o=ZC.AK(a.J+"-3Y-c"))&&ZC.P.II(o,a.AB,a.iX,a.iY,a.I,a.F),1c!==(A=ZC.AK(a.J+"-3Y-c-1v"))&&ZC.P.II(A,a.AB,a.iX,a.iY,a.I,a.F),1c!==(s=ZC.AK(a.J+"-8a-c"))&&(ZC.P.II(s,a.AB,a.iX,a.iY,a.I,a.F),ZC.A3("#"+a.J+"-2C-1N").3p()),a.A6&&a.A6.5b(),ZC.A3("."+a.J+"-2C-1Q").3p(),ZC.P.ER([a.J+"-2C-8a",a.J+"-2C"]),ZC.P.ER(a.J+"-eJ-1E"),1c!==a.I7&&ZC.P.ER([a.J+"-4Z-2R",a.J+"-4Z-cq-2R",a.J+"-4Z-ec-2R",a.J+"-4Z-5e",a.J+"-4Z-cq-5e",a.J+"-4Z-ec-5e"])}}pl(){1a e,t,i,a=1g,n=a.I+"/"+a.F,l=ZC.P.HZ({id:a.J+"-eB",2K:"k2",p:ZC.AK(a.J)});ZC.P.PO(l,{1M:"100%"===a.MW?a.MW:a.F+"px",1s:"100%"===a.FW?a.FW:a.I+"px"});1a r=ZC.P.HZ({2p:"zc-aS zc-1v",wh:n,id:a.J+"-1v",9L:"8R",2K:"4D",p:l});1P(1o.Rp&&(r.1I.1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t){if(ZC.e1){1a i=ZC.P.MH(t);if(ZC.2l(i[0]-ZC.e1.xy[0])>100&&(1m a1).bI()-ZC.e1.ts<5x){1a a=e.FO();a.c1=i[0]>ZC.e1.xy[0]?"2A":"1K",ZC.AO.C8("e1",e,a)}ZC.e1=1c}e.dZ||ZC.3m||1o.SM(t),e.P4(t)},ZC.A3("#"+e.J+"-5W").3r("4H",e.iH).3r("6f",e.P4).3r("5R",e.p0),ZC.A3("#"+e.J+"-2C-1N").4c("4H",e.iH)),e.hR=1n(t){1a i=e.FO();i.ev=t,ZC.AO.C8("aD",e,i)},ZC.A3("#"+e.J+"-5W").3r("aD",e.hR),ZC.A3("#"+e.J+"-3c").3r("aD",e.hR),e.pc=1n(t){27===t.Tm&&e.QM&&(e.l6||e.i7())},ZC.A3(2g).3r("wr",e.pc),e.i7=1n(){ZC.A3("#"+e.J+ZC.1b[66]).4j("3H",e.i7),ZC.jw=1c,ZC.P.ER(e.J+"-1V-6q"),e.a0(),1o.dL&&ZC.AK(1o.dL)&&(ZC.AK(1o.dL).1I.3L="2b")},ZC.A3("#"+e.J+ZC.1b[66]).4c("3H",e.i7)):ZC.2L&&(e.p1=1n(e){1l e.6R(),1o.SM(e),!1},ZC.A3("#"+e.J+"-5W").3r("4H",e.p1)),1c!==e.HO){1a u=ZC.1k(e.HO.dU);u=u>=50?u:5x*u,2w.5Q(1n(){e.MM(),e.2x()},u)}e.MF="",ZC.TS[e.J]=(1m a1).bI()-ZC.TS[e.J],e.E["cw-ai"]&&(ZC.AO.C8("ai",e,e.FO()),e.E["cw-ai"]=1c),e.E["cw-2x"]&&(ZC.AO.C8("2x",e,e.FO()),e.E["cw-2x"]=1c)}bX(e){1j(1a t=1g,i=0;i<t.AI.1f;i++)t.AI[i].BI&&t.AI[i].BI.sq(e)}nv(){1a e=1g,t=2g.4P("3a");t.1s=e.I,t.1M=e.F,t.4m("1O","");1j(1a i=0;i<e.AI.1f;i++)e.AI[i].BI&&e.AI[i].BI.sq(!0,t);1l t}Tp(){1c===ZC.1d(ZC.o6)&&(ZC.o6=1n(e){1o.3n(e.id,"uE")}),1o.3n(1g.J,"uI",{1E:"vs hO","1n":"ZC.o6()",8w:100})}o3(){1a e,t=1g,i={},a=t.DC.ew;t.B8.2x(i,"6A.5i.ew"),a&&ZC.2E(a,i),1===t.o[ZC.1b[16]].1f&&t.o[ZC.1b[16]][0].5i&&(e=t.o[ZC.1b[16]][0].5i.ew)&&ZC.2E(e,i);1a n=ZC.5u(ZC.1k(i.1J||1),1,2),l=i.2K||"br";-1===ZC.AU(["tl","tr","br","bl"],l)&&(l="br"),t.U0=l;1a r,o=32,s=146,A=0,C=1;ZC.6N&&(o=30,s=168,A=8,C=1),s=126,o=22;1a Z={8Y:["#Ua","#Sv"],b4:["#v6","#Sm"]},c=Z.8Y;if(1o.jQ&&(c="8Y"===t.LO||"cH"===t.LO?Z.8Y:Z.b4),1===t.o[ZC.1b[16]].1f)if(t.o[ZC.1b[16]][0][ZC.1b[0]]){1a p=ZC.AO.G7(t.o[ZC.1b[16]][0][ZC.1b[0]]);7===p.1f&&(c=ZC.AO.rT(p,Z.b4,Z.8Y))}1u if(t.o[ZC.1b[16]][0].bx){1a u=t.o[ZC.1b[16]][0].bx;c="8Y"===u||"cH"===u?Z.8Y:Z.b4}1a h,1b,d=1y 2w!==ZC.1b[31]&&2w.89?2w.89.wO:"",f=1y 2w!==ZC.1b[31]&&2w.89?2w.89.xv:"";1P(r=\'<a 5E="oS Su by hO" 1I="1r:\'+c[0]+\' !7r;2t-2e:uu !7r;3L:8y !7r;3o:1 !7r; 1E-bS:2b;" 7B="7h://8z.1o.bZ/?wO=\'+d+"&xv="+f+\'">Nr by <7D 1I="1r:\'+c[1]+\'; 2t-79:6x;">hO</7D></a>\',l){1i"br":h=t.F-o,1b=t.I-s;1p;1i"bl":h=t.F-o,1b=6;1p;1i"tr":h=2,1b=t.I-s;1p;1i"tl":h=2,1b=6}1c!==ZC.1d(e=ZC.AK(t.J+"-1v"))&&ZC.P.HZ({2p:ZC.6N?"-6N":"",p:e,id:t.J+"-eJ-1E",tl:h+"/"+1b,wh:s+"/"+(o-A),1r:ZC.6N?1===n?"#j3":"#2S":"",3v:A,3o:C,2K:"4D",4V:"8q",6W:1o.9T,4g:r},t.AB)}pn(){1a e=1g;ZC.A3("#"+e.J+"-2C").4j(ZC.1b[47],e.U8),ZC.A3("."+e.J+"-2C-1Q").4j(ZC.1b[47],e.U8),ZC.A3("."+e.J+"-2C-1Q").4j("3H 5R",e.q9).4j("7A",e.pX).4j("7T",e.q2),e.E["2C-1Q-hJ"]=!1,1c!==e.H7&&e.H7.3k(),1c!==e.D5&&e.D5.3k(),ZC.2L&&(ZC.A3("#"+e.J+"-5W").3k("4H",e.iH).3k("6f",e.P4).3k("5R",e.p0),ZC.A3("#"+e.J+"-2C-1N").4j("4H",e.iH),ZC.A3("#"+e.J+"-5W").3k("4H",e.p1)),ZC.A3("#"+e.J+"-5W").3k("aD",e.hR),ZC.A3("#"+e.J+"-3c").3k("aD",e.hR),ZC.A3(2g).3k("wr",e.pc),ZC.A3("#"+e.J+ZC.1b[66]).4j("3H",e.i7)}UF(e,t,i){1y i===ZC.1b[31]&&(i=!1);1a a=ZC.AK("zc-2C-"+(i?"eu":"1Q")+"-"+e);a&&(a.1I.3L=t?"8y":"2b")}p7(LM,ev){if(!1o.3J.w6){1a s=1g,G,i,A2,j,J8;1y LM===ZC.1b[31]&&(LM=-1);1a DC={};ZC.2E(s.DC,DC),-1!==LM&&s.o[ZC.1b[16]][LM]&&ZC.2E(s.o[ZC.1b[16]][LM].5i,DC,1c,1c,!0),ZC.A3("#"+s.J+"-2C").3p();1a RX=[];1j(1y ZC.AL===ZC.1b[31]&&RX.1h({id:"3D",46:"2b"},{id:"uF",46:"2b"},{id:"uO",46:"2b"}),i=DC.ac.1f-1;i>0;i--)1j(1a vL=DC.ac[i].id,ii=i-1;ii>=0;ii--)DC.ac[ii].id===vL&&DC.ac.6r(ii,1);if(1c!==ZC.1d(G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1c!==ZC.1d(JG.1Q)&&1c!==ZC.1d(G=JG.1Q[ZC.1b[71]])&&LH.1C(G),ZC.2L&&(s.B8.2x(LH.o,ZC.1b[65]+"[2L].1Q.2N-3X"),OK&&1c!==ZC.1d(OK.1Q)&&1c!==ZC.1d(G=OK.1Q[ZC.1b[71]])&&LH.1C(G)),LH.WW=!0,LH.1q(),UN={},JG&&1c!==ZC.1d(JG.8E)&&(UN=JG.8E);1a JT=[],EE=1c;if(pq=1c!==ZC.1d(s.N1.o.jX)&&ZC.2s(s.N1.o.jX),ZC.2L&&(EE=G1("xr"),"2b"!==EE.46&&(1c===s.DC||1c===ZC.1d(s.DC["3f-1Z"])||s.DC["3f-1Z"]?JT.1h(GQ("nb",EE.1E)):JT.1h(GQ("na",EE.1E)),JT.1h(JB("Mn")))),EE=G1("xw"),"2b"!==EE.46&&(JT.1h(GQ("f5",EE.1E)),JT.1h(JB("f5"))),1y ZC.vW!==ZC.1b[31]){EE=G1("Sg"),"2b"!==EE.46&&(EE=G1("Rb"),"2b"!==EE.46&&JT.1h(GQ("pQ",EE.1E?EE.1E:1c)),EE=G1("x6"),"2b"!==EE.46&&JT.1h(GQ("pM",EE.1E?EE.1E:1c)),JT.1h(JB("8m")));1a TS=["Qs","Qq","ua","pU","uk","uj","uc"],og=0,ob=0;1j(i=0;i<TS.1f;i++)"uk"===TS[i]&&ZC.AK(s.J+"-1V-6q")&&(TS[i]="Ki"),EE=G1(TS[i]),"2b"!==EE.46&&(og++,ob=i,JT.1h(GQ(TS[i].aN(),EE.1E)));og>0&&JT.1h(JB(TS[ob].aN()))}if(-1!==LM){1a H4=!1;1j(j=0,J8=s.AI[LM].BL.1f;j<J8;j++)s.AI[LM].BL[j].H4&&(H4=!0);if(H4&&1y mF!==ZC.1b[31]){1a hW=!1;EE=G1("Im"),"2b"!==EE.46&&(JT.1h(GQ("eG",EE.1E)),hW=!0),EE=G1("J2"),"2b"!==EE.46&&(JT.1h(GQ("f3",EE.1E)),hW=!0),EE=G1("It"),"2b"!==EE.46&&(JT.1h(GQ("gd",EE.1E)),hW=!0),hW&&JT.1h(JB("3G"))}}1a iq=!1,oy=!1;if(-1!==LM&&(-1!==ZC.AU(["1w","1N","2U","5t","6c","3O","9u"],s.AI[LM].AF)&&(iq=!0,s.XJ="2d"),-1!==ZC.AU(["97","83","dN","6O","7k","7e","aX"],s.AI[LM].AF)&&(oy=!0,s.XJ="3d")),(iq||oy)&&(EE=G1("3D"),"2b"!==EE.46&&(EE=G1(iq?"uF":"uO"),"2b"!==EE.46&&(JT.1h(GQ(iq?"n9":"nI",EE.1E)),JT.1h(JB("14N"))))),-1!==LM){1a D=s.AI[LM],nK=!1,m8=!1;1j(j=0;j<D.BL.1f;j++){1a B=D.BL[j];0===B.BC.1L(ZC.1b[51])&&(nK=!0),"3P"===B.DL&&(m8=!0)}nK&&(EE=G1("14P"),"2b"!==EE.46&&(EE=G1(m8?"uU":"uT"),"2b"!==EE.46&&(JT.1h(GQ(m8?"nH":"nn",EE.1E)),JT.1h(JB("fj"))))),(D.CY||D.KD)&&(EE=G1("o1"),"2b"!==EE.46&&(EE=G1(D.fC?"165":"17V"),"2b"!==EE.46&&(JT.1h(GQ(D.fC?"mx":"i0",EE.1E)),JT.1h(JB("2i")))))}1a m5=0,B6;if(1y ZC.w5!==ZC.1b[31]&&(EE=G1("uN"),"2b"!==EE.46&&(JT.1h(GQ("4K",EE.1E)),m5++),EE=G1("uz"),"2b"!==EE.46&&(JT.1h(GQ("4r",EE.1E)),m5++)),m5>0&&JT.1h(JB("aZ")),EE=G1("uG"),"2b"===EE.46||s.LZ||(s.QM?(EE=G1("17W"),JT.1h(GQ("iA",EE.1E)),JT.1h(JB("iA"))):(JT.1h(GQ("5X",EE.1E)),JT.1h(JB("5X")))),s.I7&&(EE=G1("17X"),"2b"!==EE.46&&JT.1h(GQ("c6",EE.1E)),EE=G1("17Y"),"2b"!==EE.46&&JT.1h(GQ("c5",EE.1E)),JT.1h(JB("4Z"))),JT.1f>0&&-1!==JT[JT.1f-1].1L("zc-2C-eu")&&JT.6r(JT.1f-1,1),s.pV={},-1!==LM)if(JG&&1c!==ZC.1d(B6=JG["5D-2B"]))1j(JT.1f>0&&JT.1h(JB("5D")),i=0,A2=B6.1f;i<A2;i++){1a mg=!0;if(1c!==ZC.1d(B6[i].46)&&("2b"===B6[i].46?mg=!1:"4t"!==B6[i].46&&(mg=!ev||7l(B6[i].46).4x(s,1o.hI(ev,s),B6[i].id,ev))),mg){1a AN,J=B6[i].id||"5D-"+i;"eu"===B6[i].id||"eu"===B6[i].1J?JT.1h(JB(J,!0)):"5K"===B6[i].1J?(AN=B6[i].1E||"qc vu "+i,JT.1h(wE(J,AN,!0))):(AN=B6[i].1E||"qc vu "+i,s.pV[J]={fn:B6[i]["1n"]||"",3R:B6[i].3R||"",2X:B6[i].2X||""},JT.1h(GQ(J,AN,!0)))}}s.TX||(JT.1h(JB("1o")),JT.1h(GQ("ur","vs hO"))),ZC.P.HZ({id:s.J+"-2C",p:2g.3s,2p:"zc-2C zc-1I",1v:1c===ZC.1d(GN)?0:GN.iY+GN.F/2,1K:1c===ZC.1d(GN)?0:GN.iX+GN.I/2,oa:s.N1.AP+"px 2V "+s.N1.BU,1U:(-1===s.N1.A0?"aG":s.N1.A0)+" "+lT(s.N1.D6),ca:s.N1.FM,di:s.N1.FN,d6:s.N1.FY,d8:s.N1.EN,4g:JT.2M("")}),s.E["2C-1Q-hJ"]||(s.q9=1n(e){1a t,i=1!==e.2X.eA?e.2X.6o.id:e.2X.id,a=i.2v(0,i.1L("-2C-1Q-")),n=1o.6Z(a);ZC.2L&&n.P4();1a l=n.mu(n.SY[0],n.SY[1]);n.9h(),ZC.2L&&1o.SM(e);1a r=i.1F(n.J+"-2C-1Q-","");n.wq({4w:l?l.J:1c,qk:r,ev:ZC.A3.BZ(e)});1a o=n.o["8m-k5"]||n.o[ZC.1b[16]][0]["8m-k5"]||"";1P(r){1i"nI":1i"n9":l&&n.pa(l.J);1p;1i"na":s.DC=s.DC||{},s.DC["3f-1Z"]=!0;1p;1i"nb":s.DC=s.DC||{},s.DC["3f-1Z"]=!1;1p;1i"i0":n.VX(l.J,!0);1p;1i"mx":n.VX(l.J,!1);1p;1i"nH":n.W4(l.J,"lK");1p;1i"nn":n.W4(l.J,"3P");1p;1i"f5":n.ph();1p;1i"pQ":n.NE("9K");1p;1i"pM":n.NE("dX");1p;1i"u3":n.NE("g3",""===o?1c:{fn:o});1p;1i"u5":n.NE("2F",""===o?1c:{fn:o});1p;1i"k8":1o.3n(n.J,"k8");1p;1i"tY":1o.3n(n.J,"wT",""===o?1c:{fn:o});1p;1i"u6":(t=G1("pU"))["5D-1n"]?n.ZO({4w:l?l.J:1c,qk:r,k5:o,"1n":t["5D-1n"]}):1o.3n(n.J,"wI",""===o?1c:{fn:o});1p;1i"sX":1i"t0":1o.3n(n.J,"vY",{t3:r});1p;1i"6I":n.kU();1p;1i"4K":n.kN();1p;1i"4r":n.iI();1p;1i"5X":n.pk();1p;1i"c6":1o.3n(n.J,"c6");1p;1i"c5":1o.3n(n.J,"c5");1p;1i"eG":l&&(n.H7.D=l,n.jM({4w:l.J}));1p;1i"f3":l&&(n.H7.D=l,n.kS({4w:l.J}));1p;1i"gd":l&&(n.H7.D=l,n.kC({4w:l.J}));1p;1i"ur":n.pz();1p;2q:1c!==ZC.1d(G=s.pV[r])&&(""!==G.fn?n.ZO({4w:l?l.J:1c,qk:r,"1n":G.fn}):""!==G.3R&&l&&l.UC(e,G.3R,G.2X))}},s.pX=1n(){1g.1I.qj=LH.A0,1g.1I.1r=LH.C1,1g.1I.lB=1g.1I.lm=LH.AP+"px 2V "+LH.BU},s.q2=1n(){1g.1I.qj=DV.A0,1g.1I.1r=DV.C1,1g.1I.lB=1g.1I.lm=DV.AP+"px 2V "+DV.BU},s.U8=1n(e){1l e.6R(),!1},ZC.A3("#"+s.J+"-2C").4c(ZC.1b[47],s.U8),ZC.A3("."+s.J+"-2C-1Q").4c(ZC.1b[47],s.U8),ZC.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t-(ZC.96?0:10)+"/"+(i-(ZC.96?0:10))}),r="";""!==e.SI&&(r="qc 188 1j<br />"+e.SI),l.4q=\'<3B 1O="zc-6t-1"><a 7B="7h://8z.1o.bZ" 2X="om">1o.bZ</a></3B><3B 1O="zc-6t-2">&1S;17U-\'+(1m a1).vS()+\'</3B><3B 1O="zc-6t-3"><3B id="\'+e.J+\'-6t-7m">\'+ZC.HE["6t-7m"]+\'</3B></3B><3B 1O="zc-6t-4" 1I="3v:\'+(i-vQ)+\'px 88 88 88;"><3B>&8u;<br />189 \'+ZC.fF+" ["+e.AB+"]</3B>"+r+"</3B>",ZC.A3("#"+e.J+"-6t-7m").3r("3H",1n(){ZC.AO.C8("18b",e,e.FO()),ZC.P.ER([e.J+"-6t",e.J+"-6t-4O"])})}NC(e,t){1a i=1g;if(ZC.AO.oM("4L",i))ZC.AO.C8("4L",i,{id:i.J,4L:e,18c:t,4G:i.E.4G||i.E.vM});1u{1a a="";a+="4h"==1y e?e.8C+":"+e.b8+"\\n\\n":e+"\\n\\n",1c!==ZC.1d(t)&&(a+="18d:"+t+"\\n\\n"),a+="3h 1V:\\n\\n"+i.E.4G+"\\n\\n",i.Y4(),1c===ZC.AK(i.J+"-1v")&&i.pl(),ZC.P.HZ({2p:"zc-3l zc-4L zc-1I",id:i.J+"-4L",p:ZC.AK(i.J+"-1v"),wh:i.I-(ZC.96?0:10)+"/"+(i.F-(ZC.96?0:10))}).4q=\'<3B 1O="zc-4I-5B-1H zc-4I-s0">\'+ZC.HE["4L-5K"]+\'</3B><3B 1O="zc-4I-5B-1H zc-4I-s1">\'+ZC.HE["4L-b8"]+\'</3B><3B 1O="zc-4I-5B-ao"><bP id="\'+i.J+\'-4L-b8" 1I="1s:\'+(i.I-35)+"px;1M:"+(i.F-135)+\'px;"></bP></3B><3B 1O="zc-4I-5B-ao zc-4I-5B-7Z"><an 1J="7K" 1T="\'+ZC.HE["4L-7m"]+\'" id="\'+i.J+\'-4L-7m" /></3B>\',ZC.A3("#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I[i].BK(A)?s[A]={fj:t}:(1c!==ZC.1d(s[A])&&(s[A].fj=t),1c!==ZC.1d(s[ZC.EA(A)])&&(s[ZC.EA(A)].fj=t))}}4v l.E["2Y"+r+".3G"],l.AI[r].AJ["3d"]||o?l.K2():l.AI[r].K2(!0,!0)}VX(e,t){1a i=1g;if(i.D5){1j(1a a=0,n=i.AI.1f;a<n;a++)e===i.AI[a].J&&(i.AI[a].fC=t,i.AI[a].E["2i-on"]=t);if(t){1a l=ZC.A3("#"+i.J+"-1v"),r={ei:ZC.DS[0]-l.2c().1K,h1:ZC.DS[1]-l.2c().1v,1J:ZC.1b[48],2X:{id:i.J+"-5W"}};i.D5.QH(r)}1u K8.h0(i.J)}}pa(e){1j(1a t=1g,i=["1w","1N","2U","5t","6c","3O","9u"],a=0,n=t.AI.1f;a<n;a++)if(e===t.AI[a].J){1a l=t.o[ZC.1b[16]][a];if("9u"===l.1J)1j(1a r=0,o=l[ZC.1b[11]].1f;r<o;r++){1a s=l[ZC.1b[11]][r];s.1J=s.1J||"1w","3d"===t.XJ?s.1J=s.1J.1F("3d",""):-1!==ZC.AU(i,s.1J)&&(s.1J=s.1J+"3d")}1u"3d"===t.XJ?l.1J=l.1J.1F("3d",""):-1!==ZC.AU(i,l.1J)&&(l.1J=l.1J+"3d")}t.XJ="3d"===t.XJ?"2d":"3d",t.E.4G=ZC.GP(3h.5g(t.o)),t.K2()}ph(e){1j(1a t,i=1g,a=0;a<i.AI.1f;a++)4v i.E["g"+a+"-1Y-dc"];if(e=e||{},ZC.AO.C8("f5",i,{id:i.J,4w:e[ZC.1b[3]]}),1c!==ZC.1d(t=e[ZC.1b[3]])){1a n=i.C5(t);1c!==n&&(i.MM(n),i.2x(n.J))}1u i.QS=[],i.NY=-1,i.MM(),i.po(),i.2x()}wu(e){1a t,i=1g;if(e=e||{},1c!==ZC.1d(t=e[ZC.1b[3]])){1a a=i.C5(t);1c!==a&&1c!==ZC.1d(e.i5)&&(i.MM(a),i.2x(t,e.i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[53]])),c)1P(t){1i"18i":if(r={},l=c.C5(i[ZC.1b[3]]))1j(a=0,n=l.BL.1f;a<n;a++){1a p=l.BL[a];"k"===p.AF?r[p.BC]={4s:p.V,4p:p.A1,w8:p.Y[p.V],wt:p.Y[p.A1]}:r[p.BC]={5r:p.B3,5q:p.BP,w8:p.Y[p.V],wt:p.Y[p.A1]}}1l r;1i"q3":c.wy(i);1p;1i"eG":c.jM(i);1p;1i"f3":c.kS(i);1p;1i"nU":if(l=c.C5(i[ZC.1b[3]]),1c!==ZC.1d(i.kL)&&i.kL)1j(a=0,n=l.BT("k").1f;a<n;a++)i["4s"+(A=1===(o=l.BT("k")[a]).L?"":"-"+o.L)]=i.4s||1c,i["4p"+A]=i.4p||1c,i["94"+A]=i.94||1c,i["8Z"+A]=i.8Z||1c;1j(a=0,n=l.BT("k").1f;a<n;a++)1c===i["4s"+(A=1===(o=l.BT("k")[a]).L?"":"-"+o.L)]&&1c===ZC.1d(i["4p"+A])&&1c===ZC.1d(i["94"+A])&&1c===ZC.1d(i["8Z"+A])||(i["7E"+A]=!0),"3P"===o.DL&&(1c!==ZC.1d(i["4s"+A])&&(i["4s"+A]=ZC.JN(i["4s"+A],o.H8)),1c!==ZC.1d(i["4p"+A])&&(i["4p"+A]=ZC.JN(i["4p"+A],o.H8)));if(1c!==ZC.1d(i.kF)&&i.kF)1j(a=0,n=l.BT("v").1f;a<n;a++)i["5r"+(A=1===(s=l.BT("v")[a]).L?"":"-"+s.L)]=i.5r||1c,i["5q"+A]=i.5q||1c;1j(a=0,n=l.BT("v").1f;a<n;a++)A=1===(s=l.BT("v")[a]).L?"":"-"+s.L,1c===ZC.1d(i["5r"+A])&&1c===ZC.1d(i["5q"+A])||(i["7N"+A]=!0),"3P"===s.DL&&(1c!==ZC.1d(i["5r"+A])&&(i["5r"+A]=ZC.JN(i["5r"+A],s.H8)),1c!==ZC.1d(i["5q"+A])&&(i["5q"+A]=ZC.JN(i["5q"+A],s.H8)));c.PI(i);1p;1i"18j":if(l=c.C5(i[ZC.1b[3]]),1c!==ZC.1d(i.kL)&&i.kL)1j(a=0,n=l.BT("k").1f;a<n;a++)i["4s"+(A=1===(o=l.BT("k")[a]).L?"":"-"+o.L)]=i.4s||1c,i["4p"+A]=i.4p||1c;1j(a=0,n=l.BT("k").1f;a<n;a++)A=1===(o=l.BT("k")[a]).L?"":"-"+o.L,1c===ZC.1d(i["4s"+A])&&1c===ZC.1d(i["4p"+A])||(l.BI&&l.BI.LQ?(i.i6=!0,i["94"+A+"-ag"]=i["4s"+A],i["4s"+A]=ZC.qf(l.BI.NQ[o.BC][ZC.1b[5]],i["4s"+A])):-1!==(C=ZC.AU(o.Y,i["4s"+A]))&&(i["4s"+A]=C),l.BI&&l.BI.LQ?(i.i6=!0,i["8Z"+A+"-ag"]=i["4p"+A],i["4p"+A]=ZC.qf(l.BI.NQ[o.BC][ZC.1b[5]],i["4p"+A])):-1!==(Z=ZC.AU(o.Y,i["4p"+A]))&&(i["4p"+A]=Z),i["7E"+A]=!0);if(1c!==ZC.1d(i.kF)&&i.kF)1j(a=0,n=l.BT("v").1f;a<n;a++)i["5r"+(A=1===(s=l.BT("v")[a]).L?"":"-"+s.L)]=i.5r||1c,i["5q"+A]=i.5q||1c;1j(a=0,n=l.BT("v").1f;a<n;a++)A=1===(s=l.BT("v")[a]).L?"":"-"+s.L,1c===ZC.1d(i["5r"+A])&&1c===ZC.1d(i["5q"+A])||(i["7N"+A]=!0);c.PI(i);1p;1i"gd":c.kC(i)}1l 1c},ZC.vW={},ZC.AO.kX=1n(e,t,i,a){"sO"===(a=a||"9K")&&(a="dX");1a n=2g.4P("3a");n.1s=t,n.1M=i,n.1I.1s=t+"px",n.1I.1M=i+"px";1a l,r=n.9d("2d");e 3E 3M||(e=[e]);1j(1a o=0,s=e.1f;o<s;o++)if(-1===e[o].7U.1L("zc-no-6I")){1a A=!1;4J{e[o].jT("4d/"+a)}4M(Z){A=!0}if(!A)if(l=e[o].bJ("1V-3t")){1a C=l.2n(",");r.d3(e[o],ZC.BM(0,C[0]),ZC.BM(0,C[1]),ZC.CQ(C[2],e[o].1s),ZC.CQ(C[3],e[o].1M),ZC.BM(0,C[0]),ZC.BM(0,C[1]),ZC.CQ(C[2],e[o].1s),ZC.CQ(C[3],e[o].1M))}1u r.d3(e[o],0,0,e[o].1s,e[o].1M,0,0,t,i)}1l n.jT("4d/"+a)},ZC.AO.pD=1n(e,t,i,a,n){1c===ZC.1d(n)&&(n=!1);1a l=ZC.AO.kX(e,t,i,a);if(n){1a r=2g.4P("5W");1l r.5a=l,r}l=l.1F("4d/"+a,"4d/nz-ky"),2g.89.7B=l},RU.5j.kU=1n(){1a e=1g,t=[];if(!e.l6){e.l6=!0;1a i=2g.3s.6Y,a=ZC.A3(2g.3s).2O(ZC.1b[0]),n=ZC.A3(2g.3s).2O("1U-4d");ZC.A3(2g.3s).2O(ZC.1b[0],"#2S").2O("1U-4d","2b");1j(1a l=0,r=i.1f;l<r;l++)1===i[l].eA&&(t[l]=i[l].1I.3L,i[l].1I.3L="2b");2g.3s.2Z(ZC.AK(e.J+"-eB")),2w.5Q(1n(){2w.6I(),2w.5Q(1n(){ZC.A3(2g.3s).2O(ZC.1b[0],a).2O("1U-4d",n),ZC.AK(e.J+"-eB")&&ZC.AK(e.J).2Z(ZC.AK(e.J+"-eB"));1j(1a l=0,r=i.1f;l<r;l++)1===i[l].eA&&(i[l].1I.3L=t[l]);e.l6=!1},5x)},50)}},RU.5j.NE=1n(e,t,i,a){1a n=1g;if(t=t||{},1y i===ZC.1b[31]&&(i=!1),!ZC.AK(n.J+"-cj")){e=e||"9K";1a l=t.g4,r=t.fn||"";ZC.P.II(ZC.AK(n.J+"-2i-c"),n.AB,0,0,n.I,n.F),ZC.A3(".zc-2i-1H").3p();1a o,s,A=("3a"===n.AB||1o.hZ||1o.3J.iz)&&"g3"!==e&&"2F"!==e;if(ZC.2L||!A||i||l||(o=ZC.P.HZ({2p:"zc-3l zc-cj zc-1I",id:n.J+"-cj",8l:5,p:ZC.AK(n.J+"-1v"),wh:n.I+"/"+n.F}),s=ZC.P.HZ({id:n.J+"-cj-7m",p:o,8l:10,tl:"5/"+(n.I-15),4g:ZC.HE["cj-7m"]}),ZC.A3(s).2O("4V","8q").2O("1K",n.I-15-ZC.A3(s).1s()+"px"),ZC.A3(s).3r("3H",1n(){ZC.A3(o).3p()})),ZC.2L&&(l=!0),!1o.3J.iz||l||"2F"!==n.AB||"9K"!==e&&"dX"!==e){1a C;if("3a"===n.AB&&"g3"!==e&&"2F"!==e){1a Z,c,p=2g.4P("3a");1j(p.1s=n.I,p.1M=n.F,Z=0,c=n.AI.1f;Z<c;Z++)n.AI[Z].BG&&n.AI[Z].BG.E9(p);1a u=[];ZC.A3("#"+n.J+" 3a").5d(1n(){-1===ZC.AU([n.J+"-2i-c",n.J+"-8a-c"],1g.id)&&u.1h(1g)}),u.1h(p),u.1h(n.nv());1a h=ZC.AO.pD(u,n.I,n.F,e,!0);h.id=n.J+"-6I-"+e,o.2Z(h)}1u if(i||n.pH(ZC.HE["8m-b3"]),"3K"===n.AB||"3a"===n.AB&&("g3"===e||"2F"===e)){1a 1b=2g.4P("3B"),d="zc-8m-2F-"+n.J;1b.id=d,1b.1I.3L="2b",2g.3s.2Z(1b),1o.aW({id:d,bb:"!2F",xn:!0,1s:n.I,1M:n.F,1V:n.E.4G,cr:n.MO,bx:n.LO,ea:!0,hJ:{2x:1n(){2w.5Q(1n(){1a e=1o.6Z(d);if(e.E["4N-2J"])1a t=2w.eN(1n(){"9w"===e.E["4N-2J"]&&(2w.9S(t),e.bX(!0),C=ZC.AK(d+"-1v").4q,e.bX(!1),1o.3n(d,"a0",{pw:!0}),f())},100);1u e.bX(!0),C=ZC.AK(d+"-1v").4q,e.bX(!1),1o.3n(d,"a0",{pw:!0}),f()},100)}}})}1u"2F"===n.AB&&(n.bX(!0),C=ZC.AK(n.J+"-1v").4q,f(),n.bX(!1));A&&!i&&(ZC.A3(s).2O("4V","8q").2O("1K",n.I-15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#"+t.J+" 3a").5d(1n(){-1===ZC.AU([t.J+"-2i-c",t.J+"-2H-c"],1g.id)&&n.1h(1g)}),n.1h(l),n.1h(t.nv()),ZC.AO.kX(n,t.I,t.F,e)},ZC.AO.sU=1n(e,t,i){if(!ZC.cA){i=i||"g8/nz-ky";1a a=2g.4P("a");8V.wY?8V.wY(1m k6([e],{1J:i}),t):i3&&"g4"in a?(a.7B=i3.t2(1m k6([e],{1J:i})),a.4m("g4",t),2g.3s.2Z(a),a.3H(),2g.3s.b2(a)):89.7B="1V:g8/nz-ky,"+eQ(e)}},ZC.AO.hK=1n(e,t){1a i,a,n,l,r,o,s,A,C,Z,c,p,u,h=[],1b="",d=[];1j("80"===(t=t||"6L")&&h.1h(\'<4g e4:o="nC:ni-nF-bZ:nx:nx" e4:x="nC:ni-nF-bZ:nx:xq" e4="7h://8z.w3.dS/TR/18m-18n">\',"<fb>","\\18o!--[if 18a nQ 9]><jO><x:vj><x:vi><x:vg><x:u2>hO</x:u2><x:vf><x:17S/></x:vf></x:vg></x:vi></x:vj></jO><![18q]--\\17D",\'<1I>td{1G:2b;2t-9B:17R,nX-nO} .92{nQ-92-5I:"0.6X";} .1E{nQ-92-5I:"@";}</1I>\',"<uY 8C=17p 17r=17s.17t>","<uY tB=u4-8>","</fb>","<3s>"),i=0,a=e.AI.1f;i<a;i++){1a f=e.AI[i],g=f.AZ.A9,B={},v=[],b=f.BT("k")[0];"4g"!==t&&"80"!==t&&"dP"!==t||(h.1h("<6q>"),f.IZ&&""!==f.IZ.AN&&(d.1h([f.IZ.AN]),h.1h("<tJ>"+f.IZ.AN+"</tJ>")),h.1h("<uC>"),h.1h("<tr>")),c=[],u=[];1a m="17u",E=!1;1j(b&&(b.FB&&"5s"===b.FB.o.1J&&(m="a1",E=!0),b.M&&b.M.AN&&(m=b.M.AN.1F(/\\"|\\\'/g,""))),"6L"===t?c.1h(\'"\'+m+\'"\'):"dP"===t?u.1h(m):"4g"!==t&&"80"!==t||c.1h("<th>"+m+"</th>"),n=0,l=g.1f;n<l;n++)(1c===ZC.1d(g[n].o["8m"])||ZC.2s(g[n].o["8m"]))&&(p=(p=1c!==ZC.1d(g[n].AN)?g[n].AN+"":"ko "+n).1F(/\\"|\\\'/g,""),"6L"===t?c.1h(\'"\'+p+\'"\'):"dP"===t?u.1h(p):"4g"!==t&&"80"!==t||c.1h("<th"+("80"===t?\' uM="vP" 1O="1E"\':"")+">"+p+"</th>"),v.1h(""));if("6L"===t?h.1h(c.2M(",")):"dP"===t?d.1h(u):"4g"!==t&&"80"!==t||h.1h(c.2M("")),"4g"!==t&&"80"!==t||(h.1h("</tr>"),h.1h("</uC>"),h.1h("<vA>")),b){1j(s=0,A=b.Y.1f;s<A;s++)B[s+""]={kg:!1,cM:[].4B(v)};1j(n=0,l=g.1f;n<l;n++)if(1c===ZC.1d(g[n].o["8m"])||ZC.2s(g[n].o["8m"]))1j(r=0,o=g[n].R.1f;r<o;r++){1a D=g[n].R[r];D&&(B[s=D.BW?""+D.BW:""+r]=B[s]||{kg:!0,cM:[].4B(v)},B[s].cM[n]=D.AE,B[s].kg=!0)}1a J=[];1j(s in B)B[s].kg&&J.1h([s,B[s].cM]);1j(J.4i(1n(e,t){1l e[0]-t[0]}),C=0,Z=J.1f;C<Z;C++)"4g"!==t&&"80"!==t||h.1h("<tr>"),"3O"!==f.AF&&"7e"!==f.AF&&"8S"!==f.AF||b.Y[J[C][0]]&&(J[C][0]=b.Y[J[C][0]]),b.BV[J[C][0]]&&(J[C][0]=b.BV[J[C][0]]),b.Y[J[C][0]]&&(J[C][0]=b.Y[J[C][0]]),E&&(J[C][0]=ZC.AO.YT(J[C][0],"%Y-%mm-%dd %h:%i:%s"),"6L"===t&&(J[C][0]=\'"\'+J[C][0]+\'"\')),"6L"===t?h.1h([].4B(J[C][0]).4B(J[C][1]).2M(",")):"dP"===t?d.1h([].4B(J[C][0]).4B(J[C][1])):"4g"!==t&&"80"!==t||h.1h("<td"+("80"===t?\' uM="5B"\':"")+">"+[].4B(J[C][0]).4B(J[C][1]).2M("</td><td>")+"</td>"),"4g"!==t&&"80"!==t||h.1h("</tr>")}"4g"!==t&&"80"!==t||(h.1h("</vA>"),h.1h("</6q>")),a>1&&i<a-1&&("6L"===t?h.1h("","",""):"4g"!==t&&"80"!==t||h.1h("<p>&8u;</p>"))}1l"80"===t&&h.1h("</3s>","</4g>"),"dP"===t?d:("6L"===t?1b=h.2M("\\n"):"4g"!==t&&"80"!==t||(1b=h.2M("")),1b)},1o.t1=1n(e,t,i){1a a,n,l,r,o,s="",A="";1n C(e){ZC.A3.a8({1J:"iG",3R:n,1V:e,aF:1n(e,t,i){l&&l(e,t,i)}})}2g.cP("zc-5X")&&(e="zc-5X"),"3e"==1y(i=i||{})&&(i=3h.1q(i));1a Z=1o.6Z(e);if(Z)1P(t){1i"vy":if(r="9K",1c!==ZC.1d(a=i.5I)&&(r=a),1c!==ZC.1d(a=i.u1)&&(r=a),"sO"===r&&(r="dX"),1o.3J.iz&&"2F"===Z.AB&&("9K"===r||"dX"===r)){Z.bX(!0);1a c=ZC.AK(Z.J+"-2F").6o.4q,p=c.1L(">"),u=c.1L("</2F>");c=(c=\'<2F e4:kn="7h://8z.w3.dS/sQ/kn" e4="7h://8z.w3.dS/v9/2F" a4="1.1" 1s="\'+Z.I+\'" 1M="\'+Z.F+\'">[hX]\'+c.2v(p+1,u+6)).1F(/<ks(.+?)<\\/ks>/g,"");1a h=1n(){1a e,t=2w.i3||2w.17A||2w;e=t.t2&&2w.k6?t.t2(1m 2w.k6([c],{1J:"4d/2F+jO;tB-tc-16"})):"1V:4d/2F+jO;tB=u4-8,"+eQ(c),Z.bX(!1);1a a=1m 2w.d2;a.u0="xD",a.5a=e,a.hL=1n(){1a t=2g.4P("3a"),n=t.9d("2d");if(t.1s=a.1s,t.1M=a.1M,n.d3(a,0,0,t.1s,t.1M),i.5F&&"1n"==1y i.5F)4J{i.5F(t.jT("4d/"+r))}4M(l){i.5F(e)}}},1b=0,d=1n(){1a e=1m hP;e.bD("sV",Z.hV[1b]),e.uw="1E",e.t4=1n(e){1a t=e.2X.ub,i=t.m0(/17B?:\\/\\/[^ \\)]+/g),a=0;i.17o(1n(e){1a n=1m hP;n.bD("sV",e),n.uw="17C",n.t4=1n(n){1a l=1m 17E;l.t4=1n(n){t=t.1F(1m 5y(e),n.2X.17F),++a===i.1f&&(c=c.1F("[hX]","[hX]<1I><![17G["+t+"]]></1I>"),++1b===Z.hV.1f?(c=c.1F("[hX]",""),h()):d())},l.17H(n.2X.ub)},n.8f()})},e.8f()};Z.hV.1f?d():(c=c.1F("[hX]",""),h())}if("3a"!==Z.AB&&!1o.hZ)1l-1;if("3a"===Z.AB){if(!i.5F||"1n"!=1y i.5F)1l Z.TK(r);4J{i.5F(Z.TK(r))}4M(B){i.5F(-1)}}1u Z.NE(r,{},!0,i.5F);1p;1i"17I":1i"17J":if(!i.g4&&"3a"!==Z.AB&&!1o.hZ)1l-1;if(r="9K",o={},1c!==ZC.1d(a=i.uq)&&(o=a),1c!==ZC.1d(a=i.cZ)&&(o.cZ=a),1c!==ZC.1d(a=i.3f)&&(o.3f=a),1c!==ZC.1d(a=i.5I)&&(r=a),1c!==ZC.1d(a=i.u1)&&(r=a),1c!==ZC.1d(a=i.k5)&&(s=a),n=Z.E.tp||"",1c!==ZC.1d(a=i.3R)&&(n=a),l=1c,1c!==ZC.1d(a=i.5F)&&(l=a),"sO"===r&&(r="dX"),i.g4&&("3a"!==Z.AB||"g3"===r))1l o.g4=!0,""!==s&&(o.fn=s),8j Z.NE(r,o);if(""!==n){if("3a"===Z.AB)1l C(Z.TK(r));Z.NE(r,o,!0,1n(e){1l C(e)})}1p;1i"k8":if(n=Z.E.tM||"",1c!==ZC.1d(a=i.3R)&&(n=a),A=ZC.AO.17K(Z),""===n)1l A;l=1c,1c!==ZC.1d(a=i.5F)&&(l=a),ZC.A3.a8({1J:"iG",3R:n,1V:A,aF:1n(e,t,i){l&&l(e,t,i)}});1p;1i"wT":A=ZC.AO.hK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2M(" ")),r=t;1p;2q:i+=e.5A(o,1),r=t}1l i},RU.5j.kN=1n(){1a e=1g;ZC.AO.C8("18p",e,e.FO());1a t=ZC.P.HZ({2p:"zc-3l zc-4K zc-1I",id:e.J+"-4K",p:ZC.AK(e.J+"-1v"),wh:e.I-(ZC.96?0:10)+"/"+(e.F-(ZC.96?0:10))});t.1I.a2=99,t.4q=ZC.j2(\'<3B 1O="zc-4I-5B-1H zc-4I-s1">&8u;<a 7B="7u:8j(0)" id="\'+e.J+\'-4K-fV" 1O="zc-cS-6C">\'+ZC.HE["4K-fV"]+\'</a>&8u;<a 7B="7u:8j(0)" id="\'+e.J+\'-4K-fU" 1O="zc-cS-ez">\'+ZC.HE["4K-fU"]+\'</a></3B><3B 1O="zc-4I-5B-ao"><bP id="\'+e.J+\'-4K-4G" 1I="1s:\'+(e.I-35)+"px;1M:"+(e.F-95)+\'px;"></bP></3B><3B 1O="zc-4I-5B-ao zc-4I-5B-7Z" id="\'+e.J+\'-4K-wB"><an 1J="7K" 1T="\'+ZC.HE["4K-7m"]+\'" id="\'+e.J+\'-4K-7m" /></3B>\'),1o.tD&&(ZC.AK(e.J+"-4K-wB").4q+=\'<an 1J="7K" 1T="\'+ZC.HE["4K-9A"]+\'" id="\'+e.J+\'-4K-9A" />\'),ZC.A3("#"+e.J+"-4K-4G").8t(ZC.AO.XA(e.E.7g)),ZC.A3("#"+e.J+"-4K-fU").3r("3H",1n(){ZC.AK(e.J+"-4K-fU").7U="zc-cS-6C",ZC.AK(e.J+"-4K-fV").7U="zc-cS-ez",ZC.A3("#"+e.J+"-4K-4G").8t(ZC.AO.XA(e.E.4G))}),ZC.A3("#"+e.J+"-4K-fV").3r("3H",1n(){ZC.AK(e.J+"-4K-fU").7U="zc-cS-ez",ZC.AK(e.J+"-4K-fV").7U="zc-cS-6C",ZC.A3("#"+e.J+"-4K-4G").8t(ZC.AO.XA(e.E.7g))}),ZC.A3("#"+e.J+"-4K-7m").3r("3H",1n(){ZC.AO.C8("wm",e,e.FO()),ZC.P.ER(e.J+"-4K")}),1o.tD&&ZC.A3("#"+e.J+"-4K-9A").3r("3H",1n(){ZC.AO.C8("wm",e,e.FO());1a t=ZC.A3("#"+e.J+"-4K-4G").8t();ZC.P.ER(e.J+"-4K"),1o.3n(e.J,"aI",{1V:t})})},RU.5j.iI=1n(){1a e=1g;if(e.I<eX||e.F<eX)2w.bD("7h://8z.1o.bZ/vV/","","");1u{1a t=ZC.P.HZ({2p:"zc-3l zc-4r zc-1I",id:e.J+"-4r",p:ZC.AK(e.J+"-1v"),wh:e.I-(ZC.96?0:10)+"/"+(e.F-(ZC.96?0:10))}),i="";i+=\'<3B 1O="zc-4I-5B-1H zc-4I-s0">\'+ZC.HE["4r-5K"]+\'</3B><3B 1O="zc-4I-5B-1H"><an 1J="wd" id="\'+e.J+\'-qV" fk="fk" /><1H 1j="\'+e.J+\'-qV">\'+ZC.HE["4r-wg"]+"</1H>",ZC.3a&&(i+=\'&8u;&8u;&8u;&8u;&8u;<an 1J="wd" id="\'+e.J+\'-r9" fk="fk" /><1H 1j="\'+e.J+\'-r9">\'+ZC.HE["4r-ux"]+"</1H>"),i+=\'</3B><3B 1O="zc-4I-5B-1H zc-4I-s1">\'+ZC.HE["4r-w9"]+\'</3B><3B 1O="zc-4I-5B-ao"><bP id="\'+e.J+\'-4r-wz" 1I="1s:\'+(e.I-35)+"px;1M:"+((e.F-eX)/2-10)+\'px;"></bP></3B><3B 1O="zc-4I-5B-1H zc-4I-s1">\'+ZC.HE["4r-wc"]+\'</3B><3B 1O="zc-4I-5B-ao"><bP id="\'+e.J+\'-4r-4G" 1I="1s:\'+(e.I-35)+"px;1M:"+(e.F-18N)/2+\'px;"></bP></3B><3B 1O="zc-4I-5B-1H zc-4I-s1">\'+ZC.HE["4r-wi"]+(e.I>=18C?" <7D>("+ZC.HE["4r-wk"]+")</7D>":"")+\'</3B><3B 1O="zc-4I-5B-ao"><an 1J="1E" id="\'+e.J+\'-4r-r4" 1I="1s:\'+(e.I-35)+\'px;" /></3B><3B 1O="zc-4I-5B-ao zc-4I-5B-7Z"><an 1J="7K" 1T="\'+ZC.HE["4r-fP"]+\'" id="\'+e.J+\'-4r-fP" /><an 1J="7K" 1T="\'+ZC.HE["4r-iT"]+\'" id="\'+e.J+\'-4r-iT" /></3B>\',t.4q=ZC.j2(i),ZC.A3("#"+e.J+"-4r-4G").8t("18u\\n----------\\n"+ZC.AO.XA(e.E.4G)+"\\n\\18v\\n----------\\n"+ZC.AO.XA(e.E.7g)),ZC.A3("#"+e.J+"-4r-iT").3r("3H",1n(){ZC.P.ER(e.J+"-4r")}),ZC.A3("#"+e.J+"-4r-fP").3r("3H",1n(){1a t=ZC.A3("#"+e.J+"-4r-r4");if(/^((\\w+\\+*\\-*)+\\.?)+@((\\w+\\+*\\-*)+\\.?)*[\\w-]+\\.[a-z]{2,6}$/.5U(t.8t())){1a i="";ZC.3a&&(i=e.TK("9K"));1a a=("wv:"+e.E.4G+" ww:"+e.E.7g).1F(/\\r|\\n|\\t|(\\s{2,})/g,""),n="",l=[];ZC.A3("#"+e.J+"-r9").3Q("fk")&&l.1h("****18w:",i),ZC.A3("#"+e.J+"-qV").3Q("fk")&&l.1h("****3h:",a),l.1h("****18x:",ZC.A3("#"+e.J+"-4r-wz").8t(),"****18y:",t.8t(),"****fF:",ZC.fF,"****18M:",e.I,"****18z:",e.F,"****i3:",2w.89.7B,"****UA:",8V.c3,"****18s:",e.AB.5M(),"****18B:",vE.1s+"x"+vE.1M);1j(1a r=0;r<l.1f-1;r+=2)n+=l[r]+eQ(l[r+1]);n+="****18D";1a o=ZC.P.rq(ZC.AK(e.J+"-4r")),s=o.4P("vU");s.93=2g.89.hM+"//8z.1o.bZ/vV/18E.18F",s.9Q="iG",o.3s.2Z(s);1a A=o.4P("wC");A.1J="1E",A.8C="1V",A.1T=n,s.2Z(A),s.fP(),2w.5Q(1n(){w7(ZC.HE["4r-wD"]),ZC.P.ER(e.J+"-4r")},5x)}1u t.8t(ZC.H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i"br":o-=i.A6.I,s-=i.A6.F;1p;1i"c":o-=i.A6.I/2,s-=i.A6.F/2;1p;1i"t":o-=i.A6.I/2;1p;1i"r":o-=i.A6.I,s-=i.A6.F/2;1p;1i"b":o-=i.A6.I/2,s-=i.A6.F;1p;1i"l":s-=i.A6.F/2}ZC.P.PO(ZC.AK(a+"-2H-c"),{1K:o/n[0]-u+"px",1v:s/n[1]-u+"px"}),1c!==(t=ZC.AK(a+"-2H-1E"))&&(t.1I.3L="2b",ZC.P.PO(t,{1s:i.A6.I+"px",1M:i.A6.F+"px",1K:o/n[0]+"px",1v:s/n[1]+"px"}),t.1I.3L="8y")}}}hj(e){1g.4n(e)}f8(e,t){1a i,a,n,l,r,o,s,A=1g,C=A.H.J,Z=e.9D||e.2X.id,c=Z.1F(/--([a-zA-Z0-9]+)/,"").1F("-ba-1N","-1N").1F("-1N-2R","").1F("-2R","").1F("-1R-3z","").1F("-1R","").2n("-").9o(),p=Z.2n("--"),u=!1,h=!1,1b=!1;if("2r"===c[1]&&"1A"===c[3]&&"ch"===c[4]&&(u=!0),ZC.P.ER([C+"-2H-1E",C+"-2H",C+"-2H-1E-9c"]),u){if(!(l=A.H.OH(c[5])))1l;if(r=l.AZ.A9[c[2]],o=r.FP(c[0]),"xy"===l.AJ.3x&&o.RV(),!o)1l;ZC.A3("#"+C+"-2Y-"+c[5]+"-1A-"+c[2]+"-bg-2N-c").4n()}1u"1Y"===c[2]&&0===c[1].1L("1Q")&&(h=!0),0!==c[2].1L("1z")||0!==c[1].1L("1Q")&&0!==c[1].1L("1R")||(1b=!0),l=A.H.OH(c[3]);if(ZC.AK(C+"-2H")||(ZC.P.K1({id:C+"-2H",p:ZC.AK(C+"-3Y"),2p:"zc-3l zc-2H",wh:A.H.I+"/"+A.H.F,9L:"8R"},A.H.AB),ZC.P.HF({id:C+"-2H-c",p:ZC.AK(C+"-2H"),2p:"zc-3l",tl:"-4S/-4S",1s:140,1M:60},A.H.AB)),A.A6=1o.6e.a7("DM",A,C+"-2H-1E"),A.A6.OE="2H",A.A6.A=A.H,l&&l.A6&&A.A6.1S(l.A6),u)A.A6.1C(r.A6.o),l.D9["p"+r.L]&&l.D9["p"+r.L]["n"+o.L]&&A.A6.1C(r.A6.o[ZC.1b[73]]),2===p.1f&&A.A6.1C(r.nl(p[1]));1u{1a d=!1;if(h&&l.BG&&1c!==ZC.1d(l.BG.o.2H)&&(A.A6.o.1E="",A.A6.1C(l.BG.o.2H),d=!0),1b){A.A6.1C({"1U-1r":"#2S","1G-1s":1,"1G-1r":"#4S"});1a f=l.BK(c[2].1F(/\\1b/g,"-"));if(f&&1c!==ZC.1d(f.o.2H)&&(A.A6.o.1E="",A.A6.1C(f.o.2H),d=!0),0===c[1].1L("7y"))f&&(-1!==c[1].1L("xA")&&f.o.1H&&f.o.1H.2H?(A.A6.o.1E="",A.A6.1C(f.o.1H.2H),d=!0):f.o.1Q&&f.o.1Q.2H&&(A.A6.o.1E="",A.A6.1C(f.o.1Q.2H),d=!0));1u if(0===c[1].1L("aM")){1a g=ZC.1k(c[1].1F("aM",""));f.Q7[g]&&f.Q7[g].o.1H&&f.Q7[g].o.1H.2H&&(A.A6.o.1E="",A.A6.1C(f.Q7[g].o.1H.2H),d=!0)}}if("2T"===c[2])if(A.A6.1C({"1U-1r":"#2S","1G-1s":1,"1G-1r":"#4S"}),e.2X.bJ("1V-jI"))A.A6.1C({1E:e.2X.bJ("1V-2H-1E")}),d=!0;1u 1j(a=0,n=l.FC.1f;a<n;a++)if(1c!==ZC.1d(l.FC[a])){1a B=l.FC[a]3E R0?l.FC[a].BD:l.FC[a];l.J+"-2T-"+c[1]===l.FC[a].J&&1c!==ZC.1d(i=B.o.2H)&&(A.A6.1C(i),A.A6.o.7a&&(A.A6.o.x=B.iX,A.A6.o.y=B.iY),d=!0)}if("1H"===c[2])1j(A.A6.1C({"1U-1r":"#2S","1G-1s":1,"1G-1r":"#4S"}),a=0,n=l.BV.1f;a<n;a++)l.J+"-1H-"+c[1]===l.B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("6F 4H",e.R5):ZC.A3("#"+t+"-5W").3r("6F 4H",e.R5),ZC.A3(".zc-2r-1N").4c("6F 4H",e.R5))}}1O sM 2k CX{2G(e){1D(e);1a t=1g;t.IK=!0,t.sw=!1,t.D=e,t.H=e.A,t.JC=!1,t.hG=!1,t.H2=1c,t.B5=1c,t.Z=1c,t.JS=0,t.I6=0,t.PD=0,t.mk=0,t.LQ=!1,t.NQ=1c,t.lZ=!1,t.BV=1c,t.mo=!1}1q(){1a e,t=1g;t.J=t.D.J+"-2z",t.4y([["4c","sw","b"],["ag","LQ","b"],["2j-6T","PD","i"],["2j-6T-x","PD","i"],["2j-6T-y","PD","i"],["2h","AM","b"]]);1a i="("+t.D.AF+").2z",a=t.H.B8;1n n(e){1l[i+".3N",i+".3N-"+e,i+".3q",i+".3q-"+e]}t.B5=1m I1(t.D),t.B5.J=t.D.J+"-2z-15C",a.2x(t.B5.o,[i]),t.B5.1C(t.o),t.B5.1q(),t.o.1H&&(t.BV=[]),t.o.3q&&t.o.3q.1H&&(t.J5=1m DM(t.D),t.J5.1C(t.o.3q.1H),t.J5.1C({1E:" "}),t.J5.1q(),t.J5.AM&&(t.mo=!0)),t.OX=1m CX(t.D),a.2x(t.OX.o,[i+".4O"]),1c!==ZC.1d(e=t.o.4O)&&t.OX.1C(e),t.OX.1q(),t.UV=1m CX(t.D),a.2x(t.UV.o,[i+".6C"]),1c!==ZC.1d(e=t.o.6C)&&t.UV.1C(e),t.UV.1q(),t.IM=1m I1(t.B5),t.HB=1m I1(t.B5),t.J9=1m I1(t.B5),t.H0=1m I1(t.B5),a.2x(t.IM.o,n("1K")),a.2x(t.HB.o,n("2A")),a.2x(t.J9.o,n("1v")),a.2x(t.H0.o,n("2a"));1j(1a l=["3q","3N"],r=0;r<l.1f;r++)1c!==ZC.1d(e=t.o[l[r]])&&(t.IM.1C(e),t.HB.1C(e),t.J9.1C(e),t.H0.1C(e)),1c!==ZC.1d(e=t.o[l[r]+"-1K"])&&t.IM.1C(e),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(s-i,s-i+ZC.A3(e.KF).1s(),A-a,A-a+ZC.A3(e.KF).1M())}1l!1},e.WL=1n(){1l 1o.3n(e.H.J,"rI",{4E:""}),e.JC&&(ZC.A3(2g.3s).3k("7V 6f",e.VL),ZC.A3(2g.3s).3k("6k 5R",e.WL),e.JC=!1,e.D.OB=!1,e.hG&&e.3G(!1),e.hG=!1),!1},ZC.A3("."+e.D.J+"-2z-3N").3r("6F 4H",e.ZB),ZC.A3("."+e.D.J+"-2z-4O").3r("3H",e.rP),e.lZ=!0}}gc(){ZC.AO.gc(1g,["Z","C7","o","I3","JU","D","H","B5","UV","KJ","JX","L7","JE","KF","J9","HB","H0","IM","9G","OX","m3","XK","m4","WC"])}}1O gP 2k CX{2G(e,t){1D(e);1a i=1g;i.D=e,i.H=e.A,i.JC=!1,i.Z=1c,i.BJ=0,i.BB=0,i.hF="",i.cE="yx"===i.D.AJ.3x,i.AF=i.im=i.uH="1Z-"+(t||"x"),i.cE&&(i.AF+="i",i.im="1Z-xi"===i.AF?"1Z-y":"1Z-x")}1q(){1a e,t=1g;t.J=t.D.J+"-"+t.im,t.4y([["2c-x","BJ"],["2c-y","BB"]]);1a i="("+t.D.AF+").",a=t.H.B8;t.AY=1m I1(t.D),a.2x(t.AY.o,[i+"1Z.2U",i+t.AF+".2U"]),1c!==ZC.1d(e=t.o.2U)&&t.AY.1C(e),t.AY.1q(),t.AW=1m I1(t.D),a.2x(t.AW.o,[i+"1Z.3q",i+t.AF+".3q"]),1c!==ZC.1d(e=t.o.3q)&&t.AW.1C(e),t.AW.1q()}1t(){1a e=1g,t=e.D.BT("k")[0],i=e.D.BT("v")[0],a=e.D.Q;if(("1Z-x"===e.AF||"1Z-xi"===e.AF)&&t.E3===t.V&&t.ED===t.A1||("1Z-y"===e.AF||"1Z-yi"===e.AF)&&i.GZ===i.B3&&i.HM===i.BP)1l e.3k(),ZC.A3("#"+e.D.J+"-"+e.AF+"-3q").3p(),ZC.A3("#"+e.D.J+"-"+e.AF+"-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o.AY.I/n,r=o.KT}a=1B.43(t/i),l=s.B6.1f-s.EG,s.B6.1f%r&&(l+=r-s.B6.1f%r),s.D0.2j=1B.2j(a*r,l),s.D0.1X=s.D0.2j+s.EG,s.VF(),s.3j(!1),s.1q(),s.1t(),o.6D(),o.3r()}3k(){1a e=1g;ZC.A3("."+e.BG.J+"-"+e.AF+"-1Y-3q").3k("6F 4H",e.RH),ZC.A3("."+e.BG.J+"-"+e.AF+"-1Y-2U").3k("3H",e.RJ)}3r(){1a e=1g,t=e.H.J,i=0,a=0;e.RH=1n(n){if(n.6R(),!(n.7K>1)){1j(1a l=n.2X;l&&"jS"!==l.8h.5M();){if(-1!==ZC.P.TF(l).1L("zc-"+e.AF+"-3q"))1p;l=l.6o}if((ZC.2L||!(n.9f>1))&&l){1a r=ZC.P.MH(n),o=ZC.A3("#"+t+"-1v").2c();if("1Z-y"===e.AF){1a s=r[1]-o.1v;a=s-e.AW.iY}1u if("1Z-x"===e.AF){1a A=r[0]-o.1K;i=A-e.AW.iX}1l ZC.A3(2g.3s).3r("7V 6f",e.RI),ZC.A3(2g.3s).3r("6k 5R",e.NR),e.JC=!0,!1}}},e.RI=1n(n){if(n.6R(),e.JC){1a l=ZC.P.MH(n),r=ZC.A3("#"+t+"-1v").2c();if("1Z-y"===e.AF){1a o=l[1]-r.1v;o-a<e.AY.iY&&(o=e.AY.iY+a),o-a+e.AW.F>e.AY.iY+e.AY.F&&(o=e.AY.iY+e.AY.F+a-e.AW.F),e.3S(o-a)}1u if("1Z-x"===e.AF){1a s=l[0]-r.1K;s-i<e.AY.iX&&(s=e.AY.iX+i),s-i+e.AW.I>e.AY.iX+e.AY.I&&(s=e.AY.iX+e.AY.I+i-e.AW.I),e.3S(s-i)}}1l!1},e.NR=1n(){1l e.H.KP=e.hF.2n(","),e.JC&&(ZC.A3(2g.3s).3k("7V 6f",e.RI),ZC.A3(2g.3s).3k("6k 5R",e.NR),e.JC=!1),!1},e.Gd=1n(t){(t.uW?-120*t.uW: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(n&&(a.E["6b-1Q"]=e),r&&(a.E["6b-1Y"]=ZC.1k(e)),i=a.s3(ZC.1k(e)),a.VF(),a.3j(!0,i),a.YZ=!0,a.1q(),a.lf(!0),a.1t(),ZC.3m=l)}s3(e){1a t,i,a=1g,n=!1;1l e>=0&&(e<a.D0.2j||e>=a.D0.1X)&&(n=!0,"1Z"===a.U1?(e%(i="1Z-y"===a.DB.AF?a.DB.GW:a.DB.KT)&&(e-=e%i),a.D0.2j=e,a.D0.1X=e+a.EG,a.D0.1X>a.B6.1f&&(a.D0.2j=a.B6.1f-a.EG,a.B6.1f%i&&(a.D0.2j=a.D0.2j+(i-a.B6.1f%i)),a.D0.1X=a.B6.1f)):"3f"===a.U1&&(t=1B.4b(e/a.EG),a.D0.2j=t*a.EG,a.D0.1X=a.D0.2j+a.EG,a.D0.3f=t+1)),n}1q(){1a e,t,i,a,n=1g;if(n.E["db-gb"]=!0,n.QE=0,n.LC=0,1c!==ZC.1d(e=n.A.A.E["2Y-"+n.A.J+"-1Y-6E"])&&(n.o.x=e.x-n.A.iX,n.o.y=e.y-n.A.iY),ZC.3m)n.FJ&&n.FJ.1q(),n.KL&&n.KL.1q();1u{a=n.A.H.B8;1a l="("+n.A.AF+")";1D.1q(),n.4y([["gz","M7","b"],["lF","V9","b"],["153","VH","b"],["5Y","TO","b"],["9L","U1"],["1X-2B","EG","i"],["6a","lY","i"],["152-3N","UW"],["6b-1A","X9","b"],["6b-1Y","LF","b"],["3u","rY"],["9l-3u","JW"]]),n.M7&&!n.V9&&(n.M7=!1),1o.3J.rZ&&(n.E["uD-3u-2K"]||(n.kP({3u:n.rY,"9l-3u":n.JW,3x:n.NH}),n.E["uD-3u-2K"]=!0)),n.X9&&1c===ZC.1d(n.o["6b-1Y"])&&(n.LF=n.X9),n.BR=1m DM(n),a.2x(n.BR.o,l+".1Y.1Q"),n.o.1Q&&1c===ZC.1d(n.o.1Q.2h)&&(n.o.1Q.2h=!0),n.BR.1C(n.o.1Q),n.BR.1q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.BB,I===d.P1&&(d.E["mq-y"]&&(d.E["mq-y"]=!1,d.E["9x-2c-y"]=d.E["9x-y"]-M.iY),M.iY=d.E["9x-y"]-d.E["9x-2c-y"]-M.DE/4),M.1t(),1y d.E.jZ!==ZC.1b[31]&&1c!==ZC.1d(d.E.jZ)||ZC.3m||("3a"!==d.A.A.AB?M.E9():d.Y2.1h(M)));1a H=d.A5.E.1J;1c!==ZC.1d(t=g[I].o["1Y-1R"])&&1c!==ZC.1d(t.1J)&&(H=t.1J);1a P,N=!1;1P("m0"!==H&&"5l"!==H||(N=!0,H=1c!==ZC.1d(t=g[I].A5.o.1J)?t:"2q"),-1!==ZC.AU(["2q","9r"],H)?P=1m I1(d):(P=1m DT(d)).DN=H,P.OE="14X",P.1C(d.A5.o),d.A.E["1A"+I+".2h"]&&"6Q"!==g[I].o["1Y-6M"]||P.1C(d.NP.o),P.N7=g[I].N7,g[I].AF){1i"3O":1i"7e":1i"8S":1i"5t":1i"6O":1i"6c":1i"7k":1i"8i":1i"7R":1i"1N":1i"83":1i"8D":1i"aA":1i"aB":1i"b7":P.A0=g[I].A0,P.AD=g[I].AD,P.GM=g[I].GM,P.HL=g[I].HL;1p;1i"6v":1i"8r":1i"5m":1i"6V":P.A0="-1"!==g[I].A5.A0?g[I].A5.A0:g[I].A0,P.AD="-1"!==g[I].A5.AD?g[I].A5.AD:g[I].AD,P.GM=""!==g[I].A5.GM?g[I].A5.GM:g[I].GM,P.HL=""!==g[I].A5.HL?g[I].A5.HL:g[I].HL;1p;2q:P.A0=g[I].B9,P.AD=g[I].B9}"1w"!==P.DN&&"1N"!==P.DN||(P.B9=P.A0,P.AX=2),N&&P.1C(g[I].A5.o),P.o["1w-1I"]="2V",P.o.1J=P.DN,P.1C(g[I].o["1Y-1R"]),N&&(P.o.1J=P.DN),P.E["4n-1R"]=!0,P.E["4n-1w"]=!1,1c!==ZC.1d(t=P.o["4n-1w"])&&(P.E["4n-1w"]=ZC.2s(t)),1c!==ZC.1d(t=M.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}1u if(K8.5O)1j(1a j in K8.5O)if(K8.5O[j]&&K8.5O[j].6C){1a q=1o.6Z(j);H=q.FO(),ZC.AO.C8("um",q,H),K8.5O[j].6C=!1}if(0===G.1f&&(l={},r={},o={},t.SA&&(1c===ZC.1d(p.ei)&&c(),t.SA=!1),Z&&Z.A.A6&&A&&A.J!==Z.J&&Z.A.A6.5b()),G.1f>0){t.SA=!0;1j(1a $=!1,ee=0,te=G.1f;ee<te;ee++){1a ie=!1;if(1c===ZC.1d(l[ee])&&(l[ee]={}),1c===ZC.1d(r[ee])&&(r[ee]={}),1c===ZC.1d(o[ee])&&(o[ee]={}),(G[ee].CY||G[ee].KD)&&"9w"===G[ee].MF){1a ae,ne=[],le=[],re=[],oe=!1,se="",Ae=[],Ce=[],Ze=[],ce=[],pe={},ue={},he=[];f=G[ee].Q;1a 6h=G[ee].CY&&1c!==ZC.1d(G[ee].CY.o.nk)&&ZC.2s(G[ee].CY.o.nk),de=-1;G[ee].CY&&(de=ZC.1k(ZC.9q(G[ee].CY.o.g2||-1))),ZC.3w,ZC.3w;1a fe,ge,Be=!0,ve=[],be="";1j(G[ee].CY&&(1c!==ZC.1d(G[ee].CY.o["1A-1H"])&&ZC.1d(1c!==(e=G[ee].CY.o["1A-1H"].ay))&&(Be=ZC.2s(e)),1c!==ZC.1d(G[ee].CY.o["1T-1H"])&&ZC.1d(1c!==(e=G[ee].CY.o["1T-1H"].ay))&&(Be=ZC.2s(e))),L=0,w=G[ee].AZ.A9.1f;L<w;L++)if(!G[ee].AZ.A9[L].LY&&(u=L,G[ee].CY&&G[ee].CY.o["9o-dW"]&&(u=w-L-1),G[ee].E["1A"+u+".2h"])){if(1c!==ZC.1d(z)&&u!==z)f2;if(!(fe=G[ee].BK(G[ee].AZ.A9[u].BT("k")[0])))f2;if(fe.D8){1a me=fe.AT?fe.iY+fe.BY:fe.iY+fe.A7,Ee=fe.AT?fe.iY+fe.F-fe.BY:fe.iY+fe.F-fe.A7;d=ZC.5u(d,me,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[P].E.8s<=b)||(ze?(Ve%Se==0&&(be+="<tr>"),be+="<td>"+ve[P]+"</td>",Ve%Se==Se-1&&(be+="</tr>"),Ve++):be+=ve[le[P].E.wJ],ze||!Qe));P++);if(ze&&(Ve%Se!=Se-1&&(be+="</tr>"),be+="</6q>"),""!==se&&(be+=se),!Be&&le.1f>0&&(1b=F=D,d=I=J,""!==be&&(le[0].o.1E=ze||Qe?be:be.2v(0,be.1f-4),le[0].1q()),M=1c!==ZC.1d(v.o.6T)?ZC.1k(v.o.6T):6,1c===ZC.1d(v.o.x)?fe.D8?1b<G[ee].iX+G[ee].I/2?le[0].iX=1b+M+14:le[0].iX=1b-le[0].I-M-14:ae&&ae.iX>=f.iX+f.I/2?le[0].iX=F-le[0].I-M:le[0].iX=F+M:le[0].iX-=f.iX,1c===ZC.1d(v.o.y)?fe.D8?ae&&ae.iY>=f.iY+f.F/2?le[0].iY=I-le[0].F-M:le[0].iY=I+M:d<G[ee].iY+G[ee].F/2?le[0].iY=d+M+14:le[0].iY=d-le[0].F-M-14:le[0].iY-=f.iY),ie){1a Ue=-1,We=-1;if($||(1c===ZC.1d(p.ei)&&c(),$=!0),Ae.1f>0){1a je=[];1j(b=ZC.3w,Y=0,x=Ae.1f;Y<x;Y++)Ae[Y][0]>=0&&(b=ZC.CQ(Ae[Y][0],b));1j(-1!==de&&(b=ZC.BM(b,de)),Y=0,x=Ae.1f;Y<x;Y++)1c!==ZC.1d(Ae[Y])&&(-1===Ae[Y][0]||Ae[Y][0]<=b)&&(G[ee].CY&&G[ee].CY.o["bO-1w"]&&ZC.2s(G[ee].CY.o["bO-1w"])?(je=[].4B(Ae[Y][1]),"xy"===G[ee].AJ.3x?Ue=ZC.4o(Ae[Y][1][1][0]):"yx"===G[ee].AJ.3x&&(We=ZC.4o(Ae[Y][1][1][1]))):je=je.4B(Ae[Y][1]));if(G[ee].CY.o.4O){1a qe=-1;je.1f>1&&je[1]&&(qe=je[1][0]||-1),G[ee].CY.9G||(G[ee].CY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(le[u].AM&&-1===ZC.AU(it,le[u]))if(fe.D8){if(le[u+1].iX<le[u].iX+le[u].I){if(le[u+1].iX-le[u].I-4<f.iX&&-1===ZC.AU(tt,le[u])&&(tt.1h(le[u]),le[u].iX=f.iX),le[u+1].iX=le[u].iX+le[u].I+4,le[u+1].iX+le[u+1].I>f.iX+f.I)1j(lt=le[u+1].iX-(f.iX+f.I-le[u+1].I),at=0,nt=le.1f;at<nt;at++)le[at].iX-lt>=f.iX?le[at].iX-=lt:(le[at].iX=f.iX,at>0&&(le[u+1].E["1R-y"]<f.iY+f.F/2?le[at].iY=le[at-1].iY+le[at-1].F+4:le[at].iY=le[at-1].iY-le[at].F-4));rt=!0}}1u if(le[u+1].iY<le[u].iY+le[u].F){if(le[u+1].iY-le[u].F-4<f.iY&&-1===ZC.AU(tt,le[u])&&(tt.1h(le[u]),le[u].iY=f.iY),le[u+1].iY=le[u].iY+le[u].F+4,le[u+1].iY+le[u+1].F>f.iY+f.F)1j(lt=le[u+1].iY-(f.iY+f.F-le[u+1].F),at=0,nt=le.1f;at<nt;at++)le[at].iY-lt>=f.iY?le[at].iY-=lt:(le[at].iY=f.iY,at>0&&(le[u+1].E["1R-x"]<f.iX+f.I/2?le[at].iX=le[at-1].iX+le[at-1].I+4:le[at].iX=le[at-1].iX-le[at].I-4));rt=!0}}}1a At=!1;1j(u=0,h=Ze.1f;u<h;u++)if(-1===Ze[u].E.8s||Ze[u].E.8s<=b){1a Ct=Ze[u];G[ee].AJ["3d"]&&(G[ee].NF(),X=1m CA(G[ee],Ct.iX+Ct.I/2-ZC.AL.DW,Ct.iY+Ct.F/2-ZC.AL.DX,0),Ct.iX=X.E7[0]-Ct.I/2,Ct.iY=X.E7[1]-Ct.F/2,X=1m CA(G[ee],Ct.DH[0]-ZC.AL.DW,Ct.DH[1]-ZC.AL.DX,0),Ct.DH[0]=X.E7[0],Ct.DH[1]=X.E7[1]),G[ee].CY&&G[ee].CY.o["bO-1w"]&&ZC.2s(G[ee].CY.o["bO-1w"])?("xy"===G[ee].AJ.3x&&Ue===ZC.4o(Ct.iX+Ct.I/2)||"yx"===G[ee].AJ.3x&&We===ZC.4o(Ct.iY+Ct.F/2))&&!At&&(Ct.1t(),At=!0):Ct.1t()}1j(b=ZC.3w,P=0,N=le.1f;P<N;P++)le[P].E.8s>=0&&(b=ZC.CQ(le[P].E.8s,b));1j(-1!==de&&(b=ZC.BM(b,de)),L=0,P=0,N=le.1f;P<N;P++)if(-1===le[P].E.8s||le[P].E.8s<=b){1a Zt=ZC.E0(le[P].DH[0],f.iX-5,f.iX+f.I+5)&&ZC.E0(le[P].DH[1],f.iY-5,f.iY+f.F+5);if(!Be||Zt){if(le[P].AM){1P(le[P].E[ZC.1b[7]]){1i"1v":fe.D8?le[P].DH[0]=le[P].iX-le[P].G2:le[P].DH[1]=le[P].iY+le[P].F+le[P].G2;1p;1i"2a":fe.D8?le[P].DH[0]=le[P].iX+le[P].I+le[P].G2:le[P].DH[1]=le[P].iY-le[P].G2}if(-1!==ZC.AU(["1v","2a"],le[P].E[ZC.1b[7]])){1a ct=le[P].iX+le[P].I/2;le[P].iX=ZC.BM(le[P].iX,0),le[P].iX=ZC.CQ(le[P].iX,t.H.I-le[P].I),le[P].iY=ZC.BM(le[P].iY,0),le[P].iY=ZC.CQ(le[P].iY,t.H.F-le[P].F),1c===ZC.1d(le[P].o["6G-2c"])&&(le[P].ET=5v(100*(ct-le[P].iX-le[P].I/2)/(le[P].I-le[P].H3),10))}if(G[ee].AJ["3d"]&&(G[ee].NF(),X=1m CA(G[ee],le[P].iX+le[P].I/2-ZC.AL.DW,le[P].iY+le[P].F/2-ZC.AL.DX,0),le[P].iX=X.E7[0]-le[P].I/2,le[P].iY=X.E7[1]-le[P].F/2,X=1m CA(G[ee],le[P].DH[0]-ZC.AL.DW,le[P].DH[1]-ZC.AL.DX,0),le[P].DH[0]=X.E7[0],le[P].DH[1]=X.E7[1],"1K"===le[P].EP?le[P].iX=le[P].DH[0]+M:le[P].iX=le[P].DH[0]-le[P].I-M),G[ee].AJ["3d"]||Be||0!==L||(le[P].iX=ZC.BM(f.iX-5,le[P].iX),le[P].iY=ZC.BM(f.iY-5,le[P].iY),le[P].iX=ZC.CQ(f.iX+f.I-le[P].I+5,le[P].iX),le[P].iY=ZC.CQ(f.iY+f.F-le[P].F+5,le[P].iY)),Be||!Be&&0===L){1a pt=Be?P:0;(!Be||"3a"===t.H.AB&&le[pt].o["1U-4d"]&&""!==le[pt].o["1U-4d"])&&le[pt].1q(),le[pt].1t(),L++}}if(Zt){1a ut=1m DT(t);if(t.H.B8.2x(ut.o,"("+G[ee].AF+").2i.1R"),ut.J=le[P].J+"-1R",ut.Z=ut.C7=a,ut.iX=le[P].E["1R-x"],ut.iY=le[P].E["1R-y"],G[ee].AJ["3d"]&&(G[ee].NF(),X=1m CA(G[ee],ut.iX-ZC.AL.DW,ut.iY-ZC.AL.DX,0),ut.iX=X.E7[0],ut.iY=X.E7[1]),y=le[P].E["2i-1I"],ut.A0=ut.AD=ZC.AO.JK(y[ZC.1b[0]]),ut.BU=y.1r,ut.1C(G[ee].CY.o.1R),ut.1C(G[ee].AZ.A9[le[P].E.7b].o["2i-1R"]),"5l"===ut.o.1J){1a ht=G[ee].AZ.A9[le[P].E.7b];ht.A5&&ht.A5.o.1J&&(ut.o.1J=ht.A5.o.1J)}ut.1q(),ut.AM&&"2b"!==ut.DN&&ut.AH>1&&ut.1t()}}}(H=G[ee].HV()).2B=ne,H.2i={x:F,y:I},H.ev=p,H["1z-1H"]=ue,ZC.AO.C8("x9",t.H,H),G[ee].PU(!0)}1u(H={}).2i={x:F,y:I},H.ev=p,ZC.AO.C8("x9",t.H,H)}}}}}},t.jq=1n(){0!==1o.3J.ru&&2w.5Q(1n(){c()},ZC.1k(1o.3J.ru))},ZC.A3(2g.3s).3r("7V 4H 6f",t.QH),ZC.A3(2g.3s).3r("5R",t.jq)}}K8.h0=1n(e){1a t=1o.6Z(e);if(t){1o.hq=1c;1a i=ZC.AK(e+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])&&(d=ZC.2s(e))),1c!==ZC.1d(e=m["fg-3A"])&&(f=ZC.2s(e)),1c!==ZC.1d(e=m["17f-3A"])&&(g=ZC.2s(e)),1c!==ZC.1d(e=m["17e-5I"])&&(B=ZC.2s(e)),1c!==ZC.1d(e=m.rk)&&(b=e),1c!==ZC.1d(b)&&b.1f>0){i=[],1c!==ZC.1d(e=m["5B-8E"])?c=e:Z.2n(/\\n/).1f>0?c="\\n":Z.2n(/\\r/).1f>0&&(c="\\r");1a E=Z.2n(c),D=0;1j(l=0,r=E.1f;l<r;l++)if(""!==E[l].1F(/\\s+/g,"")){i[D]=[];1j(1a J=0,F=0;J<E[l].1f-1;)n=E[l].2v(J,J+b[F]),i[D].1h(n),J+=b[F],F++;D++}}1u{i=[[]],a=1c!==ZC.1d(e=m["5B-8E"])?1m 5y("(\\\\"+p+"|"+e+\'|^)(?:"([^"]*(?:""[^"]*)*)"|([^"\\\\\'+p+e+"]*))","gi"):1m 5y("(\\\\"+p+\'|\\\\r?\\\\n|\\\\r|^)(?:"([^"]*(?:""[^"]*)*)"|([^"\\\\\'+p+"\\\\r\\\\n]*))","gi");1j(1a I=1c;I=a.3n(Z);){1a Y=I[1];Y.1f&&Y!==p&&i.1h([]),n=I[2]?I[2].1F(1m 5y(\'""\',"g"),\'"\'):I[3],i[i.1f-1].1h(n)}}1a x=[];1j(l=0,r=i.1f;l<r;l++)0!==i[l].2M("").1F(/\\s+/g,"").1f&&x.1h(i[l]);1a X=0,y=0;if((1c===ZC.1d(h)||h)&&(x.1f>1&&1===x[0].1f?(1c===ZC.1d(t.o.5E)?t.o.5E={1E:x[0][0]}:1c===ZC.1d(t.o.5E.1E)&&(t.o.5E.1E=x[0][0]),h=!0):h=!1),h&&X++,u){1j(i=[],h&&i.1h(x[0]),o=X,s=x.1f;o<s;o++)1j(A=0,C=x[o].1f;A<C;A++)1c===ZC.1d(i[A+X])&&(i[A+X]=[]),i[A+X].1h(x[o][A]);x=i}if("1n"==1y 1o.vH)1j(o=0,s=x.1f;o<s;o++)1j(A=0,C=x[o].1f;A<C;A++)x[o][A]=1o.vH.4x(1g,x[o][A],o,A,t.D.A.J);1a L=0;1j(l=0,r=x.1f;l<r;l++)L=ZC.BM(L,x[l].1f);1a w=[];if(1c===ZC.1d(1b)){1a M=x[X].2M("").1f;1b=x[X].2M("").1F(/[0-9]/g,"").1f/M>.75}1b&&(w=x[X],X++);1a H=[];if(1c===ZC.1d(d))if(1b&&-1!==w[0].1L("\\\\"))d=!0;1u{1a P="";1j(o=X,s=x.1f;o<s;o++)P+=x[o][0];1a N=P.1f;d=P.1F(/[0-9]/g,"").1f/N>.75}if(d){1j(o=X,s=x.1f;o<s;o++)B?H.1h(ZC.1k(x[o][y])):H.1h(x[o][y]);y++}1a G=[],T=[];1j(A=y;A<L;A++){T[A-y]=[];1a O=1c,k=1c,K=0,R=1c;1j(o=X,s=x.1f;o<s;o++)if(1c!==ZC.1d(x[o][A])&&""!==x[o][A]&&1y x[o][A]!==ZC.1b[31]){n=x[o][A],1c!==ZC.1d(R)||v||(R=n.1F(/[0-9\\-\\,\\.\\+\\e]+/g,"%v")),v||(n=n.1F(/[^0-9\\-\\,\\.\\+\\e]+/g,""));1a z=n.1L("."),S=n.1L(",");-1!==z&&-1!==S?z<S?(O=".",k=",",K=ZC.BM(0,n.1f-S)):(O=",",k=".",K=ZC.BM(0,n.1f-z)):-1===z&&-1!==S?n.1f-S-1==3?(O=",",k="."):(O=".",k=",",K=ZC.BM(0,n.1f-S)):-1!==z&&-1===S&&(n.1f-z-1==3?(O=".",k=","):(O=",",k=".",K=ZC.BM(0,n.1f-z))),"."===O&&(n=n.1F(/\\./g,"").1F(/,/g,".")),","===O&&(n=n.1F(/,/g,"")),T[A-y].1h(v?n:ZC.1W(n))}1u T[A-y].1h(1c);G[A-y]={},1c!==ZC.1d(R)&&(G[A-y].5I=R),1c!==ZC.1d(O)&&(G[A-y][ZC.1b[13]]=O),1c!==ZC.1d(O)&&(G[A-y][ZC.1b[14]]=k),0!==K&&(G[A-y][ZC.1b[12]]=K)}if(B)1j(l=0,r=T.1f;l<r;l++)1j(1a Q=0;Q<T[l].1f;Q++)T[l][Q]=[H[Q],T[l][Q]];1a V=[];1P(t.D.AF){1i"1w":1i"1N":1i"5t":1i"6c":1i"97":1i"83":1i"6O":1i"7k":1i"9u":1c===ZC.1d(t.o[ZC.1b[50]])&&(t.o[ZC.1b[50]]={});1a U=[];d&&1c!==ZC.1d(w[0])&&(U=w[0].2n(/\\\\/)),1c!==ZC.1d(U[0])&&(1c===ZC.1d(t.o[ZC.1b[50]].1H)&&(t.o[ZC.1b[50]].1H={}),1c===ZC.1d(t.o[ZC.1b[50]].1H.1E)&&(t.o[ZC.1b[50]].1H.1E=U[0])),d&&(1c===ZC.1d(t.o[ZC.1b[50]][ZC.1b[5]])?t.o[ZC.1b[50]][ZC.1b[5]]=H:1c===ZC.1d(t.o[ZC.1b[50]][ZC.1b[10]])&&(t.o[ZC.1b[50]][ZC.1b[10]]=H));1a W=[];if(1c!==ZC.1d(g)&&g)1j(l=0,r=T.1f;l<r;l++)W[l]=ZC.1b[51]+(0===l?"":"-"+(l+1));1u if(1c!==ZC.1d(f)&&f){1a j={},q=0,$=[];1j(l=0,r=T.1f;l<r;l++){1j(1a ee=0,te=0,ie=T[l].1f;te<ie;te++)ee+=T[l][te];ee/=T[l].1f;1a ae=1B.43(ZC.JN(ee)/1B.a6/2);1c===ZC.1d(j[ae])&&(j[ae]=ZC.1b[51]+(0===q?"":"-"+(q+1))),-1===ZC.AU($,G[l].5I)?(W[l]=ZC.1b[51]+(0===q?"":"-"+(q+1)),q++):(W[l]=j[ae],q++),$.1h(G[l].5I)}}1j(0===W.1f&&(W[0]=ZC.1b[51]),1c===ZC.1d(t.o[ZC.1b[11]])&&(t.o[ZC.1b[11]]=[]),l=0,r=T.1f;l<r;l++)1c===ZC.1d(t.o[ZC.1b[11]][l])&&(t.o[ZC.1b[11]][l]={}),t.o[ZC.1b[11]][l][ZC.1b[5]]=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t&&a.BL[n].Y.1f>0)&&i.1h(a.BL[n]);1l i}BK(e){1j(1a t=1g,i=0,a=t.BL.1f;i<a;i++)if(t.BL[i].BC===e)1l t.BL[i];1l 1c}NG(e){1l e}wp(e){1l 1m ZC.vF(1g,e)}O3(){1j(1a e=1g,t=0,i=e.BL.1f;t<i;t++){1a a=e.BL[t],n=a.BC;e.A.B8.2x(a.o,["("+e.AF+").4z","("+e.AF+")."+n.1F(/\\-[0-9]+/,""),"("+e.AF+")."+n.1F(/\\-[0-9]+/,"-n"),"("+e.AF+")."+n],!1,!0);1a l=n.1F(/\\-[0-9]+/,"")+"-n";e.o[l]&&a.1C(e.o[l]),e.o[n]&&a.1C(e.o[n]),e.AJ["3d"]&&e.A.B8.2x(a.o,["("+e.AF+").4z[3d]","("+e.AF+")."+n.1F(/\\-[0-9]+/,"")+"[3d]","("+e.AF+")."+n.1F(/\\-[0-9]+/,"-n")+"[3d]","("+e.AF+")."+n+"[3d]"],!1,!0),e.AJ["3d"]&&a.1C(e.o[n+"[3d]"]),a.1q()}}UQ(){1l 1c}tF(e){1a t,i,a,n=1g,l=0,r=n.AZ.A9.1f;1j(t=0;t<r;t++)l=ZC.BM(l,n.AZ.A9[t].R.1f);1n o(e){1l e=(e=(e=e.1F(/(%N|%2r-eH)/g,l)).1F(/(%P|%1A-eH)/g,r)).1F(/(%S|%1z-6g-eH)/g,a.Y.1f)}1j(t=0,i=n.BL.1f;t<i;t++)(a=n.BL[t]).H5(e),2===e&&(a.IT=o,a.DA()&&a.1q()),1c===ZC.1d(a.o["1X-2B"])&&1c===ZC.1d(a.o["1X-cC"])&&a.T6(),1c===ZC.1d(a.o["1X-9F"])&&a.lo()}OG(){}NF(){}nZ(){}ok(){}ld(){1a e=1g,t=e.A.B8,i="("+e.AF+")";e.Q=1m I1(e),e.Q.OE="2u",e.Q.J=e.J+"-2u";1a a=[i+".2u"];if(e.BI&&a.1h(i+".2u[2z]"),e.AJ["3d"]&&a.1h(i+".2u[3d]"),t.2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BL.1f;C<Z;C++)e.BL[C].WR(),e.BL[C].GT()}ta(){1a e,t,i,a=1g,n=["1v","2A","2a","1K"],l={};1j(t=0;t<n.1f;t++)l[n[t]]=!1,a.E["2u.d-2y-"+n[t]]&&(a.o.2u["2y-"+n[t]]=1c),a.o.2u&&"4N"===a.o.2u["2y-"+n[t]]&&(l[n[t]]=!0,a.o.2u["2y-"+n[t]]="20");1a r=!1,o={};if("xy"===a.AJ.3x&&(r=!0),("xy"===a.AJ.3x||"yx"===a.AJ.3x)&&(a.Q.E["d-2y"]||a.E["2u.d-2y"])){1j(1a s=0,A=a.BL.1f;s<A;s++){1a C=0,Z=0,c="",p=a.BL[s];if(p.AM&&p.TJ){"k"===p.AF?c=p.D8?"2q"===p.B7?"1K":"2A":"2q"===p.B7?"2a":"1v":"v"===p.AF&&(c=p.D8?"2q"===p.B7?"2a":"1v":"2q"===p.B7?"1K":"2A");1a u=0;if(a.Q.E["d-2y-"+c]||a.E["2u.d-2y-"+c]){1a h=1m DM(p);h.1S(p.BR);1a 1b=ZC.BM(1,ZC.1k((p.A1-p.V)/p.EG));1j(t=p.V;t<=p.A1;t+=1b)if(h.AN=p.FL(t),h.iE&&("k"===p.AF&&!p.D8||"v"===p.AF&&p.D8)&&(h.o[ZC.1b[19]]=ZC.1k(.9*p.A8)),h.1q(),h.AM)if(Z=ZC.BM(Z,h.AA%180==0?h.F:h.I),C=ZC.BM(C,h.AA%180==0?h.I:h.F),u=ZC.BM(u,1.5*h.DE*(h.AN||"").2n(/<br>|<br\\/>|<br \\/>|\\n/).1f),"1v"===c||"2a"===c){if(u=ZC.BM(u,.rc*h.DE+1.l3*ZC.2l(ZC.EH(h.AA))*ZC.BM(h.I,h.F)),C=h.I,Z=u,r&&"k"===p.AF){o[p.BC]||(o[p.BC]=[]);1a d=1c===ZC.1d(h.o["3g-3u"])||ZC.2s(h.o["3g-3u"]),f=.rc*h.DE+1.l3*ZC.2l(ZC.EC(h.AA))*ZC.BM(h.I,h.F);"2q"===p.B7?(d&&(ZC.E0(ZC.gY(h.AA),90,180)||ZC.E0(ZC.gY(h.AA),3V,2m))&&o[p.BC].1h(f),d||o[p.BC].1h(f/2)):(d&&(ZC.E0(ZC.gY(h.AA),0,90)||ZC.E0(ZC.gY(h.AA),180,3V))&&o[p.BC].1h(f),d||o[p.BC].1h(f/2))}}1u C=u=ZC.BM(u,.rc*h.DE+1.l3*ZC.2l(ZC.EC(h.AA))*ZC.BM(h.I,h.F)),Z=h.F;1a g=1m DM(p);g.1S(p.M),g.AN=p.M.AN,g.1q(),""!==g.AN&&g.AM&&(Z+=g.AA%180==0?g.F:g.I,C+=g.AA%180==0?g.I:g.F)}if(a.o.2u||(a.o.2u={}),("4N"===a.o.2u["2y-"+c]||a.Q.E["d-2y-"+c])&&(a.Q.E["d-2y-"+c]=!1,l[c]=!0,a.o.2u["2y-"+c]="0"),l[c]){a.o.2u["2y-"+c]=ZC.1W(a.o.2u["2y-"+c]||"0"),a.E[p.BC+"-6T"]=a.o.2u["2y-"+c];1a B=("1v"===c||"2a"===c?ZC.1k(Z):ZC.1k(C))+10+(a.AJ["3d"]?20:0);if(p.VT?a.o.2u["2y-"+c]=ZC.BM(a.o.2u["2y-"+c],B):a.o.2u["2y-"+c]+=B,1c!==ZC.1d(a.o.2u["2y-"+c+"-2c"])&&(a.o.2u["2y-"+c]+=ZC.1k(a.o.2u["2y-"+c+"-2c"])),!a.A.TX){1a v={},b=a.A.DC.ew;a.A.B8.2x(v,"6A.5i.ew"),b&&ZC.2E(b,v),1===a.A.o[ZC.1b[16]].1f&&a.A.o[ZC.1b[16]][0].5i&&(e=a.A.o[ZC.1b[16]][0].5i.ew)&&ZC.2E(e,v);1a m=v.2K||"br";-1===ZC.AU(["tl","tr","br","bl"],m)&&(m="br"),("2a"!==c||"bl"!==m&&"br"!==m)&&("1v"!==c||"tl"!==m&&"tr"!==m)||(a.o.2u["2y-"+c]+=15)}"2a"===c&&("xy"===a.AJ.3x&&a.I8||"yx"===a.AJ.3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c;if(!1o.4F.8n&&((e=A.o["gV-6L"])&&(A.RL=e["gV-3R"]),(e=A.o.6L)&&("4h"==1y e?e.3R?A.RL=e.3R:e["1V-3e"]&&(c=e["1V-3e"]):A.RL=e),""!==A.RL&&1c!==ZC.1d(A.A.iN[A.RL])&&(c=A.A.iN[A.RL]),A.H.NV&&(c=A.H.NV),c)){1a p=A.wp(c);A.o=p.1q()}if(A.LQ=1o.wn,A.4y([["cJ","VI","b"],["cu","NJ","f"],["ag","LQ","b"],["nj","CB","b"],["7F-1J","KR"],["Df-1J","k1"],["3R-1V","pj"],["3f","L8","i"],["6P","BS"],["4i-2J","pZ","b"]]),A.BS.1f>0)1j(C.B8.6P=[],a=0;a<A.BS.1f;a++){1a u=A.BS[a],h=ZC.AO.JK(A.BS[a],10),1b=ZC.AO.R2(A.BS[a],10);C.B8.6P.1h(["#2S",u,h,1b])}"7e"===A.AF&&(A.F6.7G=!0),(A.AJ["3d"]||A.A.dR)&&(A.LQ=!1),A.ok(),-1===ZC.AU(A.H.KP,ZC.1b[41])&&((1c!==ZC.1d(e=A.o.2z)||C.PT("2z",A.AF))&&A.AJ[ZC.1b[56]]&&(A.BI&&!A.E["db-2z-1q"]||1y sM===ZC.1b[31]||(A.E["db-2z-1q"]=!1,A.BI=1m sM(A),A.BI.OE="2z",C.2x(A.BI.o,Z+".2z"),(t=A.o.2u)&&A.BI.1C({"1U-1r":t[ZC.1b[0]],"1U-1r-1":t["1U-1r-1"],"1U-1r-2":t["1U-1r-2"],"5e-tv":t["5e-tv"],"5e-gR":t["5e-gR"]}),A.BI.1C(e),A.BI.1q())),(1c!==ZC.1d(e=A.o["1Z-x"])||C.PT("1Z-x",A.AF))&&A.AJ["4U-1Z"]&&(A.I8||1y gP===ZC.1b[31]||(A.I8=1m gP(A,"x"),A.I8.OE="17a",C.2x(A.I8.o,Z+".1Z-x"),A.I8.1C(e),A.I8.1q())),(1c!==ZC.1d(e=A.o["1Z-y"])||C.PT("1Z-y",A.AF))&&A.A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5W")&&ZC.AK(r.A.J+"-3c")){ZC.AK(r.A.J+"-5W").4m("tX","");1a Z=ZC.AK(r.A.J+"-3c").kQ(!0);1j(a=(n=Z.6Y.1f)-1;a>=0;a--)-1!==Z.6Y[a].7U.1L(r.J+"-2r-1N")&&Z.b2(Z.6Y[a]);ZC.P.ER(r.A.J+"-3c"),ZC.AK(r.A.J+"-1v").2Z(Z),ZC.AK(r.A.J+"-5W").4m("tX","#"+r.A.J+"-3c")}1P(r.AZ.HQ=[],ZC.A3("."+r.J+"-1T-3C",C).3p(),ZC.A3("."+r.J+"-1z-1R-1H",C).3p(),ZC.A3("."+r.J+"-1z-1Q",C).3p(),ZC.A3("."+r.J+"-1z-1H",C).3p(),ZC.A3("."+r.J+"-2i-1H",C).3p(),ZC.A3("."+r.J+"-2T-1H",C).3p(),ZC.A3("."+r.J+"-sZ-1H",C).3p(),e||ZC.A3("."+r.J+"-2z-1Q",C).3p(),r.A.AB){1i"2F":1j(a=0,n=r.AZ.A9.1f;a<n;a++)r.AZ.A9[a].HH=1c;ZC.A3("#"+r.A.J+"-jN").9z().5d(1n(){"16p"!==1g.8h.5M()&&(0!==1g.id.1L(r.J+"-")&&1!==r.A.AI.1f||(e?1g.id!==r.J+"-5e"&&-1===1g.id.1L("-2z-5e")&&-1===1g.id.1L("-2C-8a-5e")&&-1!==1g.id.1L(r.J+ZC.1b[35])&&(t&&r.G9||-1!==1g.id.1L(r.J+"-1Y-")&&1o.4F.dh||ZC.A3(1g).3p()):-1===1g.id.1L("zc-2C-")&&-1===1g.id.1L("-2C-8a-")&&(-1!==1g.id.1L(r.J+"-1Y-")?1o.4F.dh||ZC.A3(1g).3p():r.BI&&r.BI.LQ?-1===1g.id.1L("-2z-5e")&&ZC.A3(1g).3p():ZC.A3(1g).3p())))}),e||ZC.P.ER([r.J+"-3t",r.J+"-3t-2N",r.J+"-3t-2z"]),ZC.A3("#"+r.A.J+"-2F").9z().5d(1n(){1a e=r.J+"-";"wK"===1g.8h.aN()&&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),ZC.P.ER(r.J))),ZC.A3("#"+r.J+" .zc-6p").5d(1n(){1a i=ZC.P.TF(1g);if(-1===i.1L("zc-v5")){if(e&&(1g.id===r.J+"-2u-c"||1g.id===r.J+"-hB-c"))1l;if(-1===1g.id.1L(r.J+"-1A-")&&-1===1g.id.1L(r.J+"-4k-"))ZC.P.II(1g,r.H.AB,r.iX,r.iY,r.I,r.F,r.J);1u if(t&&r.G9&&!r.HG){if("3a"!==r.H.AB)1j(1a a=0,n=r.AZ.A9.1f;a<n;a++)r.E.bV[a]=r.AZ.A9[a].R.1f;(l=r.A.KA?1m 5y("-4k-[a-z]+-c","g").3n(1g.id):1m 5y("-1A-(\\\\d+)-[a-z]+-\\\\d+-","g").3n(1g.id))&&(!r.E["1A"+l[1]+".2h"]&&"3p"===r.7O()||r.A.KA)&&ZC.P.II(1g,r.H.AB,r.iX,r.iY,r.I,r.F,r.J),-1===i.1L("zc-vb")&&-1===i.1L("zc-fl")||ZC.P.II(1g,r.H.AB,r.iX,r.iY,r.I,r.F,r.J)}1u ZC.P.II(1g,r.H.AB,r.iX,r.iY,r.I,r.F,r.J)}}),-1!==ZC.AU(r.H.KP,ZC.1b[44]))&&((o=ZC.AK(r.H.J+"-3Y-c"))&&ZC.P.II(o,r.H.AB,r.iX,r.iY,r.I,r.F,r.J),(s=ZC.AK(r.H.J+"-3Y-c-1v"))&&ZC.P.II(s,r.H.AB,r.iX,r.iY,r.I,r.F,r.J),(A=ZC.AK(r.H.J+ZC.1b[15]))&&ZC.P.II(A,r.H.AB,r.iX,r.iY,r.I,r.F,r.J));r.ns(),r.A.E.bT=!1,r.MF="3j.ai"}3k(e,t){1c===ZC.1d(e)&&(e=!1);1a i=1g;(-1===ZC.AU(i.H.KP,ZC.1b[41])||t)&&(ZC.A3("."+i.J+"-2r-1N").4j("6F 7A 4H",i.XF).4j("6k 7T 5R",i.tG).4j("7V 6f",i.qn).4j("3H",i.TT).4j("f9",i.TT).4j("9C",i.o7),i.BG&&(1o.4F.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["p"+e])){if(1c!==ZC.1d(a.D9["p"+e]["n"+t])){if(4v a.D9["p"+e]["n"+t],l)1j(i=0;i<a.AZ.A9.1f;i++)4v a.D9["p"+i]["n"+t]}1u if("2Y"===n?(a.D9={},a.D9["p"+e]={}):"1A"===n&&(a.D9["p"+e]={}),a.D9["p"+e]["n"+t]=!0,l)1j(i=0;i<a.AZ.A9.1f;i++)a.D9["p"+i]=a.D9["p"+i]||{},a.D9["p"+i]["n"+t]=!0}1u if("2Y"===n&&(a.D9={}),a.D9["p"+e]={},a.D9["p"+e]["n"+t]=!0,l)1j(i=0;i<a.AZ.A9.1f;i++)a.D9["p"+i]=a.D9["p"+i]||{},a.D9["p"+i]["n"+t]=!0}1c!==ZC.1d(e)&&1c!==ZC.1d(t)&&(a.HG=!0,a.K2(!0,!0))}1t(e){1c===ZC.1d(e)&&(e=!1);1a t,i,a,n,l,r,o=1g;o.A.tu=o.J,o.VG=e,2w.iu(ZC.oQ[o.J]),o.A.q0("vb"+o.L);1a s,A,C,Z,c,p,u,h=o.BT("k")[0],1b=ZC.3w,d=-ZC.3w,f={},g=o.AZ.A9,B=0;1j(Z=0;Z<g.1f;Z++)if(g[Z].o.aS)1j(C=0;C<g.1f;C++)if(g[C].o.id&&g[C].o.id===g[Z].o.aS){B++,u=!0;1a v=[];1j(l=0;l<g[C].R.1f;l++)(h.EI?g[C].R[l].BW>=h.B3&&g[C].R[l].BW<=h.BP:g[C].R[l].L>=h.V&&g[C].R[l].L<=h.A1)?(s=g[C].R[l].AE,1b=1B.2j(1b,s),d=1B.1X(d,s),u?(u=!1,g[C].R[l].BW?v.1h([g[C].R[l].BW,0]):v.1h(0),p=s):g[C].R[l].BW?v.1h([g[C].R[l].BW,100*(s-p)/p]):v.1h(100*(s-p)/p)):g[C].R[l].BW?v.1h([g[C].R[l].BW,0]):v.1h(0);f["p-"+Z]=[].4B(v)}if(B>0){1j(1b=ZC.3w,d=-ZC.3w,Z=0;Z<g.1f;Z++)if(g[Z].o.aS&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!0),t=0,i=n.BL.1f;t<i;t++)n.BL[t].6D();if(!n.A.E["cw-2x"]){1a l=ZC.AO.C8("16l",n.A,n.HV(),!0);if(l)1j(1a r=[ZC.1b[10],"5L","16k","dO"],o=0;o<r.1f;o++)l[r[o]]&&(n.o[r[o]]=(n.o[r[o]]||[]).4B(l[r[o]]))}1n s(e){1a t,i,a=(e.9D||e.2X.id).1F("-1N-2R","").1F("-2R","").1F(/--([a-zA-Z0-9]+)/,"").1F("-1R","").1F("-3z","").2n("-").9o();1l"2r"===a[1]&&(t=a[2],i=a[0]),[t,i]}if(n.AJ["3d"]||(n.bh(),n.PK(),n.JQ(),-1===ZC.AU(n.H.KP,ZC.1b[41])&&n.Q1()),-1===ZC.AU(n.H.KP,ZC.1b[41])){1a A=ZC.A3("."+n.J+"-2r-1N");n.XF=1n(e){if(!(1o.aV&&"7A"===1o.mD&&"7A"===e.1J||(1o.hw=n.A.J,1o.aV=e,1o.mD=e.1J,ZC.3m||n.BG&&n.BG.Z5||-1===ZC.P.TF(e.2X).1L("zc-2r-1N")||"9w"!==n.MF))){ZC.2L&&(n.E["2r-2X-id"]=e.2X.id,ZC.3m=!1,n.H.9h(),1c===n.H.DC||1c===ZC.1d(n.H.DC["3f-1Z"])||n.H.DC["3f-1Z"]||e.6R(),n.A.W3(e));1a a=s(e);if(n.AZ.A9[a[0]]){1a l=n.AZ.A9[a[0]].FP(a[1]);if(l&&(l.N?(ZC.aq=[l.N.C1,l.N.A0,l.N.AD,l.N.BU,l.N.B9],l.N9&&ZC.aq.1h(l.N9.A0,l.N9.AD,l.N9.BU,l.N9.B9)):ZC.aq=[],n.E["1A"+a[0]+".2h"])){1a r=ZC.2L?"6F":e.gp||e.1J;(ZC.2L||r!==ZC.1b[47])&&n.A.A6&&n.A6&&n.A6.AM&&n.A.A6.f8(e);1a o=n.AZ.A9[a[0]];if("1A"===o.l2)1j(t=0,i=o.R.1f;t<i;t++)o.R[t]&&o.FP(t).HX("2N");1u l.HX("2N");l.OV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E[ZC.1b[53]]=!0,n.fQ(),n.oR(i.A.L,i.L)),i.OV(e,"3H"),i.A.UP(e,"3H"),1c!==ZC.1d(i.A.E1)&&"gr"!==i.A.E1))if(i.A.E1 3E 3M)1j(1a a=0;a<i.A.E1.1f;a++){1a l=i.A.FA;i.A.FA 3E 3M&&(l=i.A.FA[a]||"2Y="+(n.o.id||"")),a===i.L&&n.UC(e,i.EW(i.A.E1[a],1c,1c,!0),l)}1u n.UC(e,i.EW(i.A.E1,1c,1c,!0),i.A.FA||"2Y="+(n.o.id||""))}},n.o7=1n(e){if(-1!==ZC.P.TF(e.2X).1L("zc-2r-1N")&&"9w"===n.MF){1a t=s(e),i=n.AZ.A9[t[0]].FP(t[1]);i&&(i.OV(e,"w0"),i.A.UP(e,"w0"))}},ZC.2L||A.4c("3H",n.TT).4c("f9",n.TT).4c("9C",n.o7)}if(n.pi(),n.A.E["tr-ev-"+n.L]?(n.A.E["tr-ev-"+n.L]=1c,n.nT()):n.nT(),n.i1){n.i1=!1;1a C={4w:n.J};1j(t=0,i=n.BT("k").1f;t<i;t++){1a Z=n.BT("k")[t];1c!==ZC.1d(e=Z.LW)&&(C["7E"+(a=1===Z.L?"":"-"+Z.L)]=!0,C["4s"+a]=e[0],C["4p"+a]=e[1])}1j(t=0,i=n.BT("v").1f;t<i;t++){1a c=n.BT("v")[t];1c!==ZC.1d(e=c.LW)&&(C["7N"+(a=1===c.L?"":"-"+c.L)]=!0,C["5r"+a]=e[0],C["5q"+a]=e[1])}if(C.nU=!0,n.A.FZ){1j(1a p in n.A.FZ)ZC.AK(p).2Z(n.A.FZ[p]);n.A.FZ=1c}n.A.PI(C)}}pi(){}nT(){1a e=1g;if(e.A.hp<e.A.AI.1f&&(e.A.hp++,ZC.AO.C8("16j",e.A,e.HV())),ZC.AO.C8("16i",e.A,e.HV()),e.BI&&(e.BI.IK=!1),1o.aV&&1o.hw&&1o.hw===e.A.J){1a t=ZC.A3("#"+e.A.J+"-1v"),i=ZC.DS[0]-t.2c().1K,a=ZC.DS[1]-t.2c().1v,n=1o.3n(e.A.J,"vo",{x:i,y:a});if(n)1j(1a l=0;l<n.1f;l++)if("2r"===n[l].hv&&n[l].hs<10){1a r=n[l].4w+ZC.1b[35]+n[l].7b+"-2r-"+n[l].7s;1o.aV&&1o.aV.2X&&1o.aV.2X.id===r&&(e.XF(1o.aV),1o.aV=1c)}}1o.hq&&e.A.D5&&e.A.D5.QH(1o.hq),e.A.kq<e.A.AI.1f?e.A.kq++:(e.A.kq=1,e.A.hp===e.A.AI.1f&&(e.A.hp++,e.A.E["cw-2x"]=!0,e.LQ&&e.AZ.A9.1f>1&&(1o.4F.9O||ZC.AO.C8("2x",e.A,e.A.FO()))),e.A.E["cw-ai"]=!0,(e.E["2Y-K2"]||e.LQ&&e.AZ.A9.1f>1)&&(1o.4F.9O||ZC.AO.C8("ai",e.A,e.A.FO()),e.E["2Y-K2"]=1c)),0!==e.A.QS.1f&&e.A.QS[e.A.QS.1f-1]===e.A.E.4G||(e.A.QS[e.A.NY]!==e.A.E.4G&&(e.A.QS.1f=e.A.NY+1),e.A.QS[e.A.NY]=e.A.E.4G)}K2(e,t){1a i=1g;1c===ZC.1d(e)&&(e=!1),1c===ZC.1d(t)&&(t=!1),i.A.MM(i),i.E["2Y-K2"]=!0,i.3j(e,t),i.1q(),i.XI&&i.XI(),i.1t(e),i.BI&&i.BI.oz(),i.HG=!1,1o.4F.8n=!1}UC(ev,E1,FA){if(2!==ev.7K){1a s=1g,D,PG=[""];1P(1c!==ZC.1d(FA)&&(PG=FA.2n("=")),PG[0]){1i"om":2w.bD(E1,"om");1p;1i"ul":2w.1v.89.7B=E1;1p;1i"uv":2w.u9.89.7B=E1;1p;1i"2w":1c!==ZC.1d(PG[1])&&""!==PG[1]&&(2w.1v[PG[1]].89.7B=E1);1p;1i"2Y":1a YD=1c;if("()"===E1.2v(E1.1f-2)||"7u:"===E1.2v(0,11))4J{1a EF=E1.1F("7u:","").1F("()","");7l(EF)&&(YD=7l(EF).4x(s))}4M(e){}1c!==ZC.1d(PG[1])&&""!==PG[1]?"ul"===PG[1]||"uv"===PG[1]?(s.A.MM(),YD?1o.3n(s.A.J,"aI",{1V:YD}):s.A.2x(1c,E1)):(D=s.A.OH(PG[1]),D&&(s.A.MM(D),s.A.E["tr-ev-"+D.L]=!0,s.A.NY++,YD?1o.3n(s.A.J,"aI",{4w:PG[1],1V:YD}):s.A.2x(PG[1],E1))):(D=s.A.AI[0],s.A.MM(D),YD?1o.3n(s.A.J,"aI",{4w:D.J,1V:YD}):(s.A.E["tr-ev-"+D.L]=!0,s.A.NY++,s.A.2x(D.J,E1)));1p;2q:2w.89.7B=E1}}}I0(e,t,i){1a a=1g;if(1c===ZC.1d(i)&&(i=a.AZ.A9.1f-1),1c!==ZC.1d(e)&&1y e!==ZC.1b[31])1l a.AZ.A9[e];if(1c===ZC.1d(t)||1y t===ZC.1b[31])1l a.AZ.A9[i];1j(1a n=0,l=a.AZ.A9.1f;n<l;n++)if(t===a.AZ.A9[n].H1)1l a.AZ.A9[n];1l 1c}ZG(e,t){1a i,a,n=1g;(e=e||{})[ZC.1b[54]]=e[ZC.1b[54]]||n.7O();1a l=1c;if(1y e.3W!==ZC.1b[31]&&(l=ZC.1k(e.3W)),-1===l)1j(l=[],i=0,a=n.AZ.A9.1f;i<a;i++)l.1h(i);l 3E 3M||(l=[l]);1a r=e.4X||"";r 3E 3M||(r=[r]);1a o=[];1j(i=0,a=ZC.BM(l.1f,r.1f);i<a;i++){1a s=n.I0(l[i],r[i]);if(s){1a A={};ZC.2E(e,A);1a C=s.L;A.3W=C,A.4X=s.H1,("4n"===t&&!n.E["1A"+C+".2h"]||"5b"===t&&n.E["1A"+C+".2h"])&&o.1h(A)}}1j(i=0,a=o.1f;i<a;i++)n.A.o[ZC.1b[16]][n.L][ZC.1b[11]][o[i].3W].2h="4n"===t,i===a-1&&(o[i].K2=1),n.QI(o[i])}QI(e){1a t,i,a,n=1g;n.A.E["2Y."+n.J+".jY"]=!1,e=e||{};1a l=!1;1c!==ZC.1d(e.aP)&&e.aP&&(l=!0);1a r=!1;e[ZC.1b[54]]=e[ZC.1b[54]]||n.7O(),1c!==ZC.1d(t=e["cI-1Y"])&&(r=ZC.2s(t));1a o=n.I0(e.3W,e.4X);if(o){1a s=o.L;1P(e[ZC.1b[54]]){1i"5b":if(n.BG&&(n.BG.E.jZ=!0),n.E["1A"+s+".2h"]=!n.E["1A"+s+".2h"],1c!==ZC.1d(n.A.o[ZC.1b[16]][n.L][ZC.1b[11]])&&(n.A.o[ZC.1b[16]][n.L][ZC.1b[11]][s].2h=n.E["1A"+s+".2h"]),n.AJ["3d"])r=!0,l||n.K2();1u{1a A=n.E["1A"+s+".2h"]?"8y":"2b";if(1o.3J.bC||ZC.A3("."+n.J+ZC.1b[35]+s+"-2r-1N").5d(1n(){if("ud"===1g.8h.5M()){1a e=ZC.A3(1g),t=e.3Q("9e"),a=e.3Q("2T");"2b"===A?(t="-"+t.1F(/,/g,",-"),"5n"===a?4===(i=t.2n(",")).1f&&(t=[i[2],i[3],i[0],i[1]].2M(",")):"3z"===a&&3===(i=t.2n(",")).1f&&(t=[i[0],i[1],-i[2]].2M(","))):(t=t.1F(/\\-/g,""),"5n"===a&&4===(i=t.2n(",")).1f&&(t=[i[2],i[3],i[0],i[1]].2M(","))),e.3Q("9e",t)}}),n.A.KA)ZC.AK(n.J+"-4k-bl-c").1I.3L=A,ZC.AK(n.J+"-4k-fl-c").1I.3L=A,ZC.AK(n.J+"-4k-vb-c").1I.3L=A;1u{1j(a=0;a<o.SZ;a++)(t=ZC.AK(n.J+"-1A-"+s+"-bl-"+a+"-c"))&&(t.1I.3L=A);1j(a=0;a<o.jp;a++)(t=ZC.AK(n.J+"-1A-"+s+"-fl-"+a+"-c"))&&(t.1I.3L=A);(t=ZC.AK(n.J+"-1A-"+s+"-vb-c"))&&(t.1I.3L=A)}1a C=ZC.A3("."+n.J+"-1A-"+s+"-1T-3C");n.E["1A"+s+".2h"]?(C.4n(),ZC.A3("."+n.J+ZC.1b[35]+s+"-2z").4n()):(C.5b(),ZC.A3("."+n.J+ZC.1b[35]+s+"-2z").5b())}1p;1i"3p":n.fQ(),r=!0,n.E["a9-93-3p"]=!0,n.E["1A"+s+".2h"]=!n.E["1A"+s+".2h"],e.K2&&(l||(n.LG("on-1Y-a9"),n.K2(!0,!0)))}n.BG&&!r&&(n.BG.3j(),n.BG.1t())}}LG(e){1a t=1g,i=!0,a=t.o.1A||{};1c!==ZC.1d(a.8x)&&1c!==ZC.1d(a.8x[e])&&(i=ZC.2s(a.8x[e])),t.HG="us"===t.k1||!i}HV(){1l{id:1g.A.J,Fo:1g.L,4w:1g.J.1F(1g.A.J+"-2Y-",""),x:1g.iX,y:1g.iY,1s:1g.I,1M:1g.F,6A:1g.A.FO()}}S7(){}S8(){}gc(){1j(1a e=0;e<1g.BL.1f;e++)1g.BL[e].gc();1j(1a t=0;t<1g.AZ.A9.1f;t++)1g.AZ.A9[t].gc();ZC.AO.gc(1g.AZ,["A","D","H","F3","o","I3","JU"]),ZC.AO.gc(1g,["Z","C7","AJ","IZ","KN","MU","F6"])}}JY.5j.PK=1n(){1a e,t,i,a,n,l,r,o,s=1g;s.n7(),s.BV=[],s.FC=[],s.YK=[],s.LN=[],s.FI=[],s.XO={};1a A,C,Z,c=s.A.B8,p="("+s.AF+")";if(1c!==ZC.1d(A=s.o[ZC.1b[10]]))1j(t=0,i=A.1f;t<i;t++){A[t].id||(A[t].id="166"+t+"1b"+ZC.hm(5x,6H)),a=A[t].id||t,n=!1,l=!1,s.E["2J.es"]&&-1===ZC.AU(s.E["2J.es"],a)&&(n=!0,l=!0),A[t].cf&&(n=!0);1a u=1o.6e.a7("DM",s,s.J+"-1H-"+a,n);if(!l||!u.nE){if(c.2x(u.o,p+".1H"),u.1C(A[t]),1c!==ZC.1d(e=u.o.u9))1j(1a h=0;h<s.BV.1f;h++)if(""+s.BV[h].H1==""+e){u.E["p-x"]=s.BV[h].iX,u.E["p-y"]=s.BV[h].iY,u.E["p-1s"]=s.BV[h].I,u.E["p-1M"]=s.BV[h].F;1p}if(u.H1=a,u.J=s.J+"-1H-"+a,u.GI=s.J+"-1H zc-1H",1c!==ZC.1d(e=A[t].7q)&&(u.E.7q=e),u.EW=1n(t){if(!t||-1===(""+t).1L("%"))1l t;t=""+t;1a i,a=[];a.1h(["%id",s.A.J]),a.1h(["%4w",s.J.1F(s.A.J+"-2Y-","")]);1a n=s.E.3S;1j(1a l in n)a.1h(["%"+l,n[l]]);a.4i(ZC.lW);1j(1a r=0,o=a.1f;r<o;r++)i=1m 5y(a[r][0],"g"),t=t.1F(i,a[r][1]);1a A,C,Z,c,p=u.o["2q-1T"]||" ";1j(i=1m 5y("(%1A-([0-9]+?)-1T(-*)([0-9]*?))|(%1A-1T-([0-9]+?))|(%1A-1T)|(%8k)|(%2r-8e-1T)","g"),t=t.1F(i,p),i=1m 5y("\\\\((.+?)\\\\)\\\\(([0-9]*)\\\\)\\\\(([0-9]*)\\\\)");A=i.3n(t);)if("%2r-1T"===A[1]){C="";1a h=0,1b=0;""!==(e=A[2])&&(h=ZC.1k(e)),""!==(e=A[3])&&(1b=ZC.1k(e)),(c=s.AZ.A9[h])&&(Z=c.FP(1b,3))&&(C=Z.EW(A[1])),t=t.1F(A[0],C)}1l t},u.1q(),A[t]["3d"]){1a 1b=1m CA(s,u.iX+u.I/2-ZC.AL.DW,u.iY+u.F/2-ZC.AL.DX,ZC.1k(A[t].z||"0"));u.iX=1b.E7[0]-u.I/2,u.iY=1b.E7[1]-u.F/2}}s.BV.1h(u),s.FI.1h({1J:"1H",3b:t,ap:u.JP}),s.XO[a]={2T:"1H",bE:t}}if(1c!==ZC.1d(C=s.o.dO))1j(t=0,i=C.1f;t<i;t++){1a d=1m tZ(s);c.2x(d.o,p+".7I"),d.1C(C[t]),a=C[t].id||t,d.J=s.J+"-7I-"+a,d.1q(),s.YK.1h(d),s.FI.1h({1J:"7I",3b:t,ap:d.JP})}1a f,g=0;if(1c!==Z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("."+a.J+"-7I-1H").3p()),e||(ZC.A3("."+a.J+"-1H-1N").5d(1n(){if(-1===ZC.AU([a.J+"-5E-1N",a.J+"-86-1N",a.J+"-7g-1N"],1g.id)){1a e=1m 5y("16c(x|y|k|v)-(7y|aM)([0-9]+)").3n(1g.id);!t&&e&&e.1f||ZC.P.ER(1g.id)}}),ZC.A3("."+a.J+"-2T-1N").5d(1n(){(!ZC.fc||ZC.fc&&"1"!==1g.bJ("1V-3c"))&&ZC.P.ER(1g.id)}),ZC.A3("."+a.J+"-7I-1N").3p()),"2F"===a.A.AB&&ZC.A3("#"+a.A.J+"-2F").9z().5d(1n(){1a e=a.J+"-1H-";"wK"===1g.8h.aN()&&1g.id.2v(0,e.1f)===e&&ZC.P.ER(1g.id)})},JY.5j.np=1n(){1a e=1g;(e.H.O0["2J-1v"]||e.H.O0["2J-2a"])&&(ZC.A3("."+e.J+"-1H-1N").4j(ZC.2L?"4H":"6F 7A",e.pf).4j(ZC.2L?"5R":"6k 7T",e.oL).4j(ZC.2L?"6f":ZC.1b[48],e.q6),ZC.2L||ZC.A3("."+e.J+"-1H-1N").4j("3H",e.V0).4j("9C",e.V0),ZC.A3("."+e.J+"-2T-1N").4j(ZC.2L?"4H":"6F 7A",e.oJ).4j(ZC.2L?"5R":"6k 7T",e.oI).4j(ZC.2L?"6f":ZC.1b[48],e.pg),ZC.2L||ZC.A3("."+e.J+"-2T-1N").4j("3H",e.V1).4j("9C",e.V1))},JY.5j.O4=1n(){1a e,t,i,a,n=1g;if(n.YX=!1,1c!==ZC.1d(i=n.o[ZC.1b[10]]))1j(e=0,t=i.1f;e<t;e++){1a l=""+(i[e].1E||"");if(-1!==l.1L("%2r-")||-1!==l.1L("%1A-")||-1!==l.1L("%8k")||-1!==l.1L("%2r-8e-1T")||ZC.2s(i[e].4N)){n.YX=!0;1p}}if(1c!==ZC.1d(a=n.o.5L))1j(e=0,t=a.1f;e<t;e++)if(ZC.2s(a[e].4N)){n.YX=!0;1p}},JY.5j.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&&(ZC.AK(s.J+"-1H-"+l).1I.3L="2b"),1b.1t())}}},JY.5j.Q1=1n(){1a e,t,i,a=1g;(a.H.O0["2J-1v"]||a.H.O0["2J-2a"])&&(a.oJ=1n(e){ZC.2L&&(a.L6(),ZC.3m=!1,a.H.9h(),1c===a.H.DC||1c===ZC.1d(a.H.DC["3f-1Z"])||a.H.DC["3f-1Z"]||e.6R(),a.A.W3(e));1a t=n(e);t.2H&&a.A6&&a.A.A6&&a.A6.AM&&a.A.A6.f8(e);1a i=ZC.2L?"6F":e.gp||e.1J;t.jI||a.R6("2T",t.gD),a.S8(i,t)},a.oI=1n(e){ZC.2L&&(a.H.dZ||ZC.3m||(1o.SM(e),a.V1(e)),a.A.P4(e)),a.A6&&a.A.A6&&a.A6.AM&&a.A.A6.fX(e),ZC.2L||a.L6();1a t=ZC.2L?"6k":e.gp||e.1J,i=n(e);if(i.2T&&i.2T.vX&&1o.4Y.wb&&"3a"!==a.A.AB)if("2F"===a.A.AB){1a l=ZC.A3("#"+a.J+"-2T-"+i.2T.id+"-ba-2R");"4C"===i.2T.1J&&l.3Q("3i",a.E["3c-2T-6E"].3i),l.3Q("4a",a.E["3c-2T-6E"].4a),l.3Q("4a-1s",a.E["3c-2T-6E"]["4a-1s"])}1u if("3K"===a.A.AB){1a r=ZC.AK(a.J+"-2T-"+i.2T.id+"-ba-2R"),o=r.6Y[1],s=r.6Y[2],A=a.E["3c-2T-6E"];"4C"===i.2T.1J&&ZC.P.G3(s,{1r:A.3i}),ZC.P.G3(o,{79:A["4a-1s"],1r:A.4a})}a.S8(t,i)},a.pg=1n(e){1a t=n(e);t.2H&&a.A6&&a.A.A6&&a.A6.AM&&a.A.A6.hj(e),a.S8(ZC.1b[48],t)},a.V1=1n(e){1a t=n(e);if("9C"!==e.1J){e.gu||a.L6("3H"),a.TP=a.TP||{},a.TP["oK"+t.gA]?(a.TP["oK"+t.gA]=1c,a.L6("3H")):(e.gu||(a.TP={}),a.TP["oK"+t.gA]=1,a.R6("2T",t.gD,"3H")),a.S8("3H",t);1a i=a.FC[t.gD].BD||a.FC[t.gD];if(i&&i.E1&&"gr"!==i.E1)if(i.E1 3E 3M)1j(1a l=0;l<i.E1.1f;l++)1c!==ZC.1d(i.FA[l])&&a.UC(e,i.E1[l],i.FA[l]);1u a.UC(e,i.E1,i.FA)}1u a.S8("9C",t)},ZC.A3("."+a.J+"-2T-1N").4c(ZC.2L?"4H":"6F 7A",a.oJ).4c(ZC.2L?"5R":"6k 7T",a.oI).4c(ZC.2L?"6f":ZC.1b[48],a.pg),ZC.2L||ZC.A3("."+a.J+"-2T-1N").4c("3H",a.V1).4c("9C",a.V1),a.pf=1n(e){ZC.2L&&(a.L6(),ZC.3m=!1,a.H.9h(),1c===a.H.DC||1c===ZC.1d(a.H.DC["3f-1Z"])||a.H.DC["3f-1Z"]||e.6R(),a.A.W3(e));1a t=l(e);if(t.2H&&a.A6&&a.A.A6&&a.A6.AM&&a.A.A6.f8(e),1c!==t&&"1H"===t.1J){1a i=ZC.2L?"6F":e.gp||e.1J;t["1V-6C"]||a.R6("1H",t.fL),a.S7(i,t)}},a.oL=1n(e){ZC.2L&&(a.H.dZ||ZC.3m||(1o.SM(e),a.V0(e)),a.A.P4(e)),a.A6&&a.A.A6&&a.A6.AM&&a.A.A6.fX(e),ZC.2L||a.L6();1a t=l(e);if(1c!==t){1a i=ZC.2L?"6k":e.gp||e.1J;ZC.AK(a.J+"-1H-"+t.1H.id)&&(ZC.AK(a.J+"-1H-"+t.1H.id).1I.3L="8y"),a.S7(i,t)}},a.q6=1n(e){1a t=l(e);t.2H&&a.A6&&a.A.A6&&a.A6.AM&&a.A.A6.hj(e),a.S7(ZC.1b[48],t)},a.V0=1n(e){1a t=l(e);if("9C"!==e.1J){e.gu||a.L6("3H"),a.TP=a.TP||{},a.TP["oD"+t.ek]?(a.TP["oD"+t.ek]=1c,a.L6("3H")):(e.gu||(a.TP={}),a.TP["oD"+t.ek]=1,a.R6("1H",t.fL,"3H")),a.S7("3H",t);1a i=a.BV[t.fL];if(!i)1P(t.1J){1i"2Y-5E":i={E1:a.IZ.E1,FA:a.IZ.FA};1p;1i"2Y-86":i={E1:a.KN.E1,FA:a.KN.FA};1p;1i"2Y-7g":i={E1:a.MU.E1,FA:a.MU.FA}}if(i&&i.E1&&"gr"!==i.E1)if(i.E1 3E 3M)1j(1a n=0;n<i.E1.1f;n++)1c!==ZC.1d(i.FA[n])&&(i.E1[n]=i.E1[n].1F("%id",a.A.J),i.E1[n]=i.E1[n].1F("%4w",a.J.1F(a.A.J+"-2Y-","")),a.UC(e,i.E1[n],i.FA[n]));1u i.E1=i.E1.1F("%id",a.A.J),i.E1=i.E1.1F("%4w",a.J.1F(a.A.J+"-2Y-","")),a.UC(e,i.E1,i.FA)}1u a.S7("9C",t)},ZC.A3("."+a.J+"-1H-1N").4c(ZC.2L?"4H":"6F 7A",a.pf).4c(ZC.2L?"5R":"6k 7T",a.oL).4c(ZC.2L?"6f":ZC.1b[48],a.q6),ZC.2L||ZC.A3("."+a.J+"-1H-1N").4c("3H",a.V0).4c("9C",a.V0));1n n(e){1j(1a t=(e.9D||e.2X.id).1F(/\\-\\-\\d+/g,"").1F(a.J+"-2T-","").1F("-ba-1N","").1F("-1N",""),i=-1,n=1c,l=0,r=a.FC.1f;l<r;l++)if(a.FC[l]&&""+a.FC[l].H1==""+t){i=l,n=a.FC[l]3E R0?a.FC[l].BD:a.FC[l];1p}if(!n&&e.2X.bJ("1V-jI"))1l{gA:e.2X.id,jI:!0,ev:e};if(-1===i)1l 1c;1a o={gA:t,gD:i,2H:n.o.2H?1:0,2T:{id:t,3b:i,2p:n.DG,x:n.iX,y:n.iY,1J:n.DN,vX:n.o["3c-1Q"],2W:n.C,1s:n.I,1M:n.F,2e:n.AH,vZ:n.KZ,2f:n.AA,a2:n.JP},ev:e};1j(1a s in n.o)n.o.8d(s)&&"1V-"===s.2v(0,5)&&(o[s]=n.o[s]);1l o}1n l(n){1a l,r=n.9D||n.2X.id;if(r===a.J+"-5E-1N"||r===a.J+"-86-1N"||r===a.J+"-7g-1N"){1a o=1c,s=-1;1P(l=r.1F(a.J+"-","").1F("-1N","")){1i"5E":o=a.IZ,s=-1;1p;1i"86":o=a.KN,s=-2;1p;1i"7g":o=a.MU,s=-3}1l{1J:"2Y-"+l,ek:o.J,fL:s,1E:o.AN,1H:{id:o.J,3b:s,1E:o.AN},ev:n}}if(-1===r.1L("-1z")||-1===r.1L("-1Q")&&-1===r.1L("-1R")){if(-1!==r.1L("-1T-3C-")){e=r.1F(a.J+ZC.1b[35],"").1F("-1T-3C-1N",""),t=e.2n("-2r-");1a A=a.AZ.A9[ZC.1k(t[0])].FP(ZC.1k(t[1]));1l A?{1J:ZC.1b[17],ek:"w4"+t.2M("1b"),3W:ZC.1k(t[0]),5T:ZC.1k(t[1]),1E:A.AE,1H:{id:"w4"+t.2M("1b"),1E:A.AE},ev:n}:1c}e=r.1F(a.J+"-1H-","").1F("-1N","");1j(1a C=-1,Z=1c,c=0,p=a.BV.1f;c<p;c++)if(""+a.BV[c].H1==""+e){C=c,Z=a.BV[c];1p}if(i=-1===C?"":a.BV[C].AN,-1===C)1l 1c;1a u={1J:"1H",ek:e,fL:C,1E:i,2H:Z.o.2H?1:0,1H:{id:e,3b:C,2p:Z.DG,x:Z.iX+Z.BJ,y:Z.iY+Z.BB,1s:Z.I,1M:Z.F,1E:i},ev:n};1j(1a h in Z.o)Z.o.8d(h)&&"1V-"===h.2v(0,5)&&(u[h]=Z.o[h]);1l u}e=r.1F(a.J+"-","").1F("-1N","");1a 1b=(t=e.2n("-"))[1].2n("1b"),d=0;2===1b.1f?d=ZC.1k(1b[1]):3===1b.1f&&(d=ZC.1k(1b[2]));1a f,g=t[0].1F(/1b/g,"-"),B=a.BK(g);1l-1!==r.1L("-1Q")?(l="1z-1Q",f="16C"+t[1].1F("7y",""),i=B.BV[d]||B.Y[d],"16B"===f&&(i=B.M.AN)):(l="1z-1R",f="16A"+t[1].1F("aM",""),i=B.E["xY"+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)n=i.1J||Z[o].mP||"1H",a.o[n+"s"]||(a.o[n+"s"]=[]),f&&(Z[o]["3c-1Q"]=!1),a.o[n+"s"].1h(Z[o]);1u a.o[n+"s"]||(a.o[n+"s"]=[]),f&&(Z["3c-1Q"]=!1),a.o[n+"s"].1h(Z);d&&(a.O4(),a.PU(f))}i.5F&&"1n"==1y i.5F&&i.5F(i);1p;1i"nS":if(a=g.C5(i[ZC.1b[3]]),i["1O"]&&(i.2p=i["1O"]),a&&(i.id||i.2p||i.6a)){n=i.1J||"1H",A=a.o[n+"s"]||[],l=i.id?"3e"==1y i.id?[i.id]:i.id:[],r=i.2p?"3e"==1y i.2p?[i.2p]:i.2p:[],c=!1;1a B=[];1j(o=A.1f-1;o>=0;o--)(1c!==ZC.1d(A[o].id)&&-1!==ZC.AU(l,A[o].id)||1c!==ZC.1d(A[o].2p)&&-1!==ZC.AU(r,A[o].2p)||1c!==ZC.1d(A[o]["1O"])&&-1!==ZC.AU(r,A[o]["1O"])||i.6a&&A[o].6a===i.6a)&&(1c!==ZC.1d(A[o].id)&&B.1h(A[o].id),A.6r(o,1),c=!0);1j(o=0;o<B.1f;o++)ZC.P.ER([a.J+"-1H-"+B[o]+"-5e",a.J+"-1H-"+B[o]+"-1v-5e",a.J+"-2T-"+B[o]+"-5e",a.J+"-2T-"+B[o]+"-1v-5e",a.J+"-2T-"+B[o]+"-ba-5e",a.J+"-2T-"+B[o]+"-ba-1v-5e"]);c&&d&&(a.O4(),a.PU(f))}i.5F&&"1n"==1y i.5F&&i.5F(i);1p;1i"16v":if(i["1O"]&&(i.2p=i["1O"]),(a=g.C5(i[ZC.1b[3]]))&&i.1V){a.E["2J.es"]=[],n=i.1J||"1H",A=a.o[n+"s"]||[],1b="1H"===n?a.BV:a.FC,Z=(C=i.1V 3E 3M)?[]:{},ZC.2E(i.1V,Z),c=!1;1a v=1n(e,t){1a i,l,r,o=a.XO[e.id||""],s=!1;if(o&&("1H"===o.2T?(r=a.BV[o.bE],8W.d1&&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==ZC.1d(Z[o].id)&&1c!==ZC.1d(A[p].id)&&A[p].id===Z[o].id&&v(Z[o],A[p]);1c!==ZC.1d(Z[o].8x)?b=!0:m=!0,m&&b&&a.PK()}}1u if(i.6a)1j(p=0,u=A.1f;p<u;p++)A[p].6a===i.6a&&(Z.id=A[p].id,v(Z,A[p]));1u if(i.2p)1j(p=0,u=A.1f;p<u;p++)A[p].2p===i.2p&&(Z.id=A[p].id,v(Z,A[p]));1u 1j(e=Z.id||i.id,p=0,u=A.1f;p<u;p++)1c!==ZC.1d(A[p].id)&&1c!==ZC.1d(e)&&A[p].id===e&&(Z.id=e,v(Z,A[p]));!c||!d&&a.Q8||a.Q8||(a.O4(),a.PU(f))}i.5F&&"1n"==1y i.5F&&i.5F(i);1p;1i"16t":(a=g.C5(i[ZC.1b[3]]))&&(a.O4(),a.PU(f)),i.5F&&"1n"==1y i.5F&&i.5F(i);1p;1i"16s":if(i["1O"]&&(i.2p=i["1O"]),l=[],(a=g.C5(i[ZC.1b[3]]))&&i.2p){n=i.1J||"1H",A=a.o[n+"s"]||[];1a E=i.2p 3E 3M?i.2p:[i.2p];1j(o=0,s=A.1f;o<s;o++)-1===ZC.AU(E,A[o].2p)&&-1===ZC.AU(E,A[o]["1O"])||1c===ZC.1d(A[o].id)||l.1h(A[o].id)}1l l;1i"m6":1a D={x:"iX",y:"iY",1s:"I",1M:"F",1r:"C1",ir:"B9",cv:"AX",eU:"BU",eS:"AP",eP:"A0",f4:"AD",2e:"AH",1J:"DN",1E:"AN",6S:"DE",6G:"KQ",wL:"EP",mO:"BJ",mS:"BB"};if(a=g.C5(i[ZC.1b[3]]),n=i.1J||"1H",e=i.id||"",a&&""!==e){1b=[],"1H"===n?1b=a.BV:"2T"===n&&(1b=a.FC);1a J=1c;1j(o=0,s=1b.1f;o<s;o++)1b[o].H1===e&&(J=1b[o]);if(J){1a F={};if("2T"===n){if(J.M)1j(h in F.1H={},D)F.1H[h]=J.M[D[h]];J.BD&&(J=J.BD)}1j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.H.o[ZC.1b[16]][s.L][ZC.1b[11]][i][ZC.1b[5]].1h(gt),!lE&&s.H.o[ZC.1b[16]][s.L][ZC.1b[11]][i][ZC.1b[5]].1f>ZC.1k(s.HO["1X-9F"])&&s.H.o[ZC.1b[16]][s.L][ZC.1b[11]][i][ZC.1b[5]].6r(0,1)):s.H.o[ZC.1b[16]][s.L][ZC.1b[11]][i][ZC.1b[5]]=[gt],ZC.oY&&p3&&(G=DF["1A"+i],"4h"==1y G&&(G=G.2M("###")),ZC.AO.gq.1h("1o.1A."+s.J+".1A"+i,""+G)),(s.o[ZC.1b[11]][i][ZC.1b[5]].1f>pu||1===s.O5[1])&&(ZC.AO.C8("16u",s.A,s.HV(),DF),s.H.o[ZC.1b[16]][s.L][ZC.1b[11]][i][ZC.1b[5]]=[])}MQ=s.q1()}("9w"===s.MF||s.G9)&&(1===s.O5[1]&&(s.O5[1]=0),(MQ<=q5||0===q5)&&(s.MF="bK",ZC.e3(1n(){ZC.AK(s.A.J+"-3Y")&&(ZC.AO.C8("16w",s.H,s.HV(),s.o),s.1q(),s.3j(!0),s.XI(),s.1t(!0,!0))})))};if("7h"===hz||"js"===hz){1a E1=s.HO.3R;ZC.eI[s.J]=2w.5Q(1n(){if(1===s.O5[0])if(s.A.MM(s),"7h"===hz){1a F5=["g5-3e"===s.A.N3?"eK="+1B.cb():"",1o.hd?"lx="+s.H.AB:""].2M("&");ZC.A3.a8({1J:"bL",3R:E1,ej:1n(e){s.A.S0.1V||"7h-f0"!==s.A.N3||e.cn(ZC.1b[45],"cl, 8H ci dJ 6X:6X:6X dF")},1V:F5,pK:"1E",4L:1n(){},aF:1n(e){mv(e)}})}1u if("()"===E1.2v(E1.1f-2)||"7u:"===E1.2v(0,11))4J{1a EF=E1.1F("7u:","").1F("()","");7l(EF)&&7l(EF).4x(s,1n(e){mv(e)},s.HV())}4M(e){}},OW)}1u"hC"===hz&&ZC.hC&&(s.H.SJ[s.J]?"mn"===s.HO.9Q&&(ZC.eI[s.J]=2w.5Q(1n(){s.H.SJ[s.J].8f("1o.ho")},OW)):(ws=1m pP(s.HO.3R,"1o"),ws.uy=1n(){ws.8f("1o."+s.HO.1J),ws.8f("1o."+s.HO.9Q),ws.8f("1o.oc"),"mn"===s.HO.9Q&&ws.8f("1o.ho")},ws.vc=1n(e){1===s.O5[0]&&mv(e.1V)},s.H.SJ[s.J]=ws))}}},1o.nw=1n(e,t,i){1a a;2g.cP("zc-5X")&&(e="zc-5X"),"3e"==1y(i=i||{})&&(i=3h.1q(i));1a n=1o.6Z(e);if(n){1a l=n.C5(i[ZC.1b[3]]);1P(t){1i"16D":l.O5[1]=1;1p;1i"16E":1l l.HO.dU;1i"16F":ZC.AO.C8("16G",n,l.HV()),l.o.d0=l.o.d0||{},l.o.d0.dU=i.dU||1;1p;1i"my":1===l.O5[0]&&(ZC.AO.C8("16z",n,l.HV()),l.O5[0]=0,1c!==ZC.1d(a=n.SJ[l.J])&&a.8f("1o.my"));1p;1i"oc":0===l.O5[0]&&(ZC.AO.C8("16o",n,l.HV()),l.O5[0]=1,1c!==ZC.1d(a=n.SJ[l.J])&&a.8f("1o.oc"),ZC.e3(1n(){l.1q(),l.3j(!0),l.XI(),l.1t(!0,!0)}))}}1l 1c},ZC.AO.oq=1n(e){1j(1a t={},i=[],a=0,n=(i="4h"==1y e?e:3h.1q(e)).1f;a<n;a++)if(1c!==ZC.1d(e=i[a])){t["p"+a]={};1a l=[];if("4h"==1y e)l=e;1u if("3e"==1y e&&/\\d+\\-\\d+/.5U(e)){1a r=e.2n("-");if(2===r.1f){l=[];1j(1a o=ZC.1k(r[0]);o<=ZC.1k(r[1]);o++)l.1h(o)}}1u l=[e];1j(1a s=0,A=l.1f;s<A;s++)t["p"+a]["n"+l[s]]=!0}1l t},JY.5j.ok=1n(){1a e,t=1g;1c!==ZC.1d(e=t.o.aL)&&(t.D9=ZC.AO.oq(e),t.o.aL=1c)},1o.op=1n(e,t,i){1a a,n,l,r,o,s,A,C,Z;2g.cP("zc-5X")&&(e="zc-5X"),"3e"==1y(i=i||{})&&(i=3h.1q(i));1a c=1o.6Z(e);if(c)1P(t){1i"16n":if(n=c.C5(i[ZC.1b[3]])){1j(n.D9={},l=0,r=n.AZ.A9.1f;l<r;l++)n.KS[l]=!1;n.HG=!0,n.fQ(),n.K2(!0,!0)}1p;1i"16a":if(n=c.C5(i[ZC.1b[3]])){1j(s=[],l=0,r=n.AZ.A9.1f;l<r;l++)if(s[l]=1c,1c!==ZC.1d(n.D9["p"+l])){1a p=[];1j(A in n.D9["p"+l])n.D9["p"+l].8d(A)&&n.D9["p"+l][A]&&p.1h(ZC.1k(A.1F("n","")));s[l]=p}1l s}1l{};1i"16b":1a u={};s=[],1c!==ZC.1d(a=i.aL)&&(u=ZC.AO.oq(a)),(n=c.C5(i[ZC.1b[3]]))&&(n.D9=u,n.HG=!0,n.fQ(),n.K2(!0,!0));1p;1i"9P":1i"nP":1a h=[],1b=1n(e){1a i=!1;1c!==ZC.1d(a=e.a9)&&(i=ZC.2s(a));1a n=c.C5(e[ZC.1b[3]]);if(n){1j(l=0,r=n.AZ.A9.1f;l<r;l++)n.KS[l]=!1;1a s=1c,p=1c;if(1c!==ZC.1d(a=e.3W))if("4h"==1y a)s=a;1u if("3e"==1y a&&/\\d+\\-\\d+/.5U(a)){if(2===(o=a.2n("-")).1f)1j(s=[],Z=ZC.1k(o[0]);Z<=ZC.1k(o[1]);Z++)s.1h(Z)}1u s=[a];if(1c!==ZC.1d(a=e.5T))if("4h"==1y a)p=a;1u if("3e"==1y a&&/\\d+\\-\\d+/.5U(a)){if(2===(o=a.2n("-")).1f)1j(p=[],Z=ZC.1k(o[0]);Z<=ZC.1k(o[1]);Z++)p.1h(Z)}1u p=[a];if(1c===ZC.1d(s))1j(s=[],l=0,r=n.AZ.A9.1f;l<r;l++)s.1h(l);1j(l=0,r=s.1f;l<r;l++){1a u=s[l];if(n.AZ.A9[u])if(1c===ZC.1d(n.D9["p"+u])&&(n.D9["p"+u]={}),1c===Z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e){1P(e){1i"m":1l 1m YG(1g);1i"v":1l 1m ZX(1g);1i"r":1l 1m tR(1g)}}O3(){1a e=1g,t=e.F4("m","1z"),i=e.F4("v",ZC.1b[52]),a=e.F4("r","1z-r");t.BC="1z",t.J=e.J+"-1z",e.o[ZC.1b[11]]&&e.o[ZC.1b[11]].1f&&e.o[ZC.1b[11]][0][ZC.1b[5]]&&(t.NH="1x"+e.o[ZC.1b[11]][0][ZC.1b[5]].1f),i.BC=ZC.1b[52],i.J=e.J+"-1z-v",a.BC="1z-r",a.J=e.J+"-1z-r",e.BL.1h(t,i,a),1D.O3()}ns(){-1!==ZC.AU(["2F","3K"],1g.H.AB)&&ZC.A3("#"+1g.J+" .zc-6p").5d(1n(){/\\-1A-\\d+\\-bl\\-\\d+\\-/.5U(1g.id)&&ZC.A3(1g).9z().5d(1n(){/\\-8O\\-2R/.5U(1g.id)&&ZC.P.ER(1g)})})}}1O Dj 2k JY{2G(e){1D(e);1a t=1g;t.AF="8S",t.AZ=1m Ef(t)}NG(){1l""}F4(e){1P(e){1i"m":1l 1m YG(1g)}}O3(){1a e=1g,t=e.F4("m","1z");t.BC="1z",t.J=e.J+"-1z",e.BL.1h(t),1D.O3()}}1O Dl 2k JY{2G(e){1D(e);1a t=1g;if(t.AF="7d",t.AJ.3x="7d",t.AZ=1m Eb(t),-1!==ZC.AU(t.A.J,"pR")){1j(1a i=1,a=0;a<t.A.MD.dW.1f;a++)i=ZC.BM(i,t.A.MD.dW[a][ZC.1b[5]].1f);i=1B.43(2m/i).a5(),1c===ZC.1d(t.A.MD.1A)?t.A.MD.1A={76:"1N"}:ZC.2E({76:"1N"},t.A.MD.1A),1c===ZC.1d(t.A.MD["1z-k"])?t.A.MD["1z-k"]={76:"3z",5I:"%v\\Do",6g:"0:Di:"+i}:ZC.2E({76:"3z",5I:"%v\\Do",6g:"0:Di:"+i},t.A.MD["1z-k"],!0)}}NG(){1l""}F4(e){1a t=1g;1P(e){1i"m":1l 1m YG(t);1i"k":1l 1m Ch(t);1i"v":1l 1m BQ(t)}}O3(){1a e=1g,t=e.F4("k","1z-k");t.BC="1z-k",t.J=e.J+"-1z-k",e.BL.1h(t);1a i=e.F4("v",ZC.1b[52]);i.BC=ZC.1b[52],i.J=e.J+"-1z-v",e.BL.1h(i);1a a=e.F4("m","1z");a.BC="1z",a.J=e.J+"-1z",e.BL.1h(a),1D.O3()}}1O Dr 2k lu{2G(e){1D(e);1a t=1g;t.AF="8i",t.AZ=1m Er(t),t.AJ[ZC.1b[55]]=!1}}1O Ds 2k lv{2G(e){1D(e);1a t=1g;t.AF="7R",t.AJ.3x="yx",t.AZ=1m Ej(t),t.AJ[ZC.1b[55]]=!1}}1O Dx 2k NL{2G(e){1D(e);1a t=1g;t.AF="5V",t.AZ=1m Es(t),t.AJ[ZC.1b[55]]=!1,t.AJ["4U-1Z"]=!0}UQ(e){1a t=1g;if("v"===e){1a i=[];if(t.o[ZC.1b[11]]&&t.o[ZC.1b[11]].1f)1j(1a a=0;a<t.o[ZC.1b[11]].1f;a++)i.1h(t.o[ZC.1b[11]][a].1E||"16m "+(a+1));1l i}}F4(e){1P(e){1i"x":1a t=1m TC(1g);1l t.DI=!0,t;1i"y":1a i=1m TD(1g);1l i.DI=!0,i.1C({6z:1,"7a-6z":!0}),i}}}1O Dg 2k NL{2G(e){1D(e);1a t=1g;t.AF="aA",t.AZ=1m Fk(t),t.AJ[ZC.1b[55]]=!1,t.AJ["4U-cF"]=!1,t.AJ["4U-1Z"]=!1}F4(e,t){1P(e){1i"x":1a i=1D.F4(e,t);1l i.DI=!0,i;1i"y":1a a=1D.F4(e,t);1l a.DI=!0,a}}UQ(e){if("v"===e){1j(1a t=[],i=0;i<1g.o[ZC.1b[11]].1f;i++)t.1h("Co "+(i+1));1l t}}1t(){1j(1a e=1g,t=0,i=e.BL.1f;t<i;t++)"v"===e.BL[t].AF&&(e.BL[t].AT=!e.BL[t].AT);1D.1t()}}1O Cw 2k NL{2G(e){1D(e);1a t=1g;t.AF="aB",t.AZ=1m Fi(t),t.AJ[ZC.1b[55]]=!1,t.AJ["4U-cF"]=!1,t.AJ["4U-1Z"]=!1}UQ(e){if("v"===e){1j(1a t=[],i=0;i<1g.o[ZC.1b[11]].1f;i++)t.1h("Co "+(i+1));1l t}}F4(e){1P(e){1i"x":1a t=1m VD(1g);1l t.DI=!0,t;1i"y":1a i=1m VE(1g);1l i.DI=!0,i}}}1O Cp 2k NL{2G(e){1D(e);1a t=1g;t.AF="84",t.AZ=1m Fg(t),t.AJ[ZC.1b[23]]=!0,t.AJ[ZC.1b[55]]=!1,t.AJ["4U-1Z"]=!0,t.AJ[ZC.1b[56]]=!0}F4(e,t){1P(e){1i"x":1a i=1D.F4(e,t);1l i.DI=!0,i;1i"y":1l 1D.F4(e,t)}}}1O Cr 2k JY{2G(e){1D(e);1a t=1g;t.AF="8D",t.AJ.3x="8D",t.AZ=1m Ff(t)}NG(){1l""}F4(e){1a t=1g;1P(e){1i"m":1l 1m YG(t);1i"r":1l 1m By(t);1i"v":1l 1m ZX(t)}}O3(){1a e,t=1g,i=t.F4("m","1z");1j(i.BC="1z",i.J=t.J+"-1z",t.BL.1h(i),e=2;e<10;e++)if(1c!==ZC.1d(t.o["1z-"+e])){1a a=t.F4("m","1z-"+e);a.L=e,a.BC="1z-"+e,a.J=t.J+"-1z-"+e,t.BL.1h(a)}1a n=t.F4("r","1z-r");1j(n.BC="1z-r",n.J=t.J+"-1z-r",t.BL.1h(n),e=2;e<10;e++)if(1c!==ZC.1d(t.o["1z-r-"+e])){1a l=t.F4("r","1z-r-"+e);l.L=e,l.BC="1z-r-"+e,l.J=t.J+"-1z-r-"+e,t.BL.1h(l)}1D.O3()}pJ(){1a e=1g;ZC.A3("#"+e.J+"-4k-bl-2").9z().5d(1n(){ZC.P.II(1g,e.H.AB,e.iX,e.iY,e.I,e.F,e.J)})}}1O Cu 2k NL{2G(e){1D(e);1a t=1g;t.AF="5z",t.AZ=1m Fd(t),t.AJ[ZC.1b[23]]=!0,t.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a.J=a.A.J+"-ch",a.F3=1c,t=a.o.1f-1;t>=0;t--)1y a.o[t]===ZC.1b[31]&&a.o.6r(t,1);if(a.E["1A-4i"]=!1,a.o.1f>1){1j(t=0,i=a.o.1f;t<i;t++)1y a.o[t].6P===ZC.1b[31]&&(a.o[t].6P=t);1a n=[],l=[];1j(t=0,i=a.o.1f;t<i;t++)l[t]=t,n[t]={"z-3b":a.o[t]["z-3b"]||0};1j(1a r=!1;!r;)1j(r=!0,t=0,i=n.1f;t<i-1;t++){if(n[t]["z-3b"]>n[t+1]["z-3b"]){a.E["1A-4i"]=!0;1a o=n[t];n[t]=n[t+1],n[t+1]=o;1a s=l[t];l[t]=l[t+1],l[t+1]=s,r=!1}}a.PA=l}1u a.PA=[0];1j(a.A9=[],t=0,i=a.o.1f;t<i;t++){1a A="";a.A.o.1A&&1c!==ZC.1d(e=a.A.o.1A.1J)&&(A=e),1c!==ZC.1d(e=a.o[t].1J)&&(A=e);1a C=a.HI(A,t);C.OE=C.AF+"1A",C.L=t,C.JP=t,a.D.A.B8.2x(C.o,["("+C.AF+").1A"]),C.dT&&a.D.A.B8.2x(C.o,["("+C.dT+").1A"]),a.D.A.B8.2x(C.o,["("+C.AF+").1A.8x"]),1c!==ZC.1d(e=a.A.o.1A)&&C.1C(e),C.1C(a.o[t]),C.CB=a.A.CB,C.1q(),a.A9.1h(C)}1a Z={},c=[],p=[],u={},h={},1b=0,d=0;1j(t=0,i=a.A9.1f;t<i;t++)if(1c!==ZC.1d(a.A.A.E["g-"+a.A.L+"-p-"+t+".2h"])&&(a.D.E["1A"+t+".2h"]=a.A.A.E["g-"+a.A.L+"-p-"+t+".2h"]),!a.A9[t].J1&&(a.D.E["1A"+t+".2h"]||"5b"===a.D.7O())){a.A9[t].CB?(-1===(d=ZC.AU(p,a.A9[t].DU))&&(p.1h(a.A9[t].DU),d=p.1f-1),1c===ZC.1d(c[d])?c[d]=[t]:c[d].1h(t)):(p.1h(-1),d=p.1f-1,1c===ZC.1d(c[d])?c[d]=[t]:c[d].1h(t));1a f=a.A9[t].AF;if(a.A9[t].o.1J&&f!==a.A9[t].o.1J){1a g=f.1L("3d"),B=a.A9[t].o.1J.1L("3d");(-1===g&&-1!==B||-1===g&&-1===B)&&(f=a.A9[t].o.1J)}-1!==ZC.AU(["2U","dN","g7"],f)&&(f="v"+f),-1===ZC.AU(["5t","6c","8i","7R","84","6O","7k"],f)||a.A9[t].J1||(1c===ZC.1d(u[f])&&(u[f]=[]),1c===ZC.1d(h[f])&&(h[f]=[]),a.A9[t].CB?(1c===ZC.1d(Z[a.A9[t].DU])?Z[a.A9[t].DU]=1:Z[a.A9[t].DU]++,-1===(1b=ZC.AU(h[f],a.A9[t].DU))&&(h[f].1h(a.A9[t].DU),1b=h[f].1f-1),1c===ZC.1d(u[f][1b])?u[f][1b]=[t]:u[f][1b].1h(t)):(h[f].1h(-1),1b=h[f].1f-1,1c===ZC.1d(u[f][1b])?u[f][1b]=[t]:u[f][1b].1h(t)))}if(a.KC=c,a.K4=u,a.X6)1j(1a v in a.X6)a.X6[v].4i();1j(a.kc=[],t=0;t<a.KC.1f;t++)a.kc.1h(a.KC[t][a.KC[t].1f-1])}1t(){1a e=1g;1n t(i){1a a=e.PA[i];(e.A9[a].IE||e.A9[a].DY.1f&&e.A.BI||"2b"!==e.A9[a].JF)&&(e.H.O9=!1),e.iU=!0;1a n=e.D.7O();e.D.AJ["3d"]?e.D.E["1A"+a+".2h"]&&(e.A9[a].1t(),e.H.XV()):(e.D.E["1A"+a+".2h"]||"5b"===n)&&(1y e.D.E["1A-"+a+"-h6-ou"]!==ZC.1b[31]&&(e.A9[a].TZ=0),e.A9[a].1t(),e.A9[a].TZ=0,e.H.XV(),e.D.E["1A"+a+".2h"]||"5b"!==n||(e.D.E["1A"+a+".2h"]=!0,e.A.QI({3W:a,"cI-1Y":!0}))),e.D.E["1A-"+a+"-h6-ou"]=!1,i<e.A9.1f-1?e.D.LQ?ZC.oQ[e.D.J]=2w.5Q(1n(){t(i+1)},10):e.A9.1f<=100&&t(i+1):(!e.D.LQ||e.D.LQ&&e.iU)&&e.ey()}if(e.HQ=[],e.A9.1f>0)if(e.A9.1f>100&&!e.D.LQ)1j(1a i=0;i<e.A9.1f;i++)t(i);1u t(0);1u e.ey()}ey(){1a e,t=1g;t.S4=1c,t.W1=1c;1j(1a i=0;i<t.D.BL.1f;i++)t.D.BL[i].EQ=1c,t.D.BL[i].X8=1c;1n a(e){1a i=0,a=e.1L(ZC.1b[35]),n=e.1L("-2r-",a);1l-1!==a&&-1!==n&&(i=e.5A(a+14,n-a-14)),1y t.A9[i].E["z-9V"]!==ZC.1b[31]?t.A9[i].E["z-9V"]:i}(e=ZC.AK(t.D.A.J+"-3c"))&&!t.H.dR&&(-1===ZC.AU(["5m","6V","8i","7R","7d","6O","7k","9u","aX","7e","gO","177"],t.D.AF)&&1!==1o.q4||t.HQ.4i(1n(e,i){1l"7e"===t.D.AF?ZC.AO.N5(e)>ZC.AO.N5(i)?1:ZC.AO.N5(e)<ZC.AO.N5(i)?-1:0:a(e)>a(i)&&t.A.AJ["3d"]?1:a(e)<a(i)&&t.A.AJ["3d"]?-1:ZC.AO.N5(e)>ZC.AO.N5(i)?1:ZC.AO.N5(e)<ZC.AO.N5(i)?-1:0}),1o.3J.Eq?2w.5Q(1n(){e.4q+=t.HQ.2M("")},kj):e.4q+=t.HQ.2M("")),t.EZ=1c,t.D2=1c,t.D.Ep=[],t.A.ey()}}1O oi 2k LR{HI(){1l 1m QW(1g)}}1O oj 2k LR{HI(){1l 1m QX(1g)}}1O Eo 2k LR{HI(){1a e=1m QW(1g);1l e.OT=!0,e}}1O En 2k LR{HI(){1a e=1m QX(1g);1l e.OT=!0,e}}1O mW 2k LR{HI(){1l 1m QY(1g)}}1O mH 2k LR{HI(){1l 1m QZ(1g)}}1O ZU 2k LR{HI(e){1a t=1g;1P(e){2q:1l 1m QW(t);1i"bj":1a i=1m QW(t);1l i.OT=!0,i;1i"4C":1a a=1m PH(t);1l a.kB=!0,a.dT="4C",a;1i"1N":1l 1m QX(t);1i"bv":1a n=1m QX(t);1l n.OT=!0,n;1i"2U":1i"5t":1l 1m QY(t);1i"6c":1l 1m QZ(t);1i"6v":1l 1m PH(t);1i"8r":1l 1m PH(t,"8r");1i"5m":1l 1m S6(t);1i"6V":1l 1m S6(t,"6V");1i"84":1l 1m VW(t);1i"5z":1l 1m UJ(t);1i"97":1l 1m V3(t);1i"83":1l 1m V4(t);1i"dN":1i"6O":1l 1m V2(t);1i"g7":1i"8i":1l 1m TU(t);1i"7R":1l 1m TV(t)}}}1O El 2k LR{HI(){1l 1m PH(1g)}}1O 178 2k LR{HI(){1a e=1m PH(1g);1l e.kB=!0,e.dT="4C",e}}1O Ei 2k LR{HI(){1l 1m PH(1g,"8r")}}1O Ea 2k LR{HI(){1l 1m S6(1g)}}1O Eh 2k LR{HI(){1l 1m S6(1g,"6V")}}1O pW 2k LR{2G(e){1D(e);1a t=1g;t.KM=[],t.PC=[],t.U2=[]}HI(){1l 1m WO(1g)}lJ(e){1a t,i,a,n,l=1g;e&&(l.U2=[],l.PC=[]);1a r,o=l.A.BK("1z-r"),s=l.A.BK("1z"),A=.9,C=1;l.A9.1f>=10&&(C=1),l.A9.1f>=20&&(C=1.25),l.A9.1f>=30&&(C=1.5);1a Z=o.DK;1j(t=0,i=l.A9.1f;t<i;t++)1c!==ZC.1d(l.A9[t].o["3T-2f"])&&(Z=l.A9[t].DK);1j(t=0,i=l.A9.1f;t<i;t++)if(l.D.E["1A"+t+".2h"]||"5b"===l.D.7O())1j(1a c=0,p=l.A9[t].R.1f;c<p;c++)if(l.A9[t].R[c]){l.YP["n"+c]=l.YP["n"+c]||[];1a u,h,1b=l.A9[t].R[c];1c===ZC.1d(l.PC[c])&&(l.PC[c]=Z),u=1c!==ZC.1d(n=l.A9[t].o[ZC.1b[1]])?ZC.1W(n):l.PC[c],h=l.KM[c],1c!==ZC.1d(l.A9[t].o.gM)&&1c!==ZC.1d(l.A9[t].o.gM[c])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(v[0][i]-d-(Z.GG-(v[1][i]+f)))/2,C.A9[e-1].R[i].iX-=g,v[1][i]-=g,C.EB[0][i].x-=g,C.NZ[i][0][0]-=g,C.A9[e-1].R[i].iY=Z.iY+Z.GA/2,b[1][i]=Z.iY+Z.GA/2,C.EB[0][i].y=Z.iY+Z.GA/2)):2===e&&(B[e][i]=h*ZC.AQ.n1(A[i].AE,A[i].X1,A[i].X0),r=(B[0][i]*B[0][i]-B[1][i]*B[1][i]+B[2][i]*B[2][i])/(2*B[0][i]),v[e][i]=v[0][i]+r,o=1B.5C(B[2][i]*B[2][i]-r*r),b[e][i]=b[0][i]-o,3===u&&(g=(v[0][i]-d-(Z.GG-(v[1][i]+f)))/2,C.A9[0].R[i].iX-=g,C.A9[1].R[i].iX-=g,C.EB[0][i].x-=g,C.EB[1][i].x-=g,C.NZ[i][0][0]-=g,v[2][i]-=g)),A[i].iX=v[e][i]+Z.iX,A[i].iY=b[e][i],A[i].I=h*1B.5C(A[i].AE/1B.PI),A[i].F=h*1B.5C(A[i].AE/1B.PI),A[i].AH=h*1B.5C(A[i].AE/1B.PI),1c===ZC.1d(E)&&(E=A[i].AE/(1B.PI*A[i].AH*A[i].AH));1a D=h*1B.5C(A[i].AE/1B.PI),J=h*1B.5C(A[i].X1/1B.PI),F=D+J-B[e][i],I=(2*F*J-F*F)/(2*(D+J-F)),Y=F-I;if(C.EB[e][i]={x:v[e][i],y:b[e][i],sz:A[i].AH,r1:D,r2:J,dH:Y,ef:I},0===e?(o=1B.5C(D*D-(D-I)*(D-I)),C.NZ[i].1h([v[0][i]+D-I,b[0][i]-o])):2===e&&(D=C.EB[1][i].r1,J=C.EB[1][i].r2,Y=C.EB[1][i].dH,I=C.EB[1][i].ef,l=ZC.UE(1B.o4((b[1][i]-b[2][i])/B[1][i]))-ZC.UE(1B.mU((D-I)/D)),C.NZ[i].1h([v[1][i]-D*ZC.EC(l)-g,b[1][i]-D*ZC.EH(l)]),D=C.EB[2][i].r1,J=C.EB[2][i].r2,Y=C.EB[2][i].dH,I=C.EB[2][i].ef,l=ZC.UE(1B.o4((b[0][i]-b[2][i])/B[2][i]))-ZC.UE(1B.mU((J-Y)/J)),C.NZ[i].1h([v[0][i]+J*ZC.EC(l)-g,b[0][i]-J*ZC.EH(l)])),e===u-1)if(3===u){if(1c!==ZC.1d(C.A9[0].jR[i]))C.XM[i].1N=C.A9[0].jR[i];1u{1a x=[-1],X=[-1];x[1]=1b(C.NZ[i][0],C.NZ[i][2]),x[2]=1b(C.NZ[i][0],C.NZ[i][1]),x[3]=1b(C.NZ[i][2],C.NZ[i][1]),X[1]=C.EB[0][i].sz,X[2]=C.EB[1][i].sz,X[3]=C.EB[2][i].sz;1a y=.25*1B.5C((x[1]+x[2]+x[3])*(x[1]+x[2]-x[3])*(x[1]+x[3]-x[2])*(x[2]+x[3]-x[1]));1j(s=1;s<=3;s++)y+=X[s]*X[s]*1B.o4(x[s]/(2*X[s]))-x[s]/4*1B.5C(4*X[s]*X[s]-x[s]*x[s]);C.XM[i].1N=E*y}C.EB[0][i].eW=ZC.AQ.hD(C.EB[0][i].x,C.EB[0][i].y,C.EB[1][i].x,C.EB[1][i].y,C.EB[0][i].r1-(C.EB[0][i].dH+C.EB[0][i].ef)/2),C.EB[1][i].eW=ZC.AQ.hD(C.EB[1][i].x,C.EB[1][i].y,C.EB[2][i].x,C.EB[2][i].y,-(C.EB[1][i].r1-(C.EB[1][i].dH+C.EB[1][i].ef)/2)),C.EB[2][i].eW=ZC.AQ.hD(C.EB[2][i].x,C.EB[2][i].y,C.EB[0][i].x,C.EB[0][i].y,-(C.EB[2][i].r1-(C.EB[2][i].dH+C.EB[2][i].ef)/2)),C.XM[i].xy=[(C.NZ[i][0][0]+C.NZ[i][1][0]+C.NZ[i][2][0])/3,(C.NZ[i][0][1]+C.NZ[i][1][1]+C.NZ[i][2][1])/3]}1u C.EB[0][i].eW=ZC.AQ.hD(C.EB[0][i].x,C.EB[0][i].y,C.EB[1][i].x,C.EB[1][i].y,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C.1d(t.JU.2o)&&(t.C4=e),1c!==ZC.1d(e=t.E["bg-2o"])&&1c===ZC.1d(t.JU["2o-1N"])&&(t.o["2o-1N"]=e)}FP(e,t){1a i=1g;1l(1y t===ZC.1b[31]||!i.GL[t]&&i.GL[1])&&(t=1),e=5v(e,10),!i.IR||"xy"!==i.D.AJ.3x&&"yx"!==i.D.AJ.3x?i.R[e]:i.R[e]&&i.GL[t]?(i.GL[t].J=i.J+"-2r-"+e,i.GL[t].o={1T:i.Y[e]},"3e"==1y i.Y[e]&&(i.GL[t].hu=!0),i.GL[t].L=e,"1w"!==i.AF&&"1N"!==i.AF&&"bj"!==i.AF&&"bv"!==i.AF||i.U?i.GL[t].1q():1c===i.R[e].BW&&1y i.D.E["1A-"+i.L+"-h6-ou"]===ZC.1b[31]||i.GL[t].1q(),"1w"===i.AF||"1N"===i.AF||"bj"===i.AF||"bv"===i.AF?"xy"===i.D.AJ.3x?(1c!==i.R[e].BW?i.GL[t].iX=i.R[e].iX=i.B1.B2(i.R[e].BW):i.GL[t].iX=i.R[e].iX=i.B1.GY(e),i.CB&&"100%"===i.KR?i.GL[t].iY=i.R[e].iY=i.CK.B2(100*i.R[e].CL/i.A.F3[e]["%6l-"+i.DU]):i.GL[t].iY=i.R[e].iY=i.CK.B2(i.R[e].CL)):(1c!==i.R[e].BW?i.GL[t].iY=i.R[e].iY=i.B1.B2(i.R[e].BW):i.GL[t].iY=i.R[e].iY=i.B1.GY(e),i.CB&&"100%"===i.KR?i.GL[t].iX=i.R[e].iX=i.CK.B2(100*i.R[e].CL/i.A.F3[e]["%6l-"+i.DU]):i.GL[t].iX=i.R[e].iX=i.CK.B2(i.R[e].CL)):i.GL[t].RV(),i.GL[t].K0=i.R[e].K0,i.GL[t]):1c}TE(e,t){1a i=1g;i.K5[e]||(i.K5[e]=[]),(!i.IR||i.IR&&-1===ZC.AU(i.K5[e],t))&&i.K5[e].1h(t)}FX(){1l 1m ME(1g)}nl(){1l{}}ND(){1l 1g.YS("6P","jh","i"),1g.D.A.B8.ol(-1!==1g.jh?1g.jh:1g.L,1g.D.AF)}N6(){1a e=1g;if(e.BS[4]){1a t,i={};1j(1a a in e.BS[4])-1===(t=a.1L("."))?1c===ZC.1d(e.o[a])&&(i[a]=!0,e.o[a]=e.BS[4][a]):a.2v(0,t)===e.AF&&(1c===ZC.1d(e.o[a.2v(t+1)])||i[a.2v(t+1)])&&(e.o[a.2v(t+1)]=e.BS[4][a])}}HW(e,t){1a i,a,n=1g,l=!1,r="";if("2b"!==n.JF&&(n.D.KS[n.L]||n.D.LL)){1a o=!(e.E[ZC.1b[73]]||e.E[ZC.1b[72]]);n.D.D9["p"+n.L]&&n.D.D9["p"+n.L]["n"+e.L]?1o.3J.j9&&o&&n.U5[ZC.1b[73]]?(a=n.U5[ZC.1b[73]],l=!0):(r=ZC.1b[73],(a=1m DM(n)).1S(t),e.E[ZC.1b[73]]?a.RK=e.E[ZC.1b[73]]:a.RK=n.T2?n.T2.o:{}):"2b"!==n.QR&&("1A"===n.QR&&n.D.KS[n.L]||"2Y"===n.QR&&n.D.LL)&&(1o.3J.j9&&o&&n.U5[ZC.1b[72]]?(a=n.U5[ZC.1b[72]],l=!0):(r=ZC.1b[72],(a=1m DM(n)).1S(t),e.E[ZC.1b[72]]?a.RK=e.E[ZC.1b[72]]:a.RK=n.T9?n.T9.o:{})),l||(a?(a.Q2=!0,a.1q()):(a=1m DM(n)).1S(t),1o.3J.j9&&o&&""!==r&&(n.U5[r]=a))}1u(a=1m DM(n)).1S(t);1l 1c!==ZC.1d(i=n.T4[e.L])&&(0===e.A.DY.1f&&(e.A.DY=[{}]),"3e"==1y n.T4[e.L]?a.1C({"1U-1r":ZC.AO.JK(i,20)+" "+i,"1w-1r":i,"1G-1r":ZC.AO.JK(i,20)}):a.1C(n.T4[e.L]),a.1q()),a}BT(e){1a t=1g,i=[];if(1c!==ZC.1d(e))1j(1a a=0,n=t.BL.1f;a<n;a++){1a l=t.D.BK(t.BL[a]);l&&l.AF===e&&i.1h(t.BL[a])}1u i=t.BL;1l i}LS(){1a e=1g;1l{7Q:e.f6,"m1-8E":e.RD,"6K-8E":e.S3,6K:e.E8,"1X-6K":e.HD,5G:e.eZ,"5G-dm":e.TY,ax:e.eL,"ax-6K":e.SP}}1q(){1a e,t,i,a,n=1g;if(n.UX={},1D.1q(),n.K5={},1c!==ZC.1d(e=n.o.3A))1j(n.BL=e.2n(/,|;|\\s/),i=0;i<n.BL.1f;i++)n.BL[i]=ZC.V5(ZC.GP(n.BL[i]));if(n.D.o.1Y&&n.D.o.1Y["6b-1A"]&&(n.IA=!0),1c!==ZC.1d(n.o.io)&&1c===ZC.1d(n.o.5G)&&(n.o.5G=n.o.io),1c!==ZC.1d(n.o["3H-1R"])&&1c===ZC.1d(n.o["aL-4E"])&&1c===ZC.1d(n.o["dQ-1R"])&&(n.o["aL-4E"]="ay",n.o["dQ-1R"]={},ZC.2E(n.o["3H-1R"],n.o["dQ-1R"])),n.KR=n.D.KR,n.4y([["cI","J1","b"],["ax","eL","b"],[ZC.1b[25],"SP","ia"],[ZC.1b[12],"E8","ia"],["1X-6K","HD","i"],["2z","RM","b"],["nj","CB","b"],["7F-1J","KR"],["nk","RE","b"],["1E","AN"],["2H-1E","JZ"],["1Y-1E","nm"],["tj","YW"],["7F","DU","i"],["z-3b","JP","i"],["76","CR"],["4E","bW"],["17j","YB","f"],["1X-cM","MV"],["1X-oE","TA"],["fI-oE","YC","b"],["eh-6z","XY","i"],["1Z-6z-io","YO","i"],["3R","E1"],["2X","FA"],[ZC.1b[14],"S3"],[ZC.1b[13],"RD"],["5G","eZ","b"],["7Q","f6"],["5G-dm","TY"],["8F-ak","o8","b"],["Dv","SC"],["ah","T4"],["Cs","QG","b"],["6b","IA","b"],["6b-1Y","LF","b"],["2N-4E","l2"],["9V-fA","VC","b"],["17k","LY","b"],["Cq-3b","R8","i"],["Cq-2c","RT","i"],["Df","G9","b"],["Fm","LD","i"],["oT","JD","f"],["aL-4E","JF"],["6a-17d","RQ","b"],["1U-4E","QR"],["171-6g","Z2","ia"]]),n.pp=n.RE,!n.E["Dq-1q"]){1a l;if(ZC.6y(n.T4),n.IA&&(1c===ZC.1d(n.D.o.1Y)||1c===ZC.1d(n.D.o.1Y["6b-1Y"]))&&ZC.1d(1c===n.o["6b-1Y"])&&(n.LF=n.IA),1c!==ZC.1d(e=n.o.8x))n.G9=!0,1c!==ZC.1d(t=e.Fm)&&(0===(t+"").1L("ju")&&1c!==ZC.1d(l=ZC.aT[(t+"").2v(10)])&&(t=l),n.LD=ZC.1k(t),0===n.LD&&(n.G9=!1)),1c!==ZC.1d(t=e.oT)&&(0===(t+"").1L("ju")&&1c!==ZC.1d(l=ZC.aT[(t+"").2v(10)])&&(t=l),n.JD=ZC.1W(t)),1c!==ZC.1d(t=e.Dw)&&(n.LA=ZC.1W(t)),1c!==ZC.1d(t=e.9Q)&&(0===(t+"").1L("ju")&&1c!==ZC.1d(l=ZC.aT[(t+"").2v(10)])&&(t=l),n.LE=ZC.1k(t)),1c!==ZC.1d(t=e.16S)&&(0===(t+"").1L("ju")&&1c!==ZC.1d(l=ZC.aT[(t+"").2v(10)])&&(t=l),n.TZ=ZC.1k(t)),1c!==ZC.1d(t=e.170)&&(n.FS=t);1j(1a r in n.JD<10&&(n.JD*=5x),n.LA<10&&(n.LA*=5x),1y PM!==ZC.1b[31]&&(n.JD=ZC.BM(PM.UH,n.JD)),("8F"===n.bW||1y PM===ZC.1b[31]||1o.4F.aT)&&(n.G9=!1),n.H.dR&&(n.G9=!1),-1!==ZC.AU(["1w","1N","5t","6c","84","6v","5m","7d","5V"],n.AF)&&("8F"===n.bW?n.IR=!0:"5f"===n.bW||n.G9||-1!==3h.5g(n.o).1L(\'"ak"\')||-1!==3h.5g(n.o).1L(\'"js-cz"\')||0!==n.T4.1f||-1!==n.H.E.4G.1L(\'"78"\')||-1!==n.H.E.4G.1L(\'"Dv"\')||"2b"!==n.JF?n.IR=!1:n.IR=!0),n.o)if("1V-"===r.2v(0,5)){1a o=r.2v(5);n.MZ[o]=n.o[r]}1a s=n.H.B8;if(n.IB=1m CX(n),n.IB.1C(n.o),s.2x(n.IB.o,v(ZC.1b[71])),n.IB.1C(n.o[ZC.1b[71]]),1c!==ZC.1d(n.o[ZC.1b[71]])||"1w"!==n.AF&&"1N"!==n.AF||(n.IB.AM=!1),n.IA&&(n.SG=1m CX(n),s.2x(n.SG.o,v("6b-3X")),n.SG.1C(n.o),1c!==ZC.1d(e=n.o["6b-3X"])&&n.SG.1C(e),1c===ZC.1d(n.SG.o.3I)&&(n.SG.o.3I=!0)),1c!==ZC.1d(e=n.o[ZC.1b[73]])&&(n.T2=1m CX(n),s.2x(n.T2.o,v(ZC.1b[73])),n.T2.1C(e)),1c!==ZC.1d(e=n.o[ZC.1b[72]])&&(n.T9=1m CX(n),s.2x(n.T9.o,v(ZC.1b[72])),n.T9.1C(e)),n.A5=1m CX(n),s.2x(n.A5.o,v("1R")),s.2x(n.A5.o,v("1R["+n.CR+"]")),n.A5.1C(n.o.1R),"3g"===n.A5.o.1J){1a A=["3z","9r","Du","Dt","Dp"];n.A5.o.1J=A[n.L%A.1f]}if(n.A5.1q(),(n.A5.DY.1f>0||n.T4.1f>0||n.A5.o["1v-3X"])&&(n.Z0=!1),n.G5=1m CX(n),s.2x(n.G5.o,v("2N-1R")),n.G5.1C(n.o.1R),n.G5.1C(n.o["2N-1R"]),1c!==ZC.1d(e=n.o["dQ-1R"])&&(n.SB=1m CX(n),s.2x(n.SB.o,v("dQ-1R")),n.SB.1C(e)),1c!==ZC.1d(e=n.o["1U-1R"])&&(n.SO=1m CX(n),s.2x(n.SO.o,v("1U-1R")),n.SO.1C(e)),n.IA&&(n.VK=1m CX(n),n.VK.1C(n.o.1R),1c!==ZC.1d(e=n.o["6b-1R"])&&(s.2x(n.VK.o,v("6b-1R")),n.VK.1C(e))),"5f"!==n.bW&&(n.T2||n.SB)&&(n.IR=!1),"8F"===n.bW&&(n.IR=!0),n.A6=1m DM(n),n.o.2H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C.AL.DX+r.AX,e.E["z-82"]*e.E["z-5p"],e.E["z-82"]*e.E["z-5p"],"y")).J=t.J+"-1z-z-16O-"+e.L,t.CH.2P(l),(l=ZC.DD.D7(r,t,i.iX-ZC.AL.DW,i.iX-ZC.AL.DW,i.iY-ZC.AL.DX,i.iY+i.F-ZC.AL.DX,e.E["z-82"]*e.E["z-5p"],e.E["z-82"]*e.E["z-5p"]+r.AX,"y")).J=t.J+"-1z-z-16P-"+e.L,t.CH.2P(l))),t.o["1z-z"].2B&&t.o["1z-z"].2B.1f){(r=1m CX(e)).A0=r.AD="#16Q",r.C4=.25;1a u=e.E["z-82"]%t.o["1z-z"].2B.1f;r.1C(t.o["1z-z"].2B[u]),r.1q(),(l=ZC.DD.D7(r,t,i.iX-ZC.AL.DW,i.iX+i.I-ZC.AL.DW,i.iY+i.F-ZC.AL.DX,i.iY+i.F-ZC.AL.DX,e.E["z-82"]*e.E["z-5p"],e.E["z-82"]*e.E["z-5p"]+e.E["z-5p"],"z")).J=e.J+"-1Q-",t.CH.2P(l)}}}gc(){if(1g.R)1j(1a e=0;e<1g.R.1f;e++)1g.R[e]&&1g.R[e].A&&ZC.AO.gc(1g.R[e],["Z","C7","o","JU","I3","A","D","H","N","N9"]);ZC.AO.gc(1g,["Y","R","GL","K5","VJ","A6","Z","C7","UX","A5","U4","H9","G5","IB","KE","QD","B1","CK","R","GL","K5","L0","o","JU","I3","A","D","H"])}}1O WN 2k IC{2G(e){1D(e);1a t=1g;t.yw=!0,t.AF="xy",t.BL=[ZC.1b[50],ZC.1b[51]]}1t(){1D.1t()}}1O QW 2k WN{2G(e){1D(e);1a t=1g;t.AF="1w",t.CR="av",t.W=1,t.SW="6n",t.VJ=[],t.QF=!1,t.OT=!1}FX(){1l 1m sH(1g)}1q(){1a e=1g;e.BS=e.ND(),e.C1=e.BS[0],e.B9=e.BS[1],e.N6(),1D.1q(),e.4y([["6z-4e","SW"],["fg-eh","QF","b"]]),e.B1=e.D.BK(e.BT("k")[0]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),1c!==ZC.1d(oe)?Ze.2o=oe:4v Ze.2o),Ce.C=Ae,Ce.1t();1a ce=Z.au(E),pe=ZC.P.E4(se.Z,Z.H.AB),ue=1m CX(Z);ue.1S(Z),ue.CV=!0,ue.L9=!0,ue.J=Z.J+"-1w-2z",ue.DG=Z.J+"-2z",ue.AX=1,Ze&&(ue.1C(Ze),ue.1q()),ZC.CN.1t(pe,ue,ce,1c,3)}Z.CB&&(Z.A.D2=J)}}}1O hk 2k WN{2G(e){1D(e);1a t=1g;t.AF="2U",t.ow="2U",t.F0=.1,t.CZ=0,t.qd=!1,t.Z9=-1,t.CC=.1,t.CO=.1,t.EV=0,t.U3=!1,t.M3=[],t.PP="bg",t.ln=!0,t.QF=!1}1q(){1a e=1g;if(e.BS=e.ND(),e.C1=e.BS[0],e.B9=e.BS[1],e.BU=e.BS[1],e.A0=e.BS[1],e.AD=e.BS[2],e.N6(),1D.1q(),"16K"===e.CR&&(e.F0=e.CC=e.CO=0),e.4y([["6a-jK","ln","b"],["4n-cN","U3","b"],["2c-6g","M3"],["2U-8I","F0","fp"],["2U-1s","CZ","fp"],["81-1s","qd","b"],["2U-1X-1s","Z9","fp"],["jK-8I-1K","CC","fp"],["jK-8I-2A","CO","fp"],["jK-iy","EV","fp"],["fg-eh","QF","b"]]),e.ln||(e.EV=1),0===e.F0&&0===e.CC&&0===e.CO&&(e.F8=!1),e.B1=e.D.BK(e.BT("k")[0]),e.CK=e.D.BK(e.BT("v")[0]),1c!==ZC.1d(e.o.8U)){1a t=e.o.8U.2n("/");if(2===t.1f){1a i=ZC.1k(t[0]),a=ZC.1k(t[1]),n=e.CC;e.CC>=1&&(n=e.CC/e.B1.A8);1a l=e.CO;e.CO>=1&&(l=e.CO/e.B1.A8);1a r=1-n-l,o=ZC.4o(r/(3*a+1));e.CC=n+o+3*(i-1)*o,e.CO=1-e.CC-2*o}}}PN(){1a e,t=1g;if(t.RR)1l t.RR;if(t.o["8F-16R"]&&t.A.A9[0].RR)1l t.A.A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BS[1],e.AD=e.BS[1],e.B9=e.BS[2],e.BU=e.BS[2],e.N6(),1D.1q(),e.4y([["2o-1N","HT","f",0,1]]),e.B1=e.D.BK(e.BT("k")[0]),e.CK=e.D.BK(e.BT("v")[0])}1t(){1a e,t,i,a=1g;if(1D.1t(),a.KE=a.CM("bl",0),a.pB=ZC.P.E4(a.CM("bl",0),a.H.AB),a.O7(!0),a.kB){1j(e=[],t=0,i=a.R.1f;t<i;t++)e.1h([a.R[t].iX,a.R[t].iY]);e.1f&&e.1h(e[0]);1a n=1m DT(a);n.1S(a),n.C4=a.HT,n.CV=!0,n.L9=!0,n.AX=0,n.AP=0,n.EU=0,n.G4=0,n.Z=a.KE,n.C=e,n.ZJ(),n.J=a.J+"-1N",n.1t(),a.CV=!1,ZC.CN.2I(a.pB,a),ZC.CN.1t(a.pB,a,e)}}}1O S6 2k WN{2G(e,t){1D(e),1g.AF=t||"5m",1g.WH=1c,1g.WE=1c,1g.la=1,1g.JO=1,1g.pF="1N",1g.PP="jP"}FX(){1l 1m xJ(1g)}1q(){1a e=1g;e.BS=e.ND(),e.C1=e.BS[0],e.A0=e.BS[2],e.AD=e.BS[1],e.B9=e.BS[2],e.BU=e.BS[2],e.N6(),1D.1q(),e.4y([["2j-2e","WH","i"],["1X-2e","WE","i"],["16Y","pF"],["Ck-6a","la","i"],["2e-7c","JO","f"]]),e.B1=e.D.BK(e.BT("k")[0]),e.CK=e.D.BK(e.BT("v")[0]),1c===ZC.1d(e.WH)&&(e.WH=15),1c===ZC.1d(e.WE)&&(e.WE=.75*1B.2j(e.B1.A7,e.B1.BY,e.CK.A7,e.CK.BY),e.WE=ZC.BM(25,ZC.CQ(50,e.WE)))}j6(e){1a t,i=1g,a=1c;1P(e=ZC.BM(e,i.RP),t=i.X3===i.RP?e-i.RP:(e-i.RP)/(i.X3-i.RP),i.pF){1i"9i":a=i.WH+i.JO*(i.WE-i.WH)*t;1p;1i"1N":1i"5C":a=i.WH+i.JO*(i.WE-i.WH)*1B.5C(t)}1l ZC.BM(i.WH,a)}1t(){1a e=1g;if(1D.1t(),e.KE=e.CM("bl",0),1c!==ZC.1d(e.WE)){e.X3=-ZC.3w,e.RP=ZC.3w;1j(1a t=e.A.A9,i=0,a=t.1f;i<a;i++)if(t[i].la===e.la)1j(1a n=0,l=t[i].R.1f;n<l;n++)e.X3=ZC.BM(e.X3,ZC.2l(t[i].R[n].SV)),e.RP=ZC.CQ(e.RP,ZC.2l(t[i].R[n].SV))}e.O7(!0)}}1O WO 2k IC{2G(e){1D(e);1a t=1g;t.AF="3O",t.BL=["1z",ZC.1b[52],"1z-r"],t.PZ=0,t.DK=0,t.U3=!1,t.lw=!0,t.C2=1c,t.PP="bg"}FX(){1l 1m xI(1g)}1q(){1a e,t,i=1g;1c===ZC.1d(i.o[ZC.1b[17]])&&(i.o[ZC.1b[17]]={}),"9H"!==i.A.A.o.1J&&"ql"!==i.A.A.o.1J||(i.PZ=.35),i.BS=i.ND(),i.C1=i.BS[0],i.A0=i.BS[1],i.AD=i.BS[2],i.BU=i.BS[0],i.B9=i.BS[0],i.N6(),1D.1q(),i.C2=1m CX(i),i.D.A.B8.2x(i.C2.o,["2Y.1A.1T-3C.8O",i.AF+".1A.1T-3C.8O"]),1c!==ZC.1d(e=i.D.o.1A)&&1c!==ZC.1d(e[ZC.1b[17]])&&1c!==ZC.1d(t=e[ZC.1b[17]].8O)&&i.C2.1C(t),i.C2.1C(i.o[ZC.1b[17]].8O),i.4y([["2c","DP","fp"],[ZC.1b[8],"PZ","fp"],["4n-cN","U3","b"],["od","lw","b"],["3T-2f","DK","i"]]),i.DK%=2m;1j(1a a=0,n=i.R.1f;a<n;a++)i.R[a]&&(i.R[a].CJ=i.PZ,i.R[a]&&(i.D.E["1A"+i.L+".2h"]||"5b"===i.D.7O())&&(1c===ZC.1d(i.A.KM[a])&&(i.A.KM[a]=0),i.A.KM[a]+=ZC.1W(i.R[a].AE)))}1t(){1a e=1g;1D.1t(),e.KE=e.CM("bl",0),e.O7(!0)}}1O U9 2k IC{2G(e){1D(e);1a t=1g;t.AF="8S",t.BL=["1z"],t.UI=0,t.SU=0,t.DK=0,t.C2=1c,t.PP="bg",t.fB=1c}FX(){1l 1m y3(1g)}1q(){1a e,t,i=1g;i.BS=i.ND(),i.C1=i.BS[0],i.A0=i.BS[1],i.AD=i.BS[2],i.BU=i.BS[0],i.B9=i.BS[0],i.N6(),1D.1q(),i.U&&(i.C2=1m CX(i),i.D.A.B8.2x(i.C2.o,["2Y.1A.1T-3C.8O",i.AF+".1A.1T-3C.8O"]),1c!==ZC.1d(e=i.D.o.1A)&&1c!==ZC.1d(e[ZC.1b[17]])&&1c!==ZC.1d(t=e[ZC.1b[17]].8O)&&i.C2.1C(t),i.C2.1C(i.o[ZC.1b[17]].8O)),i.4y([["7z-4e","UI","fp"],["2c","UI","fp"],[ZC.1b[8],"UI","fp"],["yT-8I","SU","fp"],["3T-2f","DK","i"],["yT-164","fB"]]),i.DK%=2m;1j(1a a=0,n=i.R.1f;a<n;a++)i.R[a]&&(i.D.E["1A"+i.L+".2h"]||"5b"===i.D.7O())&&(1c===ZC.1d(i.A.KM[a])&&(i.A.KM[a]=0),i.A.KM[a]+=ZC.1W(i.R[a].AE))}1t(){1a e=1g;1D.1t(),e.KE=e.CM("bl",0),e.O7(!0)}}1O XQ 2k IC{2G(e){1D(e);1a t=1g;t.AF="7d",t.SZ=3,t.BL=["1z-k",ZC.1b[52],"1z"],t.HT=.5,t.CR="1w",t.r7=1c,t.XN=!1,t.C=[],t.AG=[]}FX(){1l 1m xR(1g)}1q(){1a e=1g;e.BS=e.ND(),e.C1=e.BS[0],e.B9=e.BS[1],e.A0=e.BS[3],e.AD=e.BS[3],e.N6(),1D.1q(),e.kx(),e.4y([["6C-1N","XN","b"],["2o-1N","HT","f",0,1],["2f-8I","r7","f"]]),e.B1=e.D.BK("1z-k"),e.CK=e.D.BK(ZC.1b[52]),"5z"===e.CR&&(e.bW="5f",e.IR=!1)}1t(){1a e=1g;1D.1t(),e.B1.Y.1f===e.Y.1f&&-1===ZC.AU(e.Y,1c)||(e.bW="5f",e.IR=!1),e.KE=ZC.AK(e.D.J+"-1A-"+e.L+"-bl-0-c"),e.iP=ZC.P.E4(e.CM("bl",0),e.H.AB),e.QD=ZC.P.E4(e.CM("bl",2),e.H.AB),e.O7(!0)}}1O nr 2k hk{2G(e){1D(e);1a t=1g;t.F0=.2,t.CC=.28,t.CO=.28,t.EV=0,t.FD=1c,t.er=[],t.Q3=[],t.yG=!0,t.PP="bg"}nl(e){1a t;if("7w"===e){if(1c!==ZC.1d(t=1g.FD.o.2H))1l t;if(1c!==ZC.1d(t=1g.FD.o["2H-1E"]))1l{1E:t}}1l{}}1q(){1a e,t=1g;if(t.BS=t.ND(),1D.1q(),1c!==ZC.1d(t.er=t.o.gZ))1j(1a i=0,a=t.er.1f;i<a;i++)1c!==ZC.1d(t.er[i])?"3e"==1y t.er[i]?t.Q3[i]=ZC.AU(t.CK.JJ,t.er[i]):t.Q3[i]=ZC.1W(t.er[i]):t.Q3[i]=1c;t.FD=1m I1(t),t.FD.1S(t),t.FD.1C({"1U-1r":t.BS[3]}),t.FD.o["2H-1E"]="%2r-7w-1T",t.H.B8.2x(t.FD.o,["("+t.AF+").1A.7w"],!0,!0),1c!==ZC.1d(e=t.o.7w)&&t.FD.1C(e),t.FD.1q()}}1O TU 2k nr{2G(e){1D(e),1g.AF="8i"}FX(){1l 1m yj(1g)}}1O TV 2k nr{2G(e){1D(e),1g.AF="7R"}FX(){1l 1m yu(1g)}}1O XR 2k WN{2G(e){1D(e);1a t=1g;t.AF="5V",t.CR="2o",t.rn="1A-1X",t.QA=.2,t.VA=1,t.PP="bg"}FX(){1l 1m ys(1g)}1q(){1a e=1g;e.BS=e.ND(),e.C1=e.BS[0],e.B9=e.BS[1],e.BU=e.BS[1],e.A0=e.BS[2],e.AD=e.BS[1],e.N6(),1D.1q(),e.4y([["2j-eD","QA","f",0,1],["1X-eD","VA","f",0,1],["cL","rn",""]]),e.QA>=e.VA&&(e.QA=.2,e.VA=1),e.B1=e.D.BK(e.BT("k")[0]),e.CK=e.D.BK(e.BT("v")[0])}1t(){1a e=1g;1D.1t(),e.KE=e.CM("bl",0),e.j7=e.jB=-ZC.3w,e.YL=e.WZ=ZC.3w,e.ro=e.rp=0;1j(1a t=0,i=e.A.A9.1f;t<i;t++)1j(1a a=e.A.A9[t],n=0,l=a.R.1f;n<l;n++)if(a.R[n]){1a r=ZC.1W(a.R[n].AE);a.L===e.L&&(e.j7=ZC.BM(e.j7,r),e.YL=ZC.CQ(e.YL,r),e.ro+=r),e.jB=ZC.BM(e.jB,r),e.WZ=ZC.CQ(e.WZ,r),e.rp+=r}e.O7()}}1O WP 2k WN{2G(e){1D(e);1a t=1g;t.L3=.1,t.NN=.1,t.M2=0,t.ja="4N",t.OY=[],t.VY=[],t.PP="bg"}1q(){1a e,t,i,a,n=1g;if(n.BS=n.ND(),n.C1=n.BS[0],n.B9=n.BS[1],n.BU=n.BS[1],n.A0=n.BS[2],n.AD=n.BS[1],n.N6(),1D.1q(),n.4y([["4e-1s","ja"],["2j-8b","M2","fp"],["8I-8g","L3","fp"],["8I-8b","NN","fp"],["2c","L3","fp"],["2c","NN","fp"]]),1c!==ZC.1d(i=n.o.8g))1j(i 3E 3M||(i=[i]),e=0,t=i.1f;e<t;e++){1a l=1m DT(n);l.o=i[e],l.1q(),n.OY.1h(l)}if(1c!==ZC.1d(a=n.o.8b))1j(a 3E 3M||(a=[a]),e=0,t=a.1f;e<t;e++){1a r=1m DT(n);r.o=a[e],r.1q(),n.VY.1h(r)}n.B1=n.D.BK(n.BT("k")[0]),n.CK=n.D.BK(n.BT("v")[0])}1t(){1a e=1g;1D.1t(),e.KE=e.CM("bl",0),e.O7()}}1O VO 2k WP{2G(e){1D(e),1g.AF="aA"}FX(){1l 1m yn(1g)}}1O VP 2k WP{2G(e){1D(e),1g.AF="aB"}FX(){1l 1m ym(1g)}}1O VW 2k hk{2G(e){1D(e);1a t=1g;t.AF="84",t.CR="ya",t.MY={2e:0},t.PP="bg"}FX(){1l 1m yh(1g)}1q(){1D.1q()}1t(){1D.1t(),1g.9p()}9p(){1a e=1g,t=e.D.BK(e.BT("v")[0]),i=t.B2(t.HK);if(e.D.BI&&e.D.BI.IK&&e.RM){1j(1a a=e.D.Q,n=e.D.BI,l=[],r=[],o=!0,s=0,A=e.R.1f;s<A;s++)if(1c!==ZC.1d(e.R[s])&&1c!==ZC.1d(e.R[s].DJ[2])){1a C=t.B2(e.R[s].DJ[2]);o&&(r.1h([e.R[s].iX,i]),o=!1),l.1h([e.R[s].iX,C]),r.1h([e.R[s].iX,C])}r.1f&&r.1h([r[r.1f-1][0],i]);1a Z=e.au(r),c=e.o.2z||{};if("1N"===(c.1J||"1N")){1a p=1m DT(e.A);p.1S(e),p.1C({"1U-1r":e.BU,"2o-1N":.2}),p.1C(c),p.1q(),p.CV=!0,p.L9=!0,p.AX=0,p.AP=0,p.EU=0,p.G4=0,p.C4=ZC.1W(p.o["2o-1N"]),p.CW=[a.iX,a.iY,a.iX+a.I,a.iY+a.F],p.J=e.J+"-1N-2z",p.Z=n.Z,p.C=Z,p.1t()}1a u=e.au(l),h=ZC.P.E4(n.Z,e.H.AB),1b=1m CX(e);1b.1S(e),1b.1C({"1w-1r":e.BU,"1w-1s":1}),1b.1C(c),1b.1q(),ZC.CN.1t(h,1b,u,1c,3)}}}1O XS 2k IC{2G(e){1D(e);1a t=1g;t.AF="8D",t.SZ=3,t.BL=["1z-r",ZC.1b[52],"1z"],t.HT=.5,t.HU=[10,0,0,0,0],t.PP="bg"}FX(){1l 1m y8(1g)}1q(){1a e,t=1g;t.BS=t.ND(),t.C1=t.BS[0],t.B9=t.BS[1],t.A0=t.BS[3],t.AD=t.BS[3],t.N6(),1D.1q(),t.4y([["2o-1N","HT","f",0,1],["yQ","HU"]]),1c!==ZC.1d(e=t.o.163)&&(t.HU[0]=ZC.1k(e)),t.HU=[ZC.1W(t.HU[0]||"10"),ZC.1W(t.HU[1]||"0"),ZC.1W(t.HU[2]||"0"),ZC.1W(t.HU[3]||"0"),ZC.1W(t.HU[4]||"0")]}1t(){1a e=1g;1D.1t(),e.KE=e.CM("bl",0),e.O7(!0)}}1O UJ 2k WN{2G(e){1D(e);1a t=1g;t.AF="5z",t.W=1,t.CR="av",t.SZ=3,t.HT=.5}FX(){1l 1m y7(1g)}1q(){1a e=1g;e.BS=e.ND(),e.C1=e.BS[0],e.B9=e.BS[1],e.A0=e.BS[0],e.AD=e.BS[1],e.N6(),1D.1q(),e.kx(),e.YS("2o-1N","HT","f",0,1),e.B1=e.D.BK(e.BT("k")[0]),e.CK=e.D.BK(e.BT("v")[0])}O7(){1a e,t,i=1g,a=i.OT;i.Y5(!1);1a n=i.D.Q;i.W=1;1a l=a?n.F:n.I;if(i.B1.EI||!i.RE&&5*(i.B1.A1-i.B1.V)>l&&(i.W=ZC.1k(5*(i.B1.A1-i.B1.V)/l)),i.B1.EI)1j(e=0,t=i.R.1f;e<t;e++)i.R[e]&&ZC.E0(i.R[e].BW,i.B1.Y[i.B1.V],i.B1.Y[i.B1.A1])&&(i.R[e].Z=i.KE,i.R[e].MP="2j",i.R[e].1t(),i.R[e].MP="1X",i.R[e].1t(),4v i.R[e].E["cQ.3b"]);1u 1j(e=i.B1.V;e<=i.B1.A1;e+=i.W)i.R[e]&&(i.R[e].MP="2j",i.R[e].1t(),i.R[e].MP="1X",i.R[e].1t(),4v i.R[e].E["cQ.3b"])}1t(){1a e=1g;1D.1t(),e.KE=e.CM("bl",0),e.iP=ZC.P.E4(e.CM("bl",1),e.H.AB),e.QD=ZC.P.E4(e.CM("bl",2),e.H.AB),e.O7(),e.C=1c,e.D2=1c,e.gQ=1c,e.SD=1c}}1O XT 2k WO{2G(e){1D(e);1g.AF="7e",1g.NO=-1}1q(){1D.1q(),1g.4y([["rA","NO","ia"]])}FX(){1l 1m B4(1g)}}1O V2 2k QY{2G(e){1D(e),1g.AF="6O"}FX(){1l 1m Bm(1g)}1q(){1a e=1g;1D.1q(),1c===ZC.1d(e.o[ZC.1b[61]])&&(e.BU=e.BS[0]),1c===ZC.1d(e.o["1w-1r"])&&(e.B9=e.BS[0])}1t(){1D.1t(),1g.k0()}}1O WQ 2k QZ{2G(e){1D(e),1g.AF="7k"}FX(){1l 1m Bn(1g)}1q(){1a e=1g;1D.1q(),1c===ZC.1d(e.o[ZC.1b[61]])&&(e.BU=e.BS[0]),1c===ZC.1d(e.o["1w-1r"])&&(e.B9=e.BS[0])}}1O V3 2k QW{2G(e){1D(e),1g.AF="97"}FX(){1l 1m Cb(1g)}1q(){1a e=1g;1D.1q(),1c===ZC.1d(e.o[ZC.1b[61]])&&(e.BU=e.BS[1])}1t(){1D.1t(),1g.k0()}}1O V4 2k QX{2G(e){1D(e),1g.AF="83"}FX(){1l 1m Bp(1g)}1q(){1a e=1g;1D.1q(),1c===ZC.1d(e.o[ZC.1b[61]])&&(e.BU=e.BS[1])}1t(){1D.1t(),1g.k0()}}1O ZE 2k IC{2G(e){1D(e);1a t=1g;t.AF="b7",t.oh=[],t.jR=[],t.BL=["1z"],t.PP="bg"}FX(){1l 1m Bs(1g)}1q(){1a e=1g;e.BS=e.ND(),e.C1=e.BS[0],e.BU=e.BS[1],e.A0=e.BS[3],e.AD=e.BS[3],e.N6(),1D.1q(),e.4y([["2M","oh"],["15n","jR"]])}1t(){1a e=1g;1D.1t(),e.KE=e.CM("bl",0),e.O7(!0)}}1O ME 2k DM{2G(e){1D(e);1a t=1g;t.D=e.A.A,t.H=t.D.A,t.L=-1,t.AE=1c,t.DJ=[],t.CL=1c,t.BW=1c,t.CI=1c,t.JL=[],t.IK=!1,t.Q2=!0,t.N=t,t.K0=!1,t.hu=!1}GS(e,t){1D.GS(1g.A,e,t,1g.M6(1c,!1),1g.A.OL)}OG(){1l[1g.iX,1g.iY,{cL:1g,3F:!0}]}iW(){1l[1g.iX,1g.iY]}9I(e,t,i){1a a,n,l,r,o=1g;1P(o.1t(!0),a=o.iX,n=o.iY,l=o.I,r=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E-"+i,ka[i]],["%kt"+i,ka[i]]);1j(i=0;i<hx.1f;i++)CU.1h(["%1z-81-1T-"+i,hx[i]],["%kv"+i,hx[i]],["%k"+i,hx[i]]);CU.1h(["%1z-81-1H",S5],["%1z-81-1E",RS],["%1z-81-1T",PQ],["%1z-81-1T-ts",qi],["%156",qi],["%kt",RS],["%kl",S5],["%kv",PQ],["%k",PQ],["%2r-1T",CI],["%v",CI],["%2r-yK-1T",s.AE],["%V",s.AE],["%2r-3b",s.L],["%2r-x",s.iX],["%2r-y",s.iY],["%b9-1s",s.H.I],["%b9-1M",s.H.F],["%i",s.L],["%n",s.L],["%2r-eH",s.A.R.1f],["%N",s.A.R.1f]);1a yW=98["%1A-7S"],hA=yW+"",za=98["%1A-e6"],gE=za+"",tT=ZC.1W(8v.F3["%aU-"+s.L+"-"+s.A.DU+"-7S"]||"0"),kd=tT+"",zm=ZC.1W(tT/8v.F3["%aU-"+s.L+"-"+s.A.DU+"-7F-1f"]),kf=6d(zm),zl=6d(8v.F3["%aU-"+s.L+"-"+s.A.DU+"-7F-1f"]),t7=0;1c!==ZC.1d(8v.F3)&&1c!==ZC.1d(8v.F3[s.L])&&(t7=ZC.1W(8v.F3[s.L]["%6l-"+s.A.DU]||"0"));1a kh=t7+"";hA=ZC.AO.GO(hA,BE),gE=ZC.AO.GO(gE,BE),kh=ZC.AO.GO(kh,BE),kd=ZC.AO.GO(kd,BE),kf=ZC.AO.GO(kf,BE),CU.1h(["%2r-4L-8o",s.E["2r-4L-8o"]],["%2r-4L-s7",s.E["2r-4L-s7"]],["%7F-6l",kd],["%7F-e6",kf],["%7F-1f",zl],["%6l",kh],["%1A-2j-3b",98["%1A-2j-3b"]],["%14R",98["%1A-2j-3b"]],["%1A-1X-3b",98["%1A-1X-3b"]],["%14S",98["%1A-1X-3b"]],["%1A-2j-1T",98["%1A-2j-1T"]],["%14T",98["%1A-2j-1T"]],["%1A-1X-1T",98["%1A-1X-1T"]],["%14U",98["%1A-1X-1T"]],["%1A-7S",hA],["%14V",hA],["%1A-e6",gE],["%17m",gE],["%1A-6g",98["%1A-6g"]],["%pv",98["%1A-6g"]]);1a zi=100*s.AE/98["%1A-7S"],Z7=zi+"";1c!==ZC.1d(BE[ZC.1b[12]])&&(Z7=ZC.AO.GO(Z7,BE)),CU.1h(["%1A-8e",Z7],["%14Q",Z7]);1a t6=!1,WJ,AV,K,BX;1j(i=0,A2=CU.1f;i<A2;i++)if("%8k"===CU[i][0]){t6=!0;1p}if(!t6&&1c!==ZC.1d(s.A.A.F3)&&1c!==ZC.1d(s.A.A.F3[s.L])){1a JM=100*s.AE/s.A.A.F3[s.L]["%6l-"+s.A.DU],HN=JM+"";1c!==ZC.1d(BE[ZC.1b[12]])&&(HN=ZC.AO.GO(HN,BE)),CU.1h(["%2r-8e-1T",HN],["%8k",HN])}1j(i=0;i<U7.1f;i++)CU.1h(["%1A-1E-"+i,U7[i]],["%t"+i,U7[i]]);1j(CU.1h(["%1A-1E",WK],["%t",WK],["%1A-tj",s.A.YW],["%1A-3b",s.A.L],["%p",s.A.L],["%1A-eH",8v.A9.1f],["%P",8v.A9.1f],["%id",s.H.J],["%4w",s.D.J.1F(s.H.J+"-2Y-","")]),-1!==AN.1L("%7Q")&&(OU&&"cV"===BE.7Q?(CU.1h(["%7Q","-"]),OU=!1):CU.1h(["%7Q",""])),CU.1h(["%2r-x",s.iX],["%2r-y",s.iY],["%2r-1s",s.I],["%2r-1M",s.F],["%2r-2e",s.E["1R.2e"]||1]),1o.3J.zd&&CU.4i(ZC.lW),7P=1m 5y("\\\\(([^(]+?)\\\\)\\\\(([0-9]*)\\\\)(\\\\(*)([0-9]*)(\\\\)*)");D1=7P.3n(AN);){WJ="";1a CT=s.A.L,D4=s.L;""!==(G=D1[2])&&(CT=ZC.1k(G)),""!==(G=D1[4])&&(D4=ZC.1k(G)),1c!==(K=8v.A9[CT])&&(AV=K.FP(D4,3),1c!==AV&&(WJ=AV.EW(D1[1],EO))),AN=AN.1F(D1[0],WJ)}if(-1!==AN.1L("%zb-")){7P=1m 5y("%zb-([a-zA-Z0-9-]+)");1j(1a k7=s.7W();D1=7P.3n(AN);)1c!==ZC.1d(k7[D1[1]])&&1c!==ZC.1d(s[k7[D1[1]]])&&(AN=AN.1F(D1[0],s[k7[D1[1]]]))}if(-1!==AN.1L("%z9"))1j(7P=1m 5y("%z9([0-9]*)");D1=7P.3n(AN);)""===D1[1]?(BX=s.N||s,BX.B9||(BX=s.A)):BX=8v.A9[D1[1]],AN=AN.1F(D1[0],BX&&BX.B9||"#4u");if(-1!==AN.1L("%yY"))1j(7P=1m 5y("%yY([0-9]*)");D1=7P.3n(AN);)""===D1[1]?(BX=s.N||s,BX.B9||(BX=s.A)):BX=8v.A9[D1[1]],AN="jP"===s.A.PP?AN.1F(D1[0],BX&&BX.A5&&BX.A5.A0||"#4u"):AN.1F(D1[0],BX&&BX.A0||"#4u");if(-1!==AN.1L("%1r"))1j(7P=1m 5y("%1r([0-9]*)");D1=7P.3n(AN);)""===D1[1]?(BX=s.N||s,BX.B9||(BX=s.A)):BX=8v.A9[D1[1]],AN="1w"===s.A.PP?AN.1F(D1[0],BX&&BX.B9||"#4u"):"jP"===s.A.PP?AN.1F(D1[0],BX&&BX.A5&&BX.A5.A0||"#4u"):AN.1F(D1[0],BX&&BX.A0||"#4u");1j(AN=ZC.AO.ZL(AN,1g),i=0,A2=CU.1f;i<A2;i++)7P=1m 5y(CU[i][0],"g"),AN=1y CU[i][1]===ZC.1b[31]?AN.1F(7P,""):LX?AN.1F(7P,eQ(CU[i][1])):AN.1F(7P,CU[i][1]);1l AN=AN.1F(1m 5y("%1V-([a-zA-Z0-9]+)","g"),""),OU&&"cV"===BE.7Q&&(AN="-"+AN),AN}1t(){}6D(){}J6(){1l{1r:1g.N.A0}}K9(){1l{"1G-1r":1g.N.A0,"1U-1r":1g.N.AD,1r:1g.N.C1}}ZZ(){1l 1g.K9()}FF(e,t){1a i,a,n,l=1g;if(t||(t=1),l.A.O1&&l.A.O1.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.A.Z1){1a A=1m DM(l.A);A.1S(r),l.A.Z1=A}if(a="4t",1c!==ZC.1d(i=o.o.1J)&&(a=i),r.AM){r.AM=!1;1a C=l.A.o[ZC.1b[17]].1E||"";if("6g("===a.2v(0,7)){1a Z=a.2v(7,a.1f).1F(")","").2n(",");-1!==ZC.AU(Z,l.AE)&&(r.AM=!0)}1u{1a c=a.2n(","),p={2j:"%1A-2j-1T",1X:"%1A-1X-1T",h6:"%1A-2j-3b",7Z:"%1A-1X-3b"};1j(1a u in p)-1!==ZC.AU(c,u)&&(("h6"!==u&&"7Z"!==u||l.L!==l.A.L0[p[u]])&&("2j"!==u&&"1X"!==u||l.AE!==l.A.L0[p[u]])||("4h"==1y C&&1c!==ZC.1d(C[u])&&(r.o.1E=C[u],r.1q()),r.AM=!0));-1!==ZC.AU(c,"4t")&&(r.AM=!0)}}}if(l.D.E["1A"+l.A.L+".2h"]||(r.E["2O-3L"]="2b"),e)1l r;if(r.AM&&1c!==ZC.1d(r.AN)&&""!==r.AN){1a h=l.HA(r);r.E.rz=h,r.iX=h[0],r.iY=h[1];1a 1b={};if(-1!==r.iX&&-1!==r.iY){1a d=!1;if(1c!==ZC.1d(r.o.iy)&&!ZC.2s(r.o.iy)){1b={x:r.iX,y:r.iY,1s:r.I,1M:r.F};1j(1a f=0,g=l.A.A.ZA.1f;f<g;f++)if(ZC.AQ.Y9(1b,l.A.A.ZA[f])){d=!0;1p}}d||(l.D.E["1A"+l.A.L+".2h"]||(r.E["2O-3L"]="2b"),r.E.tA="vb"+l.D.L,r.1t(),r.E9(),l.A.A.ZA.1h(1b),!r.KA&&ZC.AK(l.H.J+"-3c")&&l.A.A.HQ.1h(ZC.AO.O8(l.D.J,r)))}}1l r}}}xQ(e){if(1c!==ZC.1d(e.o[ZC.1b[19]])){1a t=ZC.IH(e.o[ZC.1b[19]]);t<=1&&(t=1g.I*t),e.I=t}if(1c!==ZC.1d(e.o[ZC.1b[20]])){1a i=ZC.IH(e.o[ZC.1b[20]]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===v?(u.iX=f+b.iX,h.x=f):10===v?(u.iY=g-b.iY,h.y=g):11===v&&(u.iY=g+b.iY,h.y=g),o.A.FS)u[E5.GJ[ZC.EA(B)]]=o.A.FS[B],h[ZC.EA(B)]=o.N[E5.GJ[ZC.EA(B)]];if(1c===ZC.1d(o.D.EM)&&(o.D.EM={}),1c!==ZC.1d(o.D.EM[o.A.L+"-"+o.L]))1j(B in o.D.EM[o.A.L+"-"+o.L])u[E5.GJ[ZC.EA(B)]]=o.D.EM[o.A.L+"-"+o.L][B];o.D.EM[o.A.L+"-"+o.L]={},ZC.2E(h,o.D.EM[o.A.L+"-"+o.L]);1a m=1m E5(u,h,o.A.JD,o.A.LA,E5.RO[o.A.LE],1n(){c()});m.AV=o,m.OC=1n(){o.MN(ZC.P.E4(o.A.CM("bl",0),o.H.AB))},o.L5(m)}1u{1a E="3z"===l.DN?"3z":"2R";if(o.A.HH){1a D=1n(t,i){1a a=t.kQ(!1),n=o.iX,r=o.iY;if(e){1a s=1m CA(o.D,n-ZC.AL.DW,r-ZC.AL.DX,o.A.E["z-4e"]||0);n=ZC.4o(s.E7[0]),r=ZC.4o(s.E7[1]),o.E["dY"]=[n,r]}a.4m("5H","7f("+ZC.1k(n-l.iX)+","+ZC.1k(r-l.iY)+") "+(a.bJ("5H")||"")),a.4m("id",i),"5m"!==o.A.AF&&"6V"!==o.A.AF||a.4m("r",o.E["1R.2e"]),t.6o.2Z(a)};l.MC&&D(o.A.RF,o.J+"-1R-sh-"+E),D(o.A.HH,o.J+"-1R-"+E),l.D6&&D(o.A.QB,o.J+"-1R-5c")}1u{l.1t();1a J=l.A0!==l.AD;if(!o.D.KS[o.A.L]&&o.A.Z0&&!J)if("2F"===o.H.AB){if(-1===ZC.AU(["3O","9r","5n","fi","9t","8o","5D"],l.DN))if(o.A.H9=l,1o.3J.kz&&2g.dA){1j(1a F in o.H.FZ)o.A.HH||(o.A.HH=o.H.FZ[F].dA("#"+o.J+"-1R-"+E)),l.MC&&!o.A.R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C.EA(R)]]=i.D.T0[i.A.L+"-"+i.L][R]}i.D.EM[i.A.L+"-"+i.L]={},ZC.2E(I,i.D.EM[i.A.L+"-"+i.L]),"1N"===i.A.CR&&(i.D.T0[i.A.L+"-"+i.L]={},ZC.2E(M,i.D.T0[i.A.L+"-"+i.L]));1a Q=1m E5(F,I,i.A.JD,i.A.LA,E5.RO[i.A.LE],1n(){1b()});Q.AV=i,-1!==ZC.AU(["1w","1N"],i.A.CR)&&(Q.IG=n);1a V=1c;"1N"===i.A.CR&&((V=1m E5(w,M,i.A.JD,i.A.LA,E5.RO[i.A.LE],1n(){})).AV=i),i.L5(Q,V)}1u{1P(i.A.CR){1i"1w":1i"1N":1i"5z":i.A.IR||(ZC.CN.1t(n,d,Z),"1N"!==i.A.CR&&"5z"!==i.A.CR||J.1t());1p;1i"9g":1i"8U":1i"2U":1i"9v":1i"5V":a.1t()}1b()}}HX(e){1a t=1g;ZC.3m||(t.A.IB&&t.A.AM&&(-1!==ZC.AU(["1w","1N","5z"],t.A.CR)?(t.YI(e),"1N"!==t.A.CR&&"5z"!==t.A.CR||t.LI({6p:e,1J:"1N",9a:1n(){1g.C=t.E.9X},cG:1n(){1g.AX=0,1g.AP=0,1g.C4=t.A.HT;1a e=t.D.Q;1g.CW=[e.iX,e.iY,e.iX+e.I,e.iY+e.F]}})):-1!==ZC.AU(["9g","8U","2U","9v","5V"],t.A.CR)&&t.LI({6p:e,1J:"2T",9a:1n(){1g.1S(t),1g.B9=t.A.BS[1],1g.BU=t.A.BS[1],1g.A0=t.A.BS[3],1g.AD=t.A.BS[2],1g.iX=t.5J("x"),1g.iY=t.5J("y"),1g.CJ=t.5J("sl"),1g.B0=t.5J("as"),1g.BH=t.5J("ae"),1g.DN="3O",1g.AH=t.5J("sz")}})),-1!==ZC.AU(["rh","6v","1w"],t.A.CR)&&t.S9(e))}}1O yj 2k ZV{2G(e){1D(e),1g.FD=1c}EW(e,t,i,a){1a n=1g,l=n.A.LS();ZC.2E(t,l);1a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.2j))1j(c=0,p=e.1f;c<p;c++)t.AG.1h(e[c])}if(1c!==ZC.1d(e=t.A.gQ[t.MP]))1j(g=[],c=0,p=e.1f;c<p;c++)g.1h(e[c]);if(l[t.L+t.A.W]){"2j"===t.MP?h=t.E["4W.2W.2j"]:"1X"===t.MP&&(h=t.E["4W.2W.1X"]),1b=-1===t.E["cQ.3b"]?ZC.1k(h.1f/2):t.E["cQ.3b"];1a X=n?i.AT?1:-1:i.AT?-1:1;1j(c=0;c<1b;c++)n?(g.1h([h[c][1],t.iY+X*h[c][0]*u]),B.1h([h[c][1],ZC.1k(t.iY+X*h[c][0]*u)])):(g.1h([t.iX+X*h[c][0]*u,h[c][1]]),B.1h([ZC.1k(t.iX+X*h[c][0]*u),h[c][1]]));1a y=1===t.HT?ZC.CQ(2,1b):1;1j(c=1b-1,p=h.1f;c<p;c++)n?Y.1h([h[c][1],t.iY+X*h[c][0]*u]):Y.1h([t.iX+X*h[c][0]*u,h[c][1]]);1j(c=1b-y,p=h.1f;c<p;c++)n?x.1h([h[c][1],ZC.1k(t.iY+X*h[c][0]*u)]):x.1h([ZC.1k(t.iX+X*h[c][0]*u),h[c][1]])}1u g.1h([l[t.L].iX,l[t.L].iY]),n?(Y.1h([l[t.L].iX,ZC.1k(l[t.L].iY)]),B.1h([l[t.L].iX,ZC.1k(l[t.L].iY)]),x.1h([l[t.L].iX,ZC.1k(l[t.L].iY)])):(Y.1h([ZC.1k(l[t.L].iX),l[t.L].iY]),B.1h([ZC.1k(l[t.L].iX),l[t.L].iY]),x.1h([ZC.1k(l[t.L].iX),l[t.L].iY]));t.A.gQ[t.MP]=Y,t.A.SD[t.MP]=x}if("2j"===t.MP)1j(c=0,p=B.1f;c<p;c++)t.AG.1h(B[c]);1u 1j(c=B.1f-1;c>=0;c--)t.AG.1h(B[c]);if("1X"===t.MP){1a L=1m DT(t.A);L.J=t.J+"-1N",L.Z=t.A.CM("bl",0),L.1S(t),L.AX=0,L.AP=0,L.EU=0,L.G4=0,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T","b"],["cF","H4","b"],["3G-15l","YJ","b"],["7a-6z","Q6","b"],["3G-to","LW"],["db-15k","YY","b"],["3G-to-6g","NS"],["2B-iy","jn","b"],["15j","TJ","b"],["1X-cC","EG","i"],["1X-2B","EG","i"],["3T-1T","HK","f"],[ZC.1b[12],"E8","ia"],[ZC.1b[14],"S3"],[ZC.1b[13],"RD"],["5G","eZ","b"],["5G-dm","TY"],["7Q","f6"],["ax","eL","b"],[ZC.1b[25],"SP","ia"],["fj","DL"],["3P-15h","H8","fa"],["1z-7c","P9","fa"],["4n-cC","M0"],["1X-6K","HD","i"],[ZC.1b[7],"B7"],["7c","R4","f"],["15f","dn"],["15c","VT","b"],["Cj","DI","b"]]),1c!==ZC.1d(e=t.o["3g-iB"])&&(e.1f?(t.7H[0]=ZC.2s(e[0]),t.7H[1]=ZC.2s(e[e.1f-1])):t.7H[0]=t.7H[1]=ZC.2s(e)),"3e"==1y t.BV){1a n=t.BV.2n(":"),l=1;3===n.1f&&(l=ZC.1W(n[2])),t.BV=[];1j(1a r=ZC.1W(n[0]);r<ZC.1W(n[1]);r+=l)t.BV.1h(""+r);t.BV.1h(""+n[1])}1c!==ZC.1d(t.o["7a-2B"])&&(t.EG=ZC.3w),t.EG=ZC.BM(t.EG,2),1c!==ZC.1d(e=t.o.2c)&&(t.A7=t.BY=ZC.1k(e),0!==ZC.1k(e)||"9u"!==t.A.AF&&"aX"!==t.A.AF||(t.DI=!1)),1c!==ZC.1d(e=t.o["1X-9F"])?t.P8=ZC.1k(e):t.P8=t.EG,t.P8=ZC.BM(2,t.P8),1c!==ZC.1d(e=t.o.5H)&&(t.FB=1m CX,t.FB.1C(e));1a o=t.A.A.B8,s="("+t.A.AF+")",A=t.BC.1F(/\\-[0-9]/,""),C=t.BC.1F(/\\-[0-9]/,"-n");1n Z(e){1a i=[s+".4z."+e,s+"."+t.BC+"."+e,s+"."+A+"."+e,s+"."+A+"["+t.B7+"]."+e,s+"."+C+"."+e];1l t.A.AJ["3d"]&&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.FL(t,i,a,n),o=[];o.1h(["%1z-1H",r],["%1z-3b",t],["%1z-2K",t]),l.FB&&"5s"===l.FB.o.1J?o.1h(["%1z-1T",r],["%v",r]):"3P"===l.DL&&n?o.1h(["%1z-1T",1B.6s(l.H8,t)],["%v",1B.6s(l.H8,t)]):o.1h(["%1z-1T",ZC.9q(l.Y[t],"")],["%v",ZC.9q(l.Y[t],"")]),o.1h(["%l",r],["%t",r],["%i",t],["%c",t]),o.4i(ZC.lW);1j(1a s=0,A=o.1f;s<A;s++){1a C=1m 5y(o[s][0],"g");e=e.1F(C,o[s][1])}1l e}T6(){1a e=1g,t=ZC.BM(e.Y.1f,e.BV.1f),i=0;if(t>0&&e.BR.AA%180==0){1j(1a a=ZC.BM(1,ZC.1k(t/20)),n=0;n<t;n+=a){1j(1a l=((e.BV[n]||e.Y[n])+"").2n(/<br>|<br\\/>|<br \\/>|\\n/),r=0,o=0,s=l.1f;o<s;o++)r=ZC.BM(r,10*l[o].1F(/<.+?>/gi,"").1F(/<\\/.+?>/gi,"").1f);i+=r}i/=1B.2j(20,t)}1u i=15;e.D8?e.EG=ZC.1k((e.F-e.A7-e.BY)/15):e.EG=ZC.1k((e.I-e.A7-e.BY)/i),e.EG=ZC.CQ(e.EG,20),(e.BP-e.B3)/e.CP+1<e.EG?e.EG=ZC.BM(e.EG,ZC.1k((e.BP-e.B3)/e.CP)+1):(e.BP-e.B3)/(2*e.CP)+1<e.EG&&(e.EG=ZC.BM(e.EG,ZC.1k((e.BP-e.B3)/(2*e.CP))+1)),e.EG=ZC.BM(2,e.EG)}lo(){1a e=1g;1c===ZC.1d(e.o["1X-9F"])&&(e.P8=e.EG)}H5(e){1a t,i,a,n,l,r=1g;if(1===e&&r.o.5H&&"5s"===r.o.5H.1J&&(1c===ZC.1d(r.o.5H.Ah)||ZC.2s(r.o.5H.Ah)||(r.NX=!0)),1===e&&1c!==ZC.1d(r.o[ZC.1b[5]]))if(r.Y=[],"4h"==1y r.o[ZC.1b[5]])1j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t,C,1,C],s=!0}1u if("3P"===o.DL)a=[e,t,1,1,1];1u{1a Z=1c!==ZC.1d(o.o.6z)||1c!==ZC.1d(o.o["2j-1T"])||1c!==ZC.1d(o.o["1X-1T"]);a=e!==t?ZC.AQ.ZI(e,t,o.CP,o.P9,Z):[e,t,o.CP,1,o.CP]}-1===o.QU&&(o.QU=a[4]);1a c=a[0],p=a[1];r=a[2],i&&"3P"===o.DL&&(c=1B.4b(ZC.JN(c,o.H8)),p=1B.4l(ZC.JN(p,o.H8))),1c===ZC.1d(o.o.6z)&&(p-c)/r>8p&&(r=(p-c)/8p,l=1B.4l(ZC.JN(r)/1B.a6),r=1B.6s(10,l)),1c===ZC.1d(o.o["2j-1T"])&&c!==p&&(s&&A||(c-=c%r)),1c===ZC.1d(o.o["1X-1T"])&&c!==p&&(s&&A||(p=p-p%r+(p%r==0?0:r))),l=1B.4b(ZC.JN(r)/1B.a6);1a u,h=a[3];if(l<h&&l<0&&(h=l),"3P"===o.DL&&(h=ZC.BM(1,h)),o.Y=[],s&&A){1a 1b=ZC.AO.YT(c,"%Y-%n-%d-%H-%i-%s",!1,0).2n("-"),d=!0,f=ZC.1k((""+o.o.6z).1F("ex"));0===f&&(f=1);1a g=ZC.1k(1b[1]),B=ZC.1k(1b[0]);1j(o.Y.1h(c);d&&c!==p;){d=!1;1a v=ZC.1k(1b[2]);g+f>=12&&B++,g=(g+f)%12,(31===v&&(3===g||5===g||8===g||10===g)||v>28&&1===g)&&(v=1===g?B%4==0&&B%100!=0||B%sC==0?29:28:30);1a b=1m a1(B,g,v,1b[3],1b[4],1b[5]).bI();o.Y.1h(b),b<p&&b<=t&&(d=!0)}}1u if(i)if(o.GZ=e,o.HM=t,o.OZ=ZC.1k((p-c)/r),h>0)1j(n=c;n<=p;n+=r){1a m,E;u=n;1a D=o.E8;if("3P"===o.DL)1j(1a J=!0;J;)J=!1,E=m=1B.6s(o.H8,u),m=ZC.1W(ZC.9y(m,D)),E<1&&E!==m&&ZC.BM(E,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].AE>=0||!I?E[J[i].DU][X][0]+=J[i].R[Y].AE:E[J[i].DU][X][1]+=J[i].R[Y].AE,J[i].R[Y].AE>=0||!I?J[i].R[Y].CL=E[J[i].DU][X][0]:J[i].R[Y].CL=E[J[i].DU][X][1],1c===ZC.1d(s.o[ZC.1b[5]])&&D.1h(E[J[i].DU][X][0]+y,E[J[i].DU][X][1]+y);1u if(1c===ZC.1d(s.o[ZC.1b[5]])){D.1h(J[i].R[Y].AE+y),0!==y&&D.1h(y);1j(1a L=0,w=J[i].R[Y].DJ.1f;L<w;L++)D.1h(J[i].R[Y].DJ[L]+y)}}}D.1f>0&&(l=ZC.dj(D),r=ZC.d4(D)),0!==s.Y.1f||l!==4T.hH&&r!==4T.16L||(s.Y=[0,1],l=0,r=1),1c===ZC.1d(s.o[ZC.1b[5]])&&(1c!==ZC.1d(s.o["2j-1T"])&&"3g"!==s.o["2j-1T"]?l=ZC.1W(s.o["2j-1T"]):l>0&&"3g"!==s.o["2j-1T"]&&"3P"!==s.DL&&(l=0),1c!==ZC.1d(s.o["1X-1T"])&&(r=ZC.1W(s.o["1X-1T"])),l===ZC.3w&&r===-ZC.3w?(s.V=0,s.A1=0,s.B3=0,s.BP=0):s.RZ(l,r,!0))}2===e&&(-1===s.GZ&&-1===s.HM&&(s.GZ=s.B3,s.HM=s.BP),-1===s.QU&&(s.QU=s.CP)),"3g"===s.o["2j-1T"]&&1c===ZC.1d(s.o["3T-1T"])&&(s.HK=s.B3),0===s.OZ&&(s.OZ=ZC.1k((s.BP-s.B3)/s.CP));1a M=s.H.E["2Y"+s.A.L+".3G"];if(1c===ZC.1d(s.H.E[ZC.1b[53]])||s.H.E[ZC.1b[53]]){1a H=1===s.L?"":"-"+s.L;2===e&&1y M!==ZC.1b[31]&&1c!==ZC.1d(M["5r"+H])&&1c!==ZC.1d(M["5q"+H])&&(ZC.E0(M["5r"+H],s.B3,s.BP)||(M["5r"+H]=s.B3),ZC.E0(M["5q"+H],s.B3,s.BP)||(M["5q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&&(fe=ZC.1k(ge)%2==0);1p;1i"Ab":se>15&&(fe=ZC.1k(ge)%3==0);1p;1i"da":se>45?fe=1===ZC.1k(ge)||15===ZC.1k(ge):se>30?fe=1===ZC.1k(ge)||10===ZC.1k(ge)||20===ZC.1k(ge):se>15&&(fe=1===ZC.1k(ge)||10===ZC.1k(ge)||15===ZC.1k(ge)||20===ZC.1k(ge)||25===ZC.1k(ge));1p;1i"hr":se>45?fe=ZC.1k(ge)%12==0:se>30?fe=ZC.1k(ge)%6==0:se>15&&(fe=ZC.1k(ge)%3==0);1p;1i"2j":1i"zP":se>45?fe=ZC.1k(ge)%30==0:se>30?fe=ZC.1k(ge)%10==0:se>15&&(fe=ZC.1k(ge)%5==0)}fe&&(me(t,!0),de=ge)}}ne.AM&&(ne.J=d.J+"-9F",ZC.CN.1t(o,ne,ae))}1u 1j(d.GX=0,me(d.V),d.GX=d.A1-d.V,me(d.A1),d.GX=1,t=d.V+1;t<d.A1;t++)(t-d.V)%M==0&&me(t);if(d.M.AM&&d.M.AN&&""!==d.M.AN){($=1m DM(d)).1S(d.M),$.J=d.A.J+"-"+d.BC.1F(/\\-/g,"1b")+"-iV",$.GI=d.J+"-1H "+d.A.J+"-1z-1H zc-1z-1H",$.AN=d.M.AN,$.Z=d.H.2Q()?d.H.mc():ZC.AK(d.A.J+"-3A-ml-0-c"),$.IJ=d.H.2Q()?ZC.AK(d.H.J+"-3Y"):ZC.AK(d.H.J+"-1E"),$.1q(),"5l"!==d.M.o["2t-1r"]&&"5l"!==d.M.o.1r||-1===f||($.C1=f);1a Be=d.iX+(d.AT?d.BY:d.A7),ve=d.I-d.A7-d.BY;1P("b9"===$.o["3F-fA"]&&(Be=d.A.iX,ve=d.A.I),$.OA){1i"1K":$.iX=Be;1p;1i"3F":$.iX=Be+ve/2-$.I/2;1p;1i"2A":$.iX=Be+ve-$.I}$.iY=E?n+G+oe:n-$.F-G-oe,d.M.iX=$.iX,d.M.iY=$.iY,$.AM&&(d.M8($,1c,"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t.C4=.95,t.L=0,t.AF=1c,t.M=1c,t.FT=1c,t.tU=!1,t.B7="2a",t.A7=0,t.BY=0,t.MK="5f",t.O6="5f",t.PR=[5,5],t.kp=[0,0],t.Z4=""}1q(){1D.1q();1a e,t=1g;t.4y([["1J","AF"],["1T-5z","tU","b"],["2c-4e","A7","i"],["2c-6j","BY","i"],[ZC.1b[7],"B7"],["16N-1z","Z4"],["1H-6w","MK"],["1H-i2","O6"],["5z","FT"]]),1c===ZC.1d(t.o.2o)&&(t.o.2o="1N"===t.AF?.25:.95),1c!==ZC.1d(e=t.o["1H-g2"])&&("4h"==1y e&&e.1f?(t.PR[0]=ZC.1k(e[0]||"5"),t.PR[1]=ZC.1k(e[1]||"5")):t.PR[0]=t.PR[1]=ZC.1k(e||"5")),t.4y([["2o","C4","f",0,1]]),1c===ZC.1d(e=t.o.1H)&&1c===ZC.1d(t.o.1E)||(t.M=1m DM(t),t.A.A.A.B8.2x(t.M.o,["("+t.A.AF+").4z.1R.1H"]),1c!==ZC.1d(t.o.1E)&&t.M.1C({1E:t.o.1E}),t.M.1C(e),t.M.1q(),t.kp=[t.M.BJ,t.M.BB])}1t(){1a e,t,i,a,n,l,r,o=1g;if(o.FT)if(-1===o.A.BC.1L("1z-r")){if(o.AM){1a s,A,C,Z,c=o.A,p=o.A.A.Q.AP,u=c.A.J+"-3A-"+("1v"===o.B7?"f":"b")+"l-0-c";o.Z=o.C7=ZC.AK(c.H.2Q()?c.H.J+"-3Y-c":u),e=ZC.P.E4(o.Z,c.H.AB),n=[];1a h,1b,d=0,f=0;o.BJ>-1&&o.BJ<1&&(o.BJ=1B.4l(o.BJ*c.A8)),o.BB>-1&&o.BB<1&&(o.BB=1B.4l(o.BB*c.A8)),o.M&&(o.M.Z=c.H.2Q()?c.H.mc():ZC.AK(c.A.J+"-3A-ml-0-c"),o.M.J=o.A.A.J+"-"+o.A.BC.1F(/\\-/g,"1b")+"-aM"+o.L,o.M.GI=o.A.J+"-1R-1H "+o.A.A.J+"-1z-1R-1H zc-1z-1R-1H");1a g=1n(e,t){1a i;1l-1!==(t+"").1L("%")?(i=ZC.1W(t.1F("%","")),i="k"===e.AF?ZC.1k(i*(e.ED-e.E3)/100):i*(e.HM-e.GZ)/100):i=t,o.tU||"v"===e.AF?e.B2(i):e.GY(i)};if("4C"===o.AF){1a B,v,b,m;1j(1b=o.A.A,"k"===c.AF?(B=c,v=""===o.Z4?1b.BT("v")[0]:1b.BK(o.Z4)||1b.BT("v")[0]):"v"===c.AF&&(v=c,B=""===o.Z4?1b.BT("k")[0]:1b.BK(o.Z4)||1b.BT("k")[0]),l=0,r=o.FT.1f;l<r;l++)b=g(B,o.FT[l][0]),m=v.B2(o.FT[l][1]),n.1h([b,m]),d+=b,f+=m;if(d/=n.1f,f/=n.1f,n.1f>=3){if(n[0].2M("/")!==n[n.1f-1].2M("/")&&n.1h([n[0][0],n[0][1]]),c.A.AJ["3d"])1j(c.A.NF(),t=0,i=n.1f;t<i;t++)a=1m CA(c.A,n[t][0]-ZC.AL.DW,n[t][1]-ZC.AL.DX,ZC.AL.FR),n[t][0]=a.E7[0],n[t][1]=a.E7[1];(h=1m DT(o.A)).J=c.J+"-1R-"+o.L,h.Z=h.C7=c.H.2Q()?c.H.mc():ZC.AK(u),h.1S(o),h.AX=0,h.AP=0,h.EU=0,h.G4=0,h.C=n,h.1q(),h.1t()}}1u if("1w"===o.AF){if(-1!==c.BC.1L(ZC.1b[50])?1===o.FT.1f?s=A=g(c,o.FT[0]):2===o.FT.1f&&(s=g(c,o.FT[0]),A=g(c,o.FT[1])):-1!==c.BC.1L(ZC.1b[51])&&(1===o.FT.1f?s=A=g(c,o.FT[0]):2===o.FT.1f&&(s=g(c,o.FT[0]),A=g(c,o.FT[1]))),-1!==c.BC.1L(ZC.1b[50])&&c.D8||-1!==c.BC.1L(ZC.1b[51])&&!c.D8?(n.1h([c.iX+o.A7,s],[c.iX+c.I-o.BY,A]),o.M&&("5w"===o.MK?o.M.iX=c.iX+c.I-o.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yL,E5.yM,E5.yO],ZC.aT={15P:15Q,15R:5x,15S:0,15T:1,15M:2,15U:3,15W:4,15X:5,15Y:0,15Z:1,160:2,161:3,162:1,15V:2,15K:3,15B:4,15J:5,15u:6,15v:7,15x:8,15y:9,15z:10,15A:11,15D:12,15E:13,15F:2,15G:3,15H:4,15I:5};1O PM 2k ad{2G(e){1D();1a t=1g;t.D=e,t.SE=!1,t.C6=1c,t.P5=[],t.PL={},t.lM=1c}pA(e){1a t=1g;1c===ZC.1d(t.PL[e.BC])&&(t.PL[e.BC]=e,e.M1=t,t.SE||t.4e())}2P(e){1a t=1g;e.M1=t,e.pG>0?(t.P5.1h(e),2w.5Q(1n(){e.BX.TW=!0,t.SE||t.4e()},e.pG+1)):(e.BX.TW=!0,t.P5.1h(e),t.SE||t.4e())}4e(){1a e=1g;e.SE=!0,ZC.AO.C8("17l",e.D.A,{id:e.D.A.J,4w:e.D.J});1a t=!0;!1n i(){t||e.6z(),t=!1,e.SE&&(e.C6=2w.hQ(i))}()}6z(){1a e,t=1g,i=0;if(t.SE){1j(1a a=0,n=t.P5.1f;a<n;a++)i+=t.P5[a].6M();if("3a"===t.D.H.AB)if(t.D.H.KA)1c!==ZC.1d(e=ZC.AK(t.D.J+"-4k-bl-c"))&&e.9d("2d").n6(t.D.iX,t.D.iY,t.D.I,t.D.F);1u 1j(a=0,n=t.D.AZ.A9.1f;a<n;a++)1j(1a l=0;l<t.D.AZ.A9[a].SZ;l++)1c!==ZC.1d(e=ZC.AK(t.D.J+"-1A-"+a+"-bl-"+l+"-c"))&&e.9d("2d").n6(t.D.iX,t.D.iY,t.D.I,t.D.F);1j(a=0,n=t.P5.1f;a<n;a++)0===t.P5[a].6z()&&(t.P5[a].BX.TW=!1);1j(1a r in t.PL)1j(t.PL[r].jk||(i+=1),a=0,n=t.PL[r].P5.1f;a<n;a++)t.PL[r].P5[a].XE===t.PL[r].lj?0===t.PL[r].P5[a].6z()&&(t.PL[r].P5[a].BX.TW=!1):"3a"===t.D.H.AB&&t.PL[r].P5[a].1t();0===i&&(t.PL={},t.P5=[],t.8A())}}8A(e){1c===ZC.1d(e)&&(e=!1);1a t,i=1g;if(e&&(i.18H=!0),2w.oV(i.C6),i.D.Y7(),i.D.Q8=!1,ZC.AK(i.D.H.J)){i.D.JQ(),2w.5Q(1n(){(t=ZC.AK(i.D.A.J+"-3c"))&&i.D.AZ.HQ&&(-1===ZC.AU(["5m","9u","8i","7R","7d"],i.D.AF)&&1!==1o.q4||i.D.AZ.HQ.4i(1n(e,t){1l ZC.AO.N5(e)>ZC.AO.N5(t)?1:-1}),t.4q+=i.D.AZ.HQ.2M(""))},33),i.D.oR(),i.SE=!1;1j(1a a=0,n=i.P5.1f;a<n;a++)i.P5[a].TB=1c;if(i.P5=[],i.PL={},e||ZC.AO.C8("17N",i.D.A,{id:i.D.A.J,4w:i.D.J}),1c!==ZC.1d(i.lM))4J{i.lM()}4M(l){}}}}PM.UH=33,1n(){1j(1a e=["ms","Dz","7n","o"],t=0,i=e.1f;t<i&&!2w.hQ;++t)2w.hQ=2w.17z||2w[e[t]+"17y"],2w.17x=2w.17w||2w[e[t]+"17v"]||2w[e[t]+"17q"];2w.hQ||(2w.hQ=1n(e){1l 2w.5Q(e,PM.UH)}),2w.oV||(2w.oV=1n(e){2w.iu(e)})}(),1o.3r(1c,"fJ",1n(e,t){1j(1a i,a,n=0,l=t[ZC.1b[16]].1f;n<l;n++)if(t[ZC.1b[16]][n].1J&&-1!==ZC.AU(["3O","1w","bj","1N","bv","2U","5t","6c","97","83","dN","6O","7k"],t[ZC.1b[16]][n].1J)&&t[ZC.1b[16]][n].Ed){1a r=t[ZC.1b[16]][n];ZC.6y(r);1a o=r.Ed||{};ZC.6y(o);1a s,A,C,Z=ZC.IH(o.lq||"10%"),c=o.18f||{1E:"18e"},p=o.cq||{},u=o[ZC.1b[8]]||"0.3",h=r[ZC.1b[11]]||[],1b=[];if("3O"===t[ZC.1b[16]][n].1J){1a d=0;1j(i=0;i<h.1f;i++)h[i][ZC.1b[5]]&&1c!==ZC.1d(h[i][ZC.1b[5]][0])&&(d+=h[i][ZC.1b[5]][0]);Z>0&&Z<1&&(Z*=d),s=[].4B(h);1a f=0,g="";1j(A=1,i=h.1f-1;i>=0;i--)h[i][ZC.1b[5]]&&1c!==ZC.1d(h[i][ZC.1b[5]][0])&&h[i][ZC.1b[5]][0]<Z&&(f+=h[i][ZC.1b[5]][0],g+=(h[i].1E||"Cv no."+A)+":"+h[i][ZC.1b[5]][0]+"<br>",h[i][ZC.1b[8]]=u,1b.1h(h[i]),h.6r(i,1),A++);f>0&&(A>2?(C={6g:[f],od:!1,"1V-6a":[1],"2H-1E":g=g.2v(0,g.1f-4)},ZC.2E(c,C),h.1h(C),1o.3r(e.id,"Fz",1n(t){if(t.hN.6a){1a i=1o.6Z(t.id);if(!i)1l;1a a=1o.pE(i,t.4w);1j(1a n in a.py())"3O-eY-"===n.2v(0,8)&&a.4m(n,1c);1o.3n(e.id,"do",{1V:1b}),2w.5Q(1n(){1a t=1o.3n(e.id,"m6",{4h:"2r",3W:0,5T:0}),i={id:"pL",x:t.x,y:t.y,1E:"< os",bp:"c",4V:"iC"};ZC.2E(p,i),1o.3n(e.id,"o9",{1J:"1H",1V:i})},1)}}),1o.3r(e.id,"FH",1n(t){if("pL"===t.1H.id){1a i=1o.6Z(t.id);if(!i)1l;1a a=1o.pE(i,t.4w);1j(1a n in a.py())"3O-eY-"===n.2v(0,8)&&a.4m(n,1c);1o.3n(e.id,"nS",{1J:"1H",id:"pL"}),1o.3n(e.id,"do",{1V:h})}})):r[ZC.1b[11]]=[].4B(s))}1u{1a B=0,v=[];1j(i=0;i<h.1f;i++){if(v[i]=0,h[i][ZC.1b[5]]&&h[i][ZC.1b[5]].1f)1j(a=0;a<h[i][ZC.1b[5]].1f;a++)v[i]+=ZC.2l(h[i][ZC.1b[5]][a]);B=ZC.BM(B,v[i])}Z>0&&Z<1&&(Z*=B),s=[].4B(h);1a b=[],m=[];1j(A=1,i=h.1f-1;i>=0;i--)if(v[i]<Z){if(h[i][ZC.1b[5]]&&h[i][ZC.1b[5]].1f)1j(a=0;a<h[i][ZC.1b[5]].1f;a++)b[a]=ZC.1W(b[a]||"0"),b[a]+=h[i][ZC.1b[5]][a],m[a]=m[a]||"",m[a]+=(h[i].1E||"Cv no."+A)+":"+h[i][ZC.1b[5]][a]+"<br>";1b.1h(h[i]),h.6r(i,1),A++}if(b.1f)if(A>2){1j(a=0;a<m.1f;a++)m[a]=m[a].2v(0,m[a].1f-4);C={6g:b,od:!1,"1V-6a":[1],"1V-tt-1E":m,"2H-1E":"%1V-tt-1E"},ZC.2E(c,C),h.1h(C),1o.3r(e.id,"Fz",1n(t){if(t.hN.6a){if(!1o.6Z(t.id))1l;1o.3n(e.id,"do",{1V:1b}),2w.5Q(1n(){1a t=1o.3n(e.id,"m6",{4h:"2u"}),i={id:"nL",x:t.x+t.1s/2,y:t.y,1E:"< os",bp:"c",4V:"iC"};ZC.2E(p,i),1o.3n(e.id,"o9",{1J:"1H",1V:i})},1)}}),1o.3r(e.id,"FH",1n(t){if("nL"===t.1H.id){if(!1o.6Z(t.id))1l;1o.3n(e.id,"nS",{1J:"1H",id:"nL"}),1o.3n(e.id,"do",{1V:h})}})}1u r[ZC.1b[11]]=[].4B(s)}}1l t});',62,4391,'||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||var|_|null|_n_||length|this|push|case|for|_i_|return|new|function|zingchart|break|parse|color|width|paint|else|top|line||typeof|scale|plot|Math|append|super|text|replace|border|label|style|type|left|indexOf|height|area|class|switch|item|marker|copy|value|background|data|_f_|max|legend|scroll|||||||||||bottom|none|offset||size|angle|document|visible|guide|min|extends|_a_|360|split|alpha|cls|default|node|_b_|font|plotarea|substring|window|load|margin|preview|right|items|menu||_cp_|svg|constructor|tooltip|setup|objects|position|mobile|join|hover|css|add|usc|path|fff|shape|bar|solid|points|target|graph|appendChild|||||||||||canvas|index|map||string|page|auto|JSON|fill|clear|unbind|abs|move|exec|opacity|remove|handle|bind|body|clip|align|padding|MAX|layout|MAPTX|circle|scales|div|box||instanceof|center|zoom|click|shadow|DEV|vml|display|Array|handler|pie|log|attr|url|update|ref|255|270|plotindex|state|main|tick||||round|||enabled||||stroke|floor|live|image|start|cache|html|object|sort|die|plots|ceil|setAttribute|show|_x_|xmax|innerHTML|bugreport|xmin|all|000|delete|graphid|call|assign_a|SCALE|toFixed|concat|poly|absolute|mode|SKIP|json|touchstart|form|try|viewsource|error|catch|dynamic|mask|createElement|minor|out|999|Number|enable|cursor|spline|plotid|maps|history|||||||||||src|hide|imgfill|each|gradient|normal|stringify|GESTURE|gui|prototype|front|inherit|bubble|rect|2px|depth|ymax|ymin|date|vbar|_l_|parseInt|opposite|1e3|RegExp|range|substr|row|sqrt|custom|title|callback|short|transform|format|getNodeData|header|shapes|toUpperCase|inner|GUIDES|parseFloat|setTimeout|touchend|build|nodeindex|test|piano|img|fullscreen|shared|m_|||||||||||group|highlight|hbar|String|pool|touchmove|values|_e|context|end|mouseup|total|from|middle|parentNode|layer|table|splice|pow|about|arc|scatter|placement|bold|_todash_|step|loader|repeat|active|paint_|info|mousedown|callout|9999|print|browser|decimals|csv|status|ie67|vbar3d|palette|off|preventDefault|fontSize|distance|fontWeight|hbubble|fontFamily|00|childNodes|getLoader|||||ddd||aspect|221F1F|override|weight|fixed|plotidx|factor|radar|pie3d|translate|source|http|outer|trend|hbar3d|eval|close|webkit|zcv|api|hook|important|nodeidx|eachfn|javascript|init|goal|touches|item_|slice|mouseover|href|sFontWeight|span|zoomx|stack|true3d|aAutoFit|arrow|flat|button|progress|D1D3D4|zoomy|getToggleAction|oRE|negation|hbullet|sum|mouseout|className|mousemove|getPMap|isNaN|1px|last|xls|key|cnt|area3d|stock||subtitle||5px|location|trigger|exit|ccc|hasOwnProperty|percent|send|entry|tagName|vbullet|void|npv|zidx|export|CSV|plus|1e4|pointer|hscatter|diff|val|nbsp|oPS|order|animation|block|www|stop|pattern|name|gauge|separator|fast|_p_|01|space|images|radial|static|333|zoomTo|connector|arguments|58595B|hidden|nestedpie|adjust|column|navigator|Object|eee|light|kmax|||number|action|kmin||quirks|line3d|oPPI||initcb|blocker|float|getContext|coords|which|rose|hideCM|radius|crosshair|linear|vertical|zc_legend_mousescroll|locate|reverse|paintPreview|_c_|square|DAY|cross|mixed|matrix|ready|dragged|_fixed_|children|apply|family|dblclick|targetid|side|ticks|oMask|ring|getTooltipPosition|rgba|png|overflow|frame|rgb|EVENT|select|method|pages|clearInterval|FONTFAMILY|footer|mid|EVENTS|pointsarea|change|angleEnd|destroy|Date|zIndex|root|version|toString|LN10|getInstance|ajax|toggle|setAttributeNS|filled|behaviors|ZCClass||msie|async|styles|complete|down|rules|equal||input|element|zindex|COLORS|atan|||mapPointsToPreview|segmented|SEC|exponent|multiple|10px|vfunnel|hfunnel|MIN|mousewheel|_tx_|success|transparent|rtl|setdata|flash|scrollLeft|selection|marker_|toLowerCase|scrollTop|skip|params|pyramid|rel|ANIMATION|pstack|NODE_EV|render|mixed3d|graphset|tools|icon|mdim|removeChild|wait|dark|gear|tdim|venn|message|chart|gshape|output||safe||objmove||flatten|iXVal|vline|pageX||ic_line|facet1|ctx|anchor|facet2||setNodeData|lineHeight|iYVal|varea||theme||256|Function|Resource|SKIPTRACKERS|open|idx|_INFO_|angleStart|italic|getTime|getAttribute|feed|GET|SEQ|user|single|textarea|oblique|facet3|decoration|resize|TOUCHEVENTS|datalength|A2G|togglePreviewMasks|A0B|com|IMAGES|direction|pageY|userAgent|xy_|goforward|goback|horizontal|clientX|V3D|paddingTop|random|666|A58||tween|A1V|plotset|Jan|viewimage||Thu||setRequestHeader|||back|defaults|000000||timezone|lineWidth|fire|||rule|ie678|CanvasCache|labels|fillStyle|bYX|zooming|setupcb|classic|ignore|utc|bounds|reference|nodes|zero|fontStyle|getElementById|intersect|not|tab|textAlign|dashstyle|currency|power|A7A9AC|axis|uid|refresh|keys|Image|drawImage|A25|false|paddingBottom|fromCharCode|paddingLeft|A1E|day|force|collapsed||||baseVal|LEGEND|paddingRight|A26|curtain|globalAlpha|unit|sMaster|setseriesdata|isFinite|MON|highlightItem|visibility|clientY|md5|textDecoration|bidi|||cos|querySelector|stepped|vector|preserve|addPMap|GMT|Data|dx1|OBJECTMODE|1970|getElementsByTagName|FSID|4px|bar3d|arrows|raw|selected|A1F|org|sTypeX|interval|bBS|series|jpeg|3dxy|A9Q|cccccc|swipe|8C8C8C|A27|xmlns|414042|average|AAZ|opacity2|bandwidth|hideprogresslogo|sin|forw|A1G||dx2|A87|sampling|_pageX_|beforeSend|labelid|||touch|moveTo|A5Y|A3L|A34|updates||sep||watermark|month|_end_|inactive|nodeType|wrapper|A4V|ratio|cone|A38|zoomin|count|REFRESH_TICK|license|zcrandom|A09|lon|setInterval|z3d|backgroundColor1|encodeURIComponent|A56|borderWidth|dist|borderColor|cwidth|intxy|300|sel|A53|headers|modal|continue|zoomout|backgroundColor2|reload|A0C|CACHECANVASTEXT|onmouseover|contextmenu||head|SKIPMAPS|documentElement|||smart|lat|rectangle|progression|checked||A68||dotted||styleSheets|generated||A39|IMG404|A2T||||charAt|point|aBandWidths|A1P|onreadystatechange|readyState|VERSION|found|widgets|segment|dataparse|A35|labelindex|normalize|A06|A50|submit|clearPreview|long|bIsBottom|i18n|jsonsource|originalsource|A4X|onmouseout|getstyle|3e6c7b|1800|charCodeAt|tolerance|pdf|download|query|getComputedStyle|bullet|application|DOMMouseScroll|DEFAULT|margins||viewall||A07|getElementsByClassName|dashed||rotate|overscroll|parentElement|before|after|dashdot|xtype|storage|NULL|save|A49|ctrlKey|CANVASTEXT|restore|keyvalue|1e6|collapse|shapeid|A9L|setAnchor|shapeindex|A46|bRTL|A61|A65|05|A9J|View|1024|totals|lineTo|hmixed|A4D|A04|colors|A01|A02|0px|html5|A2I|true|_ang_|goals|clearGuide|_pageY_|addColorStop|A18|hasEvent|callEvent|first|nodata|gap|facet5|nodekeyvalue|ll_|flags|ZCOUTPUT||legendminimize|3dfacet|underline|timeout|onmousemove|A2P|Close|_r_|facet4|getdata|A2E|GUIDE_EV||xydistance||A2H|infotype|NODE_EV_CHART|A2L|stroked|A1C|A45|titles|websockets|A62|A03|A7I|A67|MAX_VALUE|A0Y|events|A0Z|onload|protocol|xdata|ZingChart|XMLHttpRequest|requestAnimFrame|zc_loader_mousewheel|A1D|minute|CDCDCD|A2N|A1B|CSS|getBoundingClientRect|AJAXEXPORT|showguide|A1H|alignment|URL|modules|dataurl|previewscale|A9M|lcoords|data_||lstep|cleanTouchEvents||||dim|A48||aperture|A2F|BUILDCODE|sTypeE||multiplier|A23|b2D|lineColor|||clearTimeout|setScrollingFlag|locale|A3T|overlap|LOCALSVGEXPORT|exitfullscreen|fit|hand|A4C|A2J|FONTSIZE|post|AGB|A2B|parsecb|smooth|A3A|contour|A9R|connect|A5A|nulls|MAPSONBOTTOM|evalFn|cancel|A52|item_title|A8T||||onerror|5625|_h_|369|ffffff|applyJsRuleSvg|getSize|A5B|vboxid|CACHESELECTION|A2X|A6Z|wh_|A54||trapeze|A2V|A6X|extendAPI|aMDXY|A3Y|A85|TTLOCK|A0O|_append_|A1L|zc_guide_touchend|A83||PLOTSTATS|ANIMATION_|A0W|FSSTATUS|A1N|PATTERNS|A1J|getFormatValue|A40|A3S|blocked|A82|A0P|tap|A1M|lowlevel|_hex2rgb_|bars|Bottom|A4N|defs|xml|markerbg|THEME|AA2|BODY|toDataURL|filter|days|A0N|empty|disableanimation|showhide|sharedZScale|A1K|relative|setLineDash|PARSE3D|filename|Blob|oMap|exportdata|months|A70|A5L|A1U|A5M||A5K|hasData|A47|oNode_|500|bound||A0M|xlink|Series|A0L|A4W|textprint|foreignObject||A2S||BLANK|applyRGBA|stream|DOMFRAGMENTS|Top|bPoly|A3H|Right|Left|yall|A9Y|A24|A0T|ruler|A5J|xall|A30|A15|color2|alignPosition|cloneNode|A4E|A3G|A0S|A5V|A3J|Download|A4F|palatte|A0X|PLOTSHLAYER|base64|A41|025|595959|A29|A84|_image|929497|exec_flash|A1O|AA1||setupPlotArea||fixPlacement|A1S||opera|A55|global|_nfind_|borderRight|A44|A00|defaultView|threshold||A4P||A31|A32|A88|zcoutput|addEventListener|A4Q|36e5|borderLeft|clientLeft|A3N|A0R|minimize|A0K|butt|clientWidth|parseLayout|lin|full|onStop|TOUCHZOOM|plotdata|coord|transport|reset|A7Y|A28|currentStyle|clientTop|A20|mini|AA0|bBind|match|thousands|A5D|A3V|A5E|ABA|getobjectinfo|65535|ABX|A4Z|A3U|A2Z||A4Y||disabled|A42|undefined|isBold|AAJ|A0Q|||pull|A1X||calculate|ActiveXObject||A2Y|A22|A64|year|hideguide|stopfeed|hour|second|005|nowrap|NODE_EV_TYPE|250|AA9|marginLeft|A0V|A6Y|beginPath|attachEvent|tip|_txp_|EQUIV|offsetX|objtype|parser|AB9|offsetY|marginTop|acos|iframe|A0U|pinch|Lucida|set|strokeStyle|A6V|A2C|A9X|A2W|closePath|clearRect|initObjectsLayers|null3d|switchto3d|enablepagescroll|disablepagescroll|_iX|||Your|Submit|A6G|schemas|stacked|exact|A2U|A6H|switchtolog||A8S|EXPORTURL|A5S|clear_||setseriesvalues|createPreviewMasks|AC2|office|_sh_|octet|backgroundPosition|Page|urn|A5P|_POOL_|microsoft|A3C|switchtolin|switchto2d|dummy|AB2|navxy_btnback|reorder|A4O|serif|deselect|mso|legend_toggle_action|removeobject|A3K|zoomto|Wait|A6O|sans|oPlot_|AC5|Loading|Guide|A2R|A4R|asin|ABH|showZCAbout|A1Z|A7G|addobject|borderBottom|A2M|startfeed|detach|||A6S|AC9|A4K|A4L|A81|AAH|_blank||TIMEOUT|AB6|A4U|A0J|Back||run|media|sMetaType|A8V|b3D|setScalesInfo|SYNTAX|A6I|xObj|l_|trackers|modify|200|2e3|A12|A0G|s_|A11|A8U|AAW|A90|customprogresstext|ASYNC_TICK|A2A|JavaScript|speed|xdist|clearAnimFrame|ydist|xzoomed|webstorage|yzoomed|AGA|zc_loader_touchstart_static|unicode|AA5|customprogresslogo|logo|STACKINGLOGIC|A17|fullscreenmode|AB1|A0I|CHECKDECIMALS|A2O|AC4||A0E|A0H|A4M|A7X|A9T|A16|A7Z||_unbind_|clearGenerated|AB4|ABL|A2Q|AC3||A4J||skipfs||getAttributes|A5W|A5X|_oCtxNode|A5Z|AC0|getGraph|AA3|A7F|A3M|kv_|hideLayer_|dataType|navpie_btnback|viewasjpg|hamburger|A59|WebSocket|viewaspng|polar|mimeTypes|resource|DownloadXLS|A1R|A5Q|AGC|A4I|A5H|clearLabelBoxes|A3P|AGD|pan|SORTTRACKERS|A5N|A0F|A6U|2048|AGE|A6T||Custom|bKeyWidth||AAO|A5I|A4B|A6R|backgroundColor|menuitemid|ring3d|pointserror|A10|KEEPSOURCE|high|low|A60|A9S|AC6|A92|ABF|vrange|globalCompositeOperation|bgc1|bgc2|funnel|ZINDEX|changedTouches|A7D|load_|AC1|loadModules|SMARTDATELABELS|dot|Sans|dash|miter|offsetWidth|A6M|SPREADTYPE|offsetHeight|600|cssFloat|A3B|CMZINDEX|A6N|chkdata|e1eaec|appendToValueBox|99999|chars|score|||17px|email|A3I|bandspace|A6K|1e9|chkcapture|A1W||465|||A14|RESOURCES|dots|8px|extension|columns||over|A7E|A6L|A5C|ABQ|A9P|A9I||GUIDETIMEOUT||A8W|||positioninfo|thickness|14px|joined|A13|oldcursor|A0A|minvalue|maxvalue|setmode|polypoints|textContent|createDocumentFragment|paintCANVASText|msecond|formats|AGF|statusText|A9N|ABG|AAN|NOABOUT|ABN|A3F|fillText|sAlign|MEDIARULES|||en_us|scrollTo|file|A4H|A5G|minus|next|A3Q|rotation|hasPassive|styleFloat|getPropertyValue||HTMLMODE|mathpoints||wrapped|A7K|||runtimeStyle|A1T|_cpa_|ABE|toggleMasks|atan2|marginRight||marginBottom||AC7|verticalAlign|passive||A5O|toggling|400|cylinder|srcElement|A8Y|zc_legend_mouseout|A3D|oP0|zc_legend_mouseover|AAI|A3E|A94|A9Z|jpg|A2D|1999|A7H|autoFit|insertBefore|downloadFile|get|focusposition|viewdatatable|areanode|mapshape|hidedatatable|ABS|createObjectURL|menuid|onloadend|paintHistory|bNpv|A7J|_window_onunload_|dasharray|setupDynamicPlotArea||utf|||FFF|D1D2D3||AAL|description|DEBOUNCESPEED||sync|A6P||exportimageurl|676667||||GRAPHID|stops|_width_|||shader|lbltype|charset|A5F|EDITSOURCE|AAY|A5U|A1Y|USERCSS|C6C6C6|caption|A21|F0F1F1|exportdataurl|_oMarker|Show|A9O|02|A93|A6Q|A91|A6J|7CA82B|zcvml|useMap|downloadcsv|ACG|crossOrigin|filetype|Name|downloadpdf|UTF|downloadsvg|downloadxls|preserveAspectRatio|whiteSpace|parent|DownloadCSV|response|Print|AREA||svg0html|AB7|AD8|ACH|ExportData|ViewDataTable|_top|guide_mouseout|LICENSE|flexible||options|xmiabt|initial||11px|_parent|responseType|sendcapture|onopen|BugReport|textBaseline|alphabetic|thead|forced|toggleabout|SwitchTo3D|FullScreen|sTypeN|addmenuitem|skip_objects_tracking|elementFromPoint|ABD|scope|ViewSource|SwitchTo2D|gear6|A6W|AAR|tilt|LogScale|LinScale|ABP|detail|AAQ|meta|pageYOffset|||||pageXOffset|persistent|FFFFFF|strong|_height_|2000|legendmaximize||onmessage|minindex||WorksheetOptions|ExcelWorksheet|tspan|ExcelWorksheets|ExcelWorkbook|dominantBaseline||ABU|ACS|getxyinfo|prev|ABV|f90|About||Menu||fold|pagination|getimagedata|localhost|tbody|maxindex|A51|rLen|screen|AAT|zcgraph|csvParser|limit|FSZINDEX|fromAPI|sBId|rawsource|PATTERN_|backgroundImage|col|215|defaultsurl|getFullYear|contextMenu|FORM|support|A8O|mapItem|viewDataTable|size2|doubleclick|msg|AAV||vb_|A9D|SKIPCONTEXTMENU|alert|vmin|yourcomment||LITE|jsondata|checkbox||bbox|senddata||youremail|startangle|infoemail|A0D|source_hide|ASYNC|999999|A9G|A33|keyup||vmax|AAX|Parsed|Original|oval|ADA|comment|IGNORESUBUNIT|actions|INPUT|confirm|A3R|asc|AAM|A4S|downloadXLS|pos|clippath|calloutPosition|quadraticCurveTo|CHARTS|origin|lineCap|dataload|vPos|tile|downloadCSV|A63|endangle|iphone|ipad|msSaveBlob|SKIPPROGRESS|hPos|||blur|FASTWIDTH|900|SaveAsImageJPG|A69|createPattern|guide_mousemove|clipPath|A80|borderTop|coordsize||emailmandatory|gradientradial|coordorigin||AB8|globals|encoding|layers|imggen|themesloaded|ABJ|excel|PageScroll|3dtx|heatmap|userSpaceOnUse|pathname|Reload|createRadialGradient||createLinearGradient|_title|getPlacementInfo|ABC|anonymous|sigma|State|VML|6px|A97|A74|A6B|white|child|ownerNode|author|behavior|setupValueBoxWH|A7N|COPYDATA|RESIZESPEED|onunload|jumped|Scroll|scaletext|marker_text_|paintMarker|Table|||A4T|12px|A57|EF8535|A7R|A7Q|265E96|candlestick|A05F18|A14BC9|ABK||ACQ|ABW|A7P||A6C|addRule|D31E1E|A6F|A6E|29A2CC|2c4a59|LOGO_ABOUT||A7O|1AB6E3|A6D|Zoom|bXY||AD9|backEaseOut|fillAngle|Error|ABB|Bug|Send|bUrl|A9W|A9H|mozilla|elasticEaseOut|numeric|bounceEaseOut|strongEaseOut|Email|regularEaseOut|you|indicator|setModule|getModules|band|AD0|May|ABZ|Switch|backgroundcolor|Hide||Scale|Full|Screen|toStaticHTML|ACE|ACD|ACC|2654435769|linecolor|ABY|prop||SORTTOKENS||MSIE|compatMode|ShockwaveFlash|AA8|shockwave|adj|AA4|ABM|compat|6B7075|shortcut|ACU|26784e5|864e5|responseText|FF00FF|ABT|ABI|ACY|ACX|0123456789abcdef||mirrored|dateformat|1023|standard|ACK|ACJ|ACZ|_rgb2hex_|AD7|AD6|0x|316224e5|POST|plot2|sec|createElementNS|ADC|querySelectorAll|innerWidth|week|clientHeight|Opera|overlaps|getOptimalDateInterval|removeEventListener|||||childof||||||event|mon|6e4|trident||originalEventZC|ownerDocument|uniform|bKeep|paintTransformDate|stopPropagation|sortFaces|plot1||blank|LOOKUPCSSTRANSFORM|b6c8cf|365|||1089B3|detached|connected|SKIPOBJCOUNT|aaa|THEMES|||||||||||||||||||SPREADFACTOR||||||||||||A7W||||||969696|MAXPOOLSIZE|A98|96C245||Helvetica|Arial|MODULESDEP|MODULESDIR|ACL|xdiff|ACT|A79|A7A|plot0|A7C|paired|dyn|A8P|face|_rcolor_|facet|e6e6e6|f0f0f0|A8J|oP3|||||||||||||||||A8M|||||||||||||||||||oP2|oP1|A7B|ABO|f6f6f6||facets|skv|A8N|star|ranged|sizing|001|nodevalue|ZCVRangeGraph|Step|AAC|cluster|AAD|monotone||AAE|Item|A8G|A5T|A99|A9A|||||||||||||||||||||||||||||||||||||A9B|minValue|maxValue|minValue_||animate|A8F|removenode|330|A71|AAP|AAA|hint|QUOTEDVALUES|xb0|star5|quick|A8C|A8D|triangle|diamond|errors|delay|AAB|A9C|moz|||||||||||||||A96||||||||||||||||||||||A7M|A8B|addplot|nav||A5R|ACN|A73|A6A|A76|scalename|A72|scalevalue|A8R|A8Q|A9U|DELAYEDTRACKERS|A75|A8E|maxValue_|ZCVRangePlotSet|addnode|A9E|A7V|A7U|A7T|||||||||||||||||||A7S||||||||||||||||||A8L|setnodevalue|removeplot|A8K||A8I|A8H|AAU|A78|modifyplot|A77|A8A|effect|showtooltip|graphidx|AAS|A95|clicknode|bubblepie|gif|pop|AAG|hooks|shiftKey|A89|plot_click||||||||label_click|||||||||||||||||||||||||||||A7L|A9F|AAF|A4A||e0e0e0|a0a0a0|40E0D0|9c9c9c|qJhDZWB8OmFDaG8J|909090|222|spark|69c||vk3JIhGITEQsUCtkgtslo4K1wwMRxPoBbAIXJ|negative|graphs|Q8b3mQmpqvevD3VGFhuVV95PaXnbXTkr6h5M7j0mP3UDxMNo6g3TgCkSe5tiKb2QU3ttxD8PRRN7pFxkFxB|EE82EE|a6a6a6|acacac|xWR15D1fqTyEALRVtLBrU|ececec|dcdcdc|d6d6d6|||||||||||||||||||||hQWw6ePX6Nd||||||||||||||||WELTcgScyGV0BiDqCG6wCyBa0rRQdEZC7sxaxri1ckNggRYKcr6A|ZlVA4tExPxYQAQubERqJBDtSu6hfYb2k0isoX2ztWoke06s6woRayLWJCQ5kkhIyBKR7FQIRCQEIpJjCPFn|d0d0d0|c6c6c6||b0b0b0|c0c0c0|312F30|bcbcbc|VIOLET|b6b6b6|syv7|fcfcfc|57585B|808080|vstream|boxplot|hboxplot|FFFF00|vboxplot|DCDCDC|contentWindow|contentDocument||QQYK91VtUbjbmq8u4NNX2Q6zvNCuind1hPtMMot31k4MwB5iv0CylvaRXz6O3tO5VMGBLjozKUrDyVmw8szzFZwnEo5X1VA|hfloatbar||||||||||c5UOj7E1Ts8BhC5zljv||||||vfloatbar|||808285||||||||||HTML||||||||HEAD|floatbar|createEvent|ACB|||TouchEvent|8qbrzh3uZb2RgAeNY85a8dobWVLe40u8TgsEXDhEZJrHYnq46rTuS4XhK0nrW7uQmYw1lTTL5R4jFE|waterfall|5a5a5a|F7F8F8|AYKc4hVyx04biDWGx1aqwPX|ZoomIn||6C6D70|414141|execFn|125px|Yrbjmm0HqGPfwMbPPVOYIkPRA9yAZmYwG8Boi6gtnfJ1koXBeXhD1XGagDCN53vuoeksvabYi|ViewAll|population|vwaterfall|populationpyramid|small|222222|WHITE||||||ny5sogAHv4||||||hwaterfall||xhhvK|||||YELLOW||||||||||ZoomOut||C0C0C0||||||36393D|getDay|QWiu3TW1Sqk65M5ukh9vPzAUV|4B0082||LIME|00FF00|getMonth|getDate|MAGENTA|getMilliseconds|587|getSeconds|getMinutes|getHours|tooltipText|getUTCFullYear|getUTCMonth|getUTCDate|getUTCDay|299|_colorAlpha_|getUTCMilliseconds|A52A2A|FFD700|GOLD||||||||||||||||||||||||||||||||||GREEN|||008000|FUCHSIA|00FFFF|INDIGO||CYAN|BROWN|iVBORw0KGgoAAAANSUhEUgAAAJEAAAA1CAYAAABBVQnbAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABu1JREFUeNrsXLFy4zYQBW9UR7wfSHh1iqMn6S3NxLXlLp3lL5D1ARlLkw|HideDataTable|wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw|R0lGODlhAQABAIAAAP|0000FF|DEBUG|BLUE|BLACK|zc_|MAROON|getUTCSeconds|TURQUOISE|444|vjr5wKFyz9|script|AGU|Low|High|Open|||||||||||||||||||||FFC0CB|||strict||||PURPLE|||||||||Module|7dLKj0u4UboHamBpK54HEm2lgisTwgbH78ucBtDG|800080|LnFKxSTOo9DkvU2rLvBFpH2hcKgFpCI9d2JELujMQNsd5CRFdVWKRU2G||RED|FF0000|SILVER|GRAY|0084AA|loaded|firstChild|getUTCMinutes|0x4000000000000|800000|getUTCHours|setTime|BBBBBB|gLMilDUMgAYigZUm7MzAliiDBxcPu2|XS3nq9ZiQkdaTF|NAVY|dataready|1099511627776|3iet|1073741824|1048576||toExponential||||||||||||||000080||||||ORANGE|||||||||||||||ext|FFA500|PINK|YqcJkkaSwzGoqS3sUE9Lyj3yhmS6Uki4yNN7PFftH||D66C1C|RW9rdQ3KGBUxLYmGuHKG4nWk8aleqiz6XSFA5N|a0kBGIVqW7w5p|9b5FpaWogBlGlnahdp7f|MaEpYHUNl1tWbF|DGfGvEVBorFq3Wnhtx6Yqy9VxUZqqe0tfBMPEIF3FD|mUs6KHNRO7LazssfcSfmU|wTEATmQruIHqrjYrMQX05bnZ7kWZUYd2Fikjw2p6RJOCmTFgUow|pagescroll|qVNQN7LC0R1f2qsTFecq|JoRMu03lkd|WBJjiPWRH11|Ap13G5Pl60VY2tP23ebFtYgiNlhaxARkSaLYL51a4ixsAdxXPjBJ7RsSalmz60Khpy7UVCuj9tWhHxUY41VVkEK0U92kvZ2oddI5kTsGqJTF2nsDOx0A9KlKEXhWeC4cDh5LqMtRpUVxDFLH4WRJ7pV8R2LUrPCjXUn00gXG0zZ|dM8LpS7Z4I7AprPgKguBYXu2aA2LX7m8GlM1Nbp8FbLCKMyvrDe1wnjDqwgnUruDIzESuKHqLfGHWFU7qfp2SW8w0FVssOiETQKUzH2IviWO5wqfAoJA1cjCgtAHUsfaRrLcZ0QvWmQ9U4cadgB7DRvHtyc40JGgf2PG63RS7HplhPTZ0mTpiag0dNCcPCf8YVrowDijfYCZgY1Tkjuv4VdyIvc0P7TSIJNBKIDTKNl0jjRZaxQGZGmH1bNk87wkD0iop8dj4zWuY5HnHNxg54wlS45LyQfnjCwD3BzTBCKjggaCGCnURE10kz4jLEhMHywHTcJ4OqbsLbefqsrc8SNFyxXqh6G5|ZXwTNiuycKjVg6UAnU1DK2x3Wc9SQUwZijotArVk4Kk4qU5mRF3NHLUJ5HzPoAy417o6|mDXZPwp3r|La0dM88io1YD|LpR|KogIo6YW9puMNDROzGSFyOjaAiWlkQaEOfPrb6aEMWqLiSKwqYrEI8ioMAdpTENupKklsc8frtf1C|iJamYE8hWNRD8|FHY4MQWwxllcdiZClai09I7uPapDMHQ1dwFx3FORIcy11FYlHWRWKol0Tiavz8A||||||||||||||||||||||||SAvgCcGK8xwwI50SqLlQK6OSmTLrrKU|||||||||||||eISInsEMhdnu61hMlkggN6|dqKYwJd|VkTCh|sFPIO77cUufurMOB4iEfoGsPNDGag0qacrn1t345||IBG7ZbjiyQo9iuVCa1v99GggSadJXi70rlyWQBc5wRfXX4xbsoje3ZGThb9LcDL8Sj2UF4xYKOxvCXXdPaalnYh0J2x5Cl4qgc|fs20zVRLOz3bUd0w03sL4IbTwd|BasicStructure|Mobile|coWIi|CSS1Compat|Mac|appVersion|QrFO8i||enabledPlugin|SwpRBHeB1YixfuVRG1TmnSxwWyN0IJS7c9S8PojwWgDREblQFpIiZPi|Powered|vml_flag1|feature|RaJXhS6LycpIqpftZkRJhMO572|SVG11|hasFeature|implementation|iz8B4ZeKmmw8MwBobcSg7iaSoz3|isOXJyUK|||||||||||sHpv2CQbwcaz686qLg7mNWoOJJY||||||||||||||||||||||||||adapter|hosted|AAC1LYqunMJ6bAAAAAElFTkSuQmCC|1Ej7LVT54f1LOOmMYlxWO50RTCw1Zk7YE7L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otrU85wFi0nOwhLtmtQ4UtMkaJjEa20agaTGkZpGIlPS0|Tj7zU0|o2iVTBMSKhQr9|5yasb||2fH|G49I2399oJuNwtCxx4OksJshWZCNDEQnYqIMymkgYZJFxgJs5gFkEBxDikrmKF91jVE1ZTFR6L9rQOkZKZCrdKVtNxOQl6aiF5GGMoTpnpBNgm9PUvYd19RNtMz2WpU6h6VPIG7|kDDNP30|cSJtJZJwX8O959NvAUQkZDUkf8FGADBt38P1SQKxwAAAABJRU5ErkJggg|ZRanRwIAeIoYKRkpGDIoV2G3ita8dB5x7Z9xlp1NMsJ4S5de|91MI7WR9j|5vv5VEjcQJ|qO24SRzRMfZFbXj5bHUSrAAdVHa9l97qfWF6|DzfVs2U6u|m6yyJ|stcWCMb|sFaLLx3XKTmuZ31RzkdyTnL0khU17vrf7Tm4iT5TJ0kTXHlc2iUEmBe3vSco1APRIVgiH9rX9XbSJxgQiIob4WUh3y0BNCEIEIhUFmlqACbOoTo0|hole|fo5HjhzDhip7IB2j91evC|NP0t0TXQLRA8CQR3QPta0|dA4L48Qhg5heiRpTG6|mp7POvaHfv04TPly95g0ROHNJ1Ohr7lzTc|1D7HmGKf99x|O3FaQ|hdDFeefOUPthvBZqH6TR0X6hDUge7hiiIZZWu5jebXg8rAr0aB9|wHBB4N651NqL6UGinMV9l0tQsFtOXVkcGK4H0uBwucLPhigzT0vSLT||||||||||||||||||||||||||||||||4YZrNHz1GonGOsYcTkEe8W9YT3wVaxSr|||||6FLlyk7dG3KlpaSYGCr2sa7bTe1e02977rVJPCpz7R|jIo2dCfd9c1BIrIoVy0ho7y7t|sJeiZdgFxezwleaBUzwvA5n6UkuvPugJaqoIWSfS|20p2HvtBeK16w||BlackBerry|PPC|52575C|P1EAsGUPZcSM03|b79007|cc3300|ef4810|a62b02|0392bb|Q9MX3bb2wCfKYByGWZhvt69T0pIeyF9|00b0e1|DownloadSVG|007fa3|DownloadPDF|Hhx|da9b04|89b92e|UmnVcu533TixhgnyNRM0dgQgplGsPAkzYXwPzOzZnC7X81FBps0ln7DE4j7FFz7lhGSYWZ0CxLkF6pdEiin27WykHHILXKaLTuPRmQGAoidX8LoScOsD145xJQUVRD|2UJYM4scG7|Gly8ldqZxWOBc41UBB9q8UPEmcr54GRIXwBXn|ZDnzAMIzyhNVVTYKAAorAHTVgHL5pHOS|||||||||||||||||||||||||||||||||||||gEVkGqUcFnmWmB876F18Vzb5KmaijbjDAAiZ8k|SaveAsImagePNG|a7da47|6a921f||20398B|f9c332|563d02|00AE4D|link|0D457D|HuIgKZX6X7wuUGhlOxoME4FvoO1RGZ88uT6XPKAOuCgxm0aK6|874600|8832B0|8txLDPrukmci|OFFSET|oRz1|638F12|BA0505|resources|EtDO54vP7th1HL0CpYAaiGnGtSDVnEBONJ4Xozi|84680a|xhtml|stylesheet|05a0cd|alt|||||||||||||||||||||||||||||00bbf1||||||||edf3f5|1540a0|4d62b1|0b32a0||6e4503|SaveAsImage|jxVuWAXwZANAz5HirKR|Windows|epSuudpRmrP2rclZFf1zG7cIMfzS6zh9SuAyLfJE|skip_segment_tracking|skip_context_menu|09A9DA|AGH|AGG|wWjRZKI7TbgLtHD|i5CcR1RvRAp3VpUL4qt9AJMyMDznvcPkoxEZZ5uZ5iw9AWPm41ihhTB1TWPJIvdeJP3KZbrBr9wVnn20IMTBrkDka|ontouchstart|iFDTf4|Mr3cMfUhWN83PYpfQ6W|Charts|00384A|AG3|decodeURIComponent|_inj_|ACO||||||||||||sessionStorage||||||||||||||||||||2F8JpusDi3zMEzINF9Q|||||iPhone|siKWwCkzRAy|iPad|Android||5005onWQnHXM18l0kq|hFUVqR7S1l8G8QQJznxCUvX|FB301E|C0usUJLOMetQOYTOFYVPe0KRHcl7nAGK98k8k0dUIKCXNemIq0SK1RF4LK8iEXIbCMzAUCi37flOJ8UUWGCoLNRctAQiBLrHioLkbvAIswP0CoHtcFcF0Sg6FEFgNIGAeSSg8RbWhZ5ctuW|9B26AF|E2D51A|E80C60|keyCode|mfBxXECbZeDYIpPe0riMsGKim8qBXMDEFy4hQv6tighD||AD1|00BAF2|Network|preservezoom|Since|Modified|aCdvBK|ZZAmsQUXYwbyUHTR67kghQvnYMIk4k3OwKQS|use_single_canvas|use_fast_markers|use_fast_mode|||||||||||||||||Edgdh2omT9RRXE1hZAfaQYvmbx||||||||||ACW||||||||||6D6E71|skip_interactivity|MbWyNGzvXcSgKYaAL21h6hpRb5JFSiEliszxIjHVE6l798cAShQAChBIt7N8klnbQ|skip_marker_tracking||16777215|1069501632|modulesready|star8|report|bug|star4|Cancel|star6|mandatory|address|star7|problem|your|reply|star3|star9|via|receive|rpoly3|rpoly4|||||||||||rpoly5|||||||||rpoly6||||||||||||||rpoly7|||want|Address|Comment|was||sent|rpoly8|trapezoid|getrender|beforedestroy|zcdestroy|hidemenu|showmenu|history_forward|history_back|fireEvent|formatNumber|formatDate|parallelogram|nThank|textbox|getObject|getPalette|plugin|ic_area|defineModule||initThemes|||||||||||||||||||getGraphInfo|||||||||||||||clearLayer|Apply|ic_bars|Capture|Graph||closemodal|Saturday|bite|Sep|droplet|Aug|tan|Jul|Jun|Apr|Mar|Feb|Friday|Nov|both|Thursday|Wednesday|Tuesday|Monday|Sunday|Sat|Fri|||||Wed|||||||||||||||||||||||||||||||Tue|Mon|Oct|flow||rpoly9|October|Report|rpoly|Message|gear3|gear4|gear5|Occured|Has|Exporting|December|November|September|Dec|August|gear7|July|June|April|March||||||||||||||||||||||||February||||gear8|||||gear9||||ellipse|January|disable|openmodal||Forward|shadowDistance|getseriesvalues|lineStyle|appendseriesdata|lineSegmentSize|lineGapSize|getseriesdata|node_remove|borderAlpha|shadowAngle|node_add|shadowAlpha|fillOffsetY|shadowColor|removescalevalue|addscalevalue|setscalevalues|node_set|plot_modify|plot_remove|||||||||||||||||||||||||||||||||||||shadowBlur|plot_add|addgraph|setcharttype||appendseriesvalues||fillOffsetX|scalenumvalue|legend_show|getplotvalues|getnodevalue|getnodelength|getscales|getplotlength|getgraphlength|borderRadius|getoriginaljson|toggledimension||legendscroll|legend_maximize|fillType|legend_hide|getData|legend_minimize||||||||||||||||||||togglelegend||||||||ignoreduplicates|setData|gradientColors|gradientStops||backgroundRepeat|backgroundFit|backgroundScale|ADG|lineJoin|mapdata|getcharttype|clearscroll|offsetR|lonlat2xy|unbinddocument|setpage|getpage|set3dview|get3dview|getversion|showversion|toggleplot|getscaleinfo|togglebugreport|togglesource|showplot|plotshow|showhoverstate|unlocktooltip|composite|locktooltip|hidetooltip|hideplot|plothide|getbubblesize|pieSlice|bezierCurveTo|miterlimit|scalepos|scaleidx|linecap|linejoin|onviewport|stackType|maxIndex_|minIndex_|maxIndex|VMLv|minIndex|endcap|datetime|joinstyle|refAngle|logBase|offsetEnd|ADB|objectId|offsetStart|pieAngleStart|pieAngleEnd|stepSize||step_|Sun||getImageData||originalEvent|45705983|643717713|165796510|1236535329|1502002290|40341101|1804603682|1990404162|42063|1958414417|1770035416|1473231341|701558691|1200080426|176418897|1044525330|606105819|389564586|680876936|271733878|ADI|1732584194|AD3|nStrlng4Cu|373897302|38016083|271733879|35309556|textpath|svg0|writing|358537222|681279174|1094730640|155497632|1272893353|1530992060|innerText|1839030562|660478335|2022574463|378558|1926607734|1735328473|51403784|1444681467|1163531501|187363961|1019803690|568446438|405537848|tOmLlc9nc9|1732584193|textpathok||compatible||EJLl0khmPDSKBJa8fkP70KLNtrxt5pE2yjx|IvQ40ajd|||||03rqqtR|Content|With|Requested|XMLHTTP|Microsoft|cancelBubble|returnValue|_list_|hpxK6BeHRUtuasojuRTPFQYdzNGN57nxLviTf1hV4lwaFjtbv|detachEvent|MAP|parentWindow|offsetLeft|offsetTop|pixelLeft|filters|innerHeight|STRONG|unicodeBidi|polygon|tA1g0W0k7AKV1g1ouow1nG|7PVG0KjUnLRqnRSPOeqf6gu|AB0|55296|240|2097151|224|192|2047|65536|57343|56320|HOSTNAME|56319|hostname|AGJ|Q5G8dRWLio|Core|zflags|fhx|XKoJJLnmLPUYiWUuQKAOGnuAIWrSN_ZIj_LYvS|jRkihLOSfysvRQTBtQOUUO|SdgZUHWKDVQ|xST_SWRLyFKogwOclSB|jsNorthNine|urlencoded|AppIdentity|09Vczmfsf|722521979|76029189|Exit|outset||namespaces|13px|30px|||borderRadiusTopLeft|inline|3px|spacing|letter|27px|borderRadiusTopRight|20px|cssText|borderRadiusBottomRight|borderRadiusBottomLeft|60px|calloutHook|calloutWidth|80px|calloutHeight|003C4F|pixmap|khtml|calloutOffset|createStyleSheet|our|calloutExtension|XLS|putImageData|Log|Linear|Source|All|Out|patternUnits|objectBoundingBox|Export|radialGradient|linearGradient|gradientUnits|bgcolor|SVG|PDF|viewBox|use|JPG|PNG|Chart|Disable|Enable|control|csvdata|container|insertRule|fillcolor|vml0|718787259|1120210379|u2014|145523070||0html|1309151649|1560198380|30611744|1873313359||canvas0|2054922799|ADD|1051523|1894986606|1700485571|57434055|1416354905|1126891415|198630844|995338651|530742520|421815835|640364487|343485551|lock|rectShortcut|render_flash|scrollHeight|docked|ACR|IMG|panning|ACV|ADF|AD2|ADE|setLabel|setlabel|userdef|wrap|Ext|Grande|Unicode|640|480|9998|bolder|700|800|plugins|clipart|dimension|LICENSEKEY|Progression|pper|pmi|pxi|pmv|pxv|psum|softclear|legendmarker|plotinfo|legenditem|legendfooter|legendheader|drag|draggable|045|wheelDelta|kvts|animation_step|08|ACP|632448e6|markers|blended|refy|refx|master|ADJ|base|nodeinfo|used|view|snap|31556926e3|share|2629743e3|stage|2825|7475|zoomToV|stepsize|EXPAND_RIGHT|EXPAND_HORIZONTAL|facet99|SLIDE_LEFT|SLIDE_RIGHT|SLIDE_TOP|SLIDE_BOTTOM|EXPAND_BOTTOM|viewport|UNFOLD_HORIZONTAL|UNFOLD_VERTICAL|EXPAND|GROW|FLY_IN|UNFOLD|EXPAND_LEFT|EXPAND_TOP|9375|ELASTIC_EASE_OUT|625|984375|SLOW|4e3|FAST|LINEAR|BACK_EASE_OUT|BOUNCE_EASE_OUT|EXPAND_VERTICAL|STRONG_EASE_OUT|REGULAR_EASE_OUT|NO_SEQUENCE|BY_PLOT|BY_NODE|BY_PLOT_AND_NODE|FADE_IN|csize|widths|HideGuide|lbl_|cols||rows|getselection|setselection|scale_|shp_|3dshape|objectsready|legend_|_click|gcomplete|gload|imges|objectsinit|Metric|clearselection|feed_start|LINK|shape_|setobjectsmode|getobjectsbyclass|repaintobjects|feed_clear|updateobject|feed_step|4096|label_|feed_stop|sm_|si_title|si_|clearfeed|getinterval|setinterval|feed_interval_modify|366|gparse|desc|histogram|MIN_VALUE|plot_|pair|guideh|guidev|ff9900|dimensions|sequence|18e5|RefNode|12e5|6e5|3e4|scaling|2e4|attributes|extra|crosshairy|always|crosshairx||noData|hmixed3d|ACM|scrolly|scrollx|AC8|ACA|selections|keyval|separate|setguide|resetguide|359|density|clustered|animation_start|pavg|settweenmode|forEach|ProgId|CancelRequestAnimationFrame|content|Excel|Sheet|Category|CancelAnimationFrame|cancelAnimationFrame|cancelAnimFrame|RequestAnimationFrame|requestAnimationFrame|webkitURL|https|blob|x3e|FileReader|result|CDATA|readAsDataURL|exportimage|saveasimage|dataToCSV|vnd|downloadRAW|animation_end|400px|nextSibling|RECT|Calibri|DisplayGridlines|barWidth|2009|ShowGuide|ExitFullScreen|GoBack|GoForward|brightness||whisker|ohlc|edge|calloutType|1500|about_show|320|Built|Build|gte|about_hide|section|Section|Others|others|menu_item_click|postzoom|getzoom|zoomtovalues|enctype|multipart|REC|html40|x3c|source_show|endif|ADH|RENDER|scaleval|PARSED|nORIGINAL|IMAGE|COMMENT|EMAIL|HEIGHT|sticky|RESOLUTION|510|END|submitreportH5|php|modifier|bDead|getZCPoint3D|hover_image|node_|graphindex|WIDTH|210|535'.split('|'),0,{}));}
let ZC$1 = window.ZC;
var EVENT_NAMES = ['animation_end', 'animation_start', 'animation_step', 'modify', 'node_add', 'node_remove', 'plot_add', 'plot_modify', 'plot_remove', 'reload', 'setdata', 'data_export', 'image_save', 'print', 'feed_clear', 'feed_interval_modify', 'feed_start', 'feed_stop', 'beforedestroy', 'click', 'complete', 'dataparse', 'dataready', 'destroy', 'guide_mousemove', 'load', 'menu_item_click', 'resize', 'Graph Events', 'gcomplete', 'gload', 'History Events', 'history_back', 'history_forward', 'Interactive Events', 'node_deselect', 'node_select', 'plot_deselect', 'plot_select', 'legend_item_click', 'legend_marker_click', 'node_click', 'node_doubleclick', 'node_mouseout', 'node_mouseover', 'node_set', 'label_click', 'label_mousedown', 'label_mouseout', 'label_mouseover', 'label_mouseup', 'legend_marker_click', 'shape_click', 'shape_mousedown', 'shape_mouseout', 'shape_mouseover', 'shape_mouseup', 'plot_add', 'plot_click', 'plot_doubleclick', 'plot_modify', 'plot_mouseout', 'plot_mouseover', 'plot_remove', 'about_hide', 'about_show', 'bugreport_hide', 'bugreport_show', 'dimension_change', 'legend_hide', 'legend_maximize', 'legend_minimize', 'legend_show', 'lens_hide', 'lens_show', 'plot_hide', 'plot_show', 'source_hide', 'source_show'];
var METHOD_NAMES = ["addplot", "appendseriesdata", "appendseriesvalues", "getseriesdata", "getseriesvalues", "modifyplot", "removenode", "removeplot", "set3dview", "setnodevalue", "setseriesdata", "setseriesvalues", "downloadCSV", "downloadXLS", "downloadRAW", "exportdata", "getimagedata", "print", "saveasimage", "exportimage", "addmenuitem", "addscalevalue", "destroy", "load", "modify", "reload", "removescalevalue", "resize", "setdata", "setguide", "update", "clearfeed", "getinterval", "setinterval", "startfeed", "stopfeed", "getcharttype", "getdata", "getgraphlength", "getnodelength", "getnodevalue", "getobjectinfo", "getplotlength", "getplotvalues", "getrender", "getrules", "getscales", "getversion", "getxyinfo", "get3dview", "goback", "goforward", "addnote", "removenote", "updatenote", "addobject", "removeobject", "repaintobjects", "updateobject", "addrule", "removerule", "updaterule", "Selection", "clearselection", "deselect", "getselection", "select", "setselection", "clicknode", "closemodal", "disable", "enable", "exitfullscreen", "fullscreen", "hideguide", "hidemenu", "hideplot/plothide", "legendmaximize", "legendminimize", "openmodal", "showhoverstate", "showguide", "showmenu", "showplot/plotshow", "toggleabout", "togglebugreport", "toggledimension", "togglelegend", "togglesource", "toggleplot", "hidetooltip", "locktooltip", "showtooltip", "unlocktooltip", "viewall", "zoomin", "zoomout", "zoomto", "zoomtovalues"];
var DEFAULT_WIDTH = '100%';
var DEFAULT_HEIGHT = 480;
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
// One time setup globally to handle all zingchart-vue objects in the app space.
if (!window.ZCReact) {
window.ZCReact = {
instances: {},
count: 0
};
}
var ZingChart = function (_Component) {
inherits(ZingChart, _Component);
function ZingChart(props) {
classCallCheck(this, ZingChart);
var _this = possibleConstructorReturn(this, (ZingChart.__proto__ || Object.getPrototypeOf(ZingChart)).call(this, props));
_this.id = _this.props.id || 'zingchart-react-' + window.ZCReact.count++;
// Bind all methods available to zingchart to be accessed via Refs.
METHOD_NAMES.forEach(function (name) {
_this[name] = function (args) {
return window.zingchart.exec(_this.id, name, args);
};
});
_this.state = {
style: {
height: _this.props.height || DEFAULT_HEIGHT,
width: _this.props.width || DEFAULT_WIDTH
}
};
return _this;
}
createClass(ZingChart, [{
key: 'render',
value: function render() {
return React.createElement('div', { id: this.id, style: this.state.style });
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var _this2 = this;
// Bind all events registered.
Object.keys(this.props).forEach(function (eventName) {
if (EVENT_NAMES.includes(eventName)) {
// Filter through the provided events list, then register it to zingchart.
window.zingchart.bind(_this2.id, eventName, function (result) {
_this2.props[eventName](result);
});
}
});
this.renderChart();
}
// Used to check the values being passed in to avoid unnecessary changes.
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps) {
// Data change
if (JSON.stringify(nextProps.data) !== JSON.stringify(this.props.data)) {
zingchart.exec(this.id, 'setdata', {
data: nextProps.data
});
// Series change
} else if (JSON.stringify(nextProps.series) !== JSON.stringify(this.props.series)) {
zingchart.exec(this.id, 'setseriesdata', {
graphid: 0,
plotindex: 0,
data: nextProps.series
});
// Resize
} else if (nextProps.width !== this.props.width || nextProps.height !== this.props.height) {
this.setState({
style: {
width: nextProps.width || DEFAULT_WIDTH,
height: nextProps.height || DEFAULT_HEIGHT
}
});
zingchart.exec(this.id, 'resize', {
width: nextProps.width || DEFAULT_WIDTH,
height: nextProps.height || DEFAULT_HEIGHT
});
}
// React should never re-render since ZingChart controls this component.
return false;
}
}, {
key: 'renderChart',
value: function renderChart() {
var renderObject = {
id: this.id,
width: this.props.width || DEFAULT_WIDTH,
height: this.props.height || DEFAULT_HEIGHT,
data: this.props.data
};
if (this.props.series) {
renderObject.data.series = this.props.series;
}
if (this.props.theme) {
renderObject.defaults = this.props.theme;
}
zingchart.render(renderObject);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
zingchart.exec(this.id, 'destroy');
}
}]);
return ZingChart;
}(Component);
export default ZingChart;
//# sourceMappingURL=index.es.js.map
|
ajax/libs/material-ui/4.11.4/es/utils/createSvgIcon.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import SvgIcon from '../SvgIcon';
/**
* Private module reserved for @material-ui/x packages.
*/
export default function createSvgIcon(path, displayName) {
const Component = (props, ref) => /*#__PURE__*/React.createElement(SvgIcon, _extends({
ref: ref
}, props), path);
if (process.env.NODE_ENV !== 'production') {
// Need to set `displayName` on the inner component for React.memo.
// React prior to 16.14 ignores `displayName` on the wrapper.
Component.displayName = `${displayName}Icon`;
}
Component.muiName = SvgIcon.muiName;
return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component));
} |
ajax/libs/boardgame-io/0.48.0/esm/react-native.js | cdnjs/cdnjs | import 'nanoid/non-secure';
import { _ as _inherits, a as _createSuper, b as _createClass, c as _defineProperty, d as _classCallCheck, e as _objectWithoutProperties, f as _objectSpread2 } from './Debug-184adbd3.js';
import 'redux';
import './turn-order-0f5bc915.js';
import 'immer';
import 'lodash.isplainobject';
import './reducer-3d04bfdd.js';
import 'rfc6902';
import './initialize-2f801c44.js';
import './transport-0079de87.js';
import { C as Client$1 } from './client-ccbf11f4.js';
import 'flatted';
import 'setimmediate';
import './ai-0c0b2fb1.js';
import React from 'react';
import PropTypes from 'prop-types';
var _excluded = ["matchID", "playerID"];
/**
* Client
*
* boardgame.io React Native client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React Native component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE.
*/
function Client(opts) {
var _class, _temp;
var game = opts.game,
numPlayers = opts.numPlayers,
board = opts.board,
multiplayer = opts.multiplayer,
enhancer = opts.enhancer;
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _temp = _class = /*#__PURE__*/function (_React$Component) {
_inherits(WrappedBoard, _React$Component);
var _super = _createSuper(WrappedBoard);
function WrappedBoard(props) {
var _this;
_classCallCheck(this, WrappedBoard);
_this = _super.call(this, props);
_this.client = Client$1({
game: game,
numPlayers: numPlayers,
multiplayer: multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
debug: false,
enhancer: enhancer
});
return _this;
}
_createClass(WrappedBoard, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
this.unsubscribe = this.client.subscribe(function () {
return _this2.forceUpdate();
});
this.client.start();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.matchID != this.props.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (prevProps.playerID != this.props.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (prevProps.credentials != this.props.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
}, {
key: "render",
value: function render() {
var _board = null;
var state = this.client.getState();
var _this$props = this.props,
matchID = _this$props.matchID,
playerID = _this$props.playerID,
rest = _objectWithoutProperties(_this$props, _excluded);
if (board) {
_board = /*#__PURE__*/React.createElement(board, _objectSpread2(_objectSpread2(_objectSpread2({}, state), rest), {}, {
matchID: matchID,
playerID: playerID,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
step: this.client.step,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages
}));
}
return _board;
}
}]);
return WrappedBoard;
}(React.Component), _defineProperty(_class, "propTypes", {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string
}), _defineProperty(_class, "defaultProps", {
matchID: 'default',
playerID: null,
credentials: null
}), _temp;
}
export { Client };
|
ajax/libs/material-ui/4.9.4/esm/FormLabel/FormLabel.js | cdnjs/cdnjs | import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import formControlState from '../FormControl/formControlState';
import useFormControl from '../FormControl/useFormControl';
import capitalize from '../utils/capitalize';
import withStyles from '../styles/withStyles';
export var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: _extends({
color: theme.palette.text.secondary
}, theme.typography.body1, {
lineHeight: 1,
padding: 0,
'&$focused': {
color: theme.palette.primary.main
},
'&$disabled': {
color: theme.palette.text.disabled
},
'&$error': {
color: theme.palette.error.main
}
}),
/* Styles applied to the root element if the color is secondary. */
colorSecondary: {
'&$focused': {
color: theme.palette.secondary.main
}
},
/* Pseudo-class applied to the root element if `focused={true}`. */
focused: {},
/* Pseudo-class applied to the root element if `disabled={true}`. */
disabled: {},
/* Pseudo-class applied to the root element if `error={true}`. */
error: {},
/* Pseudo-class applied to the root element if `filled={true}`. */
filled: {},
/* Pseudo-class applied to the root element if `required={true}`. */
required: {},
/* Styles applied to the asterisk element. */
asterisk: {
'&$error': {
color: theme.palette.error.main
}
}
};
};
var FormLabel = React.forwardRef(function FormLabel(props, ref) {
var children = props.children,
classes = props.classes,
className = props.className,
color = props.color,
_props$component = props.component,
Component = _props$component === void 0 ? 'label' : _props$component,
disabled = props.disabled,
error = props.error,
filled = props.filled,
focused = props.focused,
required = props.required,
other = _objectWithoutProperties(props, ["children", "classes", "className", "color", "component", "disabled", "error", "filled", "focused", "required"]);
var muiFormControl = useFormControl();
var fcs = formControlState({
props: props,
muiFormControl: muiFormControl,
states: ['color', 'required', 'focused', 'disabled', 'error', 'filled']
});
return React.createElement(Component, _extends({
className: clsx(classes.root, classes["color".concat(capitalize(fcs.color || 'primary'))], className, fcs.disabled && classes.disabled, fcs.error && classes.error, fcs.filled && classes.filled, fcs.focused && classes.focused, fcs.required && classes.required),
ref: ref
}, other), children, fcs.required && React.createElement("span", {
className: clsx(classes.asterisk, fcs.error && classes.error)
}, "\u2009", '*'));
});
process.env.NODE_ENV !== "production" ? FormLabel.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['primary', 'secondary']),
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: PropTypes.elementType,
/**
* If `true`, the label should be displayed in a disabled state.
*/
disabled: PropTypes.bool,
/**
* If `true`, the label should be displayed in an error state.
*/
error: PropTypes.bool,
/**
* If `true`, the label should use filled classes key.
*/
filled: PropTypes.bool,
/**
* If `true`, the input of this label is focused (used by `FormGroup` components).
*/
focused: PropTypes.bool,
/**
* If `true`, the label will indicate that the input is required.
*/
required: PropTypes.bool
} : void 0;
export default withStyles(styles, {
name: 'MuiFormLabel'
})(FormLabel); |
ajax/libs/material-ui/4.9.4/esm/TablePagination/TablePaginationActions.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 KeyboardArrowLeft from '../internal/svg-icons/KeyboardArrowLeft';
import KeyboardArrowRight from '../internal/svg-icons/KeyboardArrowRight';
import useTheme from '../styles/useTheme';
import IconButton from '../IconButton';
/**
* @ignore - internal component.
*/
var _ref = React.createElement(KeyboardArrowRight, null);
var _ref2 = React.createElement(KeyboardArrowLeft, null);
var _ref3 = React.createElement(KeyboardArrowLeft, null);
var _ref4 = React.createElement(KeyboardArrowRight, null);
var TablePaginationActions = React.forwardRef(function TablePaginationActions(props, ref) {
var backIconButtonProps = props.backIconButtonProps,
count = props.count,
nextIconButtonProps = props.nextIconButtonProps,
onChangePage = props.onChangePage,
page = props.page,
rowsPerPage = props.rowsPerPage,
other = _objectWithoutProperties(props, ["backIconButtonProps", "count", "nextIconButtonProps", "onChangePage", "page", "rowsPerPage"]);
var theme = useTheme();
var handleBackButtonClick = function handleBackButtonClick(event) {
onChangePage(event, page - 1);
};
var handleNextButtonClick = function handleNextButtonClick(event) {
onChangePage(event, page + 1);
};
return React.createElement("div", _extends({
ref: ref
}, other), React.createElement(IconButton, _extends({
onClick: handleBackButtonClick,
disabled: page === 0,
color: "inherit"
}, backIconButtonProps), theme.direction === 'rtl' ? _ref : _ref2), React.createElement(IconButton, _extends({
onClick: handleNextButtonClick,
disabled: count !== -1 ? page >= Math.ceil(count / rowsPerPage) - 1 : false,
color: "inherit"
}, nextIconButtonProps), theme.direction === 'rtl' ? _ref3 : _ref4));
});
process.env.NODE_ENV !== "production" ? TablePaginationActions.propTypes = {
/**
* Props applied to the back arrow [`IconButton`](/api/icon-button/) element.
*/
backIconButtonProps: PropTypes.object,
/**
* The total number of rows.
*/
count: PropTypes.number.isRequired,
/**
* Props applied to the next arrow [`IconButton`](/api/icon-button/) element.
*/
nextIconButtonProps: PropTypes.object,
/**
* Callback fired when the page is changed.
*
* @param {object} event The event source of the callback.
* @param {number} page The page selected.
*/
onChangePage: PropTypes.func.isRequired,
/**
* The zero-based index of the current page.
*/
page: PropTypes.number.isRequired,
/**
* The number of rows per page.
*/
rowsPerPage: PropTypes.number.isRequired
} : void 0;
export default TablePaginationActions; |
ajax/libs/primereact/7.0.1/confirmpopup/confirmpopup.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { DomHandler, ConnectedOverlayScrollHandler, ZIndexUtils, ObjectUtils, IconUtils, classNames } from 'primereact/utils';
import { Button } from 'primereact/button';
import { CSSTransition } from 'primereact/csstransition';
import PrimeReact, { localeOption } from 'primereact/api';
import { OverlayService } from 'primereact/overlayservice';
import { Portal } from 'primereact/portal';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function confirmPopup(props) {
var appendTo = props.appendTo || document.body;
var confirmPopupWrapper = document.createDocumentFragment();
DomHandler.appendChild(confirmPopupWrapper, appendTo);
props = _objectSpread(_objectSpread({}, props), {
visible: props.visible === undefined ? true : props.visible
});
var confirmPopupEl = /*#__PURE__*/React.createElement(ConfirmPopup, props);
ReactDOM.render(confirmPopupEl, confirmPopupWrapper);
var updateConfirmPopup = function updateConfirmPopup(newProps) {
props = _objectSpread(_objectSpread({}, props), newProps);
ReactDOM.render( /*#__PURE__*/React.cloneElement(confirmPopupEl, props), confirmPopupWrapper);
};
return {
_destroy: function _destroy() {
ReactDOM.unmountComponentAtNode(confirmPopupWrapper);
},
show: function show() {
updateConfirmPopup({
visible: true,
onHide: function onHide() {
updateConfirmPopup({
visible: false
}); // reset
}
});
},
hide: function hide() {
updateConfirmPopup({
visible: false
});
},
update: function update(newProps) {
updateConfirmPopup(newProps);
}
};
}
var ConfirmPopup = /*#__PURE__*/function (_Component) {
_inherits(ConfirmPopup, _Component);
var _super = _createSuper(ConfirmPopup);
function ConfirmPopup(props) {
var _this;
_classCallCheck(this, ConfirmPopup);
_this = _super.call(this, props);
_this.state = {
visible: false
};
_this.reject = _this.reject.bind(_assertThisInitialized(_this));
_this.accept = _this.accept.bind(_assertThisInitialized(_this));
_this.hide = _this.hide.bind(_assertThisInitialized(_this));
_this.onCloseClick = _this.onCloseClick.bind(_assertThisInitialized(_this));
_this.onPanelClick = _this.onPanelClick.bind(_assertThisInitialized(_this));
_this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this));
_this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this));
_this.onExit = _this.onExit.bind(_assertThisInitialized(_this));
_this.onExited = _this.onExited.bind(_assertThisInitialized(_this));
_this.overlayRef = /*#__PURE__*/React.createRef();
_this.acceptBtnRef = /*#__PURE__*/React.createRef();
return _this;
}
_createClass(ConfirmPopup, [{
key: "acceptLabel",
value: function acceptLabel() {
return this.props.acceptLabel || localeOption('accept');
}
}, {
key: "rejectLabel",
value: function rejectLabel() {
return this.props.rejectLabel || localeOption('reject');
}
}, {
key: "bindDocumentClickListener",
value: function bindDocumentClickListener() {
var _this2 = this;
if (!this.documentClickListener && this.props.dismissable) {
this.documentClickListener = function (event) {
if (!_this2.isPanelClicked && _this2.isOutsideClicked(event.target)) {
_this2.hide();
}
_this2.isPanelClicked = false;
};
document.addEventListener('click', this.documentClickListener);
}
}
}, {
key: "unbindDocumentClickListener",
value: function unbindDocumentClickListener() {
if (this.documentClickListener) {
document.removeEventListener('click', this.documentClickListener);
this.documentClickListener = null;
}
}
}, {
key: "bindScrollListener",
value: function bindScrollListener() {
var _this3 = this;
if (!this.scrollHandler) {
this.scrollHandler = new ConnectedOverlayScrollHandler(this.props.target, function () {
if (_this3.state.visible) {
_this3.hide();
}
});
}
this.scrollHandler.bindScrollListener();
}
}, {
key: "unbindScrollListener",
value: function unbindScrollListener() {
if (this.scrollHandler) {
this.scrollHandler.unbindScrollListener();
}
}
}, {
key: "bindResizeListener",
value: function bindResizeListener() {
var _this4 = this;
if (!this.resizeListener) {
this.resizeListener = function () {
if (_this4.state.visible && !DomHandler.isAndroid()) {
_this4.hide();
}
};
window.addEventListener('resize', this.resizeListener);
}
}
}, {
key: "unbindResizeListener",
value: function unbindResizeListener() {
if (this.resizeListener) {
window.removeEventListener('resize', this.resizeListener);
this.resizeListener = null;
}
}
}, {
key: "isOutsideClicked",
value: function isOutsideClicked(target) {
return this.overlayRef && this.overlayRef.current && !(this.overlayRef.current.isSameNode(target) || this.overlayRef.current.contains(target));
}
}, {
key: "onCloseClick",
value: function onCloseClick(event) {
this.hide();
event.preventDefault();
}
}, {
key: "onPanelClick",
value: function onPanelClick(event) {
this.isPanelClicked = true;
OverlayService.emit('overlay-click', {
originalEvent: event,
target: this.props.target
});
}
}, {
key: "accept",
value: function accept() {
if (this.props.accept) {
this.props.accept();
}
this.hide('accept');
}
}, {
key: "reject",
value: function reject() {
if (this.props.reject) {
this.props.reject();
}
this.hide('reject');
}
}, {
key: "show",
value: function show() {
var _this5 = this;
this.setState({
visible: true
}, function () {
_this5.overlayEventListener = function (e) {
if (!_this5.isOutsideClicked(e.target)) {
_this5.isPanelClicked = true;
}
};
OverlayService.on('overlay-click', _this5.overlayEventListener);
});
}
}, {
key: "hide",
value: function hide(result) {
var _this6 = this;
this.setState({
visible: false
}, function () {
OverlayService.off('overlay-click', _this6.overlayEventListener);
_this6.overlayEventListener = null;
if (_this6.props.onHide) {
_this6.props.onHide(result);
}
});
}
}, {
key: "onEnter",
value: function onEnter() {
ZIndexUtils.set('overlay', this.overlayRef.current, PrimeReact.autoZIndex, PrimeReact.zIndex['overlay']);
this.align();
}
}, {
key: "onEntered",
value: function onEntered() {
this.bindDocumentClickListener();
this.bindScrollListener();
this.bindResizeListener();
if (this.acceptBtnRef && this.acceptBtnRef.current) {
this.acceptBtnRef.current.focus();
}
this.props.onShow && this.props.onShow();
}
}, {
key: "onExit",
value: function onExit() {
this.unbindDocumentClickListener();
this.unbindScrollListener();
this.unbindResizeListener();
}
}, {
key: "onExited",
value: function onExited() {
ZIndexUtils.clear(this.overlayRef.current);
}
}, {
key: "align",
value: function align() {
if (this.props.target) {
DomHandler.absolutePosition(this.overlayRef.current, this.props.target);
var containerOffset = DomHandler.getOffset(this.overlayRef.current);
var targetOffset = DomHandler.getOffset(this.props.target);
var arrowLeft = 0;
if (containerOffset.left < targetOffset.left) {
arrowLeft = targetOffset.left - containerOffset.left;
}
this.overlayRef.current.style.setProperty('--overlayArrowLeft', "".concat(arrowLeft, "px"));
if (containerOffset.top < targetOffset.top) {
DomHandler.addClass(this.overlayRef.current, 'p-confirm-popup-flipped');
}
}
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.props.visible) {
this.setState({
visible: true
});
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.visible !== this.props.visible) {
this.setState({
visible: this.props.visible
});
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.unbindDocumentClickListener();
this.unbindResizeListener();
if (this.scrollHandler) {
this.scrollHandler.destroy();
this.scrollHandler = null;
}
if (this.overlayEventListener) {
OverlayService.off('overlay-click', this.overlayEventListener);
this.overlayEventListener = null;
}
ZIndexUtils.clear(this.overlayRef.current);
}
}, {
key: "renderContent",
value: function renderContent() {
var message = ObjectUtils.getJSXElement(this.props.message, this.props);
return /*#__PURE__*/React.createElement("div", {
className: "p-confirm-popup-content"
}, IconUtils.getJSXIcon(this.props.icon, {
className: 'p-confirm-popup-icon'
}, {
props: this.props
}), /*#__PURE__*/React.createElement("span", {
className: "p-confirm-popup-message"
}, message));
}
}, {
key: "renderFooter",
value: function renderFooter() {
var acceptClassName = classNames('p-confirm-popup-accept p-button-sm', this.props.acceptClassName);
var rejectClassName = classNames('p-confirm-popup-reject p-button-sm', {
'p-button-text': !this.props.rejectClassName
}, this.props.rejectClassName);
var content = /*#__PURE__*/React.createElement("div", {
className: "p-confirm-popup-footer"
}, /*#__PURE__*/React.createElement(Button, {
label: this.rejectLabel(),
icon: this.props.rejectIcon,
className: rejectClassName,
onClick: this.reject
}), /*#__PURE__*/React.createElement(Button, {
ref: this.acceptBtnRef,
label: this.acceptLabel(),
icon: this.props.acceptIcon,
className: acceptClassName,
onClick: this.accept
}));
if (this.props.footer) {
var defaultContentOptions = {
accept: this.accept,
reject: this.reject,
className: 'p-confirm-popup-footer',
acceptClassName: acceptClassName,
rejectClassName: rejectClassName,
acceptLabel: this.acceptLabel(),
rejectLabel: this.rejectLabel(),
element: content,
props: this.props
};
return ObjectUtils.getJSXElement(this.props.footer, defaultContentOptions);
}
return content;
}
}, {
key: "renderElement",
value: function renderElement() {
var className = classNames('p-confirm-popup p-component', this.props.className);
var content = this.renderContent();
var footer = this.renderFooter();
return /*#__PURE__*/React.createElement(CSSTransition, {
nodeRef: this.overlayRef,
classNames: "p-connected-overlay",
in: this.state.visible,
timeout: {
enter: 120,
exit: 100
},
options: this.props.transitionOptions,
unmountOnExit: true,
onEnter: this.onEnter,
onEntered: this.onEntered,
onExit: this.onExit,
onExited: this.onExited
}, /*#__PURE__*/React.createElement("div", {
ref: this.overlayRef,
id: this.props.id,
className: className,
style: this.props.style,
onClick: this.onPanelClick
}, content, footer));
}
}, {
key: "render",
value: function render() {
var element = this.renderElement();
return /*#__PURE__*/React.createElement(Portal, {
element: element,
appendTo: this.props.appendTo,
visible: true
});
}
}]);
return ConfirmPopup;
}(Component);
_defineProperty(ConfirmPopup, "defaultProps", {
target: null,
visible: false,
message: null,
rejectLabel: null,
acceptLabel: null,
icon: null,
rejectIcon: null,
acceptIcon: null,
rejectClassName: null,
acceptClassName: null,
className: null,
style: null,
appendTo: null,
dismissable: true,
footer: null,
onShow: null,
onHide: null,
accept: null,
reject: null,
transitionOptions: null
});
export { ConfirmPopup, confirmPopup };
|
ajax/libs/primereact/6.5.0/rating/rating.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { tip, 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;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Rating = /*#__PURE__*/function (_Component) {
_inherits(Rating, _Component);
var _super = _createSuper(Rating);
function Rating(props) {
var _this;
_classCallCheck(this, Rating);
_this = _super.call(this, props);
_this.clear = _this.clear.bind(_assertThisInitialized(_this));
_this.onStarKeyDown = _this.onStarKeyDown.bind(_assertThisInitialized(_this));
_this.onCancelKeyDown = _this.onCancelKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(Rating, [{
key: "rate",
value: function rate(event, i) {
if (!this.props.readOnly && !this.props.disabled && this.props.onChange) {
this.props.onChange({
originalEvent: event,
value: i,
stopPropagation: function stopPropagation() {},
preventDefault: function preventDefault() {},
target: {
name: this.props.name,
id: this.props.id,
value: i
}
});
}
event.preventDefault();
}
}, {
key: "clear",
value: function clear(event) {
if (!this.props.readOnly && !this.props.disabled && this.props.onChange) {
this.props.onChange({
originalEvent: event,
value: null,
stopPropagation: function stopPropagation() {},
preventDefault: function preventDefault() {},
target: {
name: this.props.name,
id: this.props.id,
value: null
}
});
}
event.preventDefault();
}
}, {
key: "shouldComponentUpdate",
value: function shouldComponentUpdate(nextProps, nextState) {
if (nextProps.value === this.props.value && nextProps.disabled === this.props.disabled) {
return false;
}
return true;
}
}, {
key: "onStarKeyDown",
value: function onStarKeyDown(event, value) {
if (event.key === 'Enter') {
this.rate(event, value);
}
}
}, {
key: "onCancelKeyDown",
value: function onCancelKeyDown(event) {
if (event.key === 'Enter') {
this.clear(event);
}
}
}, {
key: "getFocusIndex",
value: function getFocusIndex() {
return this.props.disabled || this.props.readOnly ? null : 0;
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.props.tooltip) {
this.renderTooltip();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.tooltip !== this.props.tooltip || prevProps.tooltipOptions !== this.props.tooltipOptions) {
if (this.tooltip) this.tooltip.update(_objectSpread({
content: this.props.tooltip
}, this.props.tooltipOptions || {}));else this.renderTooltip();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.tooltip) {
this.tooltip.destroy();
this.tooltip = null;
}
}
}, {
key: "renderTooltip",
value: function renderTooltip() {
this.tooltip = tip({
target: this.element,
content: this.props.tooltip,
options: this.props.tooltipOptions
});
}
}, {
key: "renderStars",
value: function renderStars() {
var _this2 = this;
var starsArray = [];
for (var i = 0; i < this.props.stars; i++) {
starsArray[i] = i + 1;
}
var stars = starsArray.map(function (value) {
var iconClass = classNames('p-rating-icon', {
'pi pi-star-o': !_this2.props.value || value > _this2.props.value,
'pi pi-star': value <= _this2.props.value
});
return /*#__PURE__*/React.createElement("span", {
className: iconClass,
onClick: function onClick(e) {
return _this2.rate(e, value);
},
key: value,
tabIndex: _this2.getFocusIndex(),
onKeyDown: function onKeyDown(e) {
return _this2.onStarKeyDown(e, value);
}
});
});
return stars;
}
}, {
key: "renderCancelIcon",
value: function renderCancelIcon() {
if (this.props.cancel) {
return /*#__PURE__*/React.createElement("span", {
className: "p-rating-icon p-rating-cancel pi pi-ban",
onClick: this.clear,
tabIndex: this.getFocusIndex(),
onKeyDown: this.onCancelKeyDown
});
}
return null;
}
}, {
key: "render",
value: function render() {
var _this3 = this;
var className = classNames('p-rating', {
'p-disabled': this.props.disabled,
'p-rating-readonly': this.props.readOnly
}, this.props.className);
var cancelIcon = this.renderCancelIcon();
var stars = this.renderStars();
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this3.element = el;
},
id: this.props.id,
className: className,
style: this.props.style
}, cancelIcon, stars);
}
}]);
return Rating;
}(Component);
_defineProperty(Rating, "defaultProps", {
id: null,
value: null,
disabled: false,
readOnly: false,
stars: 5,
cancel: true,
style: null,
className: null,
tooltip: null,
tooltipOptions: null,
onChange: null
});
export { Rating };
|
ajax/libs/react-native-web/0.17.4/exports/YellowBox/index.js | cdnjs/cdnjs | /**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import React from 'react';
import UnimplementedView from '../../modules/UnimplementedView';
function YellowBox(props) {
return /*#__PURE__*/React.createElement(UnimplementedView, props);
}
YellowBox.ignoreWarnings = function () {};
export default YellowBox; |
ajax/libs/primereact/6.6.0/message/message.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { ObjectUtils, classNames } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Message = /*#__PURE__*/function (_Component) {
_inherits(Message, _Component);
var _super = _createSuper(Message);
function Message() {
_classCallCheck(this, Message);
return _super.apply(this, arguments);
}
_createClass(Message, [{
key: "getContent",
value: function getContent() {
if (this.props.content) {
return ObjectUtils.getJSXElement(this.props.content, this.props);
}
var icon = classNames('p-inline-message-icon pi', {
'pi-info-circle': this.props.severity === 'info',
'pi-exclamation-triangle': this.props.severity === 'warn',
'pi-times-circle': this.props.severity === 'error',
'pi-check': this.props.severity === 'success'
});
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
className: icon
}), /*#__PURE__*/React.createElement("span", {
className: "p-inline-message-text"
}, this.props.text));
}
}, {
key: "render",
value: function render() {
var className = classNames('p-inline-message p-component', {
'p-inline-message-info': this.props.severity === 'info',
'p-inline-message-warn': this.props.severity === 'warn',
'p-inline-message-error': this.props.severity === 'error',
'p-inline-message-success': this.props.severity === 'success',
'p-inline-message-icon-only': !this.props.text
}, this.props.className);
var content = this.getContent();
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
"aria-live": "polite",
className: className,
style: this.props.style,
role: "alert"
}, content);
}
}]);
return Message;
}(Component);
_defineProperty(Message, "defaultProps", {
id: null,
className: null,
style: null,
text: null,
severity: 'info',
content: null
});
export { Message };
|
ajax/libs/boardgame-io/0.39.6/esm/react-native.js | cdnjs/cdnjs | import { d as _inherits, _ as _createClass, b as _defineProperty, a as _classCallCheck, f as _possibleConstructorReturn, h as _getPrototypeOf, y as _objectWithoutProperties, k as _objectSpread2 } from './reducer-0ea50db8.js';
import 'redux';
import 'immer';
import './Debug-a41a191f.js';
import 'flatted';
import './ai-779bcbbf.js';
import './initialize-20f559ab.js';
import { C as Client$1 } from './client-051af88e.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/material-ui/4.9.4/es/MobileStepper/MobileStepper.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 Paper from '../Paper';
import capitalize from '../utils/capitalize';
import LinearProgress from '../LinearProgress';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
background: theme.palette.background.default,
padding: 8
},
/* Styles applied to the root element if `position="bottom"`. */
positionBottom: {
position: 'fixed',
bottom: 0,
left: 0,
right: 0,
zIndex: theme.zIndex.mobileStepper
},
/* Styles applied to the root element if `position="top"`. */
positionTop: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
zIndex: theme.zIndex.mobileStepper
},
/* Styles applied to the root element if `position="static"`. */
positionStatic: {},
/* Styles applied to the dots container if `variant="dots"`. */
dots: {
display: 'flex',
flexDirection: 'row'
},
/* Styles applied to each dot if `variant="dots"`. */
dot: {
backgroundColor: theme.palette.action.disabled,
borderRadius: '50%',
width: 8,
height: 8,
margin: '0 2px'
},
/* Styles applied to a dot if `variant="dots"` and this is the active step. */
dotActive: {
backgroundColor: theme.palette.primary.main
},
/* Styles applied to the Linear Progress component if `variant="progress"`. */
progress: {
width: '50%'
}
});
const MobileStepper = React.forwardRef(function MobileStepper(props, ref) {
const {
activeStep = 0,
backButton,
classes,
className,
LinearProgressProps,
nextButton,
position = 'bottom',
steps,
variant = 'dots'
} = props,
other = _objectWithoutPropertiesLoose(props, ["activeStep", "backButton", "classes", "className", "LinearProgressProps", "nextButton", "position", "steps", "variant"]);
return React.createElement(Paper, _extends({
square: true,
elevation: 0,
className: clsx(classes.root, classes[`position${capitalize(position)}`], className),
ref: ref
}, other), backButton, variant === 'text' && React.createElement(React.Fragment, null, activeStep + 1, " / ", steps), variant === 'dots' && React.createElement("div", {
className: classes.dots
}, [...new Array(steps)].map((_, index) => React.createElement("div", {
key: index,
className: clsx(classes.dot, index === activeStep && classes.dotActive)
}))), variant === 'progress' && React.createElement(LinearProgress, _extends({
className: classes.progress,
variant: "determinate",
value: Math.ceil(activeStep / (steps - 1) * 100)
}, LinearProgressProps)), nextButton);
});
process.env.NODE_ENV !== "production" ? MobileStepper.propTypes = {
/**
* Set the active step (zero based index).
* Defines which dot is highlighted when the variant is 'dots'.
*/
activeStep: PropTypes.number,
/**
* A back button element. For instance, it can be a `Button` or an `IconButton`.
*/
backButton: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Props applied to the `LinearProgress` element.
*/
LinearProgressProps: PropTypes.object,
/**
* A next button element. For instance, it can be a `Button` or an `IconButton`.
*/
nextButton: PropTypes.node,
/**
* Set the positioning type.
*/
position: PropTypes.oneOf(['bottom', 'top', 'static']),
/**
* The total steps.
*/
steps: PropTypes.number.isRequired,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['text', 'dots', 'progress'])
} : void 0;
export default withStyles(styles, {
name: 'MuiMobileStepper'
})(MobileStepper); |
ajax/libs/react-native-web/0.11.4/exports/SafeAreaView/index.js | cdnjs/cdnjs | function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import React from 'react';
import StyleSheet from '../StyleSheet';
import View from '../View';
import ViewPropTypes from '../ViewPropTypes';
var SafeAreaView =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(SafeAreaView, _React$Component);
function SafeAreaView() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = SafeAreaView.prototype;
_proto.render = function render() {
var _this$props = this.props,
style = _this$props.style,
rest = _objectWithoutPropertiesLoose(_this$props, ["style"]);
return React.createElement(View, _extends({}, rest, {
style: StyleSheet.compose(styles.root, style)
}));
};
return SafeAreaView;
}(React.Component);
SafeAreaView.displayName = 'SafeAreaView';
SafeAreaView.propTypes = process.env.NODE_ENV !== "production" ? _objectSpread({}, ViewPropTypes) : {};
var styles = StyleSheet.create({
root: {
paddingTop: 'env(safe-area-inset-top)',
paddingRight: 'env(safe-area-inset-right)',
paddingBottom: 'env(safe-area-inset-bottom)',
paddingLeft: 'env(safe-area-inset-left)'
}
});
export default SafeAreaView; |
ajax/libs/react-native-web/0.12.2/exports/ImageBackground/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) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import ensureComponentIsNative from '../../modules/ensureComponentIsNative';
import Image from '../Image';
import StyleSheet from '../StyleSheet';
import View from '../View';
import React from 'react';
var emptyObject = {};
/**
* Very simple drop-in replacement for <Image> which supports nesting views.
*/
var ImageBackground =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(ImageBackground, _React$Component);
function ImageBackground() {
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._viewRef = null;
_this._captureRef = function (ref) {
_this._viewRef = ref;
};
return _this;
}
var _proto = ImageBackground.prototype;
_proto.setNativeProps = function setNativeProps(props) {
// Work-around flow
var viewRef = this._viewRef;
if (viewRef) {
ensureComponentIsNative(viewRef);
viewRef.setNativeProps(props);
}
};
_proto.render = function render() {
var _this$props = this.props,
children = _this$props.children,
_this$props$style = _this$props.style,
style = _this$props$style === void 0 ? emptyObject : _this$props$style,
imageStyle = _this$props.imageStyle,
imageRef = _this$props.imageRef,
props = _objectWithoutPropertiesLoose(_this$props, ["children", "style", "imageStyle", "imageRef"]);
var _StyleSheet$flatten = StyleSheet.flatten(style),
height = _StyleSheet$flatten.height,
width = _StyleSheet$flatten.width;
return React.createElement(View, {
ref: this._captureRef,
style: style
}, React.createElement(Image, _extends({}, props, {
ref: imageRef,
style: [StyleSheet.absoluteFill, {
// Temporary Workaround:
// Current (imperfect yet) implementation of <Image> overwrites width and height styles
// (which is not quite correct), and these styles conflict with explicitly set styles
// of <ImageBackground> and with our internal layout model here.
// So, we have to proxy/reapply these styles explicitly for actual <Image> component.
// This workaround should be removed after implementing proper support of
// intrinsic content size of the <Image>.
width: width,
height: height,
zIndex: -1
}, imageStyle]
})), children);
};
return ImageBackground;
}(React.Component);
export default ImageBackground; |
ajax/libs/react-native-web/0.13.10/exports/Touchable/index.js | cdnjs/cdnjs | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
*/
'use strict';
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import AccessibilityUtil from '../../modules/AccessibilityUtil';
import BoundingDimensions from './BoundingDimensions';
import findNodeHandle from '../findNodeHandle';
import normalizeColor from 'normalize-css-color';
import Position from './Position';
import React from 'react';
import UIManager from '../UIManager';
import View from '../View';
var extractSingleTouch = function extractSingleTouch(nativeEvent) {
var touches = nativeEvent.touches;
var changedTouches = nativeEvent.changedTouches;
var hasTouches = touches && touches.length > 0;
var hasChangedTouches = changedTouches && changedTouches.length > 0;
return !hasTouches && hasChangedTouches ? changedTouches[0] : hasTouches ? touches[0] : nativeEvent;
};
/**
* `Touchable`: Taps done right.
*
* You hook your `ResponderEventPlugin` events into `Touchable`. `Touchable`
* will measure time/geometry and tells you when to give feedback to the user.
*
* ====================== Touchable Tutorial ===============================
* The `Touchable` mixin helps you handle the "press" interaction. It analyzes
* the geometry of elements, and observes when another responder (scroll view
* etc) has stolen the touch lock. It notifies your component when it should
* give feedback to the user. (bouncing/highlighting/unhighlighting).
*
* - When a touch was activated (typically you highlight)
* - When a touch was deactivated (typically you unhighlight)
* - When a touch was "pressed" - a touch ended while still within the geometry
* of the element, and no other element (like scroller) has "stolen" touch
* lock ("responder") (Typically you bounce the element).
*
* A good tap interaction isn't as simple as you might think. There should be a
* slight delay before showing a highlight when starting a touch. If a
* subsequent touch move exceeds the boundary of the element, it should
* unhighlight, but if that same touch is brought back within the boundary, it
* should rehighlight again. A touch can move in and out of that boundary
* several times, each time toggling highlighting, but a "press" is only
* triggered if that touch ends while within the element's boundary and no
* scroller (or anything else) has stolen the lock on touches.
*
* To create a new type of component that handles interaction using the
* `Touchable` mixin, do the following:
*
* - Initialize the `Touchable` state.
*
* getInitialState: function() {
* return merge(this.touchableGetInitialState(), yourComponentState);
* }
*
* - Choose the rendered component who's touches should start the interactive
* sequence. On that rendered node, forward all `Touchable` responder
* handlers. You can choose any rendered node you like. Choose a node whose
* hit target you'd like to instigate the interaction sequence:
*
* // In render function:
* return (
* <View
* onStartShouldSetResponder={this.touchableHandleStartShouldSetResponder}
* onResponderTerminationRequest={this.touchableHandleResponderTerminationRequest}
* onResponderGrant={this.touchableHandleResponderGrant}
* onResponderMove={this.touchableHandleResponderMove}
* onResponderRelease={this.touchableHandleResponderRelease}
* onResponderTerminate={this.touchableHandleResponderTerminate}>
* <View>
* Even though the hit detection/interactions are triggered by the
* wrapping (typically larger) node, we usually end up implementing
* custom logic that highlights this inner one.
* </View>
* </View>
* );
*
* - You may set up your own handlers for each of these events, so long as you
* also invoke the `touchable*` handlers inside of your custom handler.
*
* - Implement the handlers on your component class in order to provide
* feedback to the user. See documentation for each of these class methods
* that you should implement.
*
* touchableHandlePress: function() {
* this.performBounceAnimation(); // or whatever you want to do.
* },
* touchableHandleActivePressIn: function() {
* this.beginHighlighting(...); // Whatever you like to convey activation
* },
* touchableHandleActivePressOut: function() {
* this.endHighlighting(...); // Whatever you like to convey deactivation
* },
*
* - There are more advanced methods you can implement (see documentation below):
* touchableGetHighlightDelayMS: function() {
* return 20;
* }
* // In practice, *always* use a predeclared constant (conserve memory).
* touchableGetPressRectOffset: function() {
* return {top: 20, left: 20, right: 20, bottom: 100};
* }
*/
/**
* Touchable states.
*/
var States = {
NOT_RESPONDER: 'NOT_RESPONDER',
// Not the responder
RESPONDER_INACTIVE_PRESS_IN: 'RESPONDER_INACTIVE_PRESS_IN',
// Responder, inactive, in the `PressRect`
RESPONDER_INACTIVE_PRESS_OUT: 'RESPONDER_INACTIVE_PRESS_OUT',
// Responder, inactive, out of `PressRect`
RESPONDER_ACTIVE_PRESS_IN: 'RESPONDER_ACTIVE_PRESS_IN',
// Responder, active, in the `PressRect`
RESPONDER_ACTIVE_PRESS_OUT: 'RESPONDER_ACTIVE_PRESS_OUT',
// Responder, active, out of `PressRect`
RESPONDER_ACTIVE_LONG_PRESS_IN: 'RESPONDER_ACTIVE_LONG_PRESS_IN',
// Responder, active, in the `PressRect`, after long press threshold
RESPONDER_ACTIVE_LONG_PRESS_OUT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT',
// Responder, active, out of `PressRect`, after long press threshold
ERROR: 'ERROR'
};
/*
* Quick lookup map for states that are considered to be "active"
*/
var baseStatesConditions = {
NOT_RESPONDER: false,
RESPONDER_INACTIVE_PRESS_IN: false,
RESPONDER_INACTIVE_PRESS_OUT: false,
RESPONDER_ACTIVE_PRESS_IN: false,
RESPONDER_ACTIVE_PRESS_OUT: false,
RESPONDER_ACTIVE_LONG_PRESS_IN: false,
RESPONDER_ACTIVE_LONG_PRESS_OUT: false,
ERROR: false
};
var IsActive = _objectSpread({}, baseStatesConditions, {
RESPONDER_ACTIVE_PRESS_OUT: true,
RESPONDER_ACTIVE_PRESS_IN: true
});
/**
* Quick lookup for states that are considered to be "pressing" and are
* therefore eligible to result in a "selection" if the press stops.
*/
var IsPressingIn = _objectSpread({}, baseStatesConditions, {
RESPONDER_INACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_PRESS_IN: true,
RESPONDER_ACTIVE_LONG_PRESS_IN: true
});
var IsLongPressingIn = _objectSpread({}, baseStatesConditions, {
RESPONDER_ACTIVE_LONG_PRESS_IN: true
});
/**
* Inputs to the state machine.
*/
var Signals = {
DELAY: 'DELAY',
RESPONDER_GRANT: 'RESPONDER_GRANT',
RESPONDER_RELEASE: 'RESPONDER_RELEASE',
RESPONDER_TERMINATED: 'RESPONDER_TERMINATED',
ENTER_PRESS_RECT: 'ENTER_PRESS_RECT',
LEAVE_PRESS_RECT: 'LEAVE_PRESS_RECT',
LONG_PRESS_DETECTED: 'LONG_PRESS_DETECTED'
};
/**
* Mapping from States x Signals => States
*/
var Transitions = {
NOT_RESPONDER: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.ERROR,
RESPONDER_TERMINATED: States.ERROR,
ENTER_PRESS_RECT: States.ERROR,
LEAVE_PRESS_RECT: States.ERROR,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_INACTIVE_PRESS_IN: {
DELAY: States.RESPONDER_ACTIVE_PRESS_IN,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_INACTIVE_PRESS_OUT: {
DELAY: States.RESPONDER_ACTIVE_PRESS_OUT,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_INACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_ACTIVE_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN
},
RESPONDER_ACTIVE_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
RESPONDER_ACTIVE_LONG_PRESS_IN: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT,
LONG_PRESS_DETECTED: States.RESPONDER_ACTIVE_LONG_PRESS_IN
},
RESPONDER_ACTIVE_LONG_PRESS_OUT: {
DELAY: States.ERROR,
RESPONDER_GRANT: States.ERROR,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_IN,
LEAVE_PRESS_RECT: States.RESPONDER_ACTIVE_LONG_PRESS_OUT,
LONG_PRESS_DETECTED: States.ERROR
},
error: {
DELAY: States.NOT_RESPONDER,
RESPONDER_GRANT: States.RESPONDER_INACTIVE_PRESS_IN,
RESPONDER_RELEASE: States.NOT_RESPONDER,
RESPONDER_TERMINATED: States.NOT_RESPONDER,
ENTER_PRESS_RECT: States.NOT_RESPONDER,
LEAVE_PRESS_RECT: States.NOT_RESPONDER,
LONG_PRESS_DETECTED: States.NOT_RESPONDER
}
}; // ==== Typical Constants for integrating into UI components ====
// var HIT_EXPAND_PX = 20;
// var HIT_VERT_OFFSET_PX = 10;
var HIGHLIGHT_DELAY_MS = 130;
var PRESS_EXPAND_PX = 20;
var LONG_PRESS_THRESHOLD = 500;
var LONG_PRESS_DELAY_MS = LONG_PRESS_THRESHOLD - HIGHLIGHT_DELAY_MS;
var LONG_PRESS_ALLOWED_MOVEMENT = 10; // Default amount "active" region protrudes beyond box
/**
* By convention, methods prefixed with underscores are meant to be @private,
* and not @protected. Mixers shouldn't access them - not even to provide them
* as callback handlers.
*
*
* ========== Geometry =========
* `Touchable` only assumes that there exists a `HitRect` node. The `PressRect`
* is an abstract box that is extended beyond the `HitRect`.
*
* +--------------------------+
* | | - "Start" events in `HitRect` cause `HitRect`
* | +--------------------+ | to become the responder.
* | | +--------------+ | | - `HitRect` is typically expanded around
* | | | | | | the `VisualRect`, but shifted downward.
* | | | VisualRect | | | - After pressing down, after some delay,
* | | | | | | and before letting up, the Visual React
* | | +--------------+ | | will become "active". This makes it eligible
* | | HitRect | | for being highlighted (so long as the
* | +--------------------+ | press remains in the `PressRect`).
* | PressRect o |
* +----------------------|---+
* Out Region |
* +-----+ This gap between the `HitRect` and
* `PressRect` allows a touch to move far away
* from the original hit rect, and remain
* highlighted, and eligible for a "Press".
* Customize this via
* `touchableGetPressRectOffset()`.
*
*
*
* ======= State Machine =======
*
* +-------------+ <---+ RESPONDER_RELEASE
* |NOT_RESPONDER|
* +-------------+ <---+ RESPONDER_TERMINATED
* +
* | RESPONDER_GRANT (HitRect)
* v
* +---------------------------+ DELAY +-------------------------+ T + DELAY +------------------------------+
* |RESPONDER_INACTIVE_PRESS_IN|+-------->|RESPONDER_ACTIVE_PRESS_IN| +------------> |RESPONDER_ACTIVE_LONG_PRESS_IN|
* +---------------------------+ +-------------------------+ +------------------------------+
* + ^ + ^ + ^
* |LEAVE_ |ENTER_ |LEAVE_ |ENTER_ |LEAVE_ |ENTER_
* |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT |PRESS_RECT
* | | | | | |
* v + v + v +
* +----------------------------+ DELAY +--------------------------+ +-------------------------------+
* |RESPONDER_INACTIVE_PRESS_OUT|+------->|RESPONDER_ACTIVE_PRESS_OUT| |RESPONDER_ACTIVE_LONG_PRESS_OUT|
* +----------------------------+ +--------------------------+ +-------------------------------+
*
* T + DELAY => LONG_PRESS_DELAY_MS + DELAY
*
* Not drawn are the side effects of each transition. The most important side
* effect is the `touchableHandlePress` abstract method invocation that occurs
* when a responder is released while in either of the "Press" states.
*
* The other important side effects are the highlight abstract method
* invocations (internal callbacks) to be implemented by the mixer.
*
*
* @lends Touchable.prototype
*/
var TouchableMixin = {
// HACK (part 1): basic support for touchable interactions using a keyboard
componentDidMount: function componentDidMount() {
var _this = this;
this._touchableNode = findNodeHandle(this);
if (this._touchableNode && this._touchableNode.addEventListener) {
this._touchableBlurListener = function (e) {
if (_this._isTouchableKeyboardActive) {
if (_this.state.touchable.touchState && _this.state.touchable.touchState !== States.NOT_RESPONDER) {
_this.touchableHandleResponderTerminate({
nativeEvent: e
});
}
_this._isTouchableKeyboardActive = false;
}
};
this._touchableNode.addEventListener('blur', this._touchableBlurListener);
}
},
/**
* Clear all timeouts on unmount
*/
componentWillUnmount: function componentWillUnmount() {
if (this._touchableNode && this._touchableNode.addEventListener) {
this._touchableNode.removeEventListener('blur', this._touchableBlurListener);
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
},
/**
* It's prefer that mixins determine state in this way, having the class
* explicitly mix the state in the one and only `getInitialState` method.
*
* @return {object} State object to be placed inside of
* `this.state.touchable`.
*/
touchableGetInitialState: function touchableGetInitialState() {
return {
touchable: {
touchState: undefined,
responderID: null
}
};
},
// ==== Hooks to Gesture Responder system ====
/**
* Must return true if embedded in a native platform scroll view.
*/
touchableHandleResponderTerminationRequest: function touchableHandleResponderTerminationRequest() {
return !this.props.rejectResponderTermination;
},
/**
* Must return true to start the process of `Touchable`.
*/
touchableHandleStartShouldSetResponder: function touchableHandleStartShouldSetResponder() {
return !this.props.disabled;
},
/**
* Return true to cancel press on long press.
*/
touchableLongPressCancelsPress: function touchableLongPressCancelsPress() {
return true;
},
/**
* Place as callback for a DOM element's `onResponderGrant` event.
* @param {SyntheticEvent} e Synthetic event from event system.
*
*/
touchableHandleResponderGrant: function touchableHandleResponderGrant(e) {
var dispatchID = e.currentTarget; // Since e is used in a callback invoked on another event loop
// (as in setTimeout etc), we need to call e.persist() on the
// event to make sure it doesn't get reused in the event object pool.
e.persist();
this.pressOutDelayTimeout && clearTimeout(this.pressOutDelayTimeout);
this.pressOutDelayTimeout = null;
this.state.touchable.touchState = States.NOT_RESPONDER;
this.state.touchable.responderID = dispatchID;
this._receiveSignal(Signals.RESPONDER_GRANT, e);
var delayMS = this.touchableGetHighlightDelayMS !== undefined ? Math.max(this.touchableGetHighlightDelayMS(), 0) : HIGHLIGHT_DELAY_MS;
delayMS = isNaN(delayMS) ? HIGHLIGHT_DELAY_MS : delayMS;
if (delayMS !== 0) {
this.touchableDelayTimeout = setTimeout(this._handleDelay.bind(this, e), delayMS);
} else {
this._handleDelay(e);
}
var longDelayMS = this.touchableGetLongPressDelayMS !== undefined ? Math.max(this.touchableGetLongPressDelayMS(), 10) : LONG_PRESS_DELAY_MS;
longDelayMS = isNaN(longDelayMS) ? LONG_PRESS_DELAY_MS : longDelayMS;
this.longPressDelayTimeout = setTimeout(this._handleLongDelay.bind(this, e), longDelayMS + delayMS);
},
/**
* Place as callback for a DOM element's `onResponderRelease` event.
*/
touchableHandleResponderRelease: function touchableHandleResponderRelease(e) {
this.pressInLocation = null;
this._receiveSignal(Signals.RESPONDER_RELEASE, e);
},
/**
* Place as callback for a DOM element's `onResponderTerminate` event.
*/
touchableHandleResponderTerminate: function touchableHandleResponderTerminate(e) {
this.pressInLocation = null;
this._receiveSignal(Signals.RESPONDER_TERMINATED, e);
},
/**
* Place as callback for a DOM element's `onResponderMove` event.
*/
touchableHandleResponderMove: function touchableHandleResponderMove(e) {
// Measurement may not have returned yet.
if (!this.state.touchable.positionOnActivate) {
return;
}
var positionOnActivate = this.state.touchable.positionOnActivate;
var dimensionsOnActivate = this.state.touchable.dimensionsOnActivate;
var pressRectOffset = this.touchableGetPressRectOffset ? this.touchableGetPressRectOffset() : {
left: PRESS_EXPAND_PX,
right: PRESS_EXPAND_PX,
top: PRESS_EXPAND_PX,
bottom: PRESS_EXPAND_PX
};
var pressExpandLeft = pressRectOffset.left;
var pressExpandTop = pressRectOffset.top;
var pressExpandRight = pressRectOffset.right;
var pressExpandBottom = pressRectOffset.bottom;
var hitSlop = this.touchableGetHitSlop ? this.touchableGetHitSlop() : null;
if (hitSlop) {
pressExpandLeft += hitSlop.left || 0;
pressExpandTop += hitSlop.top || 0;
pressExpandRight += hitSlop.right || 0;
pressExpandBottom += hitSlop.bottom || 0;
}
var touch = extractSingleTouch(e.nativeEvent);
var pageX = touch && touch.pageX;
var pageY = touch && touch.pageY;
if (this.pressInLocation) {
var movedDistance = this._getDistanceBetweenPoints(pageX, pageY, this.pressInLocation.pageX, this.pressInLocation.pageY);
if (movedDistance > LONG_PRESS_ALLOWED_MOVEMENT) {
this._cancelLongPressDelayTimeout();
}
}
var isTouchWithinActive = pageX > positionOnActivate.left - pressExpandLeft && pageY > positionOnActivate.top - pressExpandTop && pageX < positionOnActivate.left + dimensionsOnActivate.width + pressExpandRight && pageY < positionOnActivate.top + dimensionsOnActivate.height + pressExpandBottom;
if (isTouchWithinActive) {
var prevState = this.state.touchable.touchState;
this._receiveSignal(Signals.ENTER_PRESS_RECT, e);
var curState = this.state.touchable.touchState;
if (curState === States.RESPONDER_INACTIVE_PRESS_IN && prevState !== States.RESPONDER_INACTIVE_PRESS_IN) {
// fix for t7967420
this._cancelLongPressDelayTimeout();
}
} else {
this._cancelLongPressDelayTimeout();
this._receiveSignal(Signals.LEAVE_PRESS_RECT, e);
}
},
/**
* Invoked when the item receives focus. Mixers might override this to
* visually distinguish the `VisualRect` so that the user knows that it
* currently has the focus. Most platforms only support a single element being
* focused at a time, in which case there may have been a previously focused
* element that was blurred just prior to this. This can be overridden when
* using `Touchable.Mixin.withoutDefaultFocusAndBlur`.
*/
touchableHandleFocus: function touchableHandleFocus(e) {
this.props.onFocus && this.props.onFocus(e);
},
/**
* Invoked when the item loses focus. Mixers might override this to
* visually distinguish the `VisualRect` so that the user knows that it
* no longer has focus. Most platforms only support a single element being
* focused at a time, in which case the focus may have moved to another.
* This can be overridden when using
* `Touchable.Mixin.withoutDefaultFocusAndBlur`.
*/
touchableHandleBlur: function touchableHandleBlur(e) {
this.props.onBlur && this.props.onBlur(e);
},
// ==== Abstract Application Callbacks ====
/**
* Invoked when the item should be highlighted. Mixers should implement this
* to visually distinguish the `VisualRect` so that the user knows that
* releasing a touch will result in a "selection" (analog to click).
*
* @abstract
* touchableHandleActivePressIn: function,
*/
/**
* Invoked when the item is "active" (in that it is still eligible to become
* a "select") but the touch has left the `PressRect`. Usually the mixer will
* want to unhighlight the `VisualRect`. If the user (while pressing) moves
* back into the `PressRect` `touchableHandleActivePressIn` will be invoked
* again and the mixer should probably highlight the `VisualRect` again. This
* event will not fire on an `touchEnd/mouseUp` event, only move events while
* the user is depressing the mouse/touch.
*
* @abstract
* touchableHandleActivePressOut: function
*/
/**
* Invoked when the item is "selected" - meaning the interaction ended by
* letting up while the item was either in the state
* `RESPONDER_ACTIVE_PRESS_IN` or `RESPONDER_INACTIVE_PRESS_IN`.
*
* @abstract
* touchableHandlePress: function
*/
/**
* Invoked when the item is long pressed - meaning the interaction ended by
* letting up while the item was in `RESPONDER_ACTIVE_LONG_PRESS_IN`. If
* `touchableHandleLongPress` is *not* provided, `touchableHandlePress` will
* be called as it normally is. If `touchableHandleLongPress` is provided, by
* default any `touchableHandlePress` callback will not be invoked. To
* override this default behavior, override `touchableLongPressCancelsPress`
* to return false. As a result, `touchableHandlePress` will be called when
* lifting up, even if `touchableHandleLongPress` has also been called.
*
* @abstract
* touchableHandleLongPress: function
*/
/**
* Returns the number of millis to wait before triggering a highlight.
*
* @abstract
* touchableGetHighlightDelayMS: function
*/
/**
* Returns the amount to extend the `HitRect` into the `PressRect`. Positive
* numbers mean the size expands outwards.
*
* @abstract
* touchableGetPressRectOffset: function
*/
// ==== Internal Logic ====
/**
* Measures the `HitRect` node on activation. The Bounding rectangle is with
* respect to viewport - not page, so adding the `pageXOffset/pageYOffset`
* should result in points that are in the same coordinate system as an
* event's `globalX/globalY` data values.
*
* - Consider caching this for the lifetime of the component, or possibly
* being able to share this cache between any `ScrollMap` view.
*
* @sideeffects
* @private
*/
_remeasureMetricsOnActivation: function _remeasureMetricsOnActivation() {
var tag = this.state.touchable.responderID;
if (tag == null) {
return;
}
UIManager.measure(tag, this._handleQueryLayout);
},
_handleQueryLayout: function _handleQueryLayout(l, t, w, h, globalX, globalY) {
//don't do anything UIManager failed to measure node
if (!l && !t && !w && !h && !globalX && !globalY) {
return;
}
this.state.touchable.positionOnActivate && Position.release(this.state.touchable.positionOnActivate);
this.state.touchable.dimensionsOnActivate && // $FlowFixMe
BoundingDimensions.release(this.state.touchable.dimensionsOnActivate);
this.state.touchable.positionOnActivate = Position.getPooled(globalX, globalY); // $FlowFixMe
this.state.touchable.dimensionsOnActivate = BoundingDimensions.getPooled(w, h);
},
_handleDelay: function _handleDelay(e) {
this.touchableDelayTimeout = null;
this._receiveSignal(Signals.DELAY, e);
},
_handleLongDelay: function _handleLongDelay(e) {
this.longPressDelayTimeout = null;
var curState = this.state.touchable.touchState;
if (curState !== States.RESPONDER_ACTIVE_PRESS_IN && curState !== States.RESPONDER_ACTIVE_LONG_PRESS_IN) {
console.error('Attempted to transition from state `' + curState + '` to `' + States.RESPONDER_ACTIVE_LONG_PRESS_IN + '`, which is not supported. This is ' + 'most likely due to `Touchable.longPressDelayTimeout` not being cancelled.');
} else {
this._receiveSignal(Signals.LONG_PRESS_DETECTED, e);
}
},
/**
* Receives a state machine signal, performs side effects of the transition
* and stores the new state. Validates the transition as well.
*
* @param {Signals} signal State machine signal.
* @throws Error if invalid state transition or unrecognized signal.
* @sideeffects
*/
_receiveSignal: function _receiveSignal(signal, e) {
var responderID = this.state.touchable.responderID;
var curState = this.state.touchable.touchState;
var nextState = Transitions[curState] && Transitions[curState][signal];
if (!responderID && signal === Signals.RESPONDER_RELEASE) {
return;
}
if (!nextState) {
throw new Error('Unrecognized signal `' + signal + '` or state `' + curState + '` for Touchable responder `' + responderID + '`');
}
if (nextState === States.ERROR) {
throw new Error('Touchable cannot transition from `' + curState + '` to `' + signal + '` for responder `' + responderID + '`');
}
if (curState !== nextState) {
this._performSideEffectsForTransition(curState, nextState, signal, e);
this.state.touchable.touchState = nextState;
}
},
_cancelLongPressDelayTimeout: function _cancelLongPressDelayTimeout() {
this.longPressDelayTimeout && clearTimeout(this.longPressDelayTimeout);
this.longPressDelayTimeout = null;
},
_isHighlight: function _isHighlight(state) {
return state === States.RESPONDER_ACTIVE_PRESS_IN || state === States.RESPONDER_ACTIVE_LONG_PRESS_IN;
},
_savePressInLocation: function _savePressInLocation(e) {
var touch = extractSingleTouch(e.nativeEvent);
var pageX = touch && touch.pageX;
var pageY = touch && touch.pageY;
var locationX = touch && touch.locationX;
var locationY = touch && touch.locationY;
this.pressInLocation = {
pageX: pageX,
pageY: pageY,
locationX: locationX,
locationY: locationY
};
},
_getDistanceBetweenPoints: function _getDistanceBetweenPoints(aX, aY, bX, bY) {
var deltaX = aX - bX;
var deltaY = aY - bY;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
},
/**
* Will perform a transition between touchable states, and identify any
* highlighting or unhighlighting that must be performed for this particular
* transition.
*
* @param {States} curState Current Touchable state.
* @param {States} nextState Next Touchable state.
* @param {Signal} signal Signal that triggered the transition.
* @param {Event} e Native event.
* @sideeffects
*/
_performSideEffectsForTransition: function _performSideEffectsForTransition(curState, nextState, signal, e) {
var curIsHighlight = this._isHighlight(curState);
var newIsHighlight = this._isHighlight(nextState);
var isFinalSignal = signal === Signals.RESPONDER_TERMINATED || signal === Signals.RESPONDER_RELEASE;
if (isFinalSignal) {
this._cancelLongPressDelayTimeout();
}
var isInitialTransition = curState === States.NOT_RESPONDER && nextState === States.RESPONDER_INACTIVE_PRESS_IN;
var isActiveTransition = !IsActive[curState] && IsActive[nextState];
if (isInitialTransition || isActiveTransition) {
this._remeasureMetricsOnActivation();
}
if (IsPressingIn[curState] && signal === Signals.LONG_PRESS_DETECTED) {
this.touchableHandleLongPress && this.touchableHandleLongPress(e);
}
if (newIsHighlight && !curIsHighlight) {
this._startHighlight(e);
} else if (!newIsHighlight && curIsHighlight) {
this._endHighlight(e);
}
if (IsPressingIn[curState] && signal === Signals.RESPONDER_RELEASE) {
var hasLongPressHandler = !!this.props.onLongPress;
var pressIsLongButStillCallOnPress = IsLongPressingIn[curState] && ( // We *are* long pressing.. // But either has no long handler
!hasLongPressHandler || !this.touchableLongPressCancelsPress()); // or we're told to ignore it.
var shouldInvokePress = !IsLongPressingIn[curState] || pressIsLongButStillCallOnPress;
if (shouldInvokePress && this.touchableHandlePress) {
if (!newIsHighlight && !curIsHighlight) {
// we never highlighted because of delay, but we should highlight now
this._startHighlight(e);
this._endHighlight(e);
}
this.touchableHandlePress(e);
}
}
this.touchableDelayTimeout && clearTimeout(this.touchableDelayTimeout);
this.touchableDelayTimeout = null;
},
_playTouchSound: function _playTouchSound() {
UIManager.playTouchSound();
},
_startHighlight: function _startHighlight(e) {
this._savePressInLocation(e);
this.touchableHandleActivePressIn && this.touchableHandleActivePressIn(e);
},
_endHighlight: function _endHighlight(e) {
var _this2 = this;
if (this.touchableHandleActivePressOut) {
if (this.touchableGetPressOutDelayMS && this.touchableGetPressOutDelayMS()) {
this.pressOutDelayTimeout = setTimeout(function () {
_this2.touchableHandleActivePressOut(e);
}, this.touchableGetPressOutDelayMS());
} else {
this.touchableHandleActivePressOut(e);
}
}
},
// HACK (part 2): basic support for touchable interactions using a keyboard (including
// delays and longPress)
touchableHandleKeyEvent: function touchableHandleKeyEvent(e) {
var type = e.type,
key = e.key;
if (key === 'Enter' || key === ' ') {
if (type === 'keydown') {
if (!this._isTouchableKeyboardActive) {
if (!this.state.touchable.touchState || this.state.touchable.touchState === States.NOT_RESPONDER) {
this.touchableHandleResponderGrant(e);
this._isTouchableKeyboardActive = true;
}
}
} else if (type === 'keyup') {
if (this._isTouchableKeyboardActive) {
if (this.state.touchable.touchState && this.state.touchable.touchState !== States.NOT_RESPONDER) {
this.touchableHandleResponderRelease(e);
this._isTouchableKeyboardActive = false;
}
}
}
e.stopPropagation(); // prevent the default behaviour unless the Touchable functions as a link
// and Enter is pressed
if (!(key === 'Enter' && AccessibilityUtil.propsToAriaRole(this.props) === 'link')) {
e.preventDefault();
}
}
},
withoutDefaultFocusAndBlur: {}
};
/**
* Provide an optional version of the mixin where `touchableHandleFocus` and
* `touchableHandleBlur` can be overridden. This allows appropriate defaults to
* be set on TV platforms, without breaking existing implementations of
* `Touchable`.
*/
var touchableHandleFocus = TouchableMixin.touchableHandleFocus,
touchableHandleBlur = TouchableMixin.touchableHandleBlur,
TouchableMixinWithoutDefaultFocusAndBlur = _objectWithoutPropertiesLoose(TouchableMixin, ["touchableHandleFocus", "touchableHandleBlur"]);
TouchableMixin.withoutDefaultFocusAndBlur = TouchableMixinWithoutDefaultFocusAndBlur;
var Touchable = {
Mixin: TouchableMixin,
TOUCH_TARGET_DEBUG: false,
// Highlights all touchable targets. Toggle with Inspector.
/**
* Renders a debugging overlay to visualize touch target with hitSlop (might not work on Android).
*/
renderDebugView: function renderDebugView(_ref) {
var color = _ref.color,
hitSlop = _ref.hitSlop;
if (!Touchable.TOUCH_TARGET_DEBUG) {
return null;
}
if (process.env.NODE_ENV !== 'production') {
throw Error('Touchable.TOUCH_TARGET_DEBUG should not be enabled in prod!');
}
var debugHitSlopStyle = {};
hitSlop = hitSlop || {
top: 0,
bottom: 0,
left: 0,
right: 0
};
for (var key in hitSlop) {
debugHitSlopStyle[key] = -hitSlop[key];
}
var normalizedColor = normalizeColor(color);
if (typeof normalizedColor !== 'number') {
return null;
}
var hexColor = '#' + ('00000000' + normalizedColor.toString(16)).substr(-8);
return React.createElement(View, {
pointerEvents: "none",
style: _objectSpread({
position: 'absolute',
borderColor: hexColor.slice(0, -2) + '55',
// More opaque
borderWidth: 1,
borderStyle: 'dashed',
backgroundColor: hexColor.slice(0, -2) + '0F'
}, debugHitSlopStyle)
});
}
};
export default Touchable; |
ajax/libs/primereact/6.5.0/progressbar/progressbar.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var ProgressBar = /*#__PURE__*/function (_Component) {
_inherits(ProgressBar, _Component);
var _super = _createSuper(ProgressBar);
function ProgressBar() {
_classCallCheck(this, ProgressBar);
return _super.apply(this, arguments);
}
_createClass(ProgressBar, [{
key: "renderLabel",
value: function renderLabel() {
if (this.props.showValue && this.props.value != null) {
var label = this.props.displayValueTemplate ? this.props.displayValueTemplate(this.props.value) : this.props.value + this.props.unit;
return /*#__PURE__*/React.createElement("div", {
className: "p-progressbar-label"
}, label);
}
return null;
}
}, {
key: "renderDeterminate",
value: function renderDeterminate() {
var className = classNames('p-progressbar p-component p-progressbar-determinate', this.props.className);
var label = this.renderLabel();
return /*#__PURE__*/React.createElement("div", {
role: "progressbar",
id: this.props.id,
className: className,
style: this.props.style,
"aria-valuemin": "0",
"aria-valuenow": this.props.value,
"aria-valuemax": "100",
"aria-label": this.props.value
}, /*#__PURE__*/React.createElement("div", {
className: "p-progressbar-value p-progressbar-value-animate",
style: {
width: this.props.value + '%',
display: 'block',
backgroundColor: this.props.color
}
}), label);
}
}, {
key: "renderIndeterminate",
value: function renderIndeterminate() {
var className = classNames('p-progressbar p-component p-progressbar-indeterminate', this.props.className);
return /*#__PURE__*/React.createElement("div", {
role: "progressbar",
id: this.props.id,
className: className,
style: this.props.style
}, /*#__PURE__*/React.createElement("div", {
className: "p-progressbar-indeterminate-container"
}, /*#__PURE__*/React.createElement("div", {
className: "p-progressbar-value p-progressbar-value-animate",
style: {
backgroundColor: this.props.color
}
})));
}
}, {
key: "render",
value: function render() {
if (this.props.mode === 'determinate') return this.renderDeterminate();else if (this.props.mode === 'indeterminate') return this.renderIndeterminate();else throw new Error(this.props.mode + " is not a valid mode for the ProgressBar. Valid values are 'determinate' and 'indeterminate'");
}
}]);
return ProgressBar;
}(Component);
_defineProperty(ProgressBar, "defaultProps", {
id: null,
value: null,
showValue: true,
unit: '%',
style: null,
className: null,
mode: 'determinate',
displayValueTemplate: null,
color: null
});
export { ProgressBar };
|
ajax/libs/primereact/7.2.0/terminal/terminal.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { TerminalService } from 'primereact/terminalservice';
import { classNames } from 'primereact/utils';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var 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/primereact/7.0.1/progressspinner/progressspinner.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames } from 'primereact/utils';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var ProgressSpinner = /*#__PURE__*/function (_Component) {
_inherits(ProgressSpinner, _Component);
var _super = _createSuper(ProgressSpinner);
function ProgressSpinner() {
_classCallCheck(this, ProgressSpinner);
return _super.apply(this, arguments);
}
_createClass(ProgressSpinner, [{
key: "render",
value: function render() {
var spinnerClass = classNames('p-progress-spinner', this.props.className);
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
style: this.props.style,
className: spinnerClass,
role: "alert",
"aria-busy": true
}, /*#__PURE__*/React.createElement("svg", {
className: "p-progress-spinner-svg",
viewBox: "25 25 50 50",
style: {
animationDuration: this.props.animationDuration
}
}, /*#__PURE__*/React.createElement("circle", {
className: "p-progress-spinner-circle",
cx: "50",
cy: "50",
r: "20",
fill: this.props.fill,
strokeWidth: this.props.strokeWidth,
strokeMiterlimit: "10"
})));
}
}]);
return ProgressSpinner;
}(Component);
_defineProperty(ProgressSpinner, "defaultProps", {
id: null,
style: null,
className: null,
strokeWidth: "2",
fill: "none",
animationDuration: "2s"
});
export { ProgressSpinner };
|
ajax/libs/boardgame-io/0.39.4/esm/react.js | cdnjs/cdnjs | import { d as _inherits, _ as _createClass, b as _defineProperty, a as _classCallCheck, f as _possibleConstructorReturn, h as _getPrototypeOf, k as _objectSpread2, v as _assertThisInitialized, o as _toConsumableArray } from './reducer-b8b81041.js';
import 'redux';
import 'immer';
import './Debug-d8f94c6a.js';
import 'flatted';
import { M as MCTSBot } from './ai-3c620496.js';
import './initialize-2ee3d05a.js';
import { C as Client$1 } from './client-06d9aecd.js';
import React from 'react';
import PropTypes from 'prop-types';
import Cookies from 'react-cookies';
import './base-c99f5be2.js';
import { S as SocketIO, L as Local } from './socketio-409a52ef.js';
import './master-deb42864.js';
import 'socket.io-client';
/**
* Client
*
* boardgame.io React client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} debug - Enables the Debug UI.
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET,
* UNDO and REDO.
*/
function Client(opts) {
var _class, _temp;
var game = opts.game,
numPlayers = opts.numPlayers,
loading = opts.loading,
board = opts.board,
multiplayer = opts.multiplayer,
enhancer = opts.enhancer,
debug = opts.debug; // Component that is displayed before the client has synced
// with the game master.
if (loading === undefined) {
var Loading = function Loading() {
return React.createElement("div", {
className: "bgio-loading"
}, "connecting...");
};
loading = Loading;
}
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _temp = _class =
/*#__PURE__*/
function (_React$Component) {
_inherits(WrappedBoard, _React$Component);
function WrappedBoard(props) {
var _this;
_classCallCheck(this, WrappedBoard);
_this = _possibleConstructorReturn(this, _getPrototypeOf(WrappedBoard).call(this, props));
if (debug === undefined) {
debug = props.debug;
}
_this.client = Client$1({
game: game,
debug: debug,
numPlayers: numPlayers,
multiplayer: multiplayer,
gameID: props.gameID,
playerID: props.playerID,
credentials: props.credentials,
enhancer: enhancer
});
return _this;
}
_createClass(WrappedBoard, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
this.unsubscribe = this.client.subscribe(function () {
return _this2.forceUpdate();
});
this.client.start();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (this.props.gameID != prevProps.gameID) {
this.client.updateGameID(this.props.gameID);
}
if (this.props.playerID != prevProps.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (this.props.credentials != prevProps.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
}, {
key: "render",
value: function render() {
var state = this.client.getState();
if (state === null) {
return React.createElement(loading);
}
var _board = null;
if (board) {
_board = React.createElement(board, _objectSpread2({}, state, {}, this.props, {
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
gameID: this.client.gameID,
playerID: this.client.playerID,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
gameMetadata: this.client.gameMetadata
}));
}
return React.createElement("div", {
className: "bgio-client"
}, _board);
}
}]);
return WrappedBoard;
}(React.Component), _defineProperty(_class, "propTypes", {
// The ID of a game to connect to.
// Only relevant in multiplayer.
gameID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string,
// Enable / disable the Debug UI.
debug: PropTypes.any
}), _defineProperty(_class, "defaultProps", {
gameID: 'default',
playerID: null,
credentials: null,
debug: true
}), _temp;
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
var _LobbyConnectionImpl =
/*#__PURE__*/
function () {
function _LobbyConnectionImpl(_ref) {
var server = _ref.server,
gameComponents = _ref.gameComponents,
playerName = _ref.playerName,
playerCredentials = _ref.playerCredentials;
_classCallCheck(this, _LobbyConnectionImpl);
this.gameComponents = gameComponents;
this.playerName = playerName || 'Visitor';
this.playerCredentials = playerCredentials;
this.server = server;
this.rooms = [];
}
_createClass(_LobbyConnectionImpl, [{
key: "_baseUrl",
value: function _baseUrl() {
return "".concat(this.server || '', "/games");
}
}, {
key: "refresh",
value: async function refresh() {
try {
this.rooms.length = 0;
var resp = await fetch(this._baseUrl());
if (resp.status !== 200) {
throw new Error('HTTP status ' + resp.status);
}
var json = await resp.json();
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = json[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var gameName = _step.value;
if (!this._getGameComponents(gameName)) continue;
var gameResp = await fetch(this._baseUrl() + '/' + gameName);
var gameJson = await gameResp.json();
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = gameJson.rooms[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var inst = _step2.value;
inst.gameName = gameName;
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
_iterator2["return"]();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this.rooms = this.rooms.concat(gameJson.rooms);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
} catch (error) {
throw new Error('failed to retrieve list of games (' + error + ')');
}
}
}, {
key: "_getGameInstance",
value: function _getGameInstance(gameID) {
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = this.rooms[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var inst = _step3.value;
if (inst['gameID'] === gameID) return inst;
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
_iterator3["return"]();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
}, {
key: "_getGameComponents",
value: function _getGameComponents(gameName) {
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = this.gameComponents[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var comp = _step4.value;
if (comp.game.name === gameName) return comp;
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
_iterator4["return"]();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
}
}, {
key: "_findPlayer",
value: function _findPlayer(playerName) {
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = this.rooms[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var inst = _step5.value;
if (inst.players.some(function (player) {
return player.name === playerName;
})) return inst;
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5["return"] != null) {
_iterator5["return"]();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
}
}, {
key: "join",
value: async function join(gameName, gameID, playerID) {
try {
var inst = this._findPlayer(this.playerName);
if (inst) {
throw new Error('player has already joined ' + inst.gameID);
}
inst = this._getGameInstance(gameID);
if (!inst) {
throw new Error('game instance ' + gameID + ' not found');
}
var resp = await fetch(this._baseUrl() + '/' + gameName + '/' + gameID + '/join', {
method: 'POST',
body: JSON.stringify({
playerID: playerID,
playerName: this.playerName
}),
headers: {
'Content-Type': 'application/json'
}
});
if (resp.status !== 200) throw new Error('HTTP status ' + resp.status);
var json = await resp.json();
inst.players[Number.parseInt(playerID)].name = this.playerName;
this.playerCredentials = json.playerCredentials;
} catch (error) {
throw new Error('failed to join room ' + gameID + ' (' + error + ')');
}
}
}, {
key: "leave",
value: async function leave(gameName, gameID) {
try {
var inst = this._getGameInstance(gameID);
if (!inst) throw new Error('game instance not found');
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
try {
for (var _iterator6 = inst.players[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var player = _step6.value;
if (player.name === this.playerName) {
var resp = await fetch(this._baseUrl() + '/' + gameName + '/' + gameID + '/leave', {
method: 'POST',
body: JSON.stringify({
playerID: player.id,
credentials: this.playerCredentials
}),
headers: {
'Content-Type': 'application/json'
}
});
if (resp.status !== 200) {
throw new Error('HTTP status ' + resp.status);
}
delete player.name;
delete this.playerCredentials;
return;
}
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6["return"] != null) {
_iterator6["return"]();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
throw new Error('player not found in room');
} catch (error) {
throw new Error('failed to leave room ' + gameID + ' (' + error + ')');
}
}
}, {
key: "disconnect",
value: async function disconnect() {
var inst = this._findPlayer(this.playerName);
if (inst) {
await this.leave(inst.gameName, inst.gameID);
}
this.rooms = [];
this.playerName = 'Visitor';
}
}, {
key: "create",
value: async function create(gameName, numPlayers) {
try {
var comp = this._getGameComponents(gameName);
if (!comp) throw new Error('game not found');
if (numPlayers < comp.game.minPlayers || numPlayers > comp.game.maxPlayers) throw new Error('invalid number of players ' + numPlayers);
var resp = await fetch(this._baseUrl() + '/' + gameName + '/create', {
method: 'POST',
body: JSON.stringify({
numPlayers: numPlayers
}),
headers: {
'Content-Type': 'application/json'
}
});
if (resp.status !== 200) throw new Error('HTTP status ' + resp.status);
} catch (error) {
throw new Error('failed to create room for ' + gameName + ' (' + error + ')');
}
}
}]);
return _LobbyConnectionImpl;
}();
/**
* LobbyConnection
*
* Lobby model.
*
* @param {string} server - '<host>:<port>' of the server.
* @param {Array} gameComponents - A map of Board and Game objects for the supported games.
* @param {string} playerName - The name of the player.
* @param {string} playerCredentials - The credentials currently used by the player, if any.
*
* Returns:
* A JS object that synchronizes the list of running game instances with the server and provides an API to create/join/start instances.
*/
function LobbyConnection(opts) {
return new _LobbyConnectionImpl(opts);
}
var LobbyLoginForm =
/*#__PURE__*/
function (_React$Component) {
_inherits(LobbyLoginForm, _React$Component);
function LobbyLoginForm() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, LobbyLoginForm);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(LobbyLoginForm)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "state", {
playerName: _this.props.playerName,
nameErrorMsg: ''
});
_defineProperty(_assertThisInitialized(_this), "onClickEnter", function () {
if (_this.state.playerName === '') return;
_this.props.onEnter(_this.state.playerName);
});
_defineProperty(_assertThisInitialized(_this), "onKeyPress", function (event) {
if (event.key === 'Enter') {
_this.onClickEnter();
}
});
_defineProperty(_assertThisInitialized(_this), "onChangePlayerName", function (event) {
var name = event.target.value.trim();
_this.setState({
playerName: name,
nameErrorMsg: name.length > 0 ? '' : 'empty player name'
});
});
return _this;
}
_createClass(LobbyLoginForm, [{
key: "render",
value: function render() {
return React.createElement("div", null, React.createElement("p", {
className: "phase-title"
}, "Choose a player name:"), React.createElement("input", {
type: "text",
value: this.state.playerName,
onChange: this.onChangePlayerName,
onKeyPress: this.onKeyPress
}), React.createElement("span", {
className: "buttons"
}, React.createElement("button", {
className: "buttons",
onClick: this.onClickEnter
}, "Enter")), React.createElement("br", null), React.createElement("span", {
className: "error-msg"
}, this.state.nameErrorMsg, React.createElement("br", null)));
}
}]);
return LobbyLoginForm;
}(React.Component);
_defineProperty(LobbyLoginForm, "propTypes", {
playerName: PropTypes.string,
onEnter: PropTypes.func.isRequired
});
_defineProperty(LobbyLoginForm, "defaultProps", {
playerName: ''
});
var LobbyRoomInstance =
/*#__PURE__*/
function (_React$Component) {
_inherits(LobbyRoomInstance, _React$Component);
function LobbyRoomInstance() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, LobbyRoomInstance);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(LobbyRoomInstance)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "_createSeat", function (player) {
return player.name || '[free]';
});
_defineProperty(_assertThisInitialized(_this), "_createButtonJoin", function (inst, seatId) {
return React.createElement("button", {
key: 'button-join-' + inst.gameID,
onClick: function onClick() {
return _this.props.onClickJoin(inst.gameName, inst.gameID, '' + seatId);
}
}, "Join");
});
_defineProperty(_assertThisInitialized(_this), "_createButtonLeave", function (inst) {
return React.createElement("button", {
key: 'button-leave-' + inst.gameID,
onClick: function onClick() {
return _this.props.onClickLeave(inst.gameName, inst.gameID);
}
}, "Leave");
});
_defineProperty(_assertThisInitialized(_this), "_createButtonPlay", function (inst, seatId) {
return React.createElement("button", {
key: 'button-play-' + inst.gameID,
onClick: function onClick() {
return _this.props.onClickPlay(inst.gameName, {
gameID: inst.gameID,
playerID: '' + seatId,
numPlayers: inst.players.length
});
}
}, "Play");
});
_defineProperty(_assertThisInitialized(_this), "_createButtonSpectate", function (inst) {
return React.createElement("button", {
key: 'button-spectate-' + inst.gameID,
onClick: function onClick() {
return _this.props.onClickPlay(inst.gameName, {
gameID: inst.gameID,
numPlayers: inst.players.length
});
}
}, "Spectate");
});
_defineProperty(_assertThisInitialized(_this), "_createInstanceButtons", function (inst) {
var playerSeat = inst.players.find(function (player) {
return player.name === _this.props.playerName;
});
var freeSeat = inst.players.find(function (player) {
return !player.name;
});
if (playerSeat && freeSeat) {
// already seated: waiting for game to start
return _this._createButtonLeave(inst);
}
if (freeSeat) {
// at least 1 seat is available
return _this._createButtonJoin(inst, freeSeat.id);
} // room is full
if (playerSeat) {
return React.createElement("div", null, [_this._createButtonPlay(inst, playerSeat.id), _this._createButtonLeave(inst)]);
} // allow spectating
return _this._createButtonSpectate(inst);
});
return _this;
}
_createClass(LobbyRoomInstance, [{
key: "render",
value: function render() {
var room = this.props.room;
var status = 'OPEN';
if (!room.players.find(function (player) {
return !player.name;
})) {
status = 'RUNNING';
}
return React.createElement("tr", {
key: 'line-' + room.gameID
}, React.createElement("td", {
key: 'cell-name-' + room.gameID
}, room.gameName), React.createElement("td", {
key: 'cell-status-' + room.gameID
}, status), React.createElement("td", {
key: 'cell-seats-' + room.gameID
}, room.players.map(this._createSeat).join(', ')), React.createElement("td", {
key: 'cell-buttons-' + room.gameID
}, this._createInstanceButtons(room)));
}
}]);
return LobbyRoomInstance;
}(React.Component);
_defineProperty(LobbyRoomInstance, "propTypes", {
room: PropTypes.shape({
gameName: PropTypes.string.isRequired,
gameID: PropTypes.string.isRequired,
players: PropTypes.array.isRequired
}),
playerName: PropTypes.string.isRequired,
onClickJoin: PropTypes.func.isRequired,
onClickLeave: PropTypes.func.isRequired,
onClickPlay: PropTypes.func.isRequired
});
var LobbyCreateRoomForm =
/*#__PURE__*/
function (_React$Component) {
_inherits(LobbyCreateRoomForm, _React$Component);
function LobbyCreateRoomForm(props) {
var _this;
_classCallCheck(this, LobbyCreateRoomForm);
_this = _possibleConstructorReturn(this, _getPrototypeOf(LobbyCreateRoomForm).call(this, props));
/* fix min and max number of players */
_defineProperty(_assertThisInitialized(_this), "state", {
selectedGame: 0,
numPlayers: 2
});
_defineProperty(_assertThisInitialized(_this), "_createGameNameOption", function (game, idx) {
return React.createElement("option", {
key: 'name-option-' + idx,
value: idx
}, game.game.name);
});
_defineProperty(_assertThisInitialized(_this), "_createNumPlayersOption", function (idx) {
return React.createElement("option", {
key: 'num-option-' + idx,
value: idx
}, idx);
});
_defineProperty(_assertThisInitialized(_this), "_createNumPlayersRange", function (game) {
return _toConsumableArray(new Array(game.maxPlayers + 1).keys()).slice(game.minPlayers);
});
_defineProperty(_assertThisInitialized(_this), "onChangeNumPlayers", function (event) {
_this.setState({
numPlayers: Number.parseInt(event.target.value)
});
});
_defineProperty(_assertThisInitialized(_this), "onChangeSelectedGame", function (event) {
var idx = Number.parseInt(event.target.value);
_this.setState({
selectedGame: idx,
numPlayers: _this.props.games[idx].game.minPlayers
});
});
_defineProperty(_assertThisInitialized(_this), "onClickCreate", function () {
_this.props.createGame(_this.props.games[_this.state.selectedGame].game.name, _this.state.numPlayers);
});
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = props.games[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var game = _step.value;
var game_details = game.game;
if (!game_details.minPlayers) {
game_details.minPlayers = 1;
}
if (!game_details.maxPlayers) {
game_details.maxPlayers = 4;
}
console.assert(game_details.maxPlayers >= game_details.minPlayers);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
_this.state = {
selectedGame: 0,
numPlayers: props.games[0].game.minPlayers
};
return _this;
}
_createClass(LobbyCreateRoomForm, [{
key: "render",
value: function render() {
var _this2 = this;
return React.createElement("div", null, React.createElement("select", {
value: this.state.selectedGame,
onChange: function onChange(evt) {
return _this2.onChangeSelectedGame(evt);
}
}, this.props.games.map(this._createGameNameOption)), React.createElement("span", null, "Players:"), React.createElement("select", {
value: this.state.numPlayers,
onChange: this.onChangeNumPlayers
}, this._createNumPlayersRange(this.props.games[this.state.selectedGame].game).map(this._createNumPlayersOption)), React.createElement("span", {
className: "buttons"
}, React.createElement("button", {
onClick: this.onClickCreate
}, "Create")));
}
}]);
return LobbyCreateRoomForm;
}(React.Component);
_defineProperty(LobbyCreateRoomForm, "propTypes", {
games: PropTypes.array.isRequired,
createGame: PropTypes.func.isRequired
});
var LobbyPhases = {
ENTER: 'enter',
PLAY: 'play',
LIST: 'list'
};
/**
* Lobby
*
* React lobby component.
*
* @param {Array} gameComponents - An array of Board and Game objects for the supported games.
* @param {string} lobbyServer - Address of the lobby server (for example 'localhost:8000').
* If not set, defaults to the server that served the page.
* @param {string} gameServer - Address of the game server (for example 'localhost:8001').
* If not set, defaults to the server that served the page.
* @param {function} clientFactory - Function that is used to create the game clients.
* @param {number} refreshInterval - Interval between server updates (default: 2000ms).
* @param {bool} debug - Enable debug information (default: false).
*
* Returns:
* A React component that provides a UI to create, list, join, leave, play or spectate game instances.
*/
var Lobby =
/*#__PURE__*/
function (_React$Component) {
_inherits(Lobby, _React$Component);
function Lobby(_props) {
var _this;
_classCallCheck(this, Lobby);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Lobby).call(this, _props));
_defineProperty(_assertThisInitialized(_this), "state", {
phase: LobbyPhases.ENTER,
playerName: 'Visitor',
runningGame: null,
errorMsg: '',
credentialStore: {}
});
_defineProperty(_assertThisInitialized(_this), "_createConnection", function (props) {
var name = _this.state.playerName;
_this.connection = LobbyConnection({
server: props.lobbyServer,
gameComponents: props.gameComponents,
playerName: name,
playerCredentials: _this.state.credentialStore[name]
});
});
_defineProperty(_assertThisInitialized(_this), "_updateCredentials", function (playerName, credentials) {
_this.setState(function (prevState) {
// clone store or componentDidUpdate will not be triggered
var store = Object.assign({}, prevState.credentialStore);
store[[playerName]] = credentials;
return {
credentialStore: store
};
});
});
_defineProperty(_assertThisInitialized(_this), "_updateConnection", async function () {
await _this.connection.refresh();
_this.forceUpdate();
});
_defineProperty(_assertThisInitialized(_this), "_enterLobby", function (playerName) {
_this.setState({
playerName: playerName,
phase: LobbyPhases.LIST
});
});
_defineProperty(_assertThisInitialized(_this), "_exitLobby", async function () {
await _this.connection.disconnect();
_this.setState({
phase: LobbyPhases.ENTER,
errorMsg: ''
});
});
_defineProperty(_assertThisInitialized(_this), "_createRoom", async function (gameName, numPlayers) {
try {
await _this.connection.create(gameName, numPlayers);
await _this.connection.refresh(); // rerender
_this.setState({});
} catch (error) {
_this.setState({
errorMsg: error.message
});
}
});
_defineProperty(_assertThisInitialized(_this), "_joinRoom", async function (gameName, gameID, playerID) {
try {
await _this.connection.join(gameName, gameID, playerID);
await _this.connection.refresh();
_this._updateCredentials(_this.connection.playerName, _this.connection.playerCredentials);
} catch (error) {
_this.setState({
errorMsg: error.message
});
}
});
_defineProperty(_assertThisInitialized(_this), "_leaveRoom", async function (gameName, gameID) {
try {
await _this.connection.leave(gameName, gameID);
await _this.connection.refresh();
_this._updateCredentials(_this.connection.playerName, _this.connection.playerCredentials);
} catch (error) {
_this.setState({
errorMsg: error.message
});
}
});
_defineProperty(_assertThisInitialized(_this), "_startGame", function (gameName, gameOpts) {
var gameCode = _this.connection._getGameComponents(gameName);
if (!gameCode) {
_this.setState({
errorMsg: 'game ' + gameName + ' not supported'
});
return;
}
var multiplayer = undefined;
if (gameOpts.numPlayers > 1) {
if (_this.props.gameServer) {
multiplayer = SocketIO({
server: _this.props.gameServer
});
} else {
multiplayer = SocketIO();
}
}
if (gameOpts.numPlayers == 1) {
var maxPlayers = gameCode.game.maxPlayers;
var bots = {};
for (var i = 1; i < maxPlayers; i++) {
bots[i + ''] = MCTSBot;
}
multiplayer = Local({
bots: bots
});
}
var app = _this.props.clientFactory({
game: gameCode.game,
board: gameCode.board,
debug: _this.props.debug,
multiplayer: multiplayer
});
var game = {
app: app,
gameID: gameOpts.gameID,
playerID: gameOpts.numPlayers > 1 ? gameOpts.playerID : '0',
credentials: _this.connection.playerCredentials
};
_this.setState({
phase: LobbyPhases.PLAY,
runningGame: game
});
});
_defineProperty(_assertThisInitialized(_this), "_exitRoom", function () {
_this.setState({
phase: LobbyPhases.LIST,
runningGame: null
});
});
_defineProperty(_assertThisInitialized(_this), "_getPhaseVisibility", function (phase) {
return _this.state.phase !== phase ? 'hidden' : 'phase';
});
_defineProperty(_assertThisInitialized(_this), "renderRooms", function (rooms, playerName) {
return rooms.map(function (room) {
var gameID = room.gameID,
gameName = room.gameName,
players = room.players;
return React.createElement(LobbyRoomInstance, {
key: 'instance-' + gameID,
room: {
gameID: gameID,
gameName: gameName,
players: Object.values(players)
},
playerName: playerName,
onClickJoin: _this._joinRoom,
onClickLeave: _this._leaveRoom,
onClickPlay: _this._startGame
});
});
});
_this._createConnection(_this.props);
setInterval(_this._updateConnection, _this.props.refreshInterval);
return _this;
}
_createClass(Lobby, [{
key: "componentDidMount",
value: function componentDidMount() {
var cookie = Cookies.load('lobbyState') || {};
if (cookie.phase && cookie.phase === LobbyPhases.PLAY) {
cookie.phase = LobbyPhases.LIST;
}
this.setState({
phase: cookie.phase || LobbyPhases.ENTER,
playerName: cookie.playerName || 'Visitor',
credentialStore: cookie.credentialStore || {}
});
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
var name = this.state.playerName;
var creds = this.state.credentialStore[name];
if (prevState.phase !== this.state.phase || prevState.credentialStore[name] !== creds || prevState.playerName !== name) {
this._createConnection(this.props);
this._updateConnection();
var cookie = {
phase: this.state.phase,
playerName: name,
credentialStore: this.state.credentialStore
};
Cookies.save('lobbyState', cookie, {
path: '/'
});
}
}
}, {
key: "render",
value: function render() {
var _this$props = this.props,
gameComponents = _this$props.gameComponents,
renderer = _this$props.renderer;
var _this$state = this.state,
errorMsg = _this$state.errorMsg,
playerName = _this$state.playerName,
phase = _this$state.phase,
runningGame = _this$state.runningGame;
if (renderer) {
return renderer({
errorMsg: errorMsg,
gameComponents: gameComponents,
rooms: this.connection.rooms,
phase: phase,
playerName: playerName,
runningGame: runningGame,
handleEnterLobby: this._enterLobby,
handleExitLobby: this._exitLobby,
handleCreateRoom: this._createRoom,
handleJoinRoom: this._joinRoom,
handleLeaveRoom: this._leaveRoom,
handleExitRoom: this._exitRoom,
handleRefreshRooms: this._updateConnection,
handleStartGame: this._startGame
});
}
return React.createElement("div", {
id: "lobby-view",
style: {
padding: 50
}
}, React.createElement("div", {
className: this._getPhaseVisibility(LobbyPhases.ENTER)
}, React.createElement(LobbyLoginForm, {
key: playerName,
playerName: playerName,
onEnter: this._enterLobby
})), React.createElement("div", {
className: this._getPhaseVisibility(LobbyPhases.LIST)
}, React.createElement("p", null, "Welcome, ", playerName), React.createElement("div", {
className: "phase-title",
id: "game-creation"
}, React.createElement("span", null, "Create a room:"), React.createElement(LobbyCreateRoomForm, {
games: gameComponents,
createGame: this._createRoom
})), React.createElement("p", {
className: "phase-title"
}, "Join a room:"), React.createElement("div", {
id: "instances"
}, React.createElement("table", null, React.createElement("tbody", null, this.renderRooms(this.connection.rooms, playerName))), React.createElement("span", {
className: "error-msg"
}, errorMsg, React.createElement("br", null))), React.createElement("p", {
className: "phase-title"
}, "Rooms that become empty are automatically deleted.")), React.createElement("div", {
className: this._getPhaseVisibility(LobbyPhases.PLAY)
}, runningGame && React.createElement(runningGame.app, {
gameID: runningGame.gameID,
playerID: runningGame.playerID,
credentials: runningGame.credentials
}), React.createElement("div", {
className: "buttons",
id: "game-exit"
}, React.createElement("button", {
onClick: this._exitRoom
}, "Exit game"))), React.createElement("div", {
className: "buttons",
id: "lobby-exit"
}, React.createElement("button", {
onClick: this._exitLobby
}, "Exit lobby")));
}
}]);
return Lobby;
}(React.Component);
_defineProperty(Lobby, "propTypes", {
gameComponents: PropTypes.array.isRequired,
lobbyServer: PropTypes.string,
gameServer: PropTypes.string,
debug: PropTypes.bool,
clientFactory: PropTypes.func,
refreshInterval: PropTypes.number
});
_defineProperty(Lobby, "defaultProps", {
debug: false,
clientFactory: Client,
refreshInterval: 2000
});
export { Client, Lobby };
|
ajax/libs/react-native-web/0.14.2/exports/createElement/index.js | cdnjs/cdnjs | /**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import AccessibilityUtil from '../../modules/AccessibilityUtil';
import createDOMProps from '../../modules/createDOMProps';
import React from 'react';
var createElement = function createElement(component, props) {
// Use equivalent platform elements where possible.
var accessibilityComponent;
if (component && component.constructor === String) {
accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props);
}
var Component = accessibilityComponent || component;
var domProps = createDOMProps(Component, props);
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
children[_key - 2] = arguments[_key];
}
return React.createElement.apply(React, [Component, domProps].concat(children));
};
export default createElement; |
ajax/libs/primereact/6.6.0-rc.1/blockui/blockui.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, ZIndexUtils, classNames, ObjectUtils, Portal } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var BlockUI = /*#__PURE__*/function (_Component) {
_inherits(BlockUI, _Component);
var _super = _createSuper(BlockUI);
function BlockUI(props) {
var _this;
_classCallCheck(this, BlockUI);
_this = _super.call(this, props);
_this.state = {
visible: props.blocked
};
_this.block = _this.block.bind(_assertThisInitialized(_this));
_this.unblock = _this.unblock.bind(_assertThisInitialized(_this));
_this.onPortalMounted = _this.onPortalMounted.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(BlockUI, [{
key: "block",
value: function block() {
this.setState({
visible: true
});
}
}, {
key: "unblock",
value: function unblock() {
var _this2 = this;
DomHandler.addClass(this.mask, 'p-component-overlay-leave');
this.mask.addEventListener('animationend', function () {
ZIndexUtils.clear(_this2.mask);
_this2.setState({
visible: false
}, function () {
_this2.props.fullScreen && DomHandler.removeClass(document.body, 'p-overflow-hidden');
_this2.props.onUnblocked && _this2.props.onUnblocked();
});
});
}
}, {
key: "onPortalMounted",
value: function onPortalMounted() {
if (this.props.fullScreen) {
DomHandler.addClass(document.body, 'p-overflow-hidden');
document.activeElement.blur();
}
if (this.props.autoZIndex) {
ZIndexUtils.set(this.props.fullScreen ? 'modal' : 'overlay', this.mask, this.props.baseZIndex);
}
this.props.onBlocked && this.props.onBlocked();
}
}, {
key: "renderMask",
value: function renderMask() {
var _this3 = this;
if (this.state.visible) {
var className = classNames('p-blockui p-component-overlay p-component-overlay-enter', {
'p-blockui-document': this.props.fullScreen
}, this.props.className);
var content = this.props.template ? ObjectUtils.getJSXElement(this.props.template, this.props) : null;
var mask = /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this3.mask = el;
},
className: className,
style: this.props.style
}, content);
return /*#__PURE__*/React.createElement(Portal, {
element: mask,
appendTo: this.props.fullScreen ? document.body : 'self',
onMounted: this.onPortalMounted
});
}
return null;
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.state.visible) {
this.block();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
if (prevProps.blocked !== this.props.blocked) {
this.props.blocked ? this.block() : this.unblock();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.props.fullScreen) {
DomHandler.removeClass(document.body, 'p-overflow-hidden');
}
ZIndexUtils.clear(this.mask);
}
}, {
key: "render",
value: function render() {
var _this4 = this;
var mask = this.renderMask();
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this4.container = el;
},
id: this.props.id,
className: "p-blockui-container"
}, this.props.children, mask);
}
}]);
return BlockUI;
}(Component);
_defineProperty(BlockUI, "defaultProps", {
id: null,
blocked: false,
fullScreen: false,
baseZIndex: 0,
autoZIndex: true,
style: null,
className: null,
template: null,
onBlocked: null,
onUnblocked: null
});
export { BlockUI };
|
ajax/libs/primereact/6.5.1/gmap/gmap.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var GMap = /*#__PURE__*/function (_Component) {
_inherits(GMap, _Component);
var _super = _createSuper(GMap);
function GMap() {
_classCallCheck(this, GMap);
return _super.apply(this, arguments);
}
_createClass(GMap, [{
key: "initMap",
value: function initMap() {
this.map = new google.maps.Map(this.container, this.props.options);
if (this.props.onMapReady) {
this.props.onMapReady({
map: this.map
});
}
this.initOverlays(this.props.overlays);
this.bindMapEvent('click', this.props.onMapClick);
this.bindMapEvent('dragend', this.props.onMapDragEnd);
this.bindMapEvent('zoom_changed', this.props.onZoomChanged);
}
}, {
key: "initOverlays",
value: function initOverlays(overlays) {
if (overlays) {
var _iterator = _createForOfIteratorHelper(overlays),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var overlay = _step.value;
overlay.setMap(this.map);
this.bindOverlayEvents(overlay);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
}
}, {
key: "bindOverlayEvents",
value: function bindOverlayEvents(overlay) {
var _this = this;
overlay.addListener('click', function (event) {
if (_this.props.onOverlayClick) {
_this.props.onOverlayClick({
originalEvent: event,
overlay: overlay,
map: _this.map
});
}
});
if (overlay.getDraggable()) {
this.bindDragEvents(overlay);
}
}
}, {
key: "bindDragEvents",
value: function bindDragEvents(overlay) {
this.bindDragEvent(overlay, 'dragstart', this.props.onOverlayDragStart);
this.bindDragEvent(overlay, 'drag', this.props.onOverlayDrag);
this.bindDragEvent(overlay, 'dragend', this.props.onOverlayDragEnd);
}
}, {
key: "bindMapEvent",
value: function bindMapEvent(eventName, callback) {
this.map.addListener(eventName, function (event) {
if (callback) {
callback(event);
}
});
}
}, {
key: "bindDragEvent",
value: function bindDragEvent(overlay, eventName, callback) {
var _this2 = this;
overlay.addListener(eventName, function (event) {
if (callback) {
callback({
originalEvent: event,
overlay: overlay,
map: _this2.map
});
}
});
}
}, {
key: "getMap",
value: function getMap() {
return this.map;
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState, snapshot) {
if (prevProps.overlays !== this.props.overlays) {
if (prevProps.overlays) {
var _iterator2 = _createForOfIteratorHelper(prevProps.overlays),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var overlay = _step2.value;
google.maps.event.clearInstanceListeners(overlay);
overlay.setMap(null);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
this.initOverlays(this.props.overlays);
}
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
this.initMap();
}
}, {
key: "render",
value: function render() {
var _this3 = this;
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this3.container = el;
},
style: this.props.style,
className: this.props.className
});
}
}]);
return GMap;
}(Component);
_defineProperty(GMap, "defaultProps", {
options: null,
overlays: null,
style: null,
className: null,
onMapReady: null,
onMapClick: null,
onMapDragEnd: null,
onZoomChanged: null,
onOverlayDragStart: null,
onOverlayDrag: null,
onOverlayDragEnd: null,
onOverlayClick: null
});
export { GMap };
|
ajax/libs/material-ui/4.10.2/es/utils/createSvgIcon.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import SvgIcon from '../SvgIcon';
/**
* Private module reserved for @material-ui/x packages.
*/
export default function createSvgIcon(path, displayName) {
const Component = (props, ref) => /*#__PURE__*/React.createElement(SvgIcon, _extends({
ref: ref
}, props), path);
if (process.env.NODE_ENV !== 'production') {
// Need to set `displayName` on the inner component for React.memo.
// React prior to 16.14 ignores `displayName` on the wrapper.
Component.displayName = `${displayName}Icon`;
}
Component.muiName = SvgIcon.muiName;
return /*#__PURE__*/React.memo( /*#__PURE__*/React.forwardRef(Component));
} |
ajax/libs/primereact/7.1.0/tooltip/tooltip.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { DomHandler, ZIndexUtils, ConnectedOverlayScrollHandler, classNames } from 'primereact/utils';
import { Portal } from 'primereact/portal';
import PrimeReact from 'primereact/api';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
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 tip(props) {
var appendTo = props.appendTo || document.body;
var tooltipWrapper = document.createDocumentFragment();
DomHandler.appendChild(tooltipWrapper, appendTo);
props = _objectSpread(_objectSpread({}, props), props.options);
var tooltipEl = /*#__PURE__*/React.createElement(Tooltip, props);
ReactDOM.render(tooltipEl, tooltipWrapper);
var updateTooltip = function updateTooltip(newProps) {
props = _objectSpread(_objectSpread({}, props), newProps);
ReactDOM.render( /*#__PURE__*/React.cloneElement(tooltipEl, props), tooltipWrapper);
};
return {
destroy: function destroy() {
ReactDOM.unmountComponentAtNode(tooltipWrapper);
},
updateContent: function updateContent(newContent) {
console.warn("The 'updateContent' method has been deprecated on Tooltip. Use update(newProps) method.");
updateTooltip({
content: newContent
});
},
update: function update(newProps) {
updateTooltip(newProps);
}
};
}
var Tooltip = /*#__PURE__*/function (_Component) {
_inherits(Tooltip, _Component);
var _super = _createSuper(Tooltip);
function Tooltip(props) {
var _this;
_classCallCheck(this, Tooltip);
_this = _super.call(this, props);
_this.state = {
visible: false,
position: _this.props.position
};
_this.show = _this.show.bind(_assertThisInitialized(_this));
_this.hide = _this.hide.bind(_assertThisInitialized(_this));
_this.onMouseEnter = _this.onMouseEnter.bind(_assertThisInitialized(_this));
_this.onMouseLeave = _this.onMouseLeave.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(Tooltip, [{
key: "isTargetContentEmpty",
value: function isTargetContentEmpty(target) {
return !(this.props.content || this.getTargetOption(target, 'tooltip'));
}
}, {
key: "isContentEmpty",
value: function isContentEmpty(target) {
return !(this.props.content || this.getTargetOption(target, 'tooltip') || this.props.children);
}
}, {
key: "isMouseTrack",
value: function isMouseTrack(target) {
return this.getTargetOption(target, 'mousetrack') || this.props.mouseTrack;
}
}, {
key: "isDisabled",
value: function isDisabled(target) {
return this.getTargetOption(target, 'disabled') === 'true' || this.hasTargetOption(target, 'disabled') || this.props.disabled;
}
}, {
key: "isShowOnDisabled",
value: function isShowOnDisabled(target) {
return this.getTargetOption(target, 'showondisabled') || this.props.showOnDisabled;
}
}, {
key: "isAutoHide",
value: function isAutoHide() {
return this.getTargetOption(this.currentTarget, 'autohide') || this.props.autoHide;
}
}, {
key: "getTargetOption",
value: function getTargetOption(target, option) {
if (this.hasTargetOption(target, "data-pr-".concat(option))) {
return target.getAttribute("data-pr-".concat(option));
}
return null;
}
}, {
key: "hasTargetOption",
value: function hasTargetOption(target, option) {
return target && target.hasAttribute(option);
}
}, {
key: "getEvents",
value: function getEvents(target) {
var showEvent = this.getTargetOption(target, 'showevent') || this.props.showEvent;
var hideEvent = this.getTargetOption(target, 'hideevent') || this.props.hideEvent;
if (this.isMouseTrack(target)) {
showEvent = 'mousemove';
hideEvent = 'mouseleave';
} else {
var event = this.getTargetOption(target, 'event') || this.props.event;
if (event === 'focus') {
showEvent = 'focus';
hideEvent = 'blur';
}
}
return {
showEvent: showEvent,
hideEvent: hideEvent
};
}
}, {
key: "getPosition",
value: function getPosition(target) {
return this.getTargetOption(target, 'position') || this.state.position;
}
}, {
key: "getMouseTrackPosition",
value: function getMouseTrackPosition(target) {
var top = this.getTargetOption(target, 'mousetracktop') || this.props.mouseTrackTop;
var left = this.getTargetOption(target, 'mousetrackleft') || this.props.mouseTrackLeft;
return {
top: top,
left: left
};
}
}, {
key: "updateText",
value: function updateText(target, callback) {
if (this.tooltipTextEl) {
var content = this.getTargetOption(target, 'tooltip') || this.props.content;
if (content) {
this.tooltipTextEl.innerHTML = ''; // remove children
this.tooltipTextEl.appendChild(document.createTextNode(content));
callback();
} else if (this.props.children) {
callback();
}
}
}
}, {
key: "show",
value: function show(e) {
var _this2 = this;
this.currentTarget = e.currentTarget;
var disabled = this.isDisabled(this.currentTarget);
var empty = this.isContentEmpty(this.isShowOnDisabled(this.currentTarget) && disabled ? this.currentTarget.firstChild : this.currentTarget);
if (empty || disabled) {
return;
}
var updateTooltipState = function updateTooltipState() {
_this2.updateText(_this2.currentTarget, function () {
if (_this2.props.autoZIndex && !ZIndexUtils.get(_this2.containerEl)) {
ZIndexUtils.set('tooltip', _this2.containerEl, PrimeReact.autoZIndex, _this2.props.baseZIndex || PrimeReact.zIndex['tooltip']);
}
_this2.containerEl.style.left = '';
_this2.containerEl.style.top = '';
if (_this2.isMouseTrack(_this2.currentTarget) && !_this2.containerSize) {
_this2.containerSize = {
width: DomHandler.getOuterWidth(_this2.containerEl),
height: DomHandler.getOuterHeight(_this2.containerEl)
};
}
_this2.align(_this2.currentTarget, {
x: e.pageX,
y: e.pageY
});
});
};
if (this.state.visible) {
this.applyDelay('updateDelay', updateTooltipState);
} else {
this.sendCallback(this.props.onBeforeShow, {
originalEvent: e,
target: this.currentTarget
});
this.applyDelay('showDelay', function () {
_this2.setState({
visible: true,
position: _this2.getPosition(_this2.currentTarget)
}, function () {
updateTooltipState();
_this2.sendCallback(_this2.props.onShow, {
originalEvent: e,
target: _this2.currentTarget
});
});
_this2.bindDocumentResizeListener();
_this2.bindScrollListener();
DomHandler.addClass(_this2.currentTarget, _this2.getTargetOption(_this2.currentTarget, 'classname'));
});
}
}
}, {
key: "hide",
value: function hide(e) {
var _this3 = this;
this.clearTimeouts();
if (this.state.visible) {
DomHandler.removeClass(this.currentTarget, this.getTargetOption(this.currentTarget, 'classname'));
this.sendCallback(this.props.onBeforeHide, {
originalEvent: e,
target: this.currentTarget
});
this.applyDelay('hideDelay', function () {
ZIndexUtils.clear(_this3.containerEl);
DomHandler.removeClass(_this3.containerEl, 'p-tooltip-active');
if (!_this3.isAutoHide() && _this3.allowHide === false) {
return;
}
_this3.setState({
visible: false,
position: _this3.props.position
}, function () {
if (_this3.tooltipTextEl) {
ReactDOM.unmountComponentAtNode(_this3.tooltipTextEl);
}
_this3.unbindDocumentResizeListener();
_this3.unbindScrollListener();
_this3.currentTarget = null;
_this3.scrollHandler = null;
_this3.containerSize = null;
_this3.allowHide = true;
_this3.sendCallback(_this3.props.onHide, {
originalEvent: e,
target: _this3.currentTarget
});
});
});
}
}
}, {
key: "align",
value: function align(target, coordinate) {
var _this4 = this;
var left = 0,
top = 0;
if (this.isMouseTrack(target) && coordinate) {
var containerSize = {
width: DomHandler.getOuterWidth(this.containerEl),
height: DomHandler.getOuterHeight(this.containerEl)
};
left = coordinate.x;
top = coordinate.y;
var _this$getMouseTrackPo = this.getMouseTrackPosition(target),
mouseTrackTop = _this$getMouseTrackPo.top,
mouseTrackLeft = _this$getMouseTrackPo.left;
switch (this.state.position) {
case 'left':
left -= containerSize.width + mouseTrackLeft;
top -= containerSize.height / 2 - mouseTrackTop;
break;
case 'right':
left += mouseTrackLeft;
top -= containerSize.height / 2 - mouseTrackTop;
break;
case 'top':
left -= containerSize.width / 2 - mouseTrackLeft;
top -= containerSize.height + mouseTrackTop;
break;
case 'bottom':
left -= containerSize.width / 2 - mouseTrackLeft;
top += mouseTrackTop;
break;
}
if (left <= 0 || this.containerSize.width > containerSize.width) {
this.containerEl.style.left = '0px';
this.containerEl.style.right = window.innerWidth - containerSize.width - left + 'px';
} else {
this.containerEl.style.right = '';
this.containerEl.style.left = left + 'px';
}
this.containerEl.style.top = top + 'px';
DomHandler.addClass(this.containerEl, 'p-tooltip-active');
} else {
var pos = DomHandler.findCollisionPosition(this.state.position);
var my = this.getTargetOption(target, 'my') || this.props.my || pos.my;
var at = this.getTargetOption(target, 'at') || this.props.at || pos.at;
this.containerEl.style.padding = '0px';
DomHandler.flipfitCollision(this.containerEl, target, my, at, function (currentPosition) {
var _currentPosition$at = currentPosition.at,
atX = _currentPosition$at.x,
atY = _currentPosition$at.y;
var myX = currentPosition.my.x;
var position = _this4.props.at ? atX !== 'center' && atX !== myX ? atX : atY : currentPosition.at["".concat(pos.axis)];
_this4.containerEl.style.padding = '';
_this4.setState({
position: position
}, function () {
_this4.updateContainerPosition();
DomHandler.addClass(_this4.containerEl, 'p-tooltip-active');
});
});
}
}
}, {
key: "updateContainerPosition",
value: function updateContainerPosition() {
if (this.containerEl) {
var style = getComputedStyle(this.containerEl);
if (this.state.position === 'left') this.containerEl.style.left = parseFloat(style.left) - parseFloat(style.paddingLeft) * 2 + 'px';else if (this.state.position === 'top') this.containerEl.style.top = parseFloat(style.top) - parseFloat(style.paddingTop) * 2 + 'px';
}
}
}, {
key: "onMouseEnter",
value: function onMouseEnter() {
if (!this.isAutoHide()) {
this.allowHide = false;
}
}
}, {
key: "onMouseLeave",
value: function onMouseLeave(e) {
if (!this.isAutoHide()) {
this.allowHide = true;
this.hide(e);
}
}
}, {
key: "bindDocumentResizeListener",
value: function bindDocumentResizeListener() {
var _this5 = this;
this.documentResizeListener = function (e) {
if (!DomHandler.isTouchDevice()) {
_this5.hide(e);
}
};
window.addEventListener('resize', this.documentResizeListener);
}
}, {
key: "unbindDocumentResizeListener",
value: function unbindDocumentResizeListener() {
if (this.documentResizeListener) {
window.removeEventListener('resize', this.documentResizeListener);
this.documentResizeListener = null;
}
}
}, {
key: "bindScrollListener",
value: function bindScrollListener() {
var _this6 = this;
if (!this.scrollHandler) {
this.scrollHandler = new ConnectedOverlayScrollHandler(this.currentTarget, function (e) {
if (_this6.state.visible) {
_this6.hide(e);
}
});
}
this.scrollHandler.bindScrollListener();
}
}, {
key: "unbindScrollListener",
value: function unbindScrollListener() {
if (this.scrollHandler) {
this.scrollHandler.unbindScrollListener();
}
}
}, {
key: "bindTargetEvent",
value: function bindTargetEvent(target) {
if (target) {
var _this$getEvents = this.getEvents(target),
showEvent = _this$getEvents.showEvent,
hideEvent = _this$getEvents.hideEvent;
var currentTarget = this.getTarget(target);
currentTarget.addEventListener(showEvent, this.show);
currentTarget.addEventListener(hideEvent, this.hide);
}
}
}, {
key: "unbindTargetEvent",
value: function unbindTargetEvent(target) {
if (target) {
var _this$getEvents2 = this.getEvents(target),
showEvent = _this$getEvents2.showEvent,
hideEvent = _this$getEvents2.hideEvent;
var currentTarget = this.getTarget(target);
currentTarget.removeEventListener(showEvent, this.show);
currentTarget.removeEventListener(hideEvent, this.hide);
}
}
}, {
key: "applyDelay",
value: function applyDelay(delayProp, callback) {
this.clearTimeouts();
var delay = this.getTargetOption(this.currentTarget, delayProp.toLowerCase()) || this.props[delayProp];
if (!!delay) {
this["".concat(delayProp, "Timeout")] = setTimeout(function () {
return callback();
}, delay);
} else {
callback();
}
}
}, {
key: "sendCallback",
value: function sendCallback(callback) {
if (callback) {
for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
callback.apply(void 0, params);
}
}
}, {
key: "clearTimeouts",
value: function clearTimeouts() {
clearTimeout(this.showDelayTimeout);
clearTimeout(this.updateDelayTimeout);
clearTimeout(this.hideDelayTimeout);
}
}, {
key: "getTarget",
value: function getTarget(target) {
if (target) {
if (this.isShowOnDisabled(target)) {
var wrapper = document.createElement('span');
target.parentNode.insertBefore(wrapper, target);
wrapper.appendChild(target);
return wrapper;
}
return target;
}
return null;
}
}, {
key: "updateTargetEvents",
value: function updateTargetEvents(target) {
this.unloadTargetEvents(target);
this.loadTargetEvents(target);
}
}, {
key: "loadTargetEvents",
value: function loadTargetEvents(target) {
this.setTargetEventOperations(target || this.props.target, 'bindTargetEvent');
}
}, {
key: "unloadTargetEvents",
value: function unloadTargetEvents(target) {
this.setTargetEventOperations(target || this.props.target, 'unbindTargetEvent');
}
}, {
key: "setTargetEventOperations",
value: function setTargetEventOperations(target, operation) {
var _this7 = this;
if (target) {
if (DomHandler.isElement(target)) {
this[operation](target);
} else {
var setEvent = function setEvent(target) {
var element = DomHandler.find(document, target);
element.forEach(function (el) {
_this7[operation](el);
});
};
if (target instanceof Array) {
target.forEach(function (t) {
setEvent(t);
});
} else {
setEvent(target);
}
}
}
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.props.target) {
this.loadTargetEvents();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
var _this8 = this;
if (prevProps.target !== this.props.target) {
this.unloadTargetEvents(prevProps.target);
this.loadTargetEvents();
}
if (this.state.visible) {
if (prevProps.content !== this.props.content) {
this.applyDelay('updateDelay', function () {
_this8.updateText(_this8.currentTarget, function () {
_this8.align(_this8.currentTarget);
});
});
}
if (this.currentTarget && this.isDisabled(this.currentTarget)) {
this.hide();
}
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.clearTimeouts();
this.unbindDocumentResizeListener();
this.unloadTargetEvents();
if (this.scrollHandler) {
this.scrollHandler.destroy();
this.scrollHandler = null;
}
ZIndexUtils.clear(this.containerEl);
}
}, {
key: "renderElement",
value: function renderElement() {
var _this9 = this;
var tooltipClassName = classNames('p-tooltip p-component', _defineProperty({}, "p-tooltip-".concat(this.state.position), true), this.props.className);
var isTargetContentEmpty = this.isTargetContentEmpty(this.currentTarget);
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
ref: function ref(el) {
return _this9.containerEl = el;
},
className: tooltipClassName,
style: this.props.style,
role: "tooltip",
"aria-hidden": this.state.visible,
onMouseEnter: this.onMouseEnter,
onMouseLeave: this.onMouseLeave
}, /*#__PURE__*/React.createElement("div", {
className: "p-tooltip-arrow"
}), /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this9.tooltipTextEl = el;
},
className: "p-tooltip-text"
}, isTargetContentEmpty && this.props.children));
}
}, {
key: "render",
value: function render() {
if (this.state.visible) {
var element = this.renderElement();
return /*#__PURE__*/React.createElement(Portal, {
element: element,
appendTo: this.props.appendTo,
visible: true
});
}
return null;
}
}]);
return Tooltip;
}(Component);
_defineProperty(Tooltip, "defaultProps", {
id: null,
target: null,
content: null,
disabled: false,
className: null,
style: null,
appendTo: null,
position: 'right',
my: null,
at: null,
event: null,
showEvent: 'mouseenter',
hideEvent: 'mouseleave',
autoZIndex: true,
baseZIndex: 0,
mouseTrack: false,
mouseTrackTop: 5,
mouseTrackLeft: 5,
showDelay: 0,
updateDelay: 0,
hideDelay: 0,
autoHide: true,
showOnDisabled: false,
onBeforeShow: null,
onBeforeHide: null,
onShow: null,
onHide: null
});
export { Tooltip, tip };
|
ajax/libs/react-native-web/0.0.0-dfb716c98/exports/Button/index.js | cdnjs/cdnjs | /**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import StyleSheet from '../StyleSheet';
import TouchableOpacity from '../TouchableOpacity';
import Text from '../Text';
import React from 'react';
export default function Button(props) {
var accessibilityLabel = props.accessibilityLabel,
color = props.color,
disabled = props.disabled,
onPress = props.onPress,
testID = props.testID,
title = props.title;
return React.createElement(TouchableOpacity, {
accessibilityLabel: accessibilityLabel,
accessibilityRole: "button",
disabled: disabled,
onPress: onPress,
style: [styles.button, color && {
backgroundColor: color
}, disabled && styles.buttonDisabled],
testID: testID
}, React.createElement(Text, {
style: [styles.text, disabled && styles.textDisabled]
}, title));
}
var styles = StyleSheet.create({
button: {
backgroundColor: '#2196F3',
borderRadius: 2
},
text: {
color: '#fff',
fontWeight: '500',
padding: 8,
textAlign: 'center',
textTransform: 'uppercase'
},
buttonDisabled: {
backgroundColor: '#dfdfdf'
},
textDisabled: {
color: '#a1a1a1'
}
}); |
ajax/libs/primereact/7.2.1/tieredmenu/tieredmenu.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, classNames, ObjectUtils, ZIndexUtils, ConnectedOverlayScrollHandler } from 'primereact/utils';
import { Ripple } from 'primereact/ripple';
import { CSSTransition } from 'primereact/csstransition';
import { OverlayService } from 'primereact/overlayservice';
import { Portal } from 'primereact/portal';
import PrimeReact from 'primereact/api';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var TieredMenuSub = /*#__PURE__*/function (_Component) {
_inherits(TieredMenuSub, _Component);
var _super = _createSuper$1(TieredMenuSub);
function TieredMenuSub(props) {
var _this;
_classCallCheck(this, TieredMenuSub);
_this = _super.call(this, props);
_this.state = {
activeItem: null
};
_this.onLeafClick = _this.onLeafClick.bind(_assertThisInitialized(_this));
_this.onChildItemKeyDown = _this.onChildItemKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(TieredMenuSub, [{
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.parentActive && !this.props.parentActive) {
this.setState({
activeItem: null
});
}
if (this.props.parentActive && !this.props.root) {
this.position();
}
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
if (!this.documentClickListener) {
this.documentClickListener = function (event) {
if (_this2.element && !_this2.element.contains(event.target)) {
_this2.setState({
activeItem: null
});
}
};
document.addEventListener('click', this.documentClickListener);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.documentClickListener) {
document.removeEventListener('click', this.documentClickListener);
this.documentClickListener = null;
}
}
}, {
key: "position",
value: function position() {
if (this.element) {
var parentItem = this.element.parentElement;
var containerOffset = DomHandler.getOffset(parentItem);
var viewport = DomHandler.getViewport();
var sublistWidth = this.element.offsetParent ? this.element.offsetWidth : DomHandler.getHiddenElementOuterWidth(this.element);
var itemOuterWidth = DomHandler.getOuterWidth(parentItem.children[0]);
if (parseInt(containerOffset.left, 10) + itemOuterWidth + sublistWidth > viewport.width - DomHandler.calculateScrollbarWidth()) {
DomHandler.addClass(this.element, 'p-submenu-list-flipped');
}
}
}
}, {
key: "onItemMouseEnter",
value: function onItemMouseEnter(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (this.props.root) {
if (this.state.activeItem || this.props.popup) {
this.setState({
activeItem: item
});
}
} else {
this.setState({
activeItem: item
});
}
}
}, {
key: "onItemClick",
value: function onItemClick(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (!item.url) {
event.preventDefault();
}
if (item.command) {
item.command({
originalEvent: event,
item: item
});
}
if (this.props.root) {
if (item.items) {
if (this.state.activeItem && item === this.state.activeItem) {
this.setState({
activeItem: null
});
} else {
this.setState({
activeItem: item
});
}
}
}
if (!item.items) {
this.onLeafClick();
}
}
}, {
key: "onItemKeyDown",
value: function onItemKeyDown(event, item) {
var listItem = event.currentTarget.parentElement;
switch (event.which) {
//down
case 40:
var nextItem = this.findNextItem(listItem);
if (nextItem) {
nextItem.children[0].focus();
}
event.preventDefault();
break;
//up
case 38:
var prevItem = this.findPrevItem(listItem);
if (prevItem) {
prevItem.children[0].focus();
}
event.preventDefault();
break;
//right
case 39:
if (item.items) {
this.setState({
activeItem: item
});
setTimeout(function () {
listItem.children[1].children[0].children[0].focus();
}, 50);
}
event.preventDefault();
break;
}
if (this.props.onKeyDown) {
this.props.onKeyDown(event, listItem);
}
}
}, {
key: "onChildItemKeyDown",
value: function onChildItemKeyDown(event, childListItem) {
//left
if (event.which === 37) {
this.setState({
activeItem: null
});
childListItem.parentElement.previousElementSibling.focus();
}
}
}, {
key: "findNextItem",
value: function findNextItem(item) {
var nextItem = item.nextElementSibling;
if (nextItem) return DomHandler.hasClass(nextItem, 'p-disabled') || !DomHandler.hasClass(nextItem, 'p-menuitem') ? this.findNextItem(nextItem) : nextItem;else return null;
}
}, {
key: "findPrevItem",
value: function findPrevItem(item) {
var prevItem = item.previousElementSibling;
if (prevItem) return DomHandler.hasClass(prevItem, 'p-disabled') || !DomHandler.hasClass(prevItem, 'p-menuitem') ? this.findPrevItem(prevItem) : prevItem;else return null;
}
}, {
key: "onLeafClick",
value: function onLeafClick() {
this.setState({
activeItem: null
});
if (this.props.onLeafClick) {
this.props.onLeafClick();
}
}
}, {
key: "renderSeparator",
value: function renderSeparator(index) {
return /*#__PURE__*/React.createElement("li", {
key: 'separator_' + index,
className: "p-menu-separator",
role: "separator"
});
}
}, {
key: "renderSubmenu",
value: function renderSubmenu(item) {
if (item.items) {
return /*#__PURE__*/React.createElement(TieredMenuSub, {
model: item.items,
onLeafClick: this.onLeafClick,
popup: this.props.popup,
onKeyDown: this.onChildItemKeyDown,
parentActive: item === this.state.activeItem
});
}
return null;
}
}, {
key: "renderMenuitem",
value: function renderMenuitem(item, index) {
var _this3 = this;
var active = this.state.activeItem === item;
var className = classNames('p-menuitem', {
'p-menuitem-active': active
}, item.className);
var linkClassName = classNames('p-menuitem-link', {
'p-disabled': item.disabled
});
var iconClassName = classNames('p-menuitem-icon', item.icon);
var submenuIconClassName = 'p-submenu-icon pi pi-angle-right';
var icon = item.icon && /*#__PURE__*/React.createElement("span", {
className: iconClassName
});
var label = item.label && /*#__PURE__*/React.createElement("span", {
className: "p-menuitem-text"
}, item.label);
var submenuIcon = item.items && /*#__PURE__*/React.createElement("span", {
className: submenuIconClassName
});
var submenu = this.renderSubmenu(item);
var content = /*#__PURE__*/React.createElement("a", {
href: item.url || '#',
className: linkClassName,
target: item.target,
role: "menuitem",
"aria-haspopup": item.items != null,
onClick: function onClick(event) {
return _this3.onItemClick(event, item);
},
onKeyDown: function onKeyDown(event) {
return _this3.onItemKeyDown(event, item);
},
"aria-disabled": item.disabled
}, icon, label, submenuIcon, /*#__PURE__*/React.createElement(Ripple, null));
if (item.template) {
var defaultContentOptions = {
onClick: function onClick(event) {
return _this3.onItemClick(event, item);
},
onKeyDown: function onKeyDown(event) {
return _this3.onItemKeyDown(event, item);
},
className: linkClassName,
labelClassName: 'p-menuitem-text',
iconClassName: iconClassName,
submenuIconClassName: submenuIconClassName,
element: content,
props: this.props,
active: active
};
content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions);
}
return /*#__PURE__*/React.createElement("li", {
key: item.label + '_' + index,
className: className,
style: item.style,
onMouseEnter: function onMouseEnter(event) {
return _this3.onItemMouseEnter(event, item);
},
role: "none"
}, content, submenu);
}
}, {
key: "renderItem",
value: function renderItem(item, index) {
if (item.separator) return this.renderSeparator(index);else return this.renderMenuitem(item, index);
}
}, {
key: "renderMenu",
value: function renderMenu() {
var _this4 = this;
if (this.props.model) {
return this.props.model.map(function (item, index) {
return _this4.renderItem(item, index);
});
}
return null;
}
}, {
key: "render",
value: function render() {
var _this5 = this;
var className = classNames({
'p-submenu-list': !this.props.root
});
var submenu = this.renderMenu();
return /*#__PURE__*/React.createElement("ul", {
ref: function ref(el) {
return _this5.element = el;
},
className: className,
role: this.props.root ? 'menubar' : 'menu',
"aria-orientation": "horizontal"
}, submenu);
}
}]);
return TieredMenuSub;
}(Component);
_defineProperty(TieredMenuSub, "defaultProps", {
model: null,
root: false,
className: null,
popup: false,
onLeafClick: null,
onKeyDown: null,
parentActive: false
});
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 TieredMenu = /*#__PURE__*/function (_Component) {
_inherits(TieredMenu, _Component);
var _super = _createSuper(TieredMenu);
function TieredMenu(props) {
var _this;
_classCallCheck(this, TieredMenu);
_this = _super.call(this, props);
_this.state = {
visible: !props.popup
};
_this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this));
_this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this));
_this.onExit = _this.onExit.bind(_assertThisInitialized(_this));
_this.onExited = _this.onExited.bind(_assertThisInitialized(_this));
_this.onPanelClick = _this.onPanelClick.bind(_assertThisInitialized(_this));
_this.menuRef = /*#__PURE__*/React.createRef();
return _this;
}
_createClass(TieredMenu, [{
key: "onPanelClick",
value: function onPanelClick(event) {
if (this.props.popup) {
OverlayService.emit('overlay-click', {
originalEvent: event,
target: this.target
});
}
}
}, {
key: "toggle",
value: function toggle(event) {
if (this.props.popup) {
if (this.state.visible) this.hide(event);else this.show(event);
}
}
}, {
key: "show",
value: function show(event) {
var _this2 = this;
this.target = event.currentTarget;
var currentEvent = event;
this.setState({
visible: true
}, function () {
if (_this2.props.onShow) {
_this2.props.onShow(currentEvent);
}
});
}
}, {
key: "hide",
value: function hide(event) {
var _this3 = this;
var currentEvent = event;
this.setState({
visible: false
}, function () {
if (_this3.props.onHide) {
_this3.props.onHide(currentEvent);
}
});
}
}, {
key: "onEnter",
value: function onEnter() {
if (this.props.autoZIndex) {
ZIndexUtils.set('menu', this.menuRef.current, PrimeReact.autoZIndex, this.props.baseZIndex || PrimeReact.zIndex['menu']);
}
DomHandler.absolutePosition(this.menuRef.current, this.target);
}
}, {
key: "onEntered",
value: function onEntered() {
this.bindDocumentListeners();
this.bindScrollListener();
}
}, {
key: "onExit",
value: function onExit() {
this.target = null;
this.unbindDocumentListeners();
this.unbindScrollListener();
}
}, {
key: "onExited",
value: function onExited() {
ZIndexUtils.clear(this.menuRef.current);
}
}, {
key: "bindDocumentListeners",
value: function bindDocumentListeners() {
this.bindDocumentClickListener();
this.bindDocumentResizeListener();
}
}, {
key: "unbindDocumentListeners",
value: function unbindDocumentListeners() {
this.unbindDocumentClickListener();
this.unbindDocumentResizeListener();
}
}, {
key: "bindDocumentClickListener",
value: function bindDocumentClickListener() {
var _this4 = this;
if (!this.documentClickListener) {
this.documentClickListener = function (event) {
if (_this4.props.popup && _this4.state.visible && _this4.menuRef.current && !_this4.menuRef.current.contains(event.target)) {
_this4.hide(event);
}
};
document.addEventListener('click', this.documentClickListener);
}
}
}, {
key: "unbindDocumentClickListener",
value: function unbindDocumentClickListener() {
if (this.documentClickListener) {
document.removeEventListener('click', this.documentClickListener);
this.documentClickListener = null;
}
}
}, {
key: "bindDocumentResizeListener",
value: function bindDocumentResizeListener() {
var _this5 = this;
if (!this.documentResizeListener) {
this.documentResizeListener = function (event) {
if (_this5.state.visible && !DomHandler.isTouchDevice()) {
_this5.hide(event);
}
};
window.addEventListener('resize', this.documentResizeListener);
}
}
}, {
key: "unbindDocumentResizeListener",
value: function unbindDocumentResizeListener() {
if (this.documentResizeListener) {
window.removeEventListener('resize', this.documentResizeListener);
this.documentResizeListener = null;
}
}
}, {
key: "bindScrollListener",
value: function bindScrollListener() {
var _this6 = this;
if (!this.scrollHandler) {
this.scrollHandler = new ConnectedOverlayScrollHandler(this.target, function (event) {
if (_this6.state.visible) {
_this6.hide(event);
}
});
}
this.scrollHandler.bindScrollListener();
}
}, {
key: "unbindScrollListener",
value: function unbindScrollListener() {
if (this.scrollHandler) {
this.scrollHandler.unbindScrollListener();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.unbindDocumentListeners();
if (this.scrollHandler) {
this.scrollHandler.destroy();
this.scrollHandler = null;
}
ZIndexUtils.clear(this.menuRef.current);
}
}, {
key: "renderElement",
value: function renderElement() {
var className = classNames('p-tieredmenu p-component', {
'p-tieredmenu-overlay': this.props.popup
}, this.props.className);
return /*#__PURE__*/React.createElement(CSSTransition, {
nodeRef: this.menuRef,
classNames: "p-connected-overlay",
"in": this.state.visible,
timeout: {
enter: 120,
exit: 100
},
options: this.props.transitionOptions,
unmountOnExit: true,
onEnter: this.onEnter,
onEntered: this.onEntered,
onExit: this.onExit,
onExited: this.onExited
}, /*#__PURE__*/React.createElement("div", {
ref: this.menuRef,
id: this.props.id,
className: className,
style: this.props.style,
onClick: this.onPanelClick
}, /*#__PURE__*/React.createElement(TieredMenuSub, {
model: this.props.model,
root: true,
popup: this.props.popup
})));
}
}, {
key: "render",
value: function render() {
var element = this.renderElement();
return this.props.popup ? /*#__PURE__*/React.createElement(Portal, {
element: element,
appendTo: this.props.appendTo
}) : element;
}
}]);
return TieredMenu;
}(Component);
_defineProperty(TieredMenu, "defaultProps", {
id: null,
model: null,
popup: false,
style: null,
className: null,
autoZIndex: true,
baseZIndex: 0,
appendTo: null,
transitionOptions: null,
onShow: null,
onHide: null
});
export { TieredMenu };
|
ajax/libs/material-ui/4.9.2/esm/Stepper/Stepper.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 Paper from '../Paper';
import StepConnector from '../StepConnector';
export var styles = {
/* Styles applied to the root element. */
root: {
display: 'flex',
padding: 24
},
/* Styles applied to the root element if `orientation="horizontal"`. */
horizontal: {
flexDirection: 'row',
alignItems: 'center'
},
/* Styles applied to the root element if `orientation="vertical"`. */
vertical: {
flexDirection: 'column'
},
/* Styles applied to the root element if `alternativeLabel={true}`. */
alternativeLabel: {
alignItems: 'flex-start'
}
};
var defaultConnector = React.createElement(StepConnector, null);
var Stepper = React.forwardRef(function Stepper(props, ref) {
var _props$activeStep = props.activeStep,
activeStep = _props$activeStep === void 0 ? 0 : _props$activeStep,
_props$alternativeLab = props.alternativeLabel,
alternativeLabel = _props$alternativeLab === void 0 ? false : _props$alternativeLab,
children = props.children,
classes = props.classes,
className = props.className,
_props$connector = props.connector,
connectorProp = _props$connector === void 0 ? defaultConnector : _props$connector,
_props$nonLinear = props.nonLinear,
nonLinear = _props$nonLinear === void 0 ? false : _props$nonLinear,
_props$orientation = props.orientation,
orientation = _props$orientation === void 0 ? 'horizontal' : _props$orientation,
other = _objectWithoutProperties(props, ["activeStep", "alternativeLabel", "children", "classes", "className", "connector", "nonLinear", "orientation"]);
var connector = React.isValidElement(connectorProp) ? React.cloneElement(connectorProp, {
orientation: orientation
}) : null;
var childrenArray = React.Children.toArray(children);
var steps = childrenArray.map(function (step, index) {
var controlProps = {
alternativeLabel: alternativeLabel,
connector: connectorProp,
last: index + 1 === childrenArray.length,
orientation: orientation
};
var state = {
index: index,
active: false,
completed: false,
disabled: false
};
if (activeStep === index) {
state.active = true;
} else if (!nonLinear && activeStep > index) {
state.completed = true;
} else if (!nonLinear && activeStep < index) {
state.disabled = true;
}
return [!alternativeLabel && connector && index !== 0 && React.cloneElement(connector, _extends({
key: index
}, state)), React.cloneElement(step, _extends({}, controlProps, {}, state, {}, step.props))];
});
return React.createElement(Paper, _extends({
square: true,
elevation: 0,
className: clsx(classes.root, classes[orientation], className, alternativeLabel && classes.alternativeLabel),
ref: ref
}, other), steps);
});
process.env.NODE_ENV !== "production" ? Stepper.propTypes = {
/**
* Set the active step (zero based index).
* Set to -1 to disable all the steps.
*/
activeStep: PropTypes.number,
/**
* If set to 'true' and orientation is horizontal,
* then the step label will be positioned under the icon.
*/
alternativeLabel: PropTypes.bool,
/**
* Two or more `<Step />` components.
*/
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,
/**
* An element to be placed between each step.
*/
connector: PropTypes.element,
/**
* If set the `Stepper` will not assist in controlling steps for linear flow.
*/
nonLinear: PropTypes.bool,
/**
* The stepper orientation (layout flow direction).
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical'])
} : void 0;
export default withStyles(styles, {
name: 'MuiStepper'
})(Stepper); |
ajax/libs/material-ui/5.0.0-alpha.19/modern/styles/useTheme.js | cdnjs/cdnjs | import { useTheme as useThemeWithoutDefault } from '@material-ui/styles';
import React from 'react';
import defaultTheme from './defaultTheme';
export default function useTheme() {
const theme = useThemeWithoutDefault() || defaultTheme;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useDebugValue(theme);
}
return theme;
} |
ajax/libs/react-native-web/0.0.0-583e16fa8/exports/ScrollView/index.js | cdnjs/cdnjs | function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import createReactClass from 'create-react-class';
import dismissKeyboard from '../../modules/dismissKeyboard';
import invariant from 'fbjs/lib/invariant';
import ScrollResponder from '../../modules/ScrollResponder';
import ScrollViewBase from './ScrollViewBase';
import StyleSheet from '../StyleSheet';
import View from '../View';
import React from 'react';
var emptyObject = {};
/* eslint-disable react/prefer-es6-class */
var ScrollView = createReactClass({
displayName: "ScrollView",
mixins: [ScrollResponder.Mixin],
getInitialState: function getInitialState() {
return this.scrollResponderMixinGetInitialState();
},
flashScrollIndicators: function flashScrollIndicators() {
this.scrollResponderFlashScrollIndicators();
},
setNativeProps: function setNativeProps(props) {
if (this._scrollNodeRef) {
this._scrollNodeRef.setNativeProps(props);
}
},
/**
* Returns a reference to the underlying scroll responder, which supports
* operations like `scrollTo`. All ScrollView-like components should
* implement this method so that they can be composed while providing access
* to the underlying scroll responder's methods.
*/
getScrollResponder: function getScrollResponder() {
return this;
},
getScrollableNode: function getScrollableNode() {
return this._scrollNodeRef;
},
getInnerViewNode: function getInnerViewNode() {
return this._innerViewRef;
},
/**
* Scrolls to a given x, y offset, either immediately or with a smooth animation.
* Syntax:
*
* scrollTo(options: {x: number = 0; y: number = 0; animated: boolean = true})
*
* Note: The weird argument signature is due to the fact that, for historical reasons,
* the function also accepts separate arguments as as alternative to the options object.
* This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.
*/
scrollTo: function scrollTo(y, x, animated) {
if (typeof y === 'number') {
console.warn('`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, animated: true})` instead.');
} else {
var _ref = y || emptyObject;
x = _ref.x;
y = _ref.y;
animated = _ref.animated;
}
this.getScrollResponder().scrollResponderScrollTo({
x: x || 0,
y: y || 0,
animated: animated !== false
});
},
/**
* If this is a vertical ScrollView scrolls to the bottom.
* If this is a horizontal ScrollView scrolls to the right.
*
* Use `scrollToEnd({ animated: true })` for smooth animated scrolling,
* `scrollToEnd({ animated: false })` for immediate scrolling.
* If no options are passed, `animated` defaults to true.
*/
scrollToEnd: function scrollToEnd(options) {
// Default to true
var animated = (options && options.animated) !== false;
var horizontal = this.props.horizontal;
var scrollResponder = this.getScrollResponder();
var scrollResponderNode = scrollResponder.scrollResponderGetScrollableNode();
var x = horizontal ? scrollResponderNode.scrollWidth : 0;
var y = horizontal ? 0 : scrollResponderNode.scrollHeight;
scrollResponder.scrollResponderScrollTo({
x: x,
y: y,
animated: animated
});
},
render: function render() {
var _this$props = this.props,
contentContainerStyle = _this$props.contentContainerStyle,
horizontal = _this$props.horizontal,
onContentSizeChange = _this$props.onContentSizeChange,
refreshControl = _this$props.refreshControl,
stickyHeaderIndices = _this$props.stickyHeaderIndices,
pagingEnabled = _this$props.pagingEnabled,
keyboardDismissMode = _this$props.keyboardDismissMode,
onScroll = _this$props.onScroll,
other = _objectWithoutPropertiesLoose(_this$props, ["contentContainerStyle", "horizontal", "onContentSizeChange", "refreshControl", "stickyHeaderIndices", "pagingEnabled", "keyboardDismissMode", "onScroll"]);
if (process.env.NODE_ENV !== 'production' && this.props.style) {
var style = StyleSheet.flatten(this.props.style);
var childLayoutProps = ['alignItems', 'justifyContent'].filter(function (prop) {
return style && style[prop] !== undefined;
});
invariant(childLayoutProps.length === 0, "ScrollView child layout (" + JSON.stringify(childLayoutProps) + ") " + 'must be applied through the contentContainerStyle prop.');
}
var contentSizeChangeProps = {};
if (onContentSizeChange) {
contentSizeChangeProps = {
onLayout: this._handleContentOnLayout
};
}
var hasStickyHeaderIndices = !horizontal && Array.isArray(stickyHeaderIndices);
var children = hasStickyHeaderIndices || pagingEnabled ? React.Children.map(this.props.children, function (child, i) {
var isSticky = hasStickyHeaderIndices && stickyHeaderIndices.indexOf(i) > -1;
if (child != null && (isSticky || pagingEnabled)) {
return React.createElement(View, {
style: StyleSheet.compose(isSticky && styles.stickyHeader, pagingEnabled && styles.pagingEnabledChild)
}, child);
} else {
return child;
}
}) : this.props.children;
var contentContainer = React.createElement(View, _extends({}, contentSizeChangeProps, {
children: children,
collapsable: false,
ref: this._setInnerViewRef,
style: StyleSheet.compose(horizontal && styles.contentContainerHorizontal, contentContainerStyle)
}));
var baseStyle = horizontal ? styles.baseHorizontal : styles.baseVertical;
var pagingEnabledStyle = horizontal ? styles.pagingEnabledHorizontal : styles.pagingEnabledVertical;
var props = _objectSpread({}, other, {
style: [baseStyle, pagingEnabled && pagingEnabledStyle, this.props.style],
onTouchStart: this.scrollResponderHandleTouchStart,
onTouchMove: this.scrollResponderHandleTouchMove,
onTouchEnd: this.scrollResponderHandleTouchEnd,
onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag,
onScrollEndDrag: this.scrollResponderHandleScrollEndDrag,
onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin,
onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd,
onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder,
onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture,
onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder,
onScroll: this._handleScroll,
onResponderGrant: this.scrollResponderHandleResponderGrant,
onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest,
onResponderTerminate: this.scrollResponderHandleTerminate,
onResponderRelease: this.scrollResponderHandleResponderRelease,
onResponderReject: this.scrollResponderHandleResponderReject
});
var ScrollViewClass = ScrollViewBase;
invariant(ScrollViewClass !== undefined, 'ScrollViewClass must not be undefined');
if (refreshControl) {
return React.cloneElement(refreshControl, {
style: props.style
}, React.createElement(ScrollViewClass, _extends({}, props, {
ref: this._setScrollNodeRef,
style: baseStyle
}), contentContainer));
}
return React.createElement(ScrollViewClass, _extends({}, props, {
ref: this._setScrollNodeRef
}), contentContainer);
},
_handleContentOnLayout: function _handleContentOnLayout(e) {
var _e$nativeEvent$layout = e.nativeEvent.layout,
width = _e$nativeEvent$layout.width,
height = _e$nativeEvent$layout.height;
this.props.onContentSizeChange(width, height);
},
_handleScroll: function _handleScroll(e) {
if (process.env.NODE_ENV !== 'production') {
if (this.props.onScroll && this.props.scrollEventThrottle == null) {
console.log('You specified `onScroll` on a <ScrollView> but not ' + '`scrollEventThrottle`. You will only receive one event. ' + 'Using `16` you get all the events but be aware that it may ' + "cause frame drops, use a bigger number if you don't need as " + 'much precision.');
}
}
if (this.props.keyboardDismissMode === 'on-drag') {
dismissKeyboard();
}
this.scrollResponderHandleScroll(e);
},
_setInnerViewRef: function _setInnerViewRef(component) {
this._innerViewRef = component;
},
_setScrollNodeRef: function _setScrollNodeRef(component) {
this._scrollNodeRef = component;
}
});
var commonStyle = {
flexGrow: 1,
flexShrink: 1,
// Enable hardware compositing in modern browsers.
// Creates a new layer with its own backing surface that can significantly
// improve scroll performance.
transform: [{
translateZ: 0
}],
// iOS native scrolling
WebkitOverflowScrolling: 'touch'
};
var styles = StyleSheet.create({
baseVertical: _objectSpread({}, commonStyle, {
flexDirection: 'column',
overflowX: 'hidden',
overflowY: 'auto'
}),
baseHorizontal: _objectSpread({}, commonStyle, {
flexDirection: 'row',
overflowX: 'auto',
overflowY: 'hidden'
}),
contentContainerHorizontal: {
flexDirection: 'row'
},
stickyHeader: {
position: 'sticky',
top: 0,
zIndex: 10
},
pagingEnabledHorizontal: {
scrollSnapType: 'x mandatory'
},
pagingEnabledVertical: {
scrollSnapType: 'y mandatory'
},
pagingEnabledChild: {
scrollSnapAlign: 'start'
}
});
export default ScrollView; |
ajax/libs/react-native-web/0.14.13/exports/YellowBox/index.js | cdnjs/cdnjs | /**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import React from 'react';
import UnimplementedView from '../../modules/UnimplementedView';
function YellowBox(props) {
return React.createElement(UnimplementedView, props);
}
YellowBox.ignoreWarnings = function () {};
export default YellowBox; |
ajax/libs/react-native-web/0.12.1/exports/CheckBox/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; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import applyNativeMethods from '../../modules/applyNativeMethods';
import createElement from '../createElement';
import StyleSheet from '../StyleSheet';
import UIManager from '../UIManager';
import View from '../View';
import React from 'react';
var CheckBox =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(CheckBox, _React$Component);
function CheckBox() {
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._handleChange = function (event) {
var _this$props = _this.props,
onChange = _this$props.onChange,
onValueChange = _this$props.onValueChange;
var value = event.nativeEvent.target.checked;
event.nativeEvent.value = value;
onChange && onChange(event);
onValueChange && onValueChange(value);
};
_this._setCheckboxRef = function (element) {
_this._checkboxElement = element;
};
return _this;
}
var _proto = CheckBox.prototype;
_proto.blur = function blur() {
UIManager.blur(this._checkboxElement);
};
_proto.focus = function focus() {
UIManager.focus(this._checkboxElement);
};
_proto.render = function render() {
var _this$props2 = this.props,
color = _this$props2.color,
disabled = _this$props2.disabled,
onChange = _this$props2.onChange,
onValueChange = _this$props2.onValueChange,
style = _this$props2.style,
value = _this$props2.value,
other = _objectWithoutPropertiesLoose(_this$props2, ["color", "disabled", "onChange", "onValueChange", "style", "value"]);
var fakeControl = React.createElement(View, {
style: [styles.fakeControl, value && styles.fakeControlChecked, // custom color
value && color && {
backgroundColor: color,
borderColor: color
}, disabled && styles.fakeControlDisabled, value && disabled && styles.fakeControlCheckedAndDisabled]
});
var nativeControl = createElement('input', {
checked: value,
disabled: disabled,
onChange: this._handleChange,
ref: this._setCheckboxRef,
style: [styles.nativeControl, styles.cursorInherit],
type: 'checkbox'
});
return React.createElement(View, _extends({}, other, {
style: [styles.root, style, disabled && styles.cursorDefault]
}), fakeControl, nativeControl);
};
return CheckBox;
}(React.Component);
CheckBox.displayName = 'CheckBox';
var styles = StyleSheet.create({
root: {
cursor: 'pointer',
height: 16,
userSelect: 'none',
width: 16
},
cursorDefault: {
cursor: 'default'
},
cursorInherit: {
cursor: 'inherit'
},
fakeControl: {
alignItems: 'center',
backgroundColor: '#fff',
borderColor: '#657786',
borderRadius: 2,
borderStyle: 'solid',
borderWidth: 2,
height: '100%',
justifyContent: 'center',
width: '100%'
},
fakeControlChecked: {
backgroundColor: '#009688',
backgroundImage: 'url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmVyc2lvbj0iMS4xIgogICB2aWV3Qm94PSIwIDAgMSAxIgogICBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWluWU1pbiBtZWV0Ij4KICA8cGF0aAogICAgIGQ9Ik0gMC4wNDAzODA1OSwwLjYyNjc3NjcgMC4xNDY0NDY2MSwwLjUyMDcxMDY4IDAuNDI5Mjg5MzIsMC44MDM1NTMzOSAwLjMyMzIyMzMsMC45MDk2MTk0MSB6IE0gMC4yMTcxNTcyOSwwLjgwMzU1MzM5IDAuODUzNTUzMzksMC4xNjcxNTcyOSAwLjk1OTYxOTQxLDAuMjczMjIzMyAwLjMyMzIyMzMsMC45MDk2MTk0MSB6IgogICAgIGlkPSJyZWN0Mzc4MCIKICAgICBzdHlsZT0iZmlsbDojZmZmZmZmO2ZpbGwtb3BhY2l0eToxO3N0cm9rZTpub25lIiAvPgo8L3N2Zz4K")',
backgroundRepeat: 'no-repeat',
borderColor: '#009688'
},
fakeControlDisabled: {
borderColor: '#CCD6DD'
},
fakeControlCheckedAndDisabled: {
backgroundColor: '#AAB8C2',
borderColor: '#AAB8C2'
},
nativeControl: _objectSpread({}, StyleSheet.absoluteFillObject, {
height: '100%',
margin: 0,
opacity: 0,
padding: 0,
width: '100%'
})
});
export default applyNativeMethods(CheckBox); |
ajax/libs/material-ui/4.9.2/esm/OutlinedInput/OutlinedInput.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { refType } from '@material-ui/utils';
import InputBase from '../InputBase';
import NotchedOutline from './NotchedOutline';
import withStyles from '../styles/withStyles';
export var styles = function styles(theme) {
var borderColor = theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)';
return {
/* Styles applied to the root element. */
root: {
position: 'relative',
borderRadius: theme.shape.borderRadius,
'&:hover $notchedOutline': {
borderColor: theme.palette.text.primary
},
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
'&:hover $notchedOutline': {
borderColor: borderColor
}
},
'&$focused $notchedOutline': {
borderColor: theme.palette.primary.main,
borderWidth: 2
},
'&$error $notchedOutline': {
borderColor: theme.palette.error.main
},
'&$disabled $notchedOutline': {
borderColor: theme.palette.action.disabled
}
},
/* Styles applied to the root element if the color is secondary. */
colorSecondary: {
'&$focused $notchedOutline': {
borderColor: theme.palette.secondary.main
}
},
/* Styles applied to the root element if the component is focused. */
focused: {},
/* Styles applied to the root element if `disabled={true}`. */
disabled: {},
/* Styles applied to the root element if `startAdornment` is provided. */
adornedStart: {
paddingLeft: 14
},
/* Styles applied to the root element if `endAdornment` is provided. */
adornedEnd: {
paddingRight: 14
},
/* Pseudo-class applied to the root element if `error={true}`. */
error: {},
/* Styles applied to the `input` element if `margin="dense"`. */
marginDense: {},
/* Styles applied to the root element if `multiline={true}`. */
multiline: {
padding: '18.5px 14px',
'&$marginDense': {
paddingTop: 10.5,
paddingBottom: 10.5
}
},
/* Styles applied to the `NotchedOutline` element. */
notchedOutline: {
borderColor: borderColor
},
/* Styles applied to the `input` element. */
input: {
padding: '18.5px 14px',
'&:-webkit-autofill': {
WebkitBoxShadow: theme.palette.type === 'dark' ? '0 0 0 100px #266798 inset' : null,
WebkitTextFillColor: theme.palette.type === 'dark' ? '#fff' : null,
borderRadius: 'inherit'
}
},
/* Styles applied to the `input` element if `margin="dense"`. */
inputMarginDense: {
paddingTop: 10.5,
paddingBottom: 10.5
},
/* Styles applied to the `input` element if `multiline={true}`. */
inputMultiline: {
padding: 0
},
/* Styles applied to the `input` element if `startAdornment` is provided. */
inputAdornedStart: {
paddingLeft: 0
},
/* Styles applied to the `input` element if `endAdornment` is provided. */
inputAdornedEnd: {
paddingRight: 0
}
};
};
var OutlinedInput = React.forwardRef(function OutlinedInput(props, ref) {
var classes = props.classes,
_props$fullWidth = props.fullWidth,
fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
_props$inputComponent = props.inputComponent,
inputComponent = _props$inputComponent === void 0 ? 'input' : _props$inputComponent,
label = props.label,
_props$labelWidth = props.labelWidth,
labelWidth = _props$labelWidth === void 0 ? 0 : _props$labelWidth,
_props$multiline = props.multiline,
multiline = _props$multiline === void 0 ? false : _props$multiline,
notched = props.notched,
_props$type = props.type,
type = _props$type === void 0 ? 'text' : _props$type,
other = _objectWithoutProperties(props, ["classes", "fullWidth", "inputComponent", "label", "labelWidth", "multiline", "notched", "type"]);
return React.createElement(InputBase, _extends({
renderSuffix: function renderSuffix(state) {
return React.createElement(NotchedOutline, {
className: classes.notchedOutline,
label: label,
labelWidth: labelWidth,
notched: typeof notched !== 'undefined' ? notched : Boolean(state.startAdornment || state.filled || state.focused)
});
},
classes: _extends({}, classes, {
root: clsx(classes.root, classes.underline),
notchedOutline: null
}),
fullWidth: fullWidth,
inputComponent: inputComponent,
multiline: multiline,
ref: ref,
type: type
}, other));
});
process.env.NODE_ENV !== "production" ? OutlinedInput.propTypes = {
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete: PropTypes.string,
/**
* If `true`, the `input` element will be focused during the first mount.
*/
autoFocus: PropTypes.bool,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* The CSS class name of the wrapper element.
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['primary', 'secondary']),
/**
* The default `input` element value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the `input` element will be disabled.
*/
disabled: PropTypes.bool,
/**
* End `InputAdornment` for this component.
*/
endAdornment: PropTypes.node,
/**
* If `true`, the input will indicate an error. This is normally obtained via context from
* FormControl.
*/
error: PropTypes.bool,
/**
* If `true`, the input will take up the full width of its container.
*/
fullWidth: PropTypes.bool,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* The component used for the native input.
* Either a string to use a DOM element or a component.
*/
inputComponent: PropTypes.elementType,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
*/
inputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* The label of the input. It is only used for layout. The actual labelling
* is handled by `InputLabel`. If specified `labelWidth` is ignored.
*/
label: PropTypes.node,
/**
* The width of the label. Is ignored if `label` is provided. Prefer `label`
* if the input label appears with a strike through.
*/
labelWidth: PropTypes.number,
/**
* If `dense`, will adjust vertical spacing. This is normally obtained via context from
* FormControl.
*/
margin: PropTypes.oneOf(['dense', 'none']),
/**
* If `true`, a textarea element will be rendered.
*/
multiline: PropTypes.bool,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
/**
* If `true`, the outline is notched to accommodate the label.
*/
notched: PropTypes.bool,
/**
* Callback fired when the value is changed.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* The short hint displayed in the input before the user enters a value.
*/
placeholder: PropTypes.string,
/**
* It prevents the user from changing the value of the field
* (not from interacting with the field).
*/
readOnly: PropTypes.bool,
/**
* If `true`, the `input` element will be required.
*/
required: PropTypes.bool,
/**
* Number of rows to display when multiline option is set to true.
*/
rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Maximum number of rows to display when multiline option is set to true.
*/
rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Start `InputAdornment` for this component.
*/
startAdornment: PropTypes.node,
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
*/
type: PropTypes.string,
/**
* The value of the `input` element, required for a controlled component.
*/
value: PropTypes.any
} : void 0;
OutlinedInput.muiName = 'Input';
export default withStyles(styles, {
name: 'MuiOutlinedInput'
})(OutlinedInput); |
ajax/libs/react-redux/7.1.0-alpha.4/react-redux.js | cdnjs/cdnjs | (function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('redux'), require('react-dom')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'redux', 'react-dom'], factory) :
(global = global || self, factory(global.ReactRedux = {}, global.React, global.Redux, global.ReactDOM));
}(this, function (exports, React, redux, reactDom) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var reactIs_development = createCommonjsModule(function (module, exports) {
{
(function() {
Object.defineProperty(exports, '__esModule', { value: true });
// 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;
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_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
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 || 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);
}
/**
* Forked from fbjs/warning:
* https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
*
* Only change is we use console.warn instead of console.error,
* and do nothing when 'console' is not supported.
* This really simplifies the code.
* ---
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var lowPriorityWarning = function () {};
{
var printWarning = function (format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.warn(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
lowPriorityWarning = function (condition, format) {
if (format === undefined) {
throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
var lowPriorityWarning$1 = lowPriorityWarning;
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_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
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;
lowPriorityWarning$1(false, '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.typeOf = typeOf;
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.isValidElementType = isValidElementType;
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;
})();
}
});
unwrapExports(reactIs_development);
var reactIs_development_1 = reactIs_development.typeOf;
var reactIs_development_2 = reactIs_development.AsyncMode;
var reactIs_development_3 = reactIs_development.ConcurrentMode;
var reactIs_development_4 = reactIs_development.ContextConsumer;
var reactIs_development_5 = reactIs_development.ContextProvider;
var reactIs_development_6 = reactIs_development.Element;
var reactIs_development_7 = reactIs_development.ForwardRef;
var reactIs_development_8 = reactIs_development.Fragment;
var reactIs_development_9 = reactIs_development.Lazy;
var reactIs_development_10 = reactIs_development.Memo;
var reactIs_development_11 = reactIs_development.Portal;
var reactIs_development_12 = reactIs_development.Profiler;
var reactIs_development_13 = reactIs_development.StrictMode;
var reactIs_development_14 = reactIs_development.Suspense;
var reactIs_development_15 = reactIs_development.isValidElementType;
var reactIs_development_16 = reactIs_development.isAsyncMode;
var reactIs_development_17 = reactIs_development.isConcurrentMode;
var reactIs_development_18 = reactIs_development.isContextConsumer;
var reactIs_development_19 = reactIs_development.isContextProvider;
var reactIs_development_20 = reactIs_development.isElement;
var reactIs_development_21 = reactIs_development.isForwardRef;
var reactIs_development_22 = reactIs_development.isFragment;
var reactIs_development_23 = reactIs_development.isLazy;
var reactIs_development_24 = reactIs_development.isMemo;
var reactIs_development_25 = reactIs_development.isPortal;
var reactIs_development_26 = reactIs_development.isProfiler;
var reactIs_development_27 = reactIs_development.isStrictMode;
var reactIs_development_28 = reactIs_development.isSuspense;
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_development;
}
});
var reactIs_1 = reactIs.isValidElementType;
var reactIs_2 = reactIs.isContextConsumer;
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
var printWarning = function() {};
{
var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
var loggedTypeFailures = {};
var has = Function.call.bind(Object.prototype.hasOwnProperty);
printWarning = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
{
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
var err = Error(
(componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.'
);
err.name = 'Invariant Violation';
throw err;
}
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
} catch (ex) {
error = ex;
}
if (error && !(error instanceof Error)) {
printWarning(
(componentName || 'React class') + ': type specification of ' +
location + ' `' + typeSpecName + '` is invalid; the type checker ' +
'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
'You may have forgotten to pass an argument to the type checker ' +
'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
'shape all require an argument).'
);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
printWarning(
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
);
}
}
}
}
}
/**
* Resets warning cache when testing.
*
* @private
*/
checkPropTypes.resetWarningCache = function() {
{
loggedTypeFailures = {};
}
};
var checkPropTypes_1 = checkPropTypes;
var has$1 = Function.call.bind(Object.prototype.hasOwnProperty);
var printWarning$1 = function() {};
{
printWarning$1 = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
function emptyFunctionThatReturnsNull() {
return null;
}
var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
elementType: createElementTypeTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker,
};
/**
* 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
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
{
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret_1) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
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;
} else if (typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
printWarning$1(
'You are manually calling a React.PropTypes validation ' +
'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunctionThatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!reactIs.isValidElementType(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
{
if (arguments.length > 1) {
printWarning$1(
'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +
'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'
);
} else {
printWarning$1('Invalid argument supplied to oneOf, expected an array.');
}
}
return emptyFunctionThatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
var type = getPreciseType(value);
if (type === 'symbol') {
return String(value);
}
return value;
});
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (has$1(propValue, key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
printWarning$1('Invalid argument supplied to oneOfType, expected an instance of array.');
return emptyFunctionThatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
printWarning$1(
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'
);
return emptyFunctionThatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
// We need to check all keys in case some are required but missing from
// props.
var allKeys = objectAssign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// falsy value can't be a Symbol
if (!propValue) {
return false;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes_1;
ReactPropTypes.resetWarningCache = checkPropTypes_1.resetWarningCache;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
var ReactIs = reactIs;
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess);
}
});
var ReactReduxContext = React__default.createContext(null);
// Default to a dummy "batch" implementation that just runs the callback
function defaultNoopBatch(callback) {
callback();
}
var batch = defaultNoopBatch; // Allow injecting another batching function later
var setBatch = function setBatch(newBatch) {
return batch = newBatch;
}; // Supply a getter just to skip dealing with ESM bindings
var getBatch = function getBatch() {
return batch;
};
// well as nesting subscriptions of descendant components, so that we can ensure the
// ancestor components re-render before descendants
var CLEARED = null;
var nullListeners = {
notify: function notify() {}
};
function createListenerCollection() {
var batch = getBatch(); // the current/next pattern is copied from redux's createStore code.
// TODO: refactor+expose that code to be reusable here?
var current = [];
var next = [];
return {
clear: function clear() {
next = CLEARED;
current = CLEARED;
},
notify: function notify() {
var listeners = current = next;
batch(function () {
for (var i = 0; i < listeners.length; i++) {
listeners[i]();
}
});
},
get: function get() {
return next;
},
subscribe: function subscribe(listener) {
var isSubscribed = true;
if (next === current) next = current.slice();
next.push(listener);
return function unsubscribe() {
if (!isSubscribed || current === CLEARED) return;
isSubscribed = false;
if (next === current) next = current.slice();
next.splice(next.indexOf(listener), 1);
};
}
};
}
var Subscription =
/*#__PURE__*/
function () {
function Subscription(store, parentSub) {
this.store = store;
this.parentSub = parentSub;
this.unsubscribe = null;
this.listeners = nullListeners;
this.handleChangeWrapper = this.handleChangeWrapper.bind(this);
}
var _proto = Subscription.prototype;
_proto.addNestedSub = function addNestedSub(listener) {
this.trySubscribe();
return this.listeners.subscribe(listener);
};
_proto.notifyNestedSubs = function notifyNestedSubs() {
this.listeners.notify();
};
_proto.handleChangeWrapper = function handleChangeWrapper() {
if (this.onStateChange) {
this.onStateChange();
}
};
_proto.isSubscribed = function isSubscribed() {
return Boolean(this.unsubscribe);
};
_proto.trySubscribe = function trySubscribe() {
if (!this.unsubscribe) {
this.unsubscribe = this.parentSub ? this.parentSub.addNestedSub(this.handleChangeWrapper) : this.store.subscribe(this.handleChangeWrapper);
this.listeners = createListenerCollection();
}
};
_proto.tryUnsubscribe = function tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
this.listeners.clear();
this.listeners = nullListeners;
}
};
return Subscription;
}();
var Provider =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Provider, _Component);
function Provider(props) {
var _this;
_this = _Component.call(this, props) || this;
var store = props.store;
_this.notifySubscribers = _this.notifySubscribers.bind(_assertThisInitialized(_this));
var subscription = new Subscription(store);
subscription.onStateChange = _this.notifySubscribers;
_this.state = {
store: store,
subscription: subscription
};
_this.previousState = store.getState();
return _this;
}
var _proto = Provider.prototype;
_proto.componentDidMount = function componentDidMount() {
this._isMounted = true;
this.state.subscription.trySubscribe();
if (this.previousState !== this.props.store.getState()) {
this.state.subscription.notifyNestedSubs();
}
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this.unsubscribe) this.unsubscribe();
this.state.subscription.tryUnsubscribe();
this._isMounted = false;
};
_proto.componentDidUpdate = function componentDidUpdate(prevProps) {
if (this.props.store !== prevProps.store) {
this.state.subscription.tryUnsubscribe();
var subscription = new Subscription(this.props.store);
subscription.onStateChange = this.notifySubscribers;
this.setState({
store: this.props.store,
subscription: subscription
});
}
};
_proto.notifySubscribers = function notifySubscribers() {
this.state.subscription.notifyNestedSubs();
};
_proto.render = function render() {
var Context = this.props.context || ReactReduxContext;
return React__default.createElement(Context.Provider, {
value: this.state
}, this.props.children);
};
return Provider;
}(React.Component);
Provider.propTypes = {
store: propTypes.shape({
subscribe: propTypes.func.isRequired,
dispatch: propTypes.func.isRequired,
getState: propTypes.func.isRequired
}),
context: propTypes.object,
children: propTypes.any
};
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 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;
function getStatics(component) {
if (reactIs.isMemo(component)) {
return MEMO_STATICS;
}
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols$1 = 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$1) {
keys = keys.concat(getOwnPropertySymbols$1(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;
}
return targetComponent;
}
var hoistNonReactStatics_cjs = hoistNonReactStatics;
/**
* 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 invariant = function(condition, format, a, b, c, d, e, f) {
{
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
var invariant_1 = invariant;
var EMPTY_ARRAY = [];
var NO_SUBSCRIPTION_ARRAY = [null, null];
var stringifyComponent = function stringifyComponent(Comp) {
try {
return JSON.stringify(Comp);
} catch (err) {
return String(Comp);
}
};
function storeStateUpdatesReducer(state, action) {
var updateCount = state[1];
return [action.payload, updateCount + 1];
}
var initStateUpdates = function initStateUpdates() {
return [null, 0];
}; // React currently throws a warning when using useLayoutEffect on the server.
// To get around it, we can conditionally useEffect on the server (no-op) and
// useLayoutEffect in the browser. We need useLayoutEffect because we want
// `connect` to perform sync updates to a ref to save the latest props after
// a render is actually committed to the DOM.
var useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
function connectAdvanced(
/*
selectorFactory is a func that is responsible for returning the selector function used to
compute new props from state, props, and dispatch. For example:
export default connectAdvanced((dispatch, options) => (state, props) => ({
thing: state.things[props.thingId],
saveThing: fields => dispatch(actionCreators.saveThing(props.thingId, fields)),
}))(YourComponent)
Access to dispatch is provided to the factory so selectorFactories can bind actionCreators
outside of their selector as an optimization. Options passed to connectAdvanced are passed to
the selectorFactory, along with displayName and WrappedComponent, as the second argument.
Note that selectorFactory is responsible for all caching/memoization of inbound and outbound
props. Do not use connectAdvanced directly without memoizing results between calls to your
selector, otherwise the Connect component will re-render on every state or props change.
*/
selectorFactory, // options object:
_ref) {
if (_ref === void 0) {
_ref = {};
}
var _ref2 = _ref,
_ref2$getDisplayName = _ref2.getDisplayName,
getDisplayName = _ref2$getDisplayName === void 0 ? function (name) {
return "ConnectAdvanced(" + name + ")";
} : _ref2$getDisplayName,
_ref2$methodName = _ref2.methodName,
methodName = _ref2$methodName === void 0 ? 'connectAdvanced' : _ref2$methodName,
_ref2$renderCountProp = _ref2.renderCountProp,
renderCountProp = _ref2$renderCountProp === void 0 ? undefined : _ref2$renderCountProp,
_ref2$shouldHandleSta = _ref2.shouldHandleStateChanges,
shouldHandleStateChanges = _ref2$shouldHandleSta === void 0 ? true : _ref2$shouldHandleSta,
_ref2$storeKey = _ref2.storeKey,
storeKey = _ref2$storeKey === void 0 ? 'store' : _ref2$storeKey,
_ref2$withRef = _ref2.withRef,
withRef = _ref2$withRef === void 0 ? false : _ref2$withRef,
_ref2$forwardRef = _ref2.forwardRef,
forwardRef = _ref2$forwardRef === void 0 ? false : _ref2$forwardRef,
_ref2$context = _ref2.context,
context = _ref2$context === void 0 ? ReactReduxContext : _ref2$context,
connectOptions = _objectWithoutPropertiesLoose(_ref2, ["getDisplayName", "methodName", "renderCountProp", "shouldHandleStateChanges", "storeKey", "withRef", "forwardRef", "context"]);
invariant_1(renderCountProp === undefined, "renderCountProp is removed. render counting is built into the latest React Dev Tools profiling extension");
invariant_1(!withRef, 'withRef is removed. To access the wrapped instance, use a ref on the connected component');
var customStoreWarningMessage = 'To use a custom Redux store for specific components, create a custom React context with ' + "React.createContext(), and pass the context object to React Redux's Provider and specific components" + ' like: <Provider context={MyContext}><ConnectedComponent context={MyContext} /></Provider>. ' + 'You may also pass a {context : MyContext} option to connect';
invariant_1(storeKey === 'store', 'storeKey has been removed and does not do anything. ' + customStoreWarningMessage);
var Context = context;
return function wrapWithConnect(WrappedComponent) {
{
invariant_1(reactIs_1(WrappedComponent), "You must pass a component to the function returned by " + (methodName + ". Instead received " + stringifyComponent(WrappedComponent)));
}
var wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
var displayName = getDisplayName(wrappedComponentName);
var selectorFactoryOptions = _extends({}, connectOptions, {
getDisplayName: getDisplayName,
methodName: methodName,
renderCountProp: renderCountProp,
shouldHandleStateChanges: shouldHandleStateChanges,
storeKey: storeKey,
displayName: displayName,
wrappedComponentName: wrappedComponentName,
WrappedComponent: WrappedComponent
});
var pure = connectOptions.pure;
function createChildSelector(store) {
return selectorFactory(store.dispatch, selectorFactoryOptions);
} // 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.
var usePureOnlyMemo = pure ? React.useMemo : function (callback) {
return callback();
};
function ConnectFunction(props) {
var _useMemo = React.useMemo(function () {
// 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.
var context = props.context,
forwardedRef = props.forwardedRef,
wrapperProps = _objectWithoutPropertiesLoose(props, ["context", "forwardedRef"]);
return [context, forwardedRef, wrapperProps];
}, [props]),
propsContext = _useMemo[0],
forwardedRef = _useMemo[1],
wrapperProps = _useMemo[2];
var ContextToUse = React.useMemo(function () {
// 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 && reactIs_2(React__default.createElement(propsContext.Consumer, null)) ? propsContext : Context;
}, [propsContext, Context]); // Retrieve the store and ancestor subscription via context, if available
var contextValue = React.useContext(ContextToUse); // The store _must_ exist as either a prop or in context
var didStoreComeFromProps = Boolean(props.store);
var didStoreComeFromContext = Boolean(contextValue) && Boolean(contextValue.store);
invariant_1(didStoreComeFromProps || didStoreComeFromContext, "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."));
var store = props.store || contextValue.store;
var childPropsSelector = React.useMemo(function () {
// The child props selector needs the store reference as an input.
// Re-create this selector whenever the store changes.
return createChildSelector(store);
}, [store]);
var _useMemo2 = React.useMemo(function () {
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.
var subscription = new Subscription(store, didStoreComeFromProps ? null : 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.
var notifyNestedSubs = subscription.notifyNestedSubs.bind(subscription);
return [subscription, notifyNestedSubs];
}, [store, didStoreComeFromProps, contextValue]),
subscription = _useMemo2[0],
notifyNestedSubs = _useMemo2[1]; // Determine what {store, subscription} value should be put into nested context, if necessary,
// and memoize that value to avoid unnecessary context updates.
var overriddenContextValue = React.useMemo(function () {
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: subscription
});
}, [didStoreComeFromProps, contextValue, subscription]); // We need to force this wrapper component to re-render whenever a Redux store update
// causes a change to the calculated child component props (or we caught an error in mapState)
var _useReducer = React.useReducer(storeStateUpdatesReducer, EMPTY_ARRAY, initStateUpdates),
_useReducer$ = _useReducer[0],
previousStateUpdateResult = _useReducer$[0],
forceComponentUpdateDispatch = _useReducer[1]; // Propagate any mapState/mapDispatch errors upwards
if (previousStateUpdateResult && previousStateUpdateResult.error) {
throw previousStateUpdateResult.error;
} // Set up refs to coordinate values between the subscription effect and the render logic
var lastChildProps = React.useRef();
var lastWrapperProps = React.useRef(wrapperProps);
var childPropsFromStoreUpdate = React.useRef();
var renderIsScheduled = React.useRef(false);
var actualChildProps = usePureOnlyMemo(function () {
// 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);
}, [store, previousStateUpdateResult, 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.
useIsomorphicLayoutEffect(function () {
// We want to capture the wrapper props and child props we used for later comparisons
lastWrapperProps.current = wrapperProps;
lastChildProps.current = actualChildProps;
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();
}
}); // Our re-subscribe logic only runs when the store/subscription setup changes
useIsomorphicLayoutEffect(function () {
// 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
var didUnsubscribe = false;
var lastThrownError = null; // We'll run this callback every time a store subscription update propagates to this component
var checkForUpdates = function checkForUpdates() {
if (didUnsubscribe) {
// Don't run stale listeners.
// Redux doesn't guarantee unsubscriptions happen until next dispatch.
return;
}
var latestStoreState = store.getState();
var 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; // If the child props _did_ change (or we caught an error), this wrapper component needs to re-render
forceComponentUpdateDispatch({
type: 'STORE_UPDATED',
payload: {
latestStoreState: latestStoreState,
error: error
}
});
}
}; // 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();
var unsubscribeWrapper = function unsubscribeWrapper() {
didUnsubscribe = true;
subscription.tryUnsubscribe();
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;
}, [store, subscription, childPropsSelector]); // 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.
var renderedWrappedComponent = React.useMemo(function () {
return React__default.createElement(WrappedComponent, _extends({}, actualChildProps, {
ref: forwardedRef
}));
}, [forwardedRef, 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.
var renderedChild = React.useMemo(function () {
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 React__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.
var Connect = pure ? React__default.memo(ConnectFunction) : ConnectFunction;
Connect.WrappedComponent = WrappedComponent;
Connect.displayName = displayName;
if (forwardRef) {
var forwarded = React__default.forwardRef(function forwardConnectRef(props, ref) {
return React__default.createElement(Connect, _extends({}, props, {
forwardedRef: ref
}));
});
forwarded.displayName = displayName;
forwarded.WrappedComponent = WrappedComponent;
return hoistNonReactStatics_cjs(forwarded, WrappedComponent);
}
return hoistNonReactStatics_cjs(Connect, WrappedComponent);
};
}
var hasOwn = Object.prototype.hasOwnProperty;
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;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return false;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
/**
* @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;
var proto = Object.getPrototypeOf(obj);
if (proto === null) return true;
var baseProto = proto;
while (Object.getPrototypeOf(baseProto) !== null) {
baseProto = Object.getPrototypeOf(baseProto);
}
return proto === baseProto;
}
/**
* 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 verifyPlainObject(value, displayName, methodName) {
if (!isPlainObject(value)) {
warning(methodName + "() in " + displayName + " must return a plain object. Instead received " + value + ".");
}
}
function wrapMapToPropsConstant(getConstant) {
return function initConstantSelector(dispatch, options) {
var constant = getConstant(dispatch, options);
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..
function getDependsOnOwnProps(mapToProps) {
return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? 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, _ref) {
var displayName = _ref.displayName;
var proxy = function mapToPropsProxy(stateOrDispatch, ownProps) {
return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch);
}; // allow detectFactoryAndVerify to get ownProps
proxy.dependsOnOwnProps = true;
proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) {
proxy.mapToProps = mapToProps;
proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps);
var 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(function (dispatch) {
return {
dispatch: dispatch
};
}) : undefined;
}
function whenMapDispatchToPropsIsObject(mapDispatchToProps) {
return mapDispatchToProps && typeof mapDispatchToProps === 'object' ? wrapMapToPropsConstant(function (dispatch) {
return redux.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(function () {
return {};
}) : undefined;
}
var defaultMapStateToPropsFactories = [whenMapStateToPropsIsFunction, whenMapStateToPropsIsMissing];
function defaultMergeProps(stateProps, dispatchProps, ownProps) {
return _extends({}, ownProps, stateProps, dispatchProps);
}
function wrapMergePropsFunc(mergeProps) {
return function initMergePropsProxy(dispatch, _ref) {
var displayName = _ref.displayName,
pure = _ref.pure,
areMergedPropsEqual = _ref.areMergedPropsEqual;
var hasRunOnce = false;
var mergedProps;
return function mergePropsProxy(stateProps, dispatchProps, ownProps) {
var nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps);
if (hasRunOnce) {
if (!pure || !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 ? function () {
return defaultMergeProps;
} : undefined;
}
var defaultMergePropsFactories = [whenMergePropsIsFunction, whenMergePropsIsOmitted];
function verify(selector, methodName, displayName) {
if (!selector) {
throw new Error("Unexpected value for " + methodName + " in " + displayName + ".");
} else if (methodName === 'mapStateToProps' || methodName === 'mapDispatchToProps') {
if (!selector.hasOwnProperty('dependsOnOwnProps')) {
warning("The selector for " + methodName + " of " + displayName + " did not specify a value for dependsOnOwnProps.");
}
}
}
function verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, displayName) {
verify(mapStateToProps, 'mapStateToProps', displayName);
verify(mapDispatchToProps, 'mapDispatchToProps', displayName);
verify(mergeProps, 'mergeProps', displayName);
}
function impureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch) {
return function impureFinalPropsSelector(state, ownProps) {
return mergeProps(mapStateToProps(state, ownProps), mapDispatchToProps(dispatch, ownProps), ownProps);
};
}
function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, _ref) {
var areStatesEqual = _ref.areStatesEqual,
areOwnPropsEqual = _ref.areOwnPropsEqual,
areStatePropsEqual = _ref.areStatePropsEqual;
var hasRunAtLeastOnce = false;
var state;
var ownProps;
var stateProps;
var dispatchProps;
var mergedProps;
function handleFirstCall(firstState, firstOwnProps) {
state = firstState;
ownProps = firstOwnProps;
stateProps = mapStateToProps(state, ownProps);
dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
hasRunAtLeastOnce = true;
return mergedProps;
}
function handleNewPropsAndNewState() {
stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewProps() {
if (mapStateToProps.dependsOnOwnProps) stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewState() {
var nextStateProps = mapStateToProps(state, ownProps);
var statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps);
stateProps = nextStateProps;
if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleSubsequentCalls(nextState, nextOwnProps) {
var propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps);
var 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
// If pure is true, the selector returned by selectorFactory will memoize its results,
// allowing connectAdvanced's shouldComponentUpdate to return false if final
// props have not changed. If false, the selector will always return a new
// object and shouldComponentUpdate will always return true.
function finalPropsSelectorFactory(dispatch, _ref2) {
var initMapStateToProps = _ref2.initMapStateToProps,
initMapDispatchToProps = _ref2.initMapDispatchToProps,
initMergeProps = _ref2.initMergeProps,
options = _objectWithoutPropertiesLoose(_ref2, ["initMapStateToProps", "initMapDispatchToProps", "initMergeProps"]);
var mapStateToProps = initMapStateToProps(dispatch, options);
var mapDispatchToProps = initMapDispatchToProps(dispatch, options);
var mergeProps = initMergeProps(dispatch, options);
{
verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, options.displayName);
}
var selectorFactory = options.pure ? pureFinalPropsSelectorFactory : impureFinalPropsSelectorFactory;
return selectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options);
}
/*
connect is a facade over connectAdvanced. It turns its args into a compatible
selectorFactory, which has the signature:
(dispatch, options) => (nextState, nextOwnProps) => nextFinalProps
connect passes its args to connectAdvanced as options, which will in turn pass them to
selectorFactory each time a Connect component instance is instantiated or hot reloaded.
selectorFactory returns a final props selector from its mapStateToProps,
mapStateToPropsFactories, mapDispatchToProps, mapDispatchToPropsFactories, mergeProps,
mergePropsFactories, and pure args.
The resulting final props selector is called by the Connect component instance whenever
it receives new props or store state.
*/
function match(arg, factories, name) {
for (var i = factories.length - 1; i >= 0; i--) {
var result = factories[i](arg);
if (result) return result;
}
return function (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;
} // createConnect with default args builds the 'official' connect behavior. Calling it with
// different options opens up some testing and extensibility scenarios
function createConnect(_temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$connectHOC = _ref.connectHOC,
connectHOC = _ref$connectHOC === void 0 ? connectAdvanced : _ref$connectHOC,
_ref$mapStateToPropsF = _ref.mapStateToPropsFactories,
mapStateToPropsFactories = _ref$mapStateToPropsF === void 0 ? defaultMapStateToPropsFactories : _ref$mapStateToPropsF,
_ref$mapDispatchToPro = _ref.mapDispatchToPropsFactories,
mapDispatchToPropsFactories = _ref$mapDispatchToPro === void 0 ? defaultMapDispatchToPropsFactories : _ref$mapDispatchToPro,
_ref$mergePropsFactor = _ref.mergePropsFactories,
mergePropsFactories = _ref$mergePropsFactor === void 0 ? defaultMergePropsFactories : _ref$mergePropsFactor,
_ref$selectorFactory = _ref.selectorFactory,
selectorFactory = _ref$selectorFactory === void 0 ? finalPropsSelectorFactory : _ref$selectorFactory;
return function connect(mapStateToProps, mapDispatchToProps, mergeProps, _ref2) {
if (_ref2 === void 0) {
_ref2 = {};
}
var _ref3 = _ref2,
_ref3$pure = _ref3.pure,
pure = _ref3$pure === void 0 ? true : _ref3$pure,
_ref3$areStatesEqual = _ref3.areStatesEqual,
areStatesEqual = _ref3$areStatesEqual === void 0 ? strictEqual : _ref3$areStatesEqual,
_ref3$areOwnPropsEqua = _ref3.areOwnPropsEqual,
areOwnPropsEqual = _ref3$areOwnPropsEqua === void 0 ? shallowEqual : _ref3$areOwnPropsEqua,
_ref3$areStatePropsEq = _ref3.areStatePropsEqual,
areStatePropsEqual = _ref3$areStatePropsEq === void 0 ? shallowEqual : _ref3$areStatePropsEq,
_ref3$areMergedPropsE = _ref3.areMergedPropsEqual,
areMergedPropsEqual = _ref3$areMergedPropsE === void 0 ? shallowEqual : _ref3$areMergedPropsE,
extraOptions = _objectWithoutPropertiesLoose(_ref3, ["pure", "areStatesEqual", "areOwnPropsEqual", "areStatePropsEqual", "areMergedPropsEqual"]);
var initMapStateToProps = match(mapStateToProps, mapStateToPropsFactories, 'mapStateToProps');
var initMapDispatchToProps = match(mapDispatchToProps, mapDispatchToPropsFactories, 'mapDispatchToProps');
var initMergeProps = match(mergeProps, mergePropsFactories, 'mergeProps');
return connectHOC(selectorFactory, _extends({
// used in error messages
methodName: 'connect',
// used to compute Connect's displayName from the wrapped component's displayName.
getDisplayName: function getDisplayName(name) {
return "Connect(" + name + ")";
},
// if mapStateToProps is falsy, the Connect component doesn't subscribe to store state changes
shouldHandleStateChanges: Boolean(mapStateToProps),
// passed through to selectorFactory
initMapStateToProps: initMapStateToProps,
initMapDispatchToProps: initMapDispatchToProps,
initMergeProps: initMergeProps,
pure: pure,
areStatesEqual: areStatesEqual,
areOwnPropsEqual: areOwnPropsEqual,
areStatePropsEqual: areStatePropsEqual,
areMergedPropsEqual: areMergedPropsEqual
}, extraOptions));
};
}
var connect = createConnect();
/**
* 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() {
var contextValue = React.useContext(ReactReduxContext);
invariant_1(contextValue, 'could not find react-redux context value; please ensure the component is wrapped in a <Provider>');
return contextValue;
}
/**
* 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>
* }
*/
function useStore() {
var _useReduxContext = useReduxContext(),
store = _useReduxContext.store;
return store;
}
/**
* A hook to access the redux `dispatch` function. Note that in most cases where you
* might want to use this hook it is recommended to use `useActions` instead to bind
* action creators to the `dispatch` function.
*
* @returns {any} redux store's `dispatch` function
*
* @example
*
* import React, { useCallback } from 'react'
* import { useReduxDispatch } 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>
* )
* }
*/
function useDispatch() {
var store = useStore();
return store.dispatch;
}
// 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
var useIsomorphicLayoutEffect$1 = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;
/**
* 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 a dependencies array as an optional second argument,
* which when passed ensures referential stability of the selector (this is primarily
* useful if you provide a selector that memoizes values).
*
* @param {Function} selector the selector function
* @param {any[]} deps (optional) dependencies array to control referential stability
* of the selector
*
* @returns {any} the selected state
*
* @example
*
* import React from 'react'
* import { useSelector } from 'react-redux'
* import { RootState } from './store'
*
* export const CounterComponent = () => {
* const counter = useSelector(state => state.counter, [])
* return <div>{counter}</div>
* }
*/
function useSelector(selector, deps) {
invariant_1(selector, "You must pass a selector to useSelectors");
var _useReduxContext = useReduxContext(),
store = _useReduxContext.store,
contextSub = _useReduxContext.subscription;
var _useReducer = React.useReducer(function (s) {
return s + 1;
}, 0),
forceRender = _useReducer[1];
var subscription = React.useMemo(function () {
return new Subscription(store, contextSub);
}, [store, contextSub]);
var memoizedSelector = React.useMemo(function () {
return selector;
}, deps);
var latestSubscriptionCallbackError = React.useRef();
var latestSelector = React.useRef(memoizedSelector);
var selectedState = undefined;
try {
selectedState = memoizedSelector(store.getState());
} catch (err) {
var errorMessage = "An error occured while selecting the store state: " + err.message + ".";
if (latestSubscriptionCallbackError.current) {
errorMessage += "\nThe error may be correlated with this previous error:\n" + latestSubscriptionCallbackError.current.stack + "\n\nOriginal stack trace:";
}
throw new Error(errorMessage);
}
var latestSelectedState = React.useRef(selectedState);
useIsomorphicLayoutEffect$1(function () {
latestSelector.current = memoizedSelector;
latestSelectedState.current = selectedState;
latestSubscriptionCallbackError.current = undefined;
});
useIsomorphicLayoutEffect$1(function () {
function checkForUpdates() {
try {
var newSelectedState = latestSelector.current(store.getState());
if (shallowEqual(newSelectedState, latestSelectedState.current)) {
return;
}
latestSelectedState.current = newSelectedState;
} catch (err) {
// we ignore all errors here, since when the component
// is re-rendered, the selectors are called again, and
// will throw again, if neither props nor store state
// changed
latestSubscriptionCallbackError.current = err;
}
forceRender({});
}
subscription.onStateChange = checkForUpdates;
subscription.trySubscribe();
checkForUpdates();
return function () {
return subscription.tryUnsubscribe();
};
}, [store, subscription]);
return selectedState;
}
/* eslint-disable import/no-unresolved */
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.connectAdvanced = connectAdvanced;
exports.useDispatch = useDispatch;
exports.useSelector = useSelector;
exports.useStore = useStore;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
ajax/libs/react-instantsearch/4.4.0/Dom.js | cdnjs/cdnjs | /*! ReactInstantSearch 4.4.0 | © Algolia, inc. | https://community.algolia.com/react-instantsearch */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Dom = {}),global.React));
}(this, (function (exports,React) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
// shim for using process in browser
// based off https://github.com/defunctzombie/node-process/blob/master/browser.js
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout() {
throw new Error('clearTimeout has not been defined');
}
var cachedSetTimeout = defaultSetTimout;
var cachedClearTimeout = defaultClearTimeout;
if (typeof global$1.setTimeout === 'function') {
cachedSetTimeout = setTimeout;
}
if (typeof global$1.clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
}
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
function nextTick(fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
}
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
var title = 'browser';
var platform = 'browser';
var browser = true;
var env = {};
var argv = [];
var version$1 = ''; // empty string to avoid regexp issues
var versions = {};
var release = {};
var config = {};
function noop() {}
var on = noop;
var addListener = noop;
var once = noop;
var off = noop;
var removeListener = noop;
var removeAllListeners = noop;
var emit = noop;
function binding(name) {
throw new Error('process.binding is not supported');
}
function cwd() {
return '/';
}
function chdir(dir) {
throw new Error('process.chdir is not supported');
}
function umask() {
return 0;
}
// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
var performance = global$1.performance || {};
var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () {
return new Date().getTime();
};
// generate timestamp or delta
// see http://nodejs.org/api/process.html#process_process_hrtime
function hrtime(previousTimestamp) {
var clocktime = performanceNow.call(performance) * 1e-3;
var seconds = Math.floor(clocktime);
var nanoseconds = Math.floor(clocktime % 1 * 1e9);
if (previousTimestamp) {
seconds = seconds - previousTimestamp[0];
nanoseconds = nanoseconds - previousTimestamp[1];
if (nanoseconds < 0) {
seconds--;
nanoseconds += 1e9;
}
}
return [seconds, nanoseconds];
}
var startTime = new Date();
function uptime() {
var currentTime = new Date();
var dif = currentTime - startTime;
return dif / 1000;
}
var process = {
nextTick: nextTick,
title: title,
browser: browser,
env: env,
argv: argv,
version: version$1,
versions: versions,
on: on,
addListener: addListener,
once: once,
off: off,
removeListener: removeListener,
removeAllListeners: removeAllListeners,
emit: emit,
binding: binding,
cwd: cwd,
chdir: chdir,
umask: umask,
hrtime: hrtime,
platform: platform,
release: release,
config: config,
uptime: uptime
};
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
var emptyFunction_1 = emptyFunction;
function invariant(condition, format, a, b, c, d, e, f) {
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
var invariant_1 = invariant;
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret_1) {
// It is still safe when called from React.
return;
}
invariant_1(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
}
shim.isRequired = shim;
function getShim() {
return shim;
}
// Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim
};
ReactPropTypes.checkPropTypes = emptyFunction_1;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = factoryWithThrowingShims();
}
});
/** Used for built-in method references. */
var objectProto$2 = 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$2;
return value === proto;
}
var _isPrototype = isPrototype;
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
var _overArg = overArg;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = _overArg(Object.keys, Object);
var _nativeKeys = nativeKeys;
/** Used for built-in method references. */
var objectProto$1 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$2 = objectProto$1.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$2.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
var _baseKeys = baseKeys;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
var _freeGlobal = freeGlobal;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = _freeGlobal || freeSelf || Function('return this')();
var _root = root;
/** Built-in value references. */
var Symbol$1 = _root.Symbol;
var _Symbol = Symbol$1;
/** Used for built-in method references. */
var objectProto$4 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$4 = objectProto$4.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto$4.toString;
/** Built-in value references. */
var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty$4.call(value, symToStringTag$1),
tag = value[symToStringTag$1];
try {
value[symToStringTag$1] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag$1] = tag;
} else {
delete value[symToStringTag$1];
}
}
return result;
}
var _getRawTag = getRawTag;
/** Used for built-in method references. */
var objectProto$5 = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString$1 = objectProto$5.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString$1.call(value);
}
var _objectToString = objectToString;
/** `Object#toString` result references. */
var nullTag = '[object Null]';
var undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? _getRawTag(value)
: _objectToString(value);
}
var _baseGetTag = baseGetTag;
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
var isObject_1 = isObject;
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]';
var funcTag = '[object Function]';
var genTag = '[object GeneratorFunction]';
var proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject_1(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = _baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var isFunction_1 = isFunction;
/** Used to detect overreaching core-js shims. */
var coreJsData = _root['__core-js_shared__'];
var _coreJsData = coreJsData;
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
var _isMasked = isMasked;
/** Used for built-in method references. */
var funcProto$1 = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString$1 = funcProto$1.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString$1.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
var _toSource = toSource;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto = Function.prototype;
var objectProto$3 = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty$3).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject_1(value) || _isMasked(value)) {
return false;
}
var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
return pattern.test(_toSource(value));
}
var _baseIsNative = baseIsNative;
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
var _getValue = getValue;
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = _getValue(object, key);
return _baseIsNative(value) ? value : undefined;
}
var _getNative = getNative;
/* Built-in method references that are verified to be native. */
var DataView = _getNative(_root, 'DataView');
var _DataView = DataView;
/* Built-in method references that are verified to be native. */
var Map = _getNative(_root, 'Map');
var _Map = Map;
/* Built-in method references that are verified to be native. */
var Promise$1 = _getNative(_root, 'Promise');
var _Promise = Promise$1;
/* Built-in method references that are verified to be native. */
var Set = _getNative(_root, 'Set');
var _Set = Set;
/* Built-in method references that are verified to be native. */
var WeakMap = _getNative(_root, 'WeakMap');
var _WeakMap = WeakMap;
/** `Object#toString` result references. */
var mapTag$1 = '[object Map]';
var objectTag = '[object Object]';
var promiseTag = '[object Promise]';
var setTag$1 = '[object Set]';
var weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = _toSource(_DataView);
var mapCtorString = _toSource(_Map);
var promiseCtorString = _toSource(_Promise);
var setCtorString = _toSource(_Set);
var weakMapCtorString = _toSource(_WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = _baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag) ||
(_Map && getTag(new _Map) != mapTag$1) ||
(_Promise && getTag(_Promise.resolve()) != promiseTag) ||
(_Set && getTag(new _Set) != setTag$1) ||
(_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$1;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag$1;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
var _getTag = getTag;
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
var isObjectLike_1 = isObjectLike;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
}
var _baseIsArguments = baseIsArguments;
/** Used for built-in method references. */
var objectProto$6 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
return isObjectLike_1(value) && hasOwnProperty$5.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
var isArguments_1 = isArguments;
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
var isArray_1 = isArray;
/** 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;
}
var isLength_1 = isLength;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength_1(value.length) && !isFunction_1(value);
}
var isArrayLike_1 = isArrayLike;
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
var stubFalse_1 = stubFalse;
var isBuffer_1 = createCommonjsModule(function (module, exports) {
/** Detect free variable `exports`. */
var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? _root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse_1;
module.exports = isBuffer;
});
/** `Object#toString` result references. */
var argsTag$1 = '[object Arguments]';
var arrayTag = '[object Array]';
var boolTag = '[object Boolean]';
var dateTag = '[object Date]';
var errorTag = '[object Error]';
var funcTag$1 = '[object Function]';
var mapTag$2 = '[object Map]';
var numberTag = '[object Number]';
var objectTag$1 = '[object Object]';
var regexpTag = '[object RegExp]';
var setTag$2 = '[object Set]';
var stringTag = '[object String]';
var weakMapTag$1 = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]';
var dataViewTag$1 = '[object DataView]';
var float32Tag = '[object Float32Array]';
var float64Tag = '[object Float64Array]';
var int8Tag = '[object Int8Array]';
var int16Tag = '[object Int16Array]';
var int32Tag = '[object Int32Array]';
var uint8Tag = '[object Uint8Array]';
var uint8ClampedTag = '[object Uint8ClampedArray]';
var uint16Tag = '[object Uint16Array]';
var uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =
typedArrayTags[mapTag$2] = typedArrayTags[numberTag] =
typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] =
typedArrayTags[setTag$2] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag$1] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike_1(value) &&
isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
}
var _baseIsTypedArray = baseIsTypedArray;
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
var _baseUnary = baseUnary;
var _nodeUtil = createCommonjsModule(function (module, exports) {
/** Detect free variable `exports`. */
var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && _freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
});
/* Node.js helper references. */
var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
var isTypedArray_1 = isTypedArray;
/** `Object#toString` result references. */
var mapTag = '[object Map]';
var setTag = '[object Set]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$1 = 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_1(value) &&
(isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) {
return !value.length;
}
var tag = _getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (_isPrototype(value)) {
return !_baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty$1.call(value, key)) {
return false;
}
}
return true;
}
var isEmpty_1 = isEmpty;
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
var _arrayMap = arrayMap;
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
var _listCacheClear = listCacheClear;
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
var eq_1 = eq;
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq_1(array[length][0], key)) {
return length;
}
}
return -1;
}
var _assocIndexOf = assocIndexOf;
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = _assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
var _listCacheDelete = listCacheDelete;
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = _assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
var _listCacheGet = listCacheGet;
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return _assocIndexOf(this.__data__, key) > -1;
}
var _listCacheHas = listCacheHas;
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = _assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
var _listCacheSet = listCacheSet;
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = _listCacheClear;
ListCache.prototype['delete'] = _listCacheDelete;
ListCache.prototype.get = _listCacheGet;
ListCache.prototype.has = _listCacheHas;
ListCache.prototype.set = _listCacheSet;
var _ListCache = ListCache;
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new _ListCache;
this.size = 0;
}
var _stackClear = stackClear;
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
var _stackDelete = stackDelete;
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
var _stackGet = stackGet;
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
var _stackHas = stackHas;
/* Built-in method references that are verified to be native. */
var nativeCreate = _getNative(Object, 'create');
var _nativeCreate = nativeCreate;
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
this.size = 0;
}
var _hashClear = hashClear;
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
var _hashDelete = hashDelete;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto$7 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (_nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty$6.call(data, key) ? data[key] : undefined;
}
var _hashGet = hashGet;
/** Used for built-in method references. */
var objectProto$8 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key);
}
var _hashHas = hashHas;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
return this;
}
var _hashSet = hashSet;
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = _hashClear;
Hash.prototype['delete'] = _hashDelete;
Hash.prototype.get = _hashGet;
Hash.prototype.has = _hashHas;
Hash.prototype.set = _hashSet;
var _Hash = Hash;
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new _Hash,
'map': new (_Map || _ListCache),
'string': new _Hash
};
}
var _mapCacheClear = mapCacheClear;
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
var _isKeyable = isKeyable;
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return _isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
var _getMapData = getMapData;
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = _getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
var _mapCacheDelete = mapCacheDelete;
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return _getMapData(this, key).get(key);
}
var _mapCacheGet = mapCacheGet;
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return _getMapData(this, key).has(key);
}
var _mapCacheHas = mapCacheHas;
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = _getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
var _mapCacheSet = mapCacheSet;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = _mapCacheClear;
MapCache.prototype['delete'] = _mapCacheDelete;
MapCache.prototype.get = _mapCacheGet;
MapCache.prototype.has = _mapCacheHas;
MapCache.prototype.set = _mapCacheSet;
var _MapCache = MapCache;
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof _ListCache) {
var pairs = data.__data__;
if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new _MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
var _stackSet = stackSet;
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new _ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = _stackClear;
Stack.prototype['delete'] = _stackDelete;
Stack.prototype.get = _stackGet;
Stack.prototype.has = _stackHas;
Stack.prototype.set = _stackSet;
var _Stack = Stack;
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
var _arrayEach = arrayEach;
var defineProperty = (function() {
try {
var func = _getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
var _defineProperty = defineProperty;
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && _defineProperty) {
_defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
var _baseAssignValue = baseAssignValue;
/** Used for built-in method references. */
var objectProto$9 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$8 = objectProto$9.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty$8.call(object, key) && eq_1(objValue, value)) ||
(value === undefined && !(key in object))) {
_baseAssignValue(object, key, value);
}
}
var _assignValue = assignValue;
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
_baseAssignValue(object, key, newValue);
} else {
_assignValue(object, key, newValue);
}
}
return object;
}
var _copyObject = copyObject;
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
var _baseTimes = baseTimes;
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER$1 = 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$1 : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
var _isIndex = isIndex;
/** Used for built-in method references. */
var objectProto$10 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$9 = objectProto$10.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray_1(value),
isArg = !isArr && isArguments_1(value),
isBuff = !isArr && !isArg && isBuffer_1(value),
isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? _baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty$9.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
_isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
var _arrayLikeKeys = arrayLikeKeys;
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
}
var keys_1 = keys;
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && _copyObject(source, keys_1(source), object);
}
var _baseAssign = baseAssign;
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
var _nativeKeysIn = nativeKeysIn;
/** Used for built-in method references. */
var objectProto$11 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$10 = objectProto$11.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject_1(object)) {
return _nativeKeysIn(object);
}
var isProto = _isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty$10.call(object, key)))) {
result.push(key);
}
}
return result;
}
var _baseKeysIn = baseKeysIn;
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn$1(object) {
return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
}
var keysIn_1 = keysIn$1;
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && _copyObject(source, keysIn_1(source), object);
}
var _baseAssignIn = baseAssignIn;
var _cloneBuffer = createCommonjsModule(function (module, exports) {
/** Detect free variable `exports`. */
var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? _root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
module.exports = cloneBuffer;
});
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
var _copyArray = copyArray;
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
var _arrayFilter = arrayFilter;
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
var stubArray_1 = stubArray;
/** Used for built-in method references. */
var objectProto$12 = Object.prototype;
/** Built-in value references. */
var propertyIsEnumerable$1 = objectProto$12.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return _arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable$1.call(object, symbol);
});
};
var _getSymbols = getSymbols;
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return _copyObject(source, _getSymbols(source), object);
}
var _copySymbols = copySymbols;
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
var _arrayPush = arrayPush;
/** Built-in value references. */
var getPrototype = _overArg(Object.getPrototypeOf, Object);
var _getPrototype = getPrototype;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
var result = [];
while (object) {
_arrayPush(result, _getSymbols(object));
object = _getPrototype(object);
}
return result;
};
var _getSymbolsIn = getSymbolsIn;
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return _copyObject(source, _getSymbolsIn(source), object);
}
var _copySymbolsIn = copySymbolsIn;
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
}
var _baseGetAllKeys = baseGetAllKeys;
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return _baseGetAllKeys(object, keys_1, _getSymbols);
}
var _getAllKeys = getAllKeys;
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
}
var _getAllKeysIn = getAllKeysIn;
/** Used for built-in method references. */
var objectProto$13 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$11 = objectProto$13.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$11.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
var _initCloneArray = initCloneArray;
/** Built-in value references. */
var Uint8Array = _root.Uint8Array;
var _Uint8Array = Uint8Array;
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
return result;
}
var _cloneArrayBuffer = cloneArrayBuffer;
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
var _cloneDataView = cloneDataView;
/**
* Adds the key-value `pair` to `map`.
*
* @private
* @param {Object} map The map to modify.
* @param {Array} pair The key-value pair to add.
* @returns {Object} Returns `map`.
*/
function addMapEntry(map, pair) {
// Don't return `map.set` because it's not chainable in IE 11.
map.set(pair[0], pair[1]);
return map;
}
var _addMapEntry = addMapEntry;
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
var _arrayReduce = arrayReduce;
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
var _mapToArray = mapToArray;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$2 = 1;
/**
* Creates a clone of `map`.
*
* @private
* @param {Object} map The map to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned map.
*/
function cloneMap(map, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(_mapToArray(map), CLONE_DEEP_FLAG$2) : _mapToArray(map);
return _arrayReduce(array, _addMapEntry, new map.constructor);
}
var _cloneMap = cloneMap;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
var _cloneRegExp = cloneRegExp;
/**
* Adds `value` to `set`.
*
* @private
* @param {Object} set The set to modify.
* @param {*} value The value to add.
* @returns {Object} Returns `set`.
*/
function addSetEntry(set, value) {
// Don't return `set.add` because it's not chainable in IE 11.
set.add(value);
return set;
}
var _addSetEntry = addSetEntry;
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
var _setToArray = setToArray;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$3 = 1;
/**
* Creates a clone of `set`.
*
* @private
* @param {Object} set The set to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned set.
*/
function cloneSet(set, isDeep, cloneFunc) {
var array = isDeep ? cloneFunc(_setToArray(set), CLONE_DEEP_FLAG$3) : _setToArray(set);
return _arrayReduce(array, _addSetEntry, new set.constructor);
}
var _cloneSet = cloneSet;
/** Used to convert symbols to primitives and strings. */
var symbolProto = _Symbol ? _Symbol.prototype : undefined;
var symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
var _cloneSymbol = cloneSymbol;
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
var _cloneTypedArray = cloneTypedArray;
/** `Object#toString` result references. */
var boolTag$2 = '[object Boolean]';
var dateTag$2 = '[object Date]';
var mapTag$4 = '[object Map]';
var numberTag$2 = '[object Number]';
var regexpTag$2 = '[object RegExp]';
var setTag$4 = '[object Set]';
var stringTag$2 = '[object String]';
var symbolTag$1 = '[object Symbol]';
var arrayBufferTag$2 = '[object ArrayBuffer]';
var dataViewTag$3 = '[object DataView]';
var float32Tag$2 = '[object Float32Array]';
var float64Tag$2 = '[object Float64Array]';
var int8Tag$2 = '[object Int8Array]';
var int16Tag$2 = '[object Int16Array]';
var int32Tag$2 = '[object Int32Array]';
var uint8Tag$2 = '[object Uint8Array]';
var uint8ClampedTag$2 = '[object Uint8ClampedArray]';
var uint16Tag$2 = '[object Uint16Array]';
var uint32Tag$2 = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {Function} cloneFunc The function to clone values.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, cloneFunc, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag$2:
return _cloneArrayBuffer(object);
case boolTag$2:
case dateTag$2:
return new Ctor(+object);
case dataViewTag$3:
return _cloneDataView(object, isDeep);
case float32Tag$2: case float64Tag$2:
case int8Tag$2: case int16Tag$2: case int32Tag$2:
case uint8Tag$2: case uint8ClampedTag$2: case uint16Tag$2: case uint32Tag$2:
return _cloneTypedArray(object, isDeep);
case mapTag$4:
return _cloneMap(object, isDeep, cloneFunc);
case numberTag$2:
case stringTag$2:
return new Ctor(object);
case regexpTag$2:
return _cloneRegExp(object);
case setTag$4:
return _cloneSet(object, isDeep, cloneFunc);
case symbolTag$1:
return _cloneSymbol(object);
}
}
var _initCloneByTag = initCloneByTag;
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject_1(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
var _baseCreate = baseCreate;
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !_isPrototype(object))
? _baseCreate(_getPrototype(object))
: {};
}
var _initCloneObject = initCloneObject;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$1 = 1;
var CLONE_FLAT_FLAG$1 = 2;
var CLONE_SYMBOLS_FLAG$1 = 4;
/** `Object#toString` result references. */
var argsTag$2 = '[object Arguments]';
var arrayTag$1 = '[object Array]';
var boolTag$1 = '[object Boolean]';
var dateTag$1 = '[object Date]';
var errorTag$1 = '[object Error]';
var funcTag$2 = '[object Function]';
var genTag$1 = '[object GeneratorFunction]';
var mapTag$3 = '[object Map]';
var numberTag$1 = '[object Number]';
var objectTag$2 = '[object Object]';
var regexpTag$1 = '[object RegExp]';
var setTag$3 = '[object Set]';
var stringTag$1 = '[object String]';
var symbolTag = '[object Symbol]';
var weakMapTag$2 = '[object WeakMap]';
var arrayBufferTag$1 = '[object ArrayBuffer]';
var dataViewTag$2 = '[object DataView]';
var float32Tag$1 = '[object Float32Array]';
var float64Tag$1 = '[object Float64Array]';
var int8Tag$1 = '[object Int8Array]';
var int16Tag$1 = '[object Int16Array]';
var int32Tag$1 = '[object Int32Array]';
var uint8Tag$1 = '[object Uint8Array]';
var uint8ClampedTag$1 = '[object Uint8ClampedArray]';
var uint16Tag$1 = '[object Uint16Array]';
var uint32Tag$1 = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] =
cloneableTags[arrayBufferTag$1] = cloneableTags[dataViewTag$2] =
cloneableTags[boolTag$1] = cloneableTags[dateTag$1] =
cloneableTags[float32Tag$1] = cloneableTags[float64Tag$1] =
cloneableTags[int8Tag$1] = cloneableTags[int16Tag$1] =
cloneableTags[int32Tag$1] = cloneableTags[mapTag$3] =
cloneableTags[numberTag$1] = cloneableTags[objectTag$2] =
cloneableTags[regexpTag$1] = cloneableTags[setTag$3] =
cloneableTags[stringTag$1] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag$1] = cloneableTags[uint8ClampedTag$1] =
cloneableTags[uint16Tag$1] = cloneableTags[uint32Tag$1] = true;
cloneableTags[errorTag$1] = cloneableTags[funcTag$2] =
cloneableTags[weakMapTag$2] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG$1,
isFlat = bitmask & CLONE_FLAT_FLAG$1,
isFull = bitmask & CLONE_SYMBOLS_FLAG$1;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject_1(value)) {
return value;
}
var isArr = isArray_1(value);
if (isArr) {
result = _initCloneArray(value);
if (!isDeep) {
return _copyArray(value, result);
}
} else {
var tag = _getTag(value),
isFunc = tag == funcTag$2 || tag == genTag$1;
if (isBuffer_1(value)) {
return _cloneBuffer(value, isDeep);
}
if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : _initCloneObject(value);
if (!isDeep) {
return isFlat
? _copySymbolsIn(value, _baseAssignIn(result, value))
: _copySymbols(value, _baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = _initCloneByTag(value, tag, baseClone, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new _Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
var keysFunc = isFull
? (isFlat ? _getAllKeysIn : _getAllKeys)
: (isFlat ? keysIn : keys_1);
var props = isArr ? undefined : keysFunc(value);
_arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
_assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
var _baseClone = baseClone;
/** `Object#toString` result references. */
var symbolTag$2 = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike_1(value) && _baseGetTag(value) == symbolTag$2);
}
var isSymbol_1 = isSymbol;
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
var reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray_1(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol_1(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
var _isKey = isKey;
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || _MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = _MapCache;
var memoize_1 = memoize;
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize_1(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
var _memoizeCapped = memoizeCapped;
/** Used to match property names within property paths. */
var reLeadingDot = /^\./;
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = _memoizeCapped(function(string) {
var result = [];
if (reLeadingDot.test(string)) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
var _stringToPath = stringToPath;
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined;
var symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray_1(value)) {
// Recursively convert values (susceptible to call stack limits).
return _arrayMap(value, baseToString) + '';
}
if (isSymbol_1(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
var _baseToString = baseToString;
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : _baseToString(value);
}
var toString_1 = toString;
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray_1(value)) {
return value;
}
return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
}
var _castPath = castPath;
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
var last_1 = last;
/** Used as references for various `Number` constants. */
var INFINITY$1 = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol_1(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
}
var _toKey = toKey;
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = _castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[_toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
var _baseGet = baseGet;
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
var _baseSlice = baseSlice;
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1));
}
var _parent = parent;
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = _castPath(path, object);
object = _parent(object, path);
return object == null || delete object[_toKey(last_1(path))];
}
var _baseUnset = baseUnset;
/** `Object#toString` result references. */
var objectTag$3 = '[object Object]';
/** Used for built-in method references. */
var funcProto$2 = Function.prototype;
var objectProto$14 = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString$2 = funcProto$2.toString;
/** Used to check objects for own properties. */
var hasOwnProperty$12 = objectProto$14.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString$2.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) {
return false;
}
var proto = _getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty$12.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString$2.call(Ctor) == objectCtorString;
}
var isPlainObject_1 = isPlainObject;
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject_1(value) ? undefined : value;
}
var _customOmitClone = customOmitClone;
/** Built-in value references. */
var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray_1(value) || isArguments_1(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
var _isFlattenable = isFlattenable;
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = _isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
_arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
var _baseFlatten = baseFlatten;
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? _baseFlatten(array, 1) : [];
}
var flatten_1 = flatten;
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
var _apply = apply;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return _apply(func, this, otherArgs);
};
}
var _overRest = overRest;
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
var constant_1 = constant;
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
var identity_1 = identity;
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !_defineProperty ? identity_1 : function(func, string) {
return _defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant_1(string),
'writable': true
});
};
var _baseSetToString = baseSetToString;
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800;
var HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
var _shortOut = shortOut;
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = _shortOut(_baseSetToString);
var _setToString = setToString;
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return _setToString(_overRest(func, undefined, flatten_1), func + '');
}
var _flatRest = flatRest;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
var CLONE_FLAT_FLAG = 2;
var CLONE_SYMBOLS_FLAG = 4;
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = _flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = _arrayMap(paths, function(path) {
path = _castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
_copyObject(object, _getAllKeysIn(object), result);
if (isDeep) {
result = _baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, _customOmitClone);
}
var length = paths.length;
while (length--) {
_baseUnset(result, paths[length]);
}
return result;
});
var omit_1 = omit;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED$2);
return this;
}
var _setCacheAdd = setCacheAdd;
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
var _setCacheHas = setCacheHas;
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new _MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
SetCache.prototype.has = _setCacheHas;
var _SetCache = SetCache;
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
var _baseFindIndex = baseFindIndex;
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
var _baseIsNaN = baseIsNaN;
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
var _strictIndexOf = strictIndexOf;
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? _strictIndexOf(array, value, fromIndex)
: _baseFindIndex(array, _baseIsNaN, fromIndex);
}
var _baseIndexOf = baseIndexOf;
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && _baseIndexOf(array, value, 0) > -1;
}
var _arrayIncludes = arrayIncludes;
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
var _arrayIncludesWith = arrayIncludesWith;
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
var _cacheHas = cacheHas;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/
function baseIntersection(arrays, iteratee, comparator) {
var includes = comparator ? _arrayIncludesWith : _arrayIncludes,
length = arrays[0].length,
othLength = arrays.length,
othIndex = othLength,
caches = Array(othLength),
maxLength = Infinity,
result = [];
while (othIndex--) {
var array = arrays[othIndex];
if (othIndex && iteratee) {
array = _arrayMap(array, _baseUnary(iteratee));
}
maxLength = nativeMin(array.length, maxLength);
caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
? new _SetCache(othIndex && array)
: undefined;
}
array = arrays[0];
var index = -1,
seen = caches[0];
outer:
while (++index < length && result.length < maxLength) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (!(seen
? _cacheHas(seen, computed)
: includes(result, computed, comparator)
)) {
othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if (!(cache
? _cacheHas(cache, computed)
: includes(arrays[othIndex], computed, comparator))
) {
continue outer;
}
}
if (seen) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
var _baseIntersection = baseIntersection;
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return _setToString(_overRest(func, start, identity_1), func + '');
}
var _baseRest = baseRest;
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike_1(value) && isArrayLike_1(value);
}
var isArrayLikeObject_1 = isArrayLikeObject;
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject_1(value) ? value : [];
}
var _castArrayLikeObject = castArrayLikeObject;
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/
var intersection = _baseRest(function(arrays) {
var mapped = _arrayMap(arrays, _castArrayLikeObject);
return (mapped.length && mapped[0] === arrays[0])
? _baseIntersection(mapped)
: [];
});
var intersection_1 = intersection;
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
var _createBaseFor = createBaseFor;
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = _createBaseFor();
var _baseFor = baseFor;
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && _baseFor(object, iteratee, keys_1);
}
var _baseForOwn = baseForOwn;
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity_1;
}
var _castFunction = castFunction;
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forOwn(object, iteratee) {
return object && _baseForOwn(object, _castFunction(iteratee));
}
var forOwn_1 = forOwn;
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike_1(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
var _createBaseEach = createBaseEach;
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = _createBaseEach(_baseForOwn);
var _baseEach = baseEach;
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray_1(collection) ? _arrayEach : _baseEach;
return func(collection, _castFunction(iteratee));
}
var forEach_1 = forEach;
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
_baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
var _baseFilter = baseFilter;
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
var _arraySome = arraySome;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$2 = 1;
var COMPARE_UNORDERED_FLAG$1 = 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$2,
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$1) ? new _SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!_arraySome(other, function(othValue, othIndex) {
if (!_cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
var _equalArrays = equalArrays;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$3 = 1;
var COMPARE_UNORDERED_FLAG$2 = 2;
/** `Object#toString` result references. */
var boolTag$3 = '[object Boolean]';
var dateTag$3 = '[object Date]';
var errorTag$2 = '[object Error]';
var mapTag$5 = '[object Map]';
var numberTag$3 = '[object Number]';
var regexpTag$3 = '[object RegExp]';
var setTag$5 = '[object Set]';
var stringTag$3 = '[object String]';
var symbolTag$3 = '[object Symbol]';
var arrayBufferTag$3 = '[object ArrayBuffer]';
var dataViewTag$4 = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined;
var symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag$4:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag$3:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
return false;
}
return true;
case boolTag$3:
case dateTag$3:
case numberTag$3:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq_1(+object, +other);
case errorTag$2:
return object.name == other.name && object.message == other.message;
case regexpTag$3:
case stringTag$3:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag$5:
var convert = _mapToArray;
case setTag$5:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3;
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$2;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag$3:
if (symbolValueOf$1) {
return symbolValueOf$1.call(object) == symbolValueOf$1.call(other);
}
}
return false;
}
var _equalByTag = equalByTag;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$4 = 1;
/** Used for built-in method references. */
var objectProto$16 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$14 = objectProto$16.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$4,
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$14.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
var _equalObjects = equalObjects;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$1 = 1;
/** `Object#toString` result references. */
var argsTag$3 = '[object Arguments]';
var arrayTag$2 = '[object Array]';
var objectTag$4 = '[object Object]';
/** Used for built-in method references. */
var objectProto$15 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$13 = objectProto$15.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray_1(object),
othIsArr = isArray_1(other),
objTag = objIsArr ? arrayTag$2 : _getTag(object),
othTag = othIsArr ? arrayTag$2 : _getTag(other);
objTag = objTag == argsTag$3 ? objectTag$4 : objTag;
othTag = othTag == argsTag$3 ? objectTag$4 : othTag;
var objIsObj = objTag == objectTag$4,
othIsObj = othTag == objectTag$4,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer_1(object)) {
if (!isBuffer_1(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new _Stack);
return (objIsArr || isTypedArray_1(object))
? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG$1)) {
var objIsWrapped = objIsObj && hasOwnProperty$13.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty$13.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new _Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new _Stack);
return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
var _baseIsEqualDeep = baseIsEqualDeep;
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) {
return value !== value && other !== other;
}
return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
var _baseIsEqual = baseIsEqual;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
var 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;
}
var _baseIsMatch = baseIsMatch;
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject_1(value);
}
var _isStrictComparable = isStrictComparable;
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys_1(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, _isStrictComparable(value)];
}
return result;
}
var _getMatchData = getMatchData;
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
var _matchesStrictComparable = matchesStrictComparable;
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = _getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || _baseIsMatch(object, source, matchData);
};
}
var _baseMatches = baseMatches;
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : _baseGet(object, path);
return result === undefined ? defaultValue : result;
}
var get_1 = get;
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
var _baseHasIn = baseHasIn;
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = _castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = _toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength_1(length) && _isIndex(key, length) &&
(isArray_1(object) || isArguments_1(object));
}
var _hasPath = hasPath;
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && _hasPath(object, path, _baseHasIn);
}
var hasIn_1 = hasIn;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$5 = 1;
var COMPARE_UNORDERED_FLAG$3 = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (_isKey(path) && _isStrictComparable(srcValue)) {
return _matchesStrictComparable(_toKey(path), srcValue);
}
return function(object) {
var objValue = get_1(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn_1(object, path)
: _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
};
}
var _baseMatchesProperty = baseMatchesProperty;
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
var _baseProperty = baseProperty;
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return _baseGet(object, path);
};
}
var _basePropertyDeep = basePropertyDeep;
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
}
var property_1 = property;
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity_1;
}
if (typeof value == 'object') {
return isArray_1(value)
? _baseMatchesProperty(value[0], value[1])
: _baseMatches(value);
}
return property_1(value);
}
var _baseIteratee = baseIteratee;
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*/
function filter(collection, predicate) {
var func = isArray_1(collection) ? _arrayFilter : _baseFilter;
return func(collection, _baseIteratee(predicate, 3));
}
var filter_1 = filter;
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike_1(collection) ? Array(collection.length) : [];
_baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
var _baseMap = baseMap;
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray_1(collection) ? _arrayMap : _baseMap;
return func(collection, _baseIteratee(iteratee, 3));
}
var map_1 = map;
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
var _baseReduce = baseReduce;
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray_1(collection) ? _arrayReduce : _baseReduce,
initAccum = arguments.length < 3;
return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEach);
}
var reduce_1 = reduce;
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol_1(value)) {
return NAN;
}
if (isObject_1(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject_1(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
var toNumber_1 = toNumber;
/** Used as references for various `Number` constants. */
var INFINITY$2 = 1 / 0;
var MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber_1(value);
if (value === INFINITY$2 || value === -INFINITY$2) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
var toFinite_1 = toFinite;
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite_1(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
var toInteger_1 = toInteger;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$1 = Math.max;
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger_1(fromIndex);
if (index < 0) {
index = nativeMax$1(length + index, 0);
}
return _baseIndexOf(array, value, index);
}
var indexOf_1 = indexOf;
/** `Object#toString` result references. */
var numberTag$4 = '[object Number]';
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike_1(value) && _baseGetTag(value) == numberTag$4);
}
var isNumber_1 = isNumber;
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN$1(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber_1(value) && value != +value;
}
var _isNaN = isNaN$1;
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return _baseIsEqual(value, other);
}
var isEqual_1 = isEqual;
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
var isUndefined_1 = isUndefined;
/** `Object#toString` result references. */
var stringTag$4 = '[object String]';
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$4);
}
var isString_1 = isString;
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike_1(collection)) {
var iteratee = _baseIteratee(predicate, 3);
collection = keys_1(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
var _createFind = createFind;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$2 = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger_1(fromIndex);
if (index < 0) {
index = nativeMax$2(length + index, 0);
}
return _baseFindIndex(array, _baseIteratee(predicate, 3), index);
}
var findIndex_1 = findIndex;
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find = _createFind(findIndex_1);
var find_1 = find;
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : _baseSlice(array, start, end);
}
var _castSlice = castSlice;
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
var _charsEndIndex = charsEndIndex;
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
var _charsStartIndex = charsStartIndex;
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
var _asciiToArray = asciiToArray;
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff';
var rsComboMarksRange = '\\u0300-\\u036f';
var reComboHalfMarksRange = '\\ufe20-\\ufe2f';
var rsComboSymbolsRange = '\\u20d0-\\u20ff';
var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;
var rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsZWJ = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
var _hasUnicode = hasUnicode;
/** Used to compose unicode character classes. */
var rsAstralRange$1 = '\\ud800-\\udfff';
var rsComboMarksRange$1 = '\\u0300-\\u036f';
var reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f';
var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff';
var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1;
var rsVarRange$1 = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange$1 + ']';
var rsCombo = '[' + rsComboRange$1 + ']';
var rsFitz = '\\ud83c[\\udffb-\\udfff]';
var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')';
var rsNonAstral = '[^' + rsAstralRange$1 + ']';
var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}';
var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]';
var rsZWJ$1 = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod = rsModifier + '?';
var rsOptVar = '[' + rsVarRange$1 + ']?';
var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*';
var rsSeq = rsOptVar + reOptMod + rsOptJoin;
var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
var _unicodeToArray = unicodeToArray;
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return _hasUnicode(string)
? _unicodeToArray(string)
: _asciiToArray(string);
}
var _stringToArray = stringToArray;
/** Used to match leading and trailing whitespace. */
var reTrim$1 = /^\s+|\s+$/g;
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString_1(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrim$1, '');
}
if (!string || !(chars = _baseToString(chars))) {
return string;
}
var strSymbols = _stringToArray(string),
chrSymbols = _stringToArray(chars),
start = _charsStartIndex(strSymbols, chrSymbols),
end = _charsEndIndex(strSymbols, chrSymbols) + 1;
return _castSlice(strSymbols, start, end).join('');
}
var trim_1 = trim;
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject_1(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike_1(object) && _isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq_1(object[index], value);
}
return false;
}
var _isIterateeCall = isIterateeCall;
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return _baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
var _createAssigner = createAssigner;
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = _createAssigner(function(object, source, srcIndex, customizer) {
_copyObject(source, keysIn_1(source), object, customizer);
});
var assignInWith_1 = assignInWith;
/** Used for built-in method references. */
var objectProto$17 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$15 = objectProto$17.hasOwnProperty;
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq_1(objValue, objectProto$17[key]) && !hasOwnProperty$15.call(object, key))) {
return srcValue;
}
return objValue;
}
var _customDefaultsAssignIn = customDefaultsAssignIn;
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = _baseRest(function(args) {
args.push(undefined, _customDefaultsAssignIn);
return _apply(assignInWith_1, undefined, args);
});
var defaults_1 = defaults;
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq_1(object[key], value)) ||
(value === undefined && !(key in object))) {
_baseAssignValue(object, key, value);
}
}
var _assignMergeValue = assignMergeValue;
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return _copyObject(value, keysIn_1(value));
}
var toPlainObject_1 = toPlainObject;
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = object[key],
srcValue = source[key],
stacked = stack.get(srcValue);
if (stacked) {
_assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray_1(srcValue),
isBuff = !isArr && isBuffer_1(srcValue),
isTyped = !isArr && !isBuff && isTypedArray_1(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray_1(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject_1(objValue)) {
newValue = _copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = _cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = _cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject_1(srcValue) || isArguments_1(srcValue)) {
newValue = objValue;
if (isArguments_1(objValue)) {
newValue = toPlainObject_1(objValue);
}
else if (!isObject_1(objValue) || (srcIndex && isFunction_1(objValue))) {
newValue = _initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
_assignMergeValue(object, key, newValue);
}
var _baseMergeDeep = baseMergeDeep;
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
_baseFor(source, function(srcValue, key) {
if (isObject_1(srcValue)) {
stack || (stack = new _Stack);
_baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(object[key], srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
_assignMergeValue(object, key, newValue);
}
}, keysIn_1);
}
var _baseMerge = baseMerge;
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = _createAssigner(function(object, source, srcIndex) {
_baseMerge(object, source, srcIndex);
});
var merge_1 = merge;
function valToNumber(v) {
if (isNumber_1(v)) {
return v;
} else if (isString_1(v)) {
return parseFloat(v);
} else if (isArray_1(v)) {
return map_1(v, valToNumber);
}
throw new Error('The value should be a number, a parseable string or an array of those.');
}
var valToNumber_1 = valToNumber;
function filterState(state, filters) {
var partialState = {};
var attributeFilters = filter_1(filters, function(f) { return f.indexOf('attribute:') !== -1; });
var attributes = map_1(attributeFilters, function(aF) { return aF.split(':')[1]; });
if (indexOf_1(attributes, '*') === -1) {
forEach_1(attributes, function(attr) {
if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) {
if (!partialState.facetsRefinements) partialState.facetsRefinements = {};
partialState.facetsRefinements[attr] = state.facetsRefinements[attr];
}
if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) {
if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {};
partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr];
}
if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) {
if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {};
partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr];
}
var numericRefinements = state.getNumericRefinements(attr);
if (!isEmpty_1(numericRefinements)) {
if (!partialState.numericRefinements) partialState.numericRefinements = {};
partialState.numericRefinements[attr] = state.numericRefinements[attr];
}
});
} else {
if (!isEmpty_1(state.numericRefinements)) {
partialState.numericRefinements = state.numericRefinements;
}
if (!isEmpty_1(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements;
if (!isEmpty_1(state.disjunctiveFacetsRefinements)) {
partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements;
}
if (!isEmpty_1(state.hierarchicalFacetsRefinements)) {
partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements;
}
}
var searchParameters = filter_1(
filters,
function(f) {
return f.indexOf('attribute:') === -1;
}
);
forEach_1(
searchParameters,
function(parameterKey) {
partialState[parameterKey] = state[parameterKey];
}
);
return partialState;
}
var filterState_1 = filterState;
/**
* Functions to manipulate refinement lists
*
* The RefinementList is not formally defined through a prototype but is based
* on a specific structure.
*
* @module SearchParameters.refinementList
*
* @typedef {string[]} SearchParameters.refinementList.Refinements
* @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList
*/
var lib = {
/**
* Adds a refinement to a RefinementList
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement, if the value is not a string it will be converted
* @return {RefinementList} a new and updated refinement list
*/
addRefinement: function addRefinement(refinementList, attribute, value) {
if (lib.isRefined(refinementList, attribute, value)) {
return refinementList;
}
var valueAsString = '' + value;
var facetRefinement = !refinementList[attribute] ?
[valueAsString] :
refinementList[attribute].concat(valueAsString);
var mod = {};
mod[attribute] = facetRefinement;
return defaults_1({}, mod, refinementList);
},
/**
* Removes refinement(s) for an attribute:
* - if the value is specified removes the refinement for the value on the attribute
* - if no value is specified removes all the refinements for this attribute
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} [value] the value of the refinement
* @return {RefinementList} a new and updated refinement lst
*/
removeRefinement: function removeRefinement(refinementList, attribute, value) {
if (isUndefined_1(value)) {
return lib.clearRefinement(refinementList, attribute);
}
var valueAsString = '' + value;
return lib.clearRefinement(refinementList, function(v, f) {
return attribute === f && valueAsString === v;
});
},
/**
* Toggles the refinement value for an attribute.
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement
* @return {RefinementList} a new and updated list
*/
toggleRefinement: function toggleRefinement(refinementList, attribute, value) {
if (isUndefined_1(value)) throw new Error('toggleRefinement should be used with a value');
if (lib.isRefined(refinementList, attribute, value)) {
return lib.removeRefinement(refinementList, attribute, value);
}
return lib.addRefinement(refinementList, attribute, value);
},
/**
* Clear all or parts of a RefinementList. Depending on the arguments, three
* kinds of behavior can happen:
* - if no attribute is provided: clears the whole list
* - if an attribute is provided as a string: clears the list for the specific attribute
* - if an attribute is provided as a function: discards the elements for which the function returns true
* @param {RefinementList} refinementList the initial list
* @param {string} [attribute] the attribute or function to discard
* @param {string} [refinementType] optional parameter to give more context to the attribute function
* @return {RefinementList} a new and updated refinement list
*/
clearRefinement: function clearRefinement(refinementList, attribute, refinementType) {
if (isUndefined_1(attribute)) {
return {};
} else if (isString_1(attribute)) {
return omit_1(refinementList, attribute);
} else if (isFunction_1(attribute)) {
return reduce_1(refinementList, function(memo, values, key) {
var facetList = filter_1(values, function(value) {
return !attribute(value, key, refinementType);
});
if (!isEmpty_1(facetList)) memo[key] = facetList;
return memo;
}, {});
}
},
/**
* Test if the refinement value is used for the attribute. If no refinement value
* is provided, test if the refinementList contains any refinement for the
* given attribute.
* @param {RefinementList} refinementList the list of refinement
* @param {string} attribute name of the attribute
* @param {string} [refinementValue] value of the filter/refinement
* @return {boolean}
*/
isRefined: function isRefined(refinementList, attribute, refinementValue) {
var indexOf = indexOf_1;
var containsRefinements = !!refinementList[attribute] &&
refinementList[attribute].length > 0;
if (isUndefined_1(refinementValue) || !containsRefinements) {
return containsRefinements;
}
var refinementValueAsString = '' + refinementValue;
return indexOf(refinementList[attribute], refinementValueAsString) !== -1;
}
};
var RefinementList = lib;
/**
* like _.find but using _.isEqual to be able to use it
* to find arrays.
* @private
* @param {any[]} array array to search into
* @param {any} searchedValue the value we're looking for
* @return {any} the searched value or undefined
*/
function findArray(array, searchedValue) {
return find_1(array, function(currentValue) {
return isEqual_1(currentValue, searchedValue);
});
}
/**
* The facet list is the structure used to store the list of values used to
* filter a single attribute.
* @typedef {string[]} SearchParameters.FacetList
*/
/**
* Structure to store numeric filters with the operator as the key. The supported operators
* are `=`, `>`, `<`, `>=`, `<=` and `!=`.
* @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList
*/
/**
* SearchParameters is the data structure that contains all the information
* usable for making a search to Algolia API. It doesn't do the search itself,
* nor does it contains logic about the parameters.
* It is an immutable object, therefore it has been created in a way that each
* changes does not change the object itself but returns a copy with the
* modification.
* This object should probably not be instantiated outside of the helper. It will
* be provided when needed. This object is documented for reference as you'll
* get it from events generated by the {@link AlgoliaSearchHelper}.
* If need be, instantiate the Helper from the factory function {@link SearchParameters.make}
* @constructor
* @classdesc contains all the parameters of a search
* @param {object|SearchParameters} newParameters existing parameters or partial object
* for the properties of a new SearchParameters
* @see SearchParameters.make
* @example <caption>SearchParameters of the first query in
* <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption>
{
"query": "",
"disjunctiveFacets": [
"customerReviewCount",
"category",
"salePrice_range",
"manufacturer"
],
"maxValuesPerFacet": 30,
"page": 0,
"hitsPerPage": 10,
"facets": [
"type",
"shipping"
]
}
*/
function SearchParameters(newParameters) {
var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {};
/**
* Targeted index. This parameter is mandatory.
* @member {string}
*/
this.index = params.index || '';
// Query
/**
* Query string of the instant search. The empty string is a valid query.
* @member {string}
* @see https://www.algolia.com/doc/rest#param-query
*/
this.query = params.query || '';
// Facets
/**
* This attribute contains the list of all the conjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.facets = params.facets || [];
/**
* This attribute contains the list of all the disjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.disjunctiveFacets = params.disjunctiveFacets || [];
/**
* This attribute contains the list of all the hierarchical facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* Hierarchical facets are a sub type of disjunctive facets that
* let you filter faceted attributes hierarchically.
* @member {string[]|object[]}
*/
this.hierarchicalFacets = params.hierarchicalFacets || [];
// Refinements
/**
* This attribute contains all the filters that need to be
* applied on the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsRefinements = params.facetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* excluded from the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters excluded for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsExcludes = params.facetsExcludes || {};
/**
* This attribute contains all the filters that need to be
* applied on the disjunctive facets. Each facet must be properly
* defined in the `disjunctiveFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* applied on the numeric attributes.
*
* The key is the name of the attribute, and the value is the
* filters to apply to this attribute.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `numericFilters` attribute.
* @member {Object.<string, SearchParameters.OperatorList>}
*/
this.numericRefinements = params.numericRefinements || {};
/**
* This attribute contains all the tags used to refine the query.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `tagFilters` attribute.
* @member {string[]}
*/
this.tagRefinements = params.tagRefinements || [];
/**
* This attribute contains all the filters that need to be
* applied on the hierarchical facets. Each facet must be properly
* defined in the `hierarchicalFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name. The FacetList values
* are structured as a string that contain the values for each level
* separated by the configured separator.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {};
/**
* Contains the numeric filters in the raw format of the Algolia API. Setting
* this parameter is not compatible with the usage of numeric filters methods.
* @see https://www.algolia.com/doc/javascript#numericFilters
* @member {string}
*/
this.numericFilters = params.numericFilters;
/**
* Contains the tag filters in the raw format of the Algolia API. Setting this
* parameter is not compatible with the of the add/remove/toggle methods of the
* tag api.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.tagFilters = params.tagFilters;
/**
* Contains the optional tag filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalTagFilters = params.optionalTagFilters;
/**
* Contains the optional facet filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalFacetFilters = params.optionalFacetFilters;
// Misc. parameters
/**
* Number of hits to be returned by the search API
* @member {number}
* @see https://www.algolia.com/doc/rest#param-hitsPerPage
*/
this.hitsPerPage = params.hitsPerPage;
/**
* Number of values for each faceted attribute
* @member {number}
* @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet
*/
this.maxValuesPerFacet = params.maxValuesPerFacet;
/**
* The current page number
* @member {number}
* @see https://www.algolia.com/doc/rest#param-page
*/
this.page = params.page || 0;
/**
* How the query should be treated by the search engine.
* Possible values: prefixAll, prefixLast, prefixNone
* @see https://www.algolia.com/doc/rest#param-queryType
* @member {string}
*/
this.queryType = params.queryType;
/**
* How the typo tolerance behave in the search engine.
* Possible values: true, false, min, strict
* @see https://www.algolia.com/doc/rest#param-typoTolerance
* @member {string}
*/
this.typoTolerance = params.typoTolerance;
/**
* Number of characters to wait before doing one character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo
* @member {number}
*/
this.minWordSizefor1Typo = params.minWordSizefor1Typo;
/**
* Number of characters to wait before doing a second character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos
* @member {number}
*/
this.minWordSizefor2Typos = params.minWordSizefor2Typos;
/**
* Configure the precision of the proximity ranking criterion
* @see https://www.algolia.com/doc/rest#param-minProximity
*/
this.minProximity = params.minProximity;
/**
* Should the engine allow typos on numerics.
* @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens
* @member {boolean}
*/
this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens;
/**
* Should the plurals be ignored
* @see https://www.algolia.com/doc/rest#param-ignorePlurals
* @member {boolean}
*/
this.ignorePlurals = params.ignorePlurals;
/**
* Restrict which attribute is searched.
* @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes
* @member {string}
*/
this.restrictSearchableAttributes = params.restrictSearchableAttributes;
/**
* Enable the advanced syntax.
* @see https://www.algolia.com/doc/rest#param-advancedSyntax
* @member {boolean}
*/
this.advancedSyntax = params.advancedSyntax;
/**
* Enable the analytics
* @see https://www.algolia.com/doc/rest#param-analytics
* @member {boolean}
*/
this.analytics = params.analytics;
/**
* Tag of the query in the analytics.
* @see https://www.algolia.com/doc/rest#param-analyticsTags
* @member {string}
*/
this.analyticsTags = params.analyticsTags;
/**
* Enable the synonyms
* @see https://www.algolia.com/doc/rest#param-synonyms
* @member {boolean}
*/
this.synonyms = params.synonyms;
/**
* Should the engine replace the synonyms in the highlighted results.
* @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight
* @member {boolean}
*/
this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight;
/**
* Add some optional words to those defined in the dashboard
* @see https://www.algolia.com/doc/rest#param-optionalWords
* @member {string}
*/
this.optionalWords = params.optionalWords;
/**
* Possible values are "lastWords" "firstWords" "allOptional" "none" (default)
* @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults
* @member {string}
*/
this.removeWordsIfNoResults = params.removeWordsIfNoResults;
/**
* List of attributes to retrieve
* @see https://www.algolia.com/doc/rest#param-attributesToRetrieve
* @member {string}
*/
this.attributesToRetrieve = params.attributesToRetrieve;
/**
* List of attributes to highlight
* @see https://www.algolia.com/doc/rest#param-attributesToHighlight
* @member {string}
*/
this.attributesToHighlight = params.attributesToHighlight;
/**
* Code to be embedded on the left part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPreTag
* @member {string}
*/
this.highlightPreTag = params.highlightPreTag;
/**
* Code to be embedded on the right part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPostTag
* @member {string}
*/
this.highlightPostTag = params.highlightPostTag;
/**
* List of attributes to snippet
* @see https://www.algolia.com/doc/rest#param-attributesToSnippet
* @member {string}
*/
this.attributesToSnippet = params.attributesToSnippet;
/**
* Enable the ranking informations in the response, set to 1 to activate
* @see https://www.algolia.com/doc/rest#param-getRankingInfo
* @member {number}
*/
this.getRankingInfo = params.getRankingInfo;
/**
* Remove duplicates based on the index setting attributeForDistinct
* @see https://www.algolia.com/doc/rest#param-distinct
* @member {boolean|number}
*/
this.distinct = params.distinct;
/**
* Center of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundLatLng
* @member {string}
*/
this.aroundLatLng = params.aroundLatLng;
/**
* Center of the search, retrieve from the user IP.
* @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP
* @member {boolean}
*/
this.aroundLatLngViaIP = params.aroundLatLngViaIP;
/**
* Radius of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundRadius
* @member {number}
*/
this.aroundRadius = params.aroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundPrecision
* @member {number}
*/
this.minimumAroundRadius = params.minimumAroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-minimumAroundRadius
* @member {number}
*/
this.aroundPrecision = params.aroundPrecision;
/**
* Geo search inside a box.
* @see https://www.algolia.com/doc/rest#param-insideBoundingBox
* @member {string}
*/
this.insideBoundingBox = params.insideBoundingBox;
/**
* Geo search inside a polygon.
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.insidePolygon = params.insidePolygon;
/**
* Allows to specify an ellipsis character for the snippet when we truncate the text
* (added before and after if truncated).
* The default value is an empty string and we recommend to set it to "…"
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.snippetEllipsisText = params.snippetEllipsisText;
/**
* Allows to specify some attributes name on which exact won't be applied.
* Attributes are separated with a comma (for example "name,address" ), you can also use a
* JSON string array encoding (for example encodeURIComponent('["name","address"]') ).
* By default the list is empty.
* @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes
* @member {string|string[]}
*/
this.disableExactOnAttributes = params.disableExactOnAttributes;
/**
* Applies 'exact' on single word queries if the word contains at least 3 characters
* and is not a stop word.
* Can take two values: true or false.
* By default, its set to false.
* @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery
* @member {boolean}
*/
this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery;
// Undocumented parameters, still needed otherwise we fail
this.offset = params.offset;
this.length = params.length;
var self = this;
forOwn_1(params, function checkForUnknownParameter(paramValue, paramName) {
if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) {
self[paramName] = paramValue;
}
});
}
/**
* List all the properties in SearchParameters and therefore all the known Algolia properties
* This doesn't contain any beta/hidden features.
* @private
*/
SearchParameters.PARAMETERS = keys_1(new SearchParameters());
/**
* @private
* @param {object} partialState full or part of a state
* @return {object} a new object with the number keys as number
*/
SearchParameters._parseNumbers = function(partialState) {
// Do not reparse numbers in SearchParameters, they ought to be parsed already
if (partialState instanceof SearchParameters) return partialState;
var numbers = {};
var numberKeys = [
'aroundPrecision',
'aroundRadius',
'getRankingInfo',
'minWordSizefor2Typos',
'minWordSizefor1Typo',
'page',
'maxValuesPerFacet',
'distinct',
'minimumAroundRadius',
'hitsPerPage',
'minProximity'
];
forEach_1(numberKeys, function(k) {
var value = partialState[k];
if (isString_1(value)) {
var parsedValue = parseFloat(value);
numbers[k] = _isNaN(parsedValue) ? value : parsedValue;
}
});
if (partialState.numericRefinements) {
var numericRefinements = {};
forEach_1(partialState.numericRefinements, function(operators, attribute) {
numericRefinements[attribute] = {};
forEach_1(operators, function(values, operator) {
var parsedValues = map_1(values, function(v) {
if (isArray_1(v)) {
return map_1(v, function(vPrime) {
if (isString_1(vPrime)) {
return parseFloat(vPrime);
}
return vPrime;
});
} else if (isString_1(v)) {
return parseFloat(v);
}
return v;
});
numericRefinements[attribute][operator] = parsedValues;
});
});
numbers.numericRefinements = numericRefinements;
}
return merge_1({}, partialState, numbers);
};
/**
* Factory for SearchParameters
* @param {object|SearchParameters} newParameters existing parameters or partial
* object for the properties of a new SearchParameters
* @return {SearchParameters} frozen instance of SearchParameters
*/
SearchParameters.make = function makeSearchParameters(newParameters) {
var instance = new SearchParameters(newParameters);
forEach_1(newParameters.hierarchicalFacets, function(facet) {
if (facet.rootPath) {
var currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) {
instance = instance.clearRefinements(facet.name);
}
// get it again in case it has been cleared
currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length === 0) {
instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath);
}
}
});
return instance;
};
/**
* Validates the new parameters based on the previous state
* @param {SearchParameters} currentState the current state
* @param {object|SearchParameters} parameters the new parameters to set
* @return {Error|null} Error if the modification is invalid, null otherwise
*/
SearchParameters.validate = function(currentState, parameters) {
var params = parameters || {};
if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) {
return new Error(
'[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' +
'an error, if it is really what you want, you should first clear the tags with clearTags method.');
}
if (currentState.tagRefinements.length > 0 && params.tagFilters) {
return new Error(
'[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' +
'an error, if it is not, you should first clear the tags with clearTags method.');
}
if (currentState.numericFilters && params.numericRefinements && !isEmpty_1(params.numericRefinements)) {
return new Error(
"[Numeric filters] Can't switch from the advanced to the managed API. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
if (!isEmpty_1(currentState.numericRefinements) && params.numericFilters) {
return new Error(
"[Numeric filters] Can't switch from the managed API to the advanced. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
return null;
};
SearchParameters.prototype = {
constructor: SearchParameters,
/**
* Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)
* @method
* @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {SearchParameters}
*/
clearRefinements: function clearRefinements(attribute) {
var clear = RefinementList.clearRefinement;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(attribute),
facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'),
facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'),
disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'),
hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet')
});
},
/**
* Remove all the refined tags from the SearchParameters
* @method
* @return {SearchParameters}
*/
clearTags: function clearTags() {
if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this;
return this.setQueryParameters({
tagFilters: undefined,
tagRefinements: []
});
},
/**
* Set the index.
* @method
* @param {string} index the index name
* @return {SearchParameters}
*/
setIndex: function setIndex(index) {
if (index === this.index) return this;
return this.setQueryParameters({
index: index
});
},
/**
* Query setter
* @method
* @param {string} newQuery value for the new query
* @return {SearchParameters}
*/
setQuery: function setQuery(newQuery) {
if (newQuery === this.query) return this;
return this.setQueryParameters({
query: newQuery
});
},
/**
* Page setter
* @method
* @param {number} newPage new page number
* @return {SearchParameters}
*/
setPage: function setPage(newPage) {
if (newPage === this.page) return this;
return this.setQueryParameters({
page: newPage
});
},
/**
* Facets setter
* The facets are the simple facets, used for conjunctive (and) faceting.
* @method
* @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting
* @return {SearchParameters}
*/
setFacets: function setFacets(facets) {
return this.setQueryParameters({
facets: facets
});
},
/**
* Disjunctive facets setter
* Change the list of disjunctive (or) facets the helper chan handle.
* @method
* @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting
* @return {SearchParameters}
*/
setDisjunctiveFacets: function setDisjunctiveFacets(facets) {
return this.setQueryParameters({
disjunctiveFacets: facets
});
},
/**
* HitsPerPage setter
* Hits per page represents the number of hits retrieved for this query
* @method
* @param {number} n number of hits retrieved per page of results
* @return {SearchParameters}
*/
setHitsPerPage: function setHitsPerPage(n) {
if (this.hitsPerPage === n) return this;
return this.setQueryParameters({
hitsPerPage: n
});
},
/**
* typoTolerance setter
* Set the value of typoTolerance
* @method
* @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict")
* @return {SearchParameters}
*/
setTypoTolerance: function setTypoTolerance(typoTolerance) {
if (this.typoTolerance === typoTolerance) return this;
return this.setQueryParameters({
typoTolerance: typoTolerance
});
},
/**
* Add a numeric filter for a given attribute
* When value is an array, they are combined with OR
* When value is a single value, it will combined with AND
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number | number[]} value value of the filter
* @return {SearchParameters}
* @example
* // for price = 50 or 40
* searchparameter.addNumericRefinement('price', '=', [50, 40]);
* @example
* // for size = 38 and 40
* searchparameter.addNumericRefinement('size', '=', 38);
* searchparameter.addNumericRefinement('size', '=', 40);
*/
addNumericRefinement: function(attribute, operator, v) {
var value = valToNumber_1(v);
if (this.isNumericRefined(attribute, operator, value)) return this;
var mod = merge_1({}, this.numericRefinements);
mod[attribute] = merge_1({}, mod[attribute]);
if (mod[attribute][operator]) {
// Array copy
mod[attribute][operator] = mod[attribute][operator].slice();
// Add the element. Concat can't be used here because value can be an array.
mod[attribute][operator].push(value);
} else {
mod[attribute][operator] = [value];
}
return this.setQueryParameters({
numericRefinements: mod
});
},
/**
* Get the list of conjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getConjunctiveRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsRefinements[facetName] || [];
},
/**
* Get the list of disjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getDisjunctiveRefinements: function(facetName) {
if (!this.isDisjunctiveFacet(facetName)) {
throw new Error(
facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration'
);
}
return this.disjunctiveFacetsRefinements[facetName] || [];
},
/**
* Get the list of hierarchical refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getHierarchicalRefinement: function(facetName) {
// we send an array but we currently do not support multiple
// hierarchicalRefinements for a hierarchicalFacet
return this.hierarchicalFacetsRefinements[facetName] || [];
},
/**
* Get the list of exclude refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getExcludeRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsExcludes[facetName] || [];
},
/**
* Remove all the numeric filter for a given (attribute, operator)
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number} [number] the value to be removed
* @return {SearchParameters}
*/
removeNumericRefinement: function(attribute, operator, paramValue) {
if (paramValue !== undefined) {
var paramValueAsNumber = valToNumber_1(paramValue);
if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator && isEqual_1(value.val, paramValueAsNumber);
})
});
} else if (operator !== undefined) {
if (!this.isNumericRefined(attribute, operator)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator;
})
});
}
if (!this.isNumericRefined(attribute)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute;
})
});
},
/**
* Get the list of numeric refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {SearchParameters.OperatorList[]} list of refinements
*/
getNumericRefinements: function(facetName) {
return this.numericRefinements[facetName] || {};
},
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
getNumericRefinement: function(attribute, operator) {
return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator];
},
/**
* Clear numeric filters.
* @method
* @private
* @param {string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {Object.<string, OperatorList>}
*/
_clearNumericRefinements: function _clearNumericRefinements(attribute) {
if (isUndefined_1(attribute)) {
return {};
} else if (isString_1(attribute)) {
return omit_1(this.numericRefinements, attribute);
} else if (isFunction_1(attribute)) {
return reduce_1(this.numericRefinements, function(memo, operators, key) {
var operatorList = {};
forEach_1(operators, function(values, operator) {
var outValues = [];
forEach_1(values, function(value) {
var predicateResult = attribute({val: value, op: operator}, key, 'numeric');
if (!predicateResult) outValues.push(value);
});
if (!isEmpty_1(outValues)) operatorList[operator] = outValues;
});
if (!isEmpty_1(operatorList)) memo[key] = operatorList;
return memo;
}, {});
}
},
/**
* Add a facet to the facets attribute of the helper configuration, if it
* isn't already present.
* @method
* @param {string} facet facet name to add
* @return {SearchParameters}
*/
addFacet: function addFacet(facet) {
if (this.isConjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
facets: this.facets.concat([facet])
});
},
/**
* Add a disjunctive facet to the disjunctiveFacets attribute of the helper
* configuration, if it isn't already present.
* @method
* @param {string} facet disjunctive facet name to add
* @return {SearchParameters}
*/
addDisjunctiveFacet: function addDisjunctiveFacet(facet) {
if (this.isDisjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
disjunctiveFacets: this.disjunctiveFacets.concat([facet])
});
},
/**
* Add a hierarchical facet to the hierarchicalFacets attribute of the helper
* configuration.
* @method
* @param {object} hierarchicalFacet hierarchical facet to add
* @return {SearchParameters}
* @throws will throw an error if a hierarchical facet with the same name was already declared
*/
addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) {
if (this.isHierarchicalFacet(hierarchicalFacet.name)) {
throw new Error(
'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`');
}
return this.setQueryParameters({
hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet])
});
},
/**
* Add a refinement on a "normal" facet
* @method
* @param {string} facet attribute to apply the faceting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addFacetRefinement: function addFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Exclude a value from a "normal" facet
* @method
* @param {string} facet attribute to apply the exclusion on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addExcludeRefinement: function addExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Adds a refinement on a disjunctive facet.
* @method
* @param {string} facet attribute to apply the faceting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.addRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* addTagRefinement adds a tag to the list used to filter the results
* @param {string} tag tag to be added
* @return {SearchParameters}
*/
addTagRefinement: function addTagRefinement(tag) {
if (this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: this.tagRefinements.concat(tag)
};
return this.setQueryParameters(modification);
},
/**
* Remove a facet from the facets attribute of the helper configuration, if it
* is present.
* @method
* @param {string} facet facet name to remove
* @return {SearchParameters}
*/
removeFacet: function removeFacet(facet) {
if (!this.isConjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
facets: filter_1(this.facets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a disjunctive facet from the disjunctiveFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet disjunctive facet name to remove
* @return {SearchParameters}
*/
removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) {
if (!this.isDisjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
disjunctiveFacets: filter_1(this.disjunctiveFacets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a hierarchical facet from the hierarchicalFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet hierarchical facet name to remove
* @return {SearchParameters}
*/
removeHierarchicalFacet: function removeHierarchicalFacet(facet) {
if (!this.isHierarchicalFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
hierarchicalFacets: filter_1(this.hierarchicalFacets, function(f) {
return f.name !== facet;
})
});
},
/**
* Remove a refinement set on facet. If a value is provided, it will clear the
* refinement for the given value, otherwise it will clear all the refinement
* values for the faceted attribute.
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} [value] value used to filter
* @return {SearchParameters}
*/
removeFacetRefinement: function removeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Remove a negative refinement on a facet
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeExcludeRefinement: function removeExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Remove a refinement on a disjunctive facet
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.removeRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Remove a tag from the list of tag refinements
* @method
* @param {string} tag the tag to remove
* @return {SearchParameters}
*/
removeTagRefinement: function removeTagRefinement(tag) {
if (!this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: filter_1(this.tagRefinements, function(t) { return t !== tag; })
};
return this.setQueryParameters(modification);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
* @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement}
*/
toggleRefinement: function toggleRefinement(facet, value) {
return this.toggleFacetRefinement(facet, value);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
*/
toggleFacetRefinement: function toggleFacetRefinement(facet, value) {
if (this.isHierarchicalFacet(facet)) {
return this.toggleHierarchicalFacetRefinement(facet, value);
} else if (this.isConjunctiveFacet(facet)) {
return this.toggleConjunctiveFacetRefinement(facet, value);
} else if (this.isDisjunctiveFacet(facet)) {
return this.toggleDisjunctiveFacetRefinement(facet, value);
}
throw new Error('Cannot refine the undeclared facet ' + facet +
'; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets');
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.toggleRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet));
var mod = {};
var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined &&
this.hierarchicalFacetsRefinements[facet].length > 0 && (
// remove current refinement:
// refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0] === value ||
// remove a parent refinement of the current refinement:
// - refinement was 'beer > IPA > Flying dog'
// - call is toggleRefine('beer > IPA')
// - refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0
);
if (upOneOrMultipleLevel) {
if (value.indexOf(separator) === -1) {
// go back to root level
mod[facet] = [];
} else {
mod[facet] = [value.slice(0, value.lastIndexOf(separator))];
}
} else {
mod[facet] = [value];
}
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Adds a refinement on a hierarchical facet.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is refined
*/
addHierarchicalFacetRefinement: function(facet, path) {
if (this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is already refined.');
}
var mod = {};
mod[facet] = [path];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is not refined
*/
removeHierarchicalFacetRefinement: function(facet) {
if (!this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is not refined.');
}
var mod = {};
mod[facet] = [];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Switch the tag refinement
* @method
* @param {string} tag the tag to remove or add
* @return {SearchParameters}
*/
toggleTagRefinement: function toggleTagRefinement(tag) {
if (this.isTagRefined(tag)) {
return this.removeTagRefinement(tag);
}
return this.addTagRefinement(tag);
},
/**
* Test if the facet name is from one of the disjunctive facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isDisjunctiveFacet: function(facet) {
return indexOf_1(this.disjunctiveFacets, facet) > -1;
},
/**
* Test if the facet name is from one of the hierarchical facets
* @method
* @param {string} facetName facet name to test
* @return {boolean}
*/
isHierarchicalFacet: function(facetName) {
return this.getHierarchicalFacetByName(facetName) !== undefined;
},
/**
* Test if the facet name is from one of the conjunctive/normal facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isConjunctiveFacet: function(facet) {
return indexOf_1(this.facets, facet) > -1;
},
/**
* Returns true if the facet is refined, either for a specific value or in
* general.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value, optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isFacetRefined: function isFacetRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsRefinements, facet, value);
},
/**
* Returns true if the facet contains exclusions or if a specific value is
* excluded.
*
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isExcludeRefined: function isExcludeRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsExcludes, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value optional, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value optional, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var refinements = this.getHierarchicalRefinement(facet);
if (!value) {
return refinements.length > 0;
}
return indexOf_1(refinements, value) !== -1;
},
/**
* Test if the triple (attribute, operator, value) is already refined.
* If only the attribute and the operator are provided, it tests if the
* contains any refinement value.
* @method
* @param {string} attribute attribute for which the refinement is applied
* @param {string} [operator] operator of the refinement
* @param {string} [value] value of the refinement
* @return {boolean} true if it is refined
*/
isNumericRefined: function isNumericRefined(attribute, operator, value) {
if (isUndefined_1(value) && isUndefined_1(operator)) {
return !!this.numericRefinements[attribute];
}
var isOperatorDefined = this.numericRefinements[attribute] &&
!isUndefined_1(this.numericRefinements[attribute][operator]);
if (isUndefined_1(value) || !isOperatorDefined) {
return isOperatorDefined;
}
var parsedValue = valToNumber_1(value);
var isAttributeValueDefined = !isUndefined_1(
findArray(this.numericRefinements[attribute][operator], parsedValue)
);
return isOperatorDefined && isAttributeValueDefined;
},
/**
* Returns true if the tag refined, false otherwise
* @method
* @param {string} tag the tag to check
* @return {boolean}
*/
isTagRefined: function isTagRefined(tag) {
return indexOf_1(this.tagRefinements, tag) !== -1;
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() {
// attributes used for numeric filter can also be disjunctive
var disjunctiveNumericRefinedFacets = intersection_1(
keys_1(this.numericRefinements),
this.disjunctiveFacets
);
return keys_1(this.disjunctiveFacetsRefinements)
.concat(disjunctiveNumericRefinedFacets)
.concat(this.getRefinedHierarchicalFacets());
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() {
return intersection_1(
// enforce the order between the two arrays,
// so that refinement name index === hierarchical facet index
map_1(this.hierarchicalFacets, 'name'),
keys_1(this.hierarchicalFacetsRefinements)
);
},
/**
* Returned the list of all disjunctive facets not refined
* @method
* @return {string[]}
*/
getUnrefinedDisjunctiveFacets: function() {
var refinedFacets = this.getRefinedDisjunctiveFacets();
return filter_1(this.disjunctiveFacets, function(f) {
return indexOf_1(refinedFacets, f) === -1;
});
},
managedParameters: [
'index',
'facets', 'disjunctiveFacets', 'facetsRefinements',
'facetsExcludes', 'disjunctiveFacetsRefinements',
'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'
],
getQueryParams: function getQueryParams() {
var managedParameters = this.managedParameters;
var queryParams = {};
forOwn_1(this, function(paramValue, paramName) {
if (indexOf_1(managedParameters, paramName) === -1 && paramValue !== undefined) {
queryParams[paramName] = paramValue;
}
});
return queryParams;
},
/**
* Let the user retrieve any parameter value from the SearchParameters
* @param {string} paramName name of the parameter
* @return {any} the value of the parameter
*/
getQueryParameter: function getQueryParameter(paramName) {
if (!this.hasOwnProperty(paramName)) {
throw new Error(
"Parameter '" + paramName + "' is not an attribute of SearchParameters " +
'(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)');
}
return this[paramName];
},
/**
* Let the user set a specific value for a given parameter. Will return the
* same instance if the parameter is invalid or if the value is the same as the
* previous one.
* @method
* @param {string} parameter the parameter name
* @param {any} value the value to be set, must be compliant with the definition
* of the attribute on the object
* @return {SearchParameters} the updated state
*/
setQueryParameter: function setParameter(parameter, value) {
if (this[parameter] === value) return this;
var modification = {};
modification[parameter] = value;
return this.setQueryParameters(modification);
},
/**
* Let the user set any of the parameters with a plain object.
* @method
* @param {object} params all the keys and the values to be updated
* @return {SearchParameters} a new updated instance
*/
setQueryParameters: function setQueryParameters(params) {
if (!params) return this;
var error = SearchParameters.validate(this, params);
if (error) {
throw error;
}
var parsedParams = SearchParameters._parseNumbers(params);
return this.mutateMe(function mergeWith(newInstance) {
var ks = keys_1(params);
forEach_1(ks, function(k) {
newInstance[k] = parsedParams[k];
});
return newInstance;
});
},
/**
* Returns an object with only the selected attributes.
* @param {string[]} filters filters to retrieve only a subset of the state. It
* accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage)
* or attributes of the index with the notation 'attribute:nameOfMyAttribute'
* @return {object}
*/
filter: function(filters) {
return filterState_1(this, filters);
},
/**
* Helper function to make it easier to build new instances from a mutating
* function
* @private
* @param {function} fn newMutableState -> previousState -> () function that will
* change the value of the newMutable to the desired state
* @return {SearchParameters} a new instance with the specified modifications applied
*/
mutateMe: function mutateMe(fn) {
var newState = new this.constructor(this);
fn(newState, this);
return newState;
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSortBy: function(hierarchicalFacet) {
return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc'];
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSeparator: function(hierarchicalFacet) {
return hierarchicalFacet.separator || ' > ';
},
/**
* Helper function to get the hierarchicalFacet prefix path or null
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.rootPath or null as default
*/
_getHierarchicalRootPath: function(hierarchicalFacet) {
return hierarchicalFacet.rootPath || null;
},
/**
* Helper function to check if we show the parent level of the hierarchicalFacet
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.showParentLevel or true as default
*/
_getHierarchicalShowParentLevel: function(hierarchicalFacet) {
if (typeof hierarchicalFacet.showParentLevel === 'boolean') {
return hierarchicalFacet.showParentLevel;
}
return true;
},
/**
* Helper function to get the hierarchicalFacet by it's name
* @param {string} hierarchicalFacetName
* @return {object} a hierarchicalFacet
*/
getHierarchicalFacetByName: function(hierarchicalFacetName) {
return find_1(
this.hierarchicalFacets,
{name: hierarchicalFacetName}
);
},
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
getHierarchicalFacetBreadcrumb: function(facetName) {
if (!this.isHierarchicalFacet(facetName)) {
throw new Error(
'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`');
}
var refinement = this.getHierarchicalRefinement(facetName)[0];
if (!refinement) return [];
var separator = this._getHierarchicalFacetSeparator(
this.getHierarchicalFacetByName(facetName)
);
var path = refinement.split(separator);
return map_1(path, trim_1);
}
};
/**
* Callback used for clearRefinement method
* @callback SearchParameters.clearCallback
* @param {OperatorList|FacetList} value the value of the filter
* @param {string} key the current attribute name
* @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude`
* depending on the type of facet
* @return {boolean} `true` if the element should be removed. `false` otherwise.
*/
var SearchParameters_1 = SearchParameters;
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
var compact_1 = compact;
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(array, iteratee) {
var result,
index = -1,
length = array.length;
while (++index < length) {
var current = iteratee(array[index]);
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}
}
return result;
}
var _baseSum = baseSum;
/**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/
function sumBy(array, iteratee) {
return (array && array.length)
? _baseSum(array, _baseIteratee(iteratee, 2))
: 0;
}
var sumBy_1 = sumBy;
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return _arrayMap(props, function(key) {
return object[key];
});
}
var _baseValues = baseValues;
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : _baseValues(object, keys_1(object));
}
var values_1 = values;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$3 = Math.max;
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike_1(collection) ? collection : values_1(collection);
fromIndex = (fromIndex && !guard) ? toInteger_1(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax$3(length + fromIndex, 0);
}
return isString_1(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && _baseIndexOf(collection, value, fromIndex) > -1);
}
var includes_1 = includes;
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
var _baseSortBy = baseSortBy;
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol_1(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol_1(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
var _compareAscending = compareAscending;
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = _compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
var _compareMultiple = compareMultiple;
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
var index = -1;
iteratees = _arrayMap(iteratees.length ? iteratees : [identity_1], _baseUnary(_baseIteratee));
var result = _baseMap(collection, function(value, key, collection) {
var criteria = _arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return _baseSortBy(result, function(object, other) {
return _compareMultiple(object, other, orders);
});
}
var _baseOrderBy = baseOrderBy;
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray_1(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray_1(orders)) {
orders = orders == null ? [] : [orders];
}
return _baseOrderBy(collection, iteratees, orders);
}
var orderBy_1 = orderBy;
/** Used to store function metadata. */
var metaMap = _WeakMap && new _WeakMap;
var _metaMap = metaMap;
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !_metaMap ? identity_1 : function(func, data) {
_metaMap.set(func, data);
return func;
};
var _baseSetData = baseSetData;
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = _baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject_1(result) ? result : thisBinding;
};
}
var _createCtor = createCtor;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$1 = 1;
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG$1,
Ctor = _createCtor(func);
function wrapper() {
var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
var _createBind = createBind;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$5 = Math.max;
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax$5(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
var _composeArgs = composeArgs;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$6 = Math.max;
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax$6(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
var _composeArgsRight = composeArgsRight;
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
var _countHolders = countHolders;
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
var _baseLodash = baseLodash;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = _baseCreate(_baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
var _LazyWrapper = LazyWrapper;
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop$1() {
// No operation performed.
}
var noop_1 = noop$1;
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !_metaMap ? noop_1 : function(func) {
return _metaMap.get(func);
};
var _getData = getData;
/** Used to lookup unminified function names. */
var realNames = {};
var _realNames = realNames;
/** Used for built-in method references. */
var objectProto$18 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$16 = objectProto$18.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$16.call(_realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
var _getFuncName = getFuncName;
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
LodashWrapper.prototype = _baseCreate(_baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
var _LodashWrapper = LodashWrapper;
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof _LazyWrapper) {
return wrapper.clone();
}
var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = _copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
var _wrapperClone = wrapperClone;
/** Used for built-in method references. */
var objectProto$19 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$17 = objectProto$19.hasOwnProperty;
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) {
if (value instanceof _LodashWrapper) {
return value;
}
if (hasOwnProperty$17.call(value, '__wrapped__')) {
return _wrapperClone(value);
}
}
return new _LodashWrapper(value);
}
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = _baseLodash.prototype;
lodash.prototype.constructor = lodash;
var wrapperLodash = lodash;
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = _getFuncName(func),
other = wrapperLodash[funcName];
if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = _getData(other);
return !!data && func === data[0];
}
var _isLaziable = isLaziable;
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = _shortOut(_baseSetData);
var _setData = setData;
/** Used to match wrap detail comments. */
var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/;
var reSplitDetails = /,? & /;
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
var _getWrapDetails = getWrapDetails;
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
var _insertWrapDetails = insertWrapDetails;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$4 = 1;
var WRAP_BIND_KEY_FLAG$3 = 2;
var WRAP_CURRY_FLAG$3 = 8;
var WRAP_CURRY_RIGHT_FLAG$2 = 16;
var WRAP_PARTIAL_FLAG$3 = 32;
var WRAP_PARTIAL_RIGHT_FLAG$2 = 64;
var WRAP_ARY_FLAG$1 = 128;
var WRAP_REARG_FLAG = 256;
var WRAP_FLIP_FLAG$1 = 512;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG$1],
['bind', WRAP_BIND_FLAG$4],
['bindKey', WRAP_BIND_KEY_FLAG$3],
['curry', WRAP_CURRY_FLAG$3],
['curryRight', WRAP_CURRY_RIGHT_FLAG$2],
['flip', WRAP_FLIP_FLAG$1],
['partial', WRAP_PARTIAL_FLAG$3],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG$2],
['rearg', WRAP_REARG_FLAG]
];
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
_arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
var _updateWrapDetails = updateWrapDetails;
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/
function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask)));
}
var _setWrapToString = setWrapToString;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$3 = 1;
var WRAP_BIND_KEY_FLAG$2 = 2;
var WRAP_CURRY_BOUND_FLAG = 4;
var WRAP_CURRY_FLAG$2 = 8;
var WRAP_PARTIAL_FLAG$2 = 32;
var WRAP_PARTIAL_RIGHT_FLAG$1 = 64;
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG$2,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$2 : WRAP_PARTIAL_RIGHT_FLAG$1);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$2);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG$3 | WRAP_BIND_KEY_FLAG$2);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (_isLaziable(func)) {
_setData(result, newData);
}
result.placeholder = placeholder;
return _setWrapToString(result, func, bitmask);
}
var _createRecurry = createRecurry;
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = func;
return object.placeholder;
}
var _getHolder = getHolder;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin$1 = Math.min;
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin$1(indexes.length, arrLength),
oldArray = _copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
var _reorder = reorder;
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
var _replaceHolders = replaceHolders;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$2 = 1;
var WRAP_BIND_KEY_FLAG$1 = 2;
var WRAP_CURRY_FLAG$1 = 8;
var WRAP_CURRY_RIGHT_FLAG$1 = 16;
var WRAP_ARY_FLAG = 128;
var WRAP_FLIP_FLAG = 512;
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG,
isBind = bitmask & WRAP_BIND_FLAG$2,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG$1,
isCurried = bitmask & (WRAP_CURRY_FLAG$1 | WRAP_CURRY_RIGHT_FLAG$1),
isFlip = bitmask & WRAP_FLIP_FLAG,
Ctor = isBindKey ? undefined : _createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = _getHolder(wrapper),
holdersCount = _countHolders(args, placeholder);
}
if (partials) {
args = _composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = _composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = _replaceHolders(args, placeholder);
return _createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = _reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== _root && this instanceof wrapper) {
fn = Ctor || _createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
var _createHybrid = createHybrid;
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = _createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = _getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: _replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return _createRecurry(
func, bitmask, _createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
return _apply(fn, this, args);
}
return wrapper;
}
var _createCurry = createCurry;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$5 = 1;
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG$5,
Ctor = _createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return _apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
var _createPartial = createPartial;
/** Used as the internal argument placeholder. */
var PLACEHOLDER$1 = '__lodash_placeholder__';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$6 = 1;
var WRAP_BIND_KEY_FLAG$4 = 2;
var WRAP_CURRY_BOUND_FLAG$1 = 4;
var WRAP_CURRY_FLAG$4 = 8;
var WRAP_ARY_FLAG$2 = 128;
var WRAP_REARG_FLAG$1 = 256;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin$2 = Math.min;
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG$6 | WRAP_BIND_KEY_FLAG$4 | WRAP_ARY_FLAG$2);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_CURRY_FLAG$4)) ||
((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$4));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG$6) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG$6 ? 0 : WRAP_CURRY_BOUND_FLAG$1;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? _composeArgs(partials, value, source[4]) : value;
data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER$1) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER$1) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG$2) {
data[8] = data[8] == null ? source[8] : nativeMin$2(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
var _mergeData = mergeData;
/** Error message constants. */
var FUNC_ERROR_TEXT$1 = 'Expected a function';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
var WRAP_BIND_KEY_FLAG = 2;
var WRAP_CURRY_FLAG = 8;
var WRAP_CURRY_RIGHT_FLAG = 16;
var WRAP_PARTIAL_FLAG$1 = 32;
var WRAP_PARTIAL_RIGHT_FLAG = 64;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$4 = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT$1);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG$1 | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax$4(toInteger_1(ary), 0);
arity = arity === undefined ? arity : toInteger_1(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : _getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
_mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax$4(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = _createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = _createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG$1 || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG$1)) && !holders.length) {
result = _createPartial(func, bitmask, thisArg, partials);
} else {
result = _createHybrid.apply(undefined, newData);
}
var setter = data ? _baseSetData : _setData;
return _setWrapToString(setter(result, newData), func, bitmask);
}
var _createWrap = createWrap;
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_FLAG = 32;
/**
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = _baseRest(function(func, partials) {
var holders = _replaceHolders(partials, _getHolder(partial));
return _createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
});
// Assign default placeholders.
partial.placeholder = {};
var partial_1 = partial;
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_RIGHT_FLAG$3 = 64;
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = _baseRest(function(func, partials) {
var holders = _replaceHolders(partials, _getHolder(partialRight));
return _createWrap(func, WRAP_PARTIAL_RIGHT_FLAG$3, undefined, partials, holders);
});
// Assign default placeholders.
partialRight.placeholder = {};
var partialRight_1 = partialRight;
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
var _baseClamp = baseClamp;
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString_1(string);
position = position == null
? 0
: _baseClamp(toInteger_1(position), 0, string.length);
target = _baseToString(target);
return string.slice(position, position + target.length) == target;
}
var startsWith_1 = startsWith;
/**
* Transform sort format from user friendly notation to lodash format
* @param {string[]} sortBy array of predicate of the form "attribute:order"
* @return {array.<string[]>} array containing 2 elements : attributes, orders
*/
var formatSort = function formatSort(sortBy, defaults) {
return reduce_1(sortBy, function preparePredicate(out, sortInstruction) {
var sortInstructions = sortInstruction.split(':');
if (defaults && sortInstructions.length === 1) {
var similarDefault = find_1(defaults, function(predicate) {
return startsWith_1(predicate, sortInstruction[0]);
});
if (similarDefault) {
sortInstructions = similarDefault.split(':');
}
}
out[0].push(sortInstructions[0]);
out[1].push(sortInstructions[1]);
return out;
}, [[], []]);
};
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject_1(object)) {
return object;
}
path = _castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = _toKey(path[index]),
newValue = value;
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject_1(objValue)
? objValue
: (_isIndex(path[index + 1]) ? [] : {});
}
}
_assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
var _baseSet = baseSet;
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = _baseGet(object, path);
if (predicate(value, path)) {
_baseSet(result, _castPath(path, object), value);
}
}
return result;
}
var _basePickBy = basePickBy;
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = _arrayMap(_getAllKeysIn(object), function(prop) {
return [prop];
});
predicate = _baseIteratee(predicate);
return _basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
var pickBy_1 = pickBy;
var generateHierarchicalTree_1 = generateTrees;
function generateTrees(state) {
return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) {
var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex];
var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] &&
state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || '';
var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet);
var sortBy = formatSort(state._getHierarchicalFacetSortBy(hierarchicalFacet));
var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, hierarchicalFacetRefinement);
var results = hierarchicalFacetResult;
if (hierarchicalRootPath) {
results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length);
}
return reduce_1(results, generateTreeFn, {
name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
count: null, // root level, no count
isRefined: true, // root level, always refined
path: null, // root level, no path
data: null
});
};
}
function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, currentRefinement) {
return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) {
var parent = hierarchicalTree;
if (currentHierarchicalLevel > 0) {
var level = 0;
parent = hierarchicalTree;
while (level < currentHierarchicalLevel) {
parent = parent && find_1(parent.data, {isRefined: true});
level++;
}
}
// we found a refined parent, let's add current level data under it
if (parent) {
// filter values in case an object has multiple categories:
// {
// categories: {
// level0: ['beers', 'bières'],
// level1: ['beers > IPA', 'bières > Belges']
// }
// }
//
// If parent refinement is `beers`, then we do not want to have `bières > Belges`
// showing up
var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath,
currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel);
parent.data = orderBy_1(
map_1(
pickBy_1(hierarchicalFacetResult.data, onlyMatchingValuesFn),
formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement)
),
sortBy[0], sortBy[1]
);
}
return hierarchicalTree;
};
}
function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel) {
return function(facetCount, facetValue) {
// we want the facetValue is a child of hierarchicalRootPath
if (hierarchicalRootPath &&
(facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) {
return false;
}
// we always want root levels (only when there is no prefix path)
return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 ||
// if there is a rootPath, being root level mean 1 level under rootPath
hierarchicalRootPath &&
facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 ||
// if current refinement is a root level and current facetValue is a root level,
// keep the facetValue
facetValue.indexOf(hierarchicalSeparator) === -1 &&
currentRefinement.indexOf(hierarchicalSeparator) === -1 ||
// currentRefinement is a child of the facet value
currentRefinement.indexOf(facetValue) === 0 ||
// facetValue is a child of the current parent, add it
facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 &&
(hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0);
};
}
function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) {
return function format(facetCount, facetValue) {
return {
name: trim_1(last_1(facetValue.split(hierarchicalSeparator))),
path: facetValue,
count: facetCount,
isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0,
data: null
};
};
}
/**
* @typedef SearchResults.Facet
* @type {object}
* @property {string} name name of the attribute in the record
* @property {object} data the faceting data: value, number of entries
* @property {object} stats undefined unless facet_stats is retrieved from algolia
*/
/**
* @typedef SearchResults.HierarchicalFacet
* @type {object}
* @property {string} name name of the current value given the hierarchical level, trimmed.
* If root node, you get the facet name
* @property {number} count number of objects matching this hierarchical value
* @property {string} path the current hierarchical value full path
* @property {boolean} isRefined `true` if the current value was refined, `false` otherwise
* @property {HierarchicalFacet[]} data sub values for the current level
*/
/**
* @typedef SearchResults.FacetValue
* @type {object}
* @property {string} name the facet value itself
* @property {number} count times this facet appears in the results
* @property {boolean} isRefined is the facet currently selected
* @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets)
*/
/**
* @typedef Refinement
* @type {object}
* @property {string} type the type of filter used:
* `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical`
* @property {string} attributeName name of the attribute used for filtering
* @property {string} name the value of the filter
* @property {number} numericValue the value as a number. Only for numeric filters.
* @property {string} operator the operator used. Only for numeric filters.
* @property {number} count the number of computed hits for this filter. Only on facets.
* @property {boolean} exhaustive if the count is exhaustive
*/
function getIndices(obj) {
var indices = {};
forEach_1(obj, function(val, idx) { indices[val] = idx; });
return indices;
}
function assignFacetStats(dest, facetStats, key) {
if (facetStats && facetStats[key]) {
dest.stats = facetStats[key];
}
}
function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) {
return find_1(
hierarchicalFacets,
function facetKeyMatchesAttribute(hierarchicalFacet) {
return includes_1(hierarchicalFacet.attributes, hierarchicalAttributeName);
}
);
}
/*eslint-disable */
/**
* Constructor for SearchResults
* @class
* @classdesc SearchResults contains the results of a query to Algolia using the
* {@link AlgoliaSearchHelper}.
* @param {SearchParameters} state state that led to the response
* @param {array.<object>} results the results from algolia client
* @example <caption>SearchResults of the first query in
* <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption>
{
"hitsPerPage": 10,
"processingTimeMS": 2,
"facets": [
{
"name": "type",
"data": {
"HardGood": 6627,
"BlackTie": 550,
"Music": 665,
"Software": 131,
"Game": 456,
"Movie": 1571
},
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"Free shipping": 5507
},
"name": "shipping"
}
],
"hits": [
{
"thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
"_highlightResult": {
"shortDescription": {
"matchLevel": "none",
"value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"matchedWords": []
},
"category": {
"matchLevel": "none",
"value": "Computer Security Software",
"matchedWords": []
},
"manufacturer": {
"matchedWords": [],
"value": "Webroot",
"matchLevel": "none"
},
"name": {
"value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"matchedWords": [],
"matchLevel": "none"
}
},
"image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
"shipping": "Free shipping",
"bestSellingRank": 4,
"shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
"name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"category": "Computer Security Software",
"salePrice_range": "1 - 50",
"objectID": "1688832",
"type": "Software",
"customerReviewCount": 5980,
"salePrice": 49.99,
"manufacturer": "Webroot"
},
....
],
"nbHits": 10000,
"disjunctiveFacets": [
{
"exhaustive": false,
"data": {
"5": 183,
"12": 112,
"7": 149,
...
},
"name": "customerReviewCount",
"stats": {
"max": 7461,
"avg": 157.939,
"min": 1
}
},
{
"data": {
"Printer Ink": 142,
"Wireless Speakers": 60,
"Point & Shoot Cameras": 48,
...
},
"name": "category",
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"> 5000": 2,
"1 - 50": 6524,
"501 - 2000": 566,
"201 - 500": 1501,
"101 - 200": 1360,
"2001 - 5000": 47
},
"name": "salePrice_range"
},
{
"data": {
"Dynex™": 202,
"Insignia™": 230,
"PNY": 72,
...
},
"name": "manufacturer",
"exhaustive": false
}
],
"query": "",
"nbPages": 100,
"page": 0,
"index": "bestbuy"
}
**/
/*eslint-enable */
function SearchResults(state, results) {
var mainSubResponse = results[0];
this._rawResults = results;
/**
* query used to generate the results
* @member {string}
*/
this.query = mainSubResponse.query;
/**
* The query as parsed by the engine given all the rules.
* @member {string}
*/
this.parsedQuery = mainSubResponse.parsedQuery;
/**
* all the records that match the search parameters. Each record is
* augmented with a new attribute `_highlightResult`
* which is an object keyed by attribute and with the following properties:
* - `value` : the value of the facet highlighted (html)
* - `matchLevel`: full, partial or none depending on how the query terms match
* @member {object[]}
*/
this.hits = mainSubResponse.hits;
/**
* index where the results come from
* @member {string}
*/
this.index = mainSubResponse.index;
/**
* number of hits per page requested
* @member {number}
*/
this.hitsPerPage = mainSubResponse.hitsPerPage;
/**
* total number of hits of this query on the index
* @member {number}
*/
this.nbHits = mainSubResponse.nbHits;
/**
* total number of pages with respect to the number of hits per page and the total number of hits
* @member {number}
*/
this.nbPages = mainSubResponse.nbPages;
/**
* current page
* @member {number}
*/
this.page = mainSubResponse.page;
/**
* sum of the processing time of all the queries
* @member {number}
*/
this.processingTimeMS = sumBy_1(results, 'processingTimeMS');
/**
* The position if the position was guessed by IP.
* @member {string}
* @example "48.8637,2.3615",
*/
this.aroundLatLng = mainSubResponse.aroundLatLng;
/**
* The radius computed by Algolia.
* @member {string}
* @example "126792922",
*/
this.automaticRadius = mainSubResponse.automaticRadius;
/**
* String identifying the server used to serve this request.
* @member {string}
* @example "c7-use-2.algolia.net",
*/
this.serverUsed = mainSubResponse.serverUsed;
/**
* Boolean that indicates if the computation of the counts did time out.
* @deprecated
* @member {boolean}
*/
this.timeoutCounts = mainSubResponse.timeoutCounts;
/**
* Boolean that indicates if the computation of the hits did time out.
* @deprecated
* @member {boolean}
*/
this.timeoutHits = mainSubResponse.timeoutHits;
/**
* True if the counts of the facets is exhaustive
* @member {boolean}
*/
this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount;
/**
* True if the number of hits is exhaustive
* @member {boolean}
*/
this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits;
/**
* Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/).
* @member {object[]}
*/
this.userData = mainSubResponse.userData;
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
this.disjunctiveFacets = [];
/**
* disjunctive facets results
* @member {SearchResults.HierarchicalFacet[]}
*/
this.hierarchicalFacets = map_1(state.hierarchicalFacets, function initFutureTree() {
return [];
});
/**
* other facets results
* @member {SearchResults.Facet[]}
*/
this.facets = [];
var disjunctiveFacets = state.getRefinedDisjunctiveFacets();
var facetsIndices = getIndices(state.facets);
var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets);
var nextDisjunctiveResult = 1;
var self = this;
// Since we send request only for disjunctive facets that have been refined,
// we get the facets informations from the first, general, response.
forEach_1(mainSubResponse.facets, function(facetValueObject, facetKey) {
var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName(
state.hierarchicalFacets,
facetKey
);
if (hierarchicalFacet) {
// Place the hierarchicalFacet data at the correct index depending on
// the attributes order that was defined at the helper initialization
var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey);
var idxAttributeName = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name});
self.hierarchicalFacets[idxAttributeName][facetIndex] = {
attribute: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
} else {
var isFacetDisjunctive = indexOf_1(state.disjunctiveFacets, facetKey) !== -1;
var isFacetConjunctive = indexOf_1(state.facets, facetKey) !== -1;
var position;
if (isFacetDisjunctive) {
position = disjunctiveFacetsIndices[facetKey];
self.disjunctiveFacets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey);
}
if (isFacetConjunctive) {
position = facetsIndices[facetKey];
self.facets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey);
}
}
});
// Make sure we do not keep holes within the hierarchical facets
this.hierarchicalFacets = compact_1(this.hierarchicalFacets);
// aggregate the refined disjunctive facets
forEach_1(disjunctiveFacets, function(disjunctiveFacet) {
var result = results[nextDisjunctiveResult];
var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet);
// There should be only item in facets.
forEach_1(result.facets, function(facetResults, dfacet) {
var position;
if (hierarchicalFacet) {
position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
self.hierarchicalFacets[position][attributeIndex].data = merge_1(
{},
self.hierarchicalFacets[position][attributeIndex].data,
facetResults
);
} else {
position = disjunctiveFacetsIndices[dfacet];
var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {};
self.disjunctiveFacets[position] = {
name: dfacet,
data: defaults_1({}, facetResults, dataFromMainRequest),
exhaustive: result.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet);
if (state.disjunctiveFacetsRefinements[dfacet]) {
forEach_1(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) {
// add the disjunctive refinements if it is no more retrieved
if (!self.disjunctiveFacets[position].data[refinementValue] &&
indexOf_1(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) {
self.disjunctiveFacets[position].data[refinementValue] = 0;
}
});
}
}
});
nextDisjunctiveResult++;
});
// if we have some root level values for hierarchical facets, merge them
forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are already at a root refinement (or no refinement at all), there is no
// root level values request
if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) {
return;
}
var result = results[nextDisjunctiveResult];
forEach_1(result.facets, function(facetResults, dfacet) {
var position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
// when we always get root levels, if the hits refinement is `beers > IPA` (count: 5),
// then the disjunctive values will be `beers` (count: 100),
// but we do not want to display
// | beers (100)
// > IPA (5)
// We want
// | beers (5)
// > IPA (5)
var defaultData = {};
if (currentRefinement.length > 0) {
var root = currentRefinement[0].split(separator)[0];
defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root];
}
self.hierarchicalFacets[position][attributeIndex].data = defaults_1(
defaultData,
facetResults,
self.hierarchicalFacets[position][attributeIndex].data
);
});
nextDisjunctiveResult++;
});
// add the excludes
forEach_1(state.facetsExcludes, function(excludes, facetName) {
var position = facetsIndices[facetName];
self.facets[position] = {
name: facetName,
data: mainSubResponse.facets[facetName],
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
forEach_1(excludes, function(facetValue) {
self.facets[position] = self.facets[position] || {name: facetName};
self.facets[position].data = self.facets[position].data || {};
self.facets[position].data[facetValue] = 0;
});
});
this.hierarchicalFacets = map_1(this.hierarchicalFacets, generateHierarchicalTree_1(state));
this.facets = compact_1(this.facets);
this.disjunctiveFacets = compact_1(this.disjunctiveFacets);
this._state = state;
}
/**
* Get a facet object with its name
* @deprecated
* @param {string} name name of the faceted attribute
* @return {SearchResults.Facet} the facet object
*/
SearchResults.prototype.getFacetByName = function(name) {
var predicate = {name: name};
return find_1(this.facets, predicate) ||
find_1(this.disjunctiveFacets, predicate) ||
find_1(this.hierarchicalFacets, predicate);
};
/**
* Get the facet values of a specified attribute from a SearchResults object.
* @private
* @param {SearchResults} results the search results to search in
* @param {string} attribute name of the faceted attribute to search for
* @return {array|object} facet values. For the hierarchical facets it is an object.
*/
function extractNormalizedFacetValues(results, attribute) {
var predicate = {name: attribute};
if (results._state.isConjunctiveFacet(attribute)) {
var facet = find_1(results.facets, predicate);
if (!facet) return [];
return map_1(facet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isFacetRefined(attribute, k),
isExcluded: results._state.isExcludeRefined(attribute, k)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find_1(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return map_1(disjunctiveFacet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isDisjunctiveFacetRefined(attribute, k)
};
});
} else if (results._state.isHierarchicalFacet(attribute)) {
return find_1(results.hierarchicalFacets, predicate);
}
}
/**
* Sort nodes of a hierarchical facet results
* @private
* @param {HierarchicalFacet} node node to upon which we want to apply the sort
*/
function recSort(sortFn, node) {
if (!node.data || node.data.length === 0) {
return node;
}
var children = map_1(node.data, partial_1(recSort, sortFn));
var sortedChildren = sortFn(children);
var newNode = merge_1({}, node, {data: sortedChildren});
return newNode;
}
SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc'];
function vanillaSortFn(order, data) {
return data.sort(order);
}
/**
* Get a the list of values for a given facet attribute. Those values are sorted
* refinement first, descending count (bigger value on top), and name ascending
* (alphabetical order). The sort formula can overridden using either string based
* predicates or a function.
*
* This method will return all the values returned by the Algolia engine plus all
* the values already refined. This means that it can happen that the
* `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet)
* might not be respected if you have facet values that are already refined.
* @param {string} attribute attribute name
* @param {object} opts configuration options.
* @param {Array.<string> | function} opts.sortBy
* When using strings, it consists of
* the name of the [FacetValue](#SearchResults.FacetValue) or the
* [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the
* order (`asc` or `desc`). For example to order the value by count, the
* argument would be `['count:asc']`.
*
* If only the attribute name is specified, the ordering defaults to the one
* specified in the default value for this attribute.
*
* When not specified, the order is
* ascending. This parameter can also be a function which takes two facet
* values and should return a number, 0 if equal, 1 if the first argument is
* bigger or -1 otherwise.
*
* The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']`
* @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('results', function(content){
* //get values ordered only by name ascending using the string predicate
* content.getFacetValues('city', {sortBy: ['name:asc']});
* //get values ordered only by count ascending using a function
* content.getFacetValues('city', {
* // this is equivalent to ['count:asc']
* sortBy: function(a, b) {
* if (a.count === b.count) return 0;
* if (a.count > b.count) return 1;
* if (b.count > a.count) return -1;
* }
* });
* });
*/
SearchResults.prototype.getFacetValues = function(attribute, opts) {
var facetValues = extractNormalizedFacetValues(this, attribute);
if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.');
var options = defaults_1({}, opts, {sortBy: SearchResults.DEFAULT_SORT});
if (isArray_1(options.sortBy)) {
var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT);
if (isArray_1(facetValues)) {
return orderBy_1(facetValues, order[0], order[1]);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partialRight_1(orderBy_1, order[0], order[1]), facetValues);
} else if (isFunction_1(options.sortBy)) {
if (isArray_1(facetValues)) {
return facetValues.sort(options.sortBy);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partial_1(vanillaSortFn, options.sortBy), facetValues);
}
throw new Error(
'options.sortBy is optional but if defined it must be ' +
'either an array of string (predicates) or a sorting function'
);
};
/**
* Returns the facet stats if attribute is defined and the facet contains some.
* Otherwise returns undefined.
* @param {string} attribute name of the faceted attribute
* @return {object} The stats of the facet
*/
SearchResults.prototype.getFacetStats = function(attribute) {
if (this._state.isConjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.facets, attribute);
} else if (this._state.isDisjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute);
}
throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`');
};
function getFacetStatsIfAvailable(facetList, facetName) {
var data = find_1(facetList, {name: facetName});
return data && data.stats;
}
/**
* Returns all refinements for all filters + tags. It also provides
* additional information: count and exhausistivity for each filter.
*
* See the [refinement type](#Refinement) for an exhaustive view of the available
* data.
*
* @return {Array.<Refinement>} all the refinements
*/
SearchResults.prototype.getRefinements = function() {
var state = this._state;
var results = this;
var res = [];
forEach_1(state.facetsRefinements, function(refinements, attributeName) {
forEach_1(refinements, function(name) {
res.push(getRefinement(state, 'facet', attributeName, name, results.facets));
});
});
forEach_1(state.facetsExcludes, function(refinements, attributeName) {
forEach_1(refinements, function(name) {
res.push(getRefinement(state, 'exclude', attributeName, name, results.facets));
});
});
forEach_1(state.disjunctiveFacetsRefinements, function(refinements, attributeName) {
forEach_1(refinements, function(name) {
res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets));
});
});
forEach_1(state.hierarchicalFacetsRefinements, function(refinements, attributeName) {
forEach_1(refinements, function(name) {
res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets));
});
});
forEach_1(state.numericRefinements, function(operators, attributeName) {
forEach_1(operators, function(values, operator) {
forEach_1(values, function(value) {
res.push({
type: 'numeric',
attributeName: attributeName,
name: value,
numericValue: value,
operator: operator
});
});
});
});
forEach_1(state.tagRefinements, function(name) {
res.push({type: 'tag', attributeName: '_tags', name: name});
});
return res;
};
function getRefinement(state, type, attributeName, name, resultsFacets) {
var facet = find_1(resultsFacets, {name: attributeName});
var count = get_1(facet, 'data[' + name + ']');
var exhaustive = get_1(facet, 'exhaustive');
return {
type: type,
attributeName: attributeName,
name: name,
count: count || 0,
exhaustive: exhaustive || false
};
}
function getHierarchicalRefinement(state, attributeName, name, resultsFacets) {
var facet = find_1(resultsFacets, {name: attributeName});
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var splitted = name.split(facetDeclaration.separator);
var configuredName = splitted[splitted.length - 1];
for (var i = 0; facet !== undefined && i < splitted.length; ++i) {
facet = find_1(facet.data, {name: splitted[i]});
}
var count = get_1(facet, 'count');
var exhaustive = get_1(facet, 'exhaustive');
return {
type: 'hierarchical',
attributeName: attributeName,
name: configuredName,
count: count || 0,
exhaustive: exhaustive || false
};
}
var SearchResults_1 = SearchResults;
var isBufferBrowser = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
};
var inherits_browser = createCommonjsModule(function (module) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
};
}
});
var util = createCommonjsModule(function (module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(commonjsGlobal.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = isBufferBrowser;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = inherits_browser;
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
});
var util_1 = util.format;
var util_2 = util.deprecate;
var util_3 = util.debuglog;
var util_4 = util.inspect;
var util_5 = util.isArray;
var util_6 = util.isBoolean;
var util_7 = util.isNull;
var util_8 = util.isNullOrUndefined;
var util_9 = util.isNumber;
var util_10 = util.isString;
var util_11 = util.isSymbol;
var util_12 = util.isUndefined;
var util_13 = util.isRegExp;
var util_14 = util.isObject;
var util_15 = util.isDate;
var util_16 = util.isError;
var util_17 = util.isFunction;
var util_18 = util.isPrimitive;
var util_19 = util.isBuffer;
var util_20 = util.log;
var util_21 = util.inherits;
var util_22 = util._extend;
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
var events = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber$2(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject$2(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined$2(handler))
return false;
if (isFunction$2(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject$2(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction$2(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction$2(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject$2(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject$2(this._events[type]) && !this._events[type].warned) {
if (!isUndefined$2(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction$2(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction$2(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction$2(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject$2(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction$2(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction$2(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction$2(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction$2(arg) {
return typeof arg === 'function';
}
function isNumber$2(arg) {
return typeof arg === 'number';
}
function isObject$2(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined$2(arg) {
return arg === void 0;
}
/**
* A DerivedHelper is a way to create sub requests to
* Algolia from a main helper.
* @class
* @classdesc The DerivedHelper provides an event based interface for search callbacks:
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
*/
function DerivedHelper(mainHelper, fn) {
this.main = mainHelper;
this.fn = fn;
this.lastResults = null;
}
util.inherits(DerivedHelper, events.EventEmitter);
/**
* Detach this helper from the main helper
* @return {undefined}
* @throws Error if the derived helper is already detached
*/
DerivedHelper.prototype.detach = function() {
this.removeAllListeners();
this.main.detachDerivedHelper(this);
};
DerivedHelper.prototype.getModifiedState = function(parameters) {
return this.fn(parameters);
};
var DerivedHelper_1 = DerivedHelper;
var requestBuilder = {
/**
* Get all the queries to send to the client, those queries can used directly
* with the Algolia client.
* @private
* @return {object[]} The queries
*/
_getQueries: function getQueries(index, state) {
var queries = [];
// One query for the hits
queries.push({
indexName: index,
params: requestBuilder._getHitsSearchParams(state)
});
// One for each disjunctive facets
forEach_1(state.getRefinedDisjunctiveFacets(), function(refinedFacet) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet)
});
});
// maybe more to get the root level of hierarchical facets when activated
forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are deeper than level 0 (starting from `beer > IPA`)
// we want to get the root values
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true)
});
}
});
return queries;
},
/**
* Build search parameters used to fetch hits
* @private
* @return {object.<string, any>}
*/
_getHitsSearchParams: function(state) {
var facets = state.facets
.concat(state.disjunctiveFacets)
.concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state));
var facetFilters = requestBuilder._getFacetFilters(state);
var numericFilters = requestBuilder._getNumericFilters(state);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
facets: facets,
tagFilters: tagFilters
};
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
return merge_1(state.getQueryParams(), additionalParams);
},
/**
* Build search parameters used to fetch a disjunctive facet
* @private
* @param {string} facet the associated facet name
* @param {boolean} hierarchicalRootLevel ?? FIXME
* @return {object}
*/
_getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) {
var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel);
var numericFilters = requestBuilder._getNumericFilters(state, facet);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
hitsPerPage: 1,
page: 0,
attributesToRetrieve: [],
attributesToHighlight: [],
attributesToSnippet: [],
tagFilters: tagFilters,
analytics: false
};
var hierarchicalFacet = state.getHierarchicalFacetByName(facet);
if (hierarchicalFacet) {
additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute(
state,
hierarchicalFacet,
hierarchicalRootLevel
);
} else {
additionalParams.facets = facet;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
return merge_1(state.getQueryParams(), additionalParams);
},
/**
* Return the numeric filters in an algolia request fashion
* @private
* @param {string} [facetName] the name of the attribute for which the filters should be excluded
* @return {string[]} the numeric filters in the algolia format
*/
_getNumericFilters: function(state, facetName) {
if (state.numericFilters) {
return state.numericFilters;
}
var numericFilters = [];
forEach_1(state.numericRefinements, function(operators, attribute) {
forEach_1(operators, function(values, operator) {
if (facetName !== attribute) {
forEach_1(values, function(value) {
if (isArray_1(value)) {
var vs = map_1(value, function(v) {
return attribute + operator + v;
});
numericFilters.push(vs);
} else {
numericFilters.push(attribute + operator + value);
}
});
}
});
});
return numericFilters;
},
/**
* Return the tags filters depending
* @private
* @return {string}
*/
_getTagFilters: function(state) {
if (state.tagFilters) {
return state.tagFilters;
}
return state.tagRefinements.join(',');
},
/**
* Build facetFilters parameter based on current refinements. The array returned
* contains strings representing the facet filters in the algolia format.
* @private
* @param {string} [facet] if set, the current disjunctive facet
* @return {array.<string>}
*/
_getFacetFilters: function(state, facet, hierarchicalRootLevel) {
var facetFilters = [];
forEach_1(state.facetsRefinements, function(facetValues, facetName) {
forEach_1(facetValues, function(facetValue) {
facetFilters.push(facetName + ':' + facetValue);
});
});
forEach_1(state.facetsExcludes, function(facetValues, facetName) {
forEach_1(facetValues, function(facetValue) {
facetFilters.push(facetName + ':-' + facetValue);
});
});
forEach_1(state.disjunctiveFacetsRefinements, function(facetValues, facetName) {
if (facetName === facet || !facetValues || facetValues.length === 0) return;
var orFilters = [];
forEach_1(facetValues, function(facetValue) {
orFilters.push(facetName + ':' + facetValue);
});
facetFilters.push(orFilters);
});
forEach_1(state.hierarchicalFacetsRefinements, function(facetValues, facetName) {
var facetValue = facetValues[0];
if (facetValue === undefined) {
return;
}
var hierarchicalFacet = state.getHierarchicalFacetByName(facetName);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeToRefine;
var attributesIndex;
// we ask for parent facet values only when the `facet` is the current hierarchical facet
if (facet === facetName) {
// if we are at the root level already, no need to ask for facet values, we get them from
// the hits query
if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) ||
(rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) {
return;
}
if (!rootPath) {
attributesIndex = facetValue.split(separator).length - 2;
facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator));
} else {
attributesIndex = rootPath.split(separator).length - 1;
facetValue = rootPath;
}
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
} else {
attributesIndex = facetValue.split(separator).length - 1;
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
}
if (attributeToRefine) {
facetFilters.push([attributeToRefine + ':' + facetValue]);
}
});
return facetFilters;
},
_getHitsHierarchicalFacetsAttributes: function(state) {
var out = [];
return reduce_1(
state.hierarchicalFacets,
// ask for as much levels as there's hierarchical refinements
function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) {
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0];
// if no refinement, ask for root level
if (!hierarchicalRefinement) {
allAttributes.push(hierarchicalFacet.attributes[0]);
return allAttributes;
}
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var level = hierarchicalRefinement.split(separator).length;
var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1);
return allAttributes.concat(newAttributes);
}, out);
},
_getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) {
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (rootLevel === true) {
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeIndex = 0;
if (rootPath) {
attributeIndex = rootPath.split(separator).length;
}
return [hierarchicalFacet.attributes[attributeIndex]];
}
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || '';
// if refinement is 'beers > IPA > Flying dog',
// then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values)
var parentLevel = hierarchicalRefinement.split(separator).length - 1;
return hierarchicalFacet.attributes.slice(0, parentLevel + 1);
},
getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) {
var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ?
state.clearRefinements(facetName) :
state;
var searchForFacetSearchParameters = {
facetQuery: query,
facetName: facetName
};
if (typeof maxFacetHits === 'number') {
searchForFacetSearchParameters.maxFacetHits = maxFacetHits;
}
var queries = merge_1(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters);
return queries;
}
};
var requestBuilder_1 = requestBuilder;
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
_baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
var _baseInverter = baseInverter;
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return _baseInverter(object, setter, toIteratee(iteratee), {});
};
}
var _createInverter = createInverter;
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = _createInverter(function(result, value, key) {
result[value] = key;
}, constant_1(identity_1));
var invert_1 = invert;
var keys2Short = {
advancedSyntax: 'aS',
allowTyposOnNumericTokens: 'aTONT',
analyticsTags: 'aT',
analytics: 'a',
aroundLatLngViaIP: 'aLLVIP',
aroundLatLng: 'aLL',
aroundPrecision: 'aP',
aroundRadius: 'aR',
attributesToHighlight: 'aTH',
attributesToRetrieve: 'aTR',
attributesToSnippet: 'aTS',
disjunctiveFacetsRefinements: 'dFR',
disjunctiveFacets: 'dF',
distinct: 'd',
facetsExcludes: 'fE',
facetsRefinements: 'fR',
facets: 'f',
getRankingInfo: 'gRI',
hierarchicalFacetsRefinements: 'hFR',
hierarchicalFacets: 'hF',
highlightPostTag: 'hPoT',
highlightPreTag: 'hPrT',
hitsPerPage: 'hPP',
ignorePlurals: 'iP',
index: 'idx',
insideBoundingBox: 'iBB',
insidePolygon: 'iPg',
length: 'l',
maxValuesPerFacet: 'mVPF',
minimumAroundRadius: 'mAR',
minProximity: 'mP',
minWordSizefor1Typo: 'mWS1T',
minWordSizefor2Typos: 'mWS2T',
numericFilters: 'nF',
numericRefinements: 'nR',
offset: 'o',
optionalWords: 'oW',
page: 'p',
queryType: 'qT',
query: 'q',
removeWordsIfNoResults: 'rWINR',
replaceSynonymsInHighlight: 'rSIH',
restrictSearchableAttributes: 'rSA',
synonyms: 's',
tagFilters: 'tF',
tagRefinements: 'tR',
typoTolerance: 'tT',
optionalTagFilters: 'oTF',
optionalFacetFilters: 'oFF',
snippetEllipsisText: 'sET',
disableExactOnAttributes: 'dEOA',
enableExactOnSingleWordQuery: 'eEOSWQ'
};
var short2Keys = invert_1(keys2Short);
var shortener = {
/**
* All the keys of the state, encoded.
* @const
*/
ENCODED_PARAMETERS: keys_1(short2Keys),
/**
* Decode a shorten attribute
* @param {string} shortKey the shorten attribute
* @return {string} the decoded attribute, undefined otherwise
*/
decode: function(shortKey) {
return short2Keys[shortKey];
},
/**
* Encode an attribute into a short version
* @param {string} key the attribute
* @return {string} the shorten attribute
*/
encode: function(key) {
return keys2Short[key];
}
};
var utils = createCommonjsModule(function (module, exports) {
var has = Object.prototype.hasOwnProperty;
var hexTable = (function () {
var array = [];
for (var i = 0; i < 256; ++i) {
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
}
return array;
}());
var compactQueue = function compactQueue(queue) {
var obj;
while (queue.length) {
var item = queue.pop();
obj = item.obj[item.prop];
if (Array.isArray(obj)) {
var compacted = [];
for (var j = 0; j < obj.length; ++j) {
if (typeof obj[j] !== 'undefined') {
compacted.push(obj[j]);
}
}
item.obj[item.prop] = compacted;
}
}
return obj;
};
exports.arrayToObject = function arrayToObject(source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
exports.merge = function merge(target, source, options) {
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (Array.isArray(target)) {
target.push(source);
} else if (typeof target === 'object') {
if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) {
target[source] = true;
}
} else {
return [target, source];
}
return target;
}
if (typeof target !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (Array.isArray(target) && !Array.isArray(source)) {
mergeTarget = exports.arrayToObject(target, options);
}
if (Array.isArray(target) && Array.isArray(source)) {
source.forEach(function (item, i) {
if (has.call(target, i)) {
if (target[i] && typeof target[i] === 'object') {
target[i] = exports.merge(target[i], item, options);
} else {
target.push(item);
}
} else {
target[i] = item;
}
});
return target;
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (has.call(acc, key)) {
acc[key] = exports.merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
exports.assign = function assignSingleSource(target, source) {
return Object.keys(source).reduce(function (acc, key) {
acc[key] = source[key];
return acc;
}, target);
};
exports.decode = function (str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
return str;
}
};
exports.encode = function encode(str) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = typeof str === 'string' ? str : String(str);
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D // -
|| c === 0x2E // .
|| c === 0x5F // _
|| c === 0x7E // ~
|| (c >= 0x30 && c <= 0x39) // 0-9
|| (c >= 0x41 && c <= 0x5A) // a-z
|| (c >= 0x61 && c <= 0x7A) // A-Z
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)]
+ hexTable[0x80 | ((c >> 12) & 0x3F)]
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
+ hexTable[0x80 | (c & 0x3F)];
}
return out;
};
exports.compact = function compact(value) {
var queue = [{ obj: { o: value }, prop: 'o' }];
var refs = [];
for (var i = 0; i < queue.length; ++i) {
var item = queue[i];
var obj = item.obj[item.prop];
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
var val = obj[key];
if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
queue.push({ obj: obj, prop: key });
refs.push(val);
}
}
}
return compactQueue(queue);
};
exports.isRegExp = function isRegExp(obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
exports.isBuffer = function isBuffer(obj) {
if (obj === null || typeof obj === 'undefined') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
});
var utils_1 = utils.arrayToObject;
var utils_2 = utils.merge;
var utils_3 = utils.assign;
var utils_4 = utils.decode;
var utils_5 = utils.encode;
var utils_6 = utils.compact;
var utils_7 = utils.isRegExp;
var utils_8 = utils.isBuffer;
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
var formats = {
'default': 'RFC3986',
formatters: {
RFC1738: function (value) {
return replace.call(value, percentTwenties, '+');
},
RFC3986: function (value) {
return value;
}
},
RFC1738: 'RFC1738',
RFC3986: 'RFC3986'
};
var arrayPrefixGenerators = {
brackets: function brackets(prefix) { // eslint-disable-line func-name-matching
return prefix + '[]';
},
indices: function indices(prefix, key) { // eslint-disable-line func-name-matching
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) { // eslint-disable-line func-name-matching
return prefix;
}
};
var toISO = Date.prototype.toISOString;
var defaults$2 = {
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$2.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$2.encoder);
return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$2.encoder))];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (Array.isArray(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
if (Array.isArray(obj)) {
values = values.concat(stringify(
obj[key],
generateArrayPrefix(prefix, key),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly
));
} else {
values = values.concat(stringify(
obj[key],
prefix + (allowDots ? '.' + key : '[' + key + ']'),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly
));
}
}
return values;
};
var stringify_1 = function (object, opts) {
var obj = object;
var options = opts ? utils.assign({}, opts) : {};
if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
var delimiter = typeof options.delimiter === 'undefined' ? defaults$2.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$2.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults$2.skipNulls;
var encode = typeof options.encode === 'boolean' ? options.encode : defaults$2.encode;
var encoder = typeof options.encoder === 'function' ? options.encoder : defaults$2.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$2.serializeDate;
var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults$2.encodeValuesOnly;
if (typeof options.format === 'undefined') {
options.format = formats['default'];
} else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
throw new TypeError('Unknown format option provided.');
}
var formatter = formats.formatters[options.format];
var objKeys;
var filter;
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (Array.isArray(options.filter)) {
filter = options.filter;
objKeys = filter;
}
var keys = [];
if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (options.arrayFormat in arrayPrefixGenerators) {
arrayFormat = options.arrayFormat;
} else if ('indices' in options) {
arrayFormat = options.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (sort) {
objKeys.sort(sort);
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
keys = keys.concat(stringify(
obj[key],
key,
generateArrayPrefix,
strictNullHandling,
skipNulls,
encode ? encoder : null,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly
));
}
var joined = keys.join(delimiter);
var prefix = options.addQueryPrefix === true ? '?' : '';
return joined.length > 0 ? prefix + joined : '';
};
var has = Object.prototype.hasOwnProperty;
var defaults$3 = {
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$3.decoder);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos), defaults$3.decoder);
val = options.decoder(part.slice(pos + 1), defaults$3.decoder);
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function (chain, val, options) {
var leaf = val;
for (var i = chain.length - 1; i >= 0; --i) {
var obj;
var root = chain[i];
if (root === '[]') {
obj = [];
obj = obj.concat(leaf);
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
var index = parseInt(cleanRoot, 10);
if (
!isNaN(index)
&& root !== cleanRoot
&& String(index) === cleanRoot
&& index >= 0
&& (options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = leaf;
} else {
obj[cleanRoot] = leaf;
}
}
leaf = obj;
}
return leaf;
};
var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
// The regex chunks
var brackets = /(\[[^[\]]*])/;
var child = /(\[[^[\]]*])/g;
// Get the parent
var segment = brackets.exec(key);
var parent = segment ? key.slice(0, segment.index) : key;
// Stash the parent if it exists
var keys = [];
if (parent) {
// If we aren't using plain objects, optionally prefix keys
// that would overwrite object prototype properties
if (!options.plainObjects && has.call(Object.prototype, parent)) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(parent);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options);
};
var parse = function (str, opts) {
var options = opts ? utils.assign({}, opts) : {};
if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
options.ignoreQueryPrefix = options.ignoreQueryPrefix === true;
options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults$3.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : defaults$3.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults$3.arrayLimit;
options.parseArrays = options.parseArrays !== false;
options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults$3.decoder;
options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults$3.allowDots;
options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults$3.plainObjects;
options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults$3.allowPrototypes;
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults$3.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$3.strictNullHandling;
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options);
obj = utils.merge(obj, newObj, options);
}
return utils.compact(obj);
};
var lib$1 = {
formats: formats,
parse: parse,
stringify: stringify_1
};
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$7 = 1;
var WRAP_PARTIAL_FLAG$4 = 32;
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = _baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG$7;
if (partials.length) {
var holders = _replaceHolders(partials, _getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG$4;
}
return _createWrap(func, bitmask, thisArg, partials, holders);
});
// Assign default placeholders.
bind.placeholder = {};
var bind_1 = bind;
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return _basePickBy(object, paths, function(value, path) {
return hasIn_1(object, path);
});
}
var _basePick = basePick;
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = _flatRest(function(object, paths) {
return object == null ? {} : _basePick(object, paths);
});
var pick_1 = pick;
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/
function mapKeys(object, iteratee) {
var result = {};
iteratee = _baseIteratee(iteratee, 3);
_baseForOwn(object, function(value, key, object) {
_baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
var mapKeys_1 = mapKeys;
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = _baseIteratee(iteratee, 3);
_baseForOwn(object, function(value, key, object) {
_baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
var mapValues_1 = mapValues;
/**
* Module containing the functions to serialize and deserialize
* {SearchParameters} in the query string format
* @module algoliasearchHelper.url
*/
var encode = utils.encode;
function recursiveEncode(input) {
if (isPlainObject_1(input)) {
return mapValues_1(input, recursiveEncode);
}
if (isArray_1(input)) {
return map_1(input, recursiveEncode);
}
if (isString_1(input)) {
return encode(input);
}
return input;
}
var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR'];
var stateKeys = shortener.ENCODED_PARAMETERS;
function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) {
if (prefixRegexp !== null) {
a = a.replace(prefixRegexp, '');
b = b.replace(prefixRegexp, '');
}
a = invertedMapping[a] || a;
b = invertedMapping[b] || b;
if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) {
if (a === 'q') return -1;
if (b === 'q') return 1;
var isARefinements = refinementsParameters.indexOf(a) !== -1;
var isBRefinements = refinementsParameters.indexOf(b) !== -1;
if (isARefinements && !isBRefinements) {
return 1;
} else if (isBRefinements && !isARefinements) {
return -1;
}
}
return a.localeCompare(b);
}
/**
* Read a query string and return an object containing the state
* @param {string} queryString the query string that will be decoded
* @param {object} [options] accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
*/
var getStateFromQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var invertedMapping = invert_1(mapping);
var partialStateWithPrefix = lib$1.parse(queryString);
var prefixRegexp = new RegExp('^' + prefixForParameters);
var partialState = mapKeys_1(
partialStateWithPrefix,
function(v, k) {
var hasPrefix = prefixForParameters && prefixRegexp.test(k);
var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k;
var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey);
return decodedKey || unprefixedKey;
}
);
var partialStateWithParsedNumbers = SearchParameters_1._parseNumbers(partialState);
return pick_1(partialStateWithParsedNumbers, SearchParameters_1.PARAMETERS);
};
/**
* Retrieve an object of all the properties that are not understandable as helper
* parameters.
* @param {string} queryString the query string to read
* @param {object} [options] the options
* - prefixForParameters : prefix used for the helper configuration keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
var getUnrecognizedParametersInQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix;
var mapping = options && options.mapping || {};
var invertedMapping = invert_1(mapping);
var foreignConfig = {};
var config = lib$1.parse(queryString);
if (prefixForParameters) {
var prefixRegexp = new RegExp('^' + prefixForParameters);
forEach_1(config, function(v, key) {
if (!prefixRegexp.test(key)) foreignConfig[key] = v;
});
} else {
forEach_1(config, function(v, key) {
if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v;
});
}
return foreignConfig;
};
/**
* Generate a query string for the state passed according to the options
* @param {SearchParameters} state state to serialize
* @param {object} [options] May contain the following parameters :
* - prefix : prefix in front of the keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* - moreAttributes : more values to be added in the query string. Those values
* won't be prefixed.
* - safe : get safe urls for use in emails, chat apps or any application auto linking urls.
* All parameters and values will be encoded in a way that it's safe to share them.
* Default to false for legacy reasons ()
* @return {string} the query string
*/
var getQueryStringFromState = function(state, options) {
var moreAttributes = options && options.moreAttributes;
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var safe = options && options.safe || false;
var invertedMapping = invert_1(mapping);
var stateForUrl = safe ? state : recursiveEncode(state);
var encodedState = mapKeys_1(
stateForUrl,
function(v, k) {
var shortK = shortener.encode(k);
return prefixForParameters + (mapping[shortK] || shortK);
}
);
var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters);
var sort = bind_1(sortQueryStringValues, null, prefixRegexp, invertedMapping);
if (!isEmpty_1(moreAttributes)) {
var stateQs = lib$1.stringify(encodedState, {encode: safe, sort: sort});
var moreQs = lib$1.stringify(moreAttributes, {encode: safe});
if (!stateQs) return moreQs;
return stateQs + '&' + moreQs;
}
return lib$1.stringify(encodedState, {encode: safe, sort: sort});
};
var url = {
getStateFromQueryString: getStateFromQueryString,
getUnrecognizedParametersInQueryString: getUnrecognizedParametersInQueryString,
getQueryStringFromState: getQueryStringFromState
};
var version$2 = '2.22.0';
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {SearchParameters} state the current parameters with the latest changes applied
* @property {SearchResults} lastResults the previous results received from Algolia. `null` before
* the first request
* @example
* helper.on('change', function(state, lastResults) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when a main search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {SearchParameters} state the parameters used for this search
* @property {SearchResults} lastResults the results from the previous search. `null` if
* it is the first search.
* @example
* helper.on('search', function(state, lastResults) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when a search using `searchForFacetValues` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchForFacetValues
* @property {SearchParameters} state the parameters used for this search
* it is the first search.
* @property {string} facet the facet searched into
* @property {string} query the query used to search in the facets
* @example
* helper.on('searchForFacetValues', function(state, facet, query) {
* console.log('searchForFacetValues sent');
* });
*/
/**
* Event triggered when a search using `searchOnce` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchOnce
* @property {SearchParameters} state the parameters used for this search
* it is the first search.
* @example
* helper.on('searchOnce', function(state) {
* console.log('searchOnce sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {SearchResults} results the results received from Algolia
* @property {SearchParameters} state the parameters used to query Algolia. Those might
* be different from the one in the helper instance (for example if the network is unreliable).
* @example
* helper.on('result', function(results, state) {
* console.log('Search results received');
* });
*/
/**
* Event triggered when Algolia sends back an error. For example, if an unknown parameter is
* used, the error can be caught using this event.
* @event AlgoliaSearchHelper#event:error
* @property {Error} error the error returned by the Algolia.
* @example
* helper.on('error', function(error) {
* console.log('Houston we got a problem.');
* });
*/
/**
* Event triggered when the queue of queries have been depleted (with any result or outdated queries)
* @event AlgoliaSearchHelper#event:searchQueueEmpty
* @example
* helper.on('searchQueueEmpty', function() {
* console.log('No more search pending');
* // This is received before the result event if we're not expecting new results
* });
*
* helper.search();
*/
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
* search. It provides an event based interface for search callbacks:
* - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the
* {@link SearchResults} of the last result if any.
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial
* config of the search. It doesn't have to be a {SearchParameters},
* just an object containing the properties you need from it.
*/
function AlgoliaSearchHelper(client, index, options) {
if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line
else if (!doesClientAgentContainsHelper(client)) client.addAlgoliaAgent('JS Helper ' + version$2);
this.setClient(client);
var opts = options || {};
opts.index = index;
this.state = SearchParameters_1.make(opts);
this.lastResults = null;
this._queryId = 0;
this._lastQueryIdReceived = -1;
this.derivedHelpers = [];
this._currentNbQueries = 0;
}
util.inherits(AlgoliaSearchHelper, events.EventEmitter);
/**
* Start the search with the parameters set in the state. When the
* method is called, it triggers a `search` event. The results will
* be available through the `result` event. If an error occurs, an
* `error` will be fired instead.
* @return {AlgoliaSearchHelper}
* @fires search
* @fires result
* @fires error
* @chainable
*/
AlgoliaSearchHelper.prototype.search = function() {
this._search();
return this;
};
/**
* Gets the search query parameters that would be sent to the Algolia Client
* for the hits
* @return {object} Query Parameters
*/
AlgoliaSearchHelper.prototype.getQuery = function() {
var state = this.state;
return requestBuilder_1._getHitsSearchParams(state);
};
/**
* Start a search using a modified version of the current state. This method does
* not trigger the helper lifecycle and does not modify the state kept internally
* by the helper. This second aspect means that the next search call will be the
* same as a search call before calling searchOnce.
* @param {object} options can contain all the parameters that can be set to SearchParameters
* plus the index
* @param {function} [callback] optional callback executed when the response from the
* server is back.
* @return {promise|undefined} if a callback is passed the method returns undefined
* otherwise it returns a promise containing an object with two keys :
* - content with a SearchResults
* - state with the state used for the query as a SearchParameters
* @example
* // Changing the number of records returned per page to 1
* // This example uses the callback API
* var state = helper.searchOnce({hitsPerPage: 1},
* function(error, content, state) {
* // if an error occurred it will be passed in error, otherwise its value is null
* // content contains the results formatted as a SearchResults
* // state is the instance of SearchParameters used for this search
* });
* @example
* // Changing the number of records returned per page to 1
* // This example uses the promise API
* var state1 = helper.searchOnce({hitsPerPage: 1})
* .then(promiseHandler);
*
* function promiseHandler(res) {
* // res contains
* // {
* // content : SearchResults
* // state : SearchParameters (the one used for this specific search)
* // }
* }
*/
AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) {
var tempState = !options ? this.state : this.state.setQueryParameters(options);
var queries = requestBuilder_1._getQueries(tempState.index, tempState);
var self = this;
this._currentNbQueries++;
this.emit('searchOnce', tempState);
if (cb) {
return this.client.search(
queries,
function(err, content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
if (err) cb(err, null, tempState);
else cb(err, new SearchResults_1(tempState, content.results), tempState);
}
);
}
return this.client.search(queries).then(function(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
return {
content: new SearchResults_1(tempState, content.results),
state: tempState,
_originalResponse: content
};
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Structure of each result when using
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* @typedef FacetSearchHit
* @type {object}
* @property {string} value the facet value
* @property {string} highlighted the facet value highlighted with the query string
* @property {number} count number of occurrence of this facet value
* @property {boolean} isRefined true if the value is already refined
*/
/**
* Structure of the data resolved by the
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* promise.
* @typedef FacetSearchResult
* @type {object}
* @property {FacetSearchHit} facetHits the results for this search for facet values
* @property {number} processingTimeMS time taken by the query inside the engine
*/
/**
* Search for facet values based on an query and the name of a faceted attribute. This
* triggers a search and will return a promise. On top of using the query, it also sends
* the parameters from the state so that the search is narrowed down to only the possible values.
*
* See the description of [FacetSearchResult](reference.html#FacetSearchResult)
* @param {string} facet the name of the faceted attribute
* @param {string} query the string query for the search
* @param {number} maxFacetHits the maximum number values returned. Should be > 0 and <= 100
* @return {promise<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits) {
var state = this.state;
var index = this.client.initIndex(this.state.index);
var isDisjunctive = state.isDisjunctiveFacet(facet);
var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, this.state);
this._currentNbQueries++;
var self = this;
this.emit('searchForFacetValues', state, facet, query);
return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
content.facetHits = forEach_1(content.facetHits, function(f) {
f.isRefined = isDisjunctive ?
state.isDisjunctiveFacetRefined(facet, f.value) :
state.isFacetRefined(facet, f.value);
});
return content;
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Sets the text query used for the search.
*
* This method resets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setQuery = function(q) {
this.state = this.state.setPage(0).setQuery(q);
this._change();
return this;
};
/**
* Remove all the types of refinements except tags. A string can be provided to remove
* only the refinements of a specific attribute. For more advanced use case, you can
* provide a function instead. This function should follow the
* [clearCallback definition](#SearchParameters.clearCallback).
*
* This method resets the current page to 0.
* @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* // Removing all the refinements
* helper.clearRefinements().search();
* @example
* // Removing all the filters on a the category attribute.
* helper.clearRefinements('category').search();
* @example
* // Removing only the exclude filters on the category facet.
* helper.clearRefinements(function(value, attribute, type) {
* return type === 'exclude' && attribute === 'category';
* }).search();
*/
AlgoliaSearchHelper.prototype.clearRefinements = function(name) {
this.state = this.state.setPage(0).clearRefinements(name);
this._change();
return this;
};
/**
* Remove all the tag filters.
*
* This method resets the current page to 0.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.clearTags = function() {
this.state = this.state.setPage(0).clearTags();
this._change();
return this;
};
/**
* Adds a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() {
return this.addDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Adds a refinement on a hierarchical facet. It will throw
* an exception if the facet is not defined or if the facet
* is already refined.
*
* This method resets the current page to 0.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is refined
* @chainable
* @fires change
*/
AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value);
this._change();
return this;
};
/**
* Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} operator the operator of the filter
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Adds a filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addRefine = function() {
return this.addFacetRefinement.apply(this, arguments);
};
/**
* Adds a an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).addExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion}
*/
AlgoliaSearchHelper.prototype.addExclude = function() {
return this.addFacetExclusion.apply(this, arguments);
};
/**
* Adds a tag filter with the `tag` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addTag = function(tag) {
this.state = this.state.setPage(0).addTagRefinement(tag);
this._change();
return this;
};
/**
* Removes an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* Some parameters are optional, triggering different behavior:
* - if the value is not provided, then all the numeric value will be removed for the
* specified attribute/operator couple.
* - if the operator is not provided either, then all the numeric filter on this attribute
* will be removed.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} [operator] the operator of the filter
* @param {number} [value] the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Removes a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() {
return this.removeDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is not refined
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) {
this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet);
this._change();
return this;
};
/**
* Removes a filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeRefine = function() {
return this.removeFacetRefinement.apply(this, arguments);
};
/**
* Removes an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).removeExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion}
*/
AlgoliaSearchHelper.prototype.removeExclude = function() {
return this.removeFacetExclusion.apply(this, arguments);
};
/**
* Removes a tag filter with the `tag` provided. If the
* filter is not set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeTag = function(tag) {
this.state = this.state.setPage(0).removeTagRefinement(tag);
this._change();
return this;
};
/**
* Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion}
*/
AlgoliaSearchHelper.prototype.toggleExclude = function() {
return this.toggleFacetExclusion.apply(this, arguments);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
* @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) {
return this.toggleFacetRefinement(facet, value);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).toggleFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefine = function() {
return this.toggleFacetRefinement.apply(this, arguments);
};
/**
* Adds or removes a tag filter with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleTag = function(tag) {
this.state = this.state.setPage(0).toggleTagRefinement(tag);
this._change();
return this;
};
/**
* Increments the page number by one.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setPage(0).nextPage().getPage();
* // returns 1
*/
AlgoliaSearchHelper.prototype.nextPage = function() {
return this.setPage(this.state.page + 1);
};
/**
* Decrements the page number by one.
* @fires change
* @return {AlgoliaSearchHelper}
* @chainable
* @example
* helper.setPage(1).previousPage().getPage();
* // returns 0
*/
AlgoliaSearchHelper.prototype.previousPage = function() {
return this.setPage(this.state.page - 1);
};
/**
* @private
*/
function setCurrentPage(page) {
if (page < 0) throw new Error('Page requested below 0.');
this.state = this.state.setPage(page);
this._change();
return this;
}
/**
* Change the current page
* @deprecated
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage;
/**
* Updates the current page.
* @function
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setPage = setCurrentPage;
/**
* Updates the name of the index that will be targeted by the query.
*
* This method resets the current page to 0.
* @param {string} name the index name
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setIndex = function(name) {
this.state = this.state.setPage(0).setIndex(name);
this._change();
return this;
};
/**
* Update a parameter of the search. This method reset the page
*
* The complete list of parameters is available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters and facets have their own API)
*
* This method resets the current page to 0.
* @param {string} parameter name of the parameter to update
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setQueryParameter('hitsPerPage', 20).search();
*/
AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) {
var newState = this.state.setPage(0).setQueryParameter(parameter, value);
if (this.state === newState) return this;
this.state = newState;
this._change();
return this;
};
/**
* Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setState = function(newState) {
this.state = SearchParameters_1.make(newState);
this._change();
return this;
};
/**
* Get the current search state stored in the helper. This object is immutable.
* @param {string[]} [filters] optional filters to retrieve only a subset of the state
* @return {SearchParameters|object} if filters is specified a plain object is
* returned containing only the requested fields, otherwise return the unfiltered
* state
* @example
* // Get the complete state as stored in the helper
* helper.getState();
* @example
* // Get a part of the state with all the refinements on attributes and the query
* helper.getState(['query', 'attribute:category']);
*/
AlgoliaSearchHelper.prototype.getState = function(filters) {
if (filters === undefined) return this.state;
return this.state.filter(filters);
};
/**
* DEPRECATED Get part of the state as a query string. By default, the output keys will not
* be prefixed and will only take the applied refinements and the query.
* @deprecated
* @param {object} [options] May contain the following parameters :
*
* **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for
* the index, all the refinements with `attribute:*` or for some specific attributes with
* `attribute:theAttribute`
*
* **prefix** : prefix in front of the keys
*
* **moreAttributes** : more values to be added in the query string. Those values
* won't be prefixed.
* @return {string} the query string
*/
AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) {
var filters = options && options.filters || ['query', 'attribute:*'];
var partialState = this.getState(filters);
return url.getQueryStringFromState(partialState, options);
};
/**
* DEPRECATED Read a query string and return an object containing the state. Use
* url module.
* @deprecated
* @static
* @param {string} queryString the query string that will be decoded
* @param {object} options accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
* @see {@link url#getStateFromQueryString}
*/
AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString;
/**
* DEPRECATED Retrieve an object of all the properties that are not understandable as helper
* parameters. Use url module.
* @deprecated
* @static
* @param {string} queryString the query string to read
* @param {object} options the options
* - prefixForParameters : prefix used for the helper configuration keys
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString;
/**
* DEPRECATED Overrides part of the state with the properties stored in the provided query
* string.
* @deprecated
* @param {string} queryString the query string containing the informations to url the state
* @param {object} options optional parameters :
* - prefix : prefix used for the algolia parameters
* - triggerChange : if set to true the state update will trigger a change event
*/
AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) {
var triggerChange = options && options.triggerChange || false;
var configuration = url.getStateFromQueryString(queryString, options);
var updatedState = this.state.setQueryParameters(configuration);
if (triggerChange) this.setState(updatedState);
else this.overrideStateWithoutTriggeringChangeEvent(updatedState);
};
/**
* Override the current state without triggering a change event.
* Do not use this method unless you know what you are doing. (see the example
* for a legit use case)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @example
* helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
* updateYourURL(state)
* })
* window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
* helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
* @chainable
*/
AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) {
this.state = new SearchParameters_1(newState);
return this;
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isRefined = function(facet, value) {
if (this.state.isConjunctiveFacet(facet)) {
return this.state.isFacetRefined(facet, value);
} else if (this.state.isDisjunctiveFacet(facet)) {
return this.state.isDisjunctiveFacetRefined(facet, value);
}
throw new Error(facet +
' is not properly defined in this helper configuration' +
'(use the facets or disjunctiveFacets keys to configure it)');
};
/**
* Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
* @example
* // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
* helper.hasRefinements('price'); // false
* helper.addNumericRefinement('price', '>', 100);
* helper.hasRefinements('price'); // true
*
* helper.hasRefinements('color'); // false
* helper.addFacetRefinement('color', 'blue');
* helper.hasRefinements('color'); // true
*
* helper.hasRefinements('material'); // false
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* helper.hasRefinements('material'); // true
*
* helper.hasRefinements('categories'); // false
* helper.toggleFacetRefinement('categories', 'kitchen > knife');
* helper.hasRefinements('categories'); // true
*
*/
AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) {
if (!isEmpty_1(this.state.getNumericRefinements(attribute))) {
return true;
} else if (this.state.isConjunctiveFacet(attribute)) {
return this.state.isFacetRefined(attribute);
} else if (this.state.isDisjunctiveFacet(attribute)) {
return this.state.isDisjunctiveFacetRefined(attribute);
} else if (this.state.isHierarchicalFacet(attribute)) {
return this.state.isHierarchicalFacetRefined(attribute);
}
// there's currently no way to know that the user did call `addNumericRefinement` at some point
// thus we cannot distinguish if there once was a numeric refinement that was cleared
// so we will return false in every other situations to be consistent
// while what we should do here is throw because we did not find the attribute in any type
// of refinement
return false;
};
/**
* Check if a value is excluded for a specific faceted attribute. If the value
* is omitted then the function checks if there is any excluding refinements.
*
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} true if refined
* @example
* helper.isExcludeRefined('color'); // false
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // false
*
* helper.addFacetExclusion('color', 'red');
*
* helper.isExcludeRefined('color'); // true
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // true
*/
AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) {
return this.state.isExcludeRefined(facet, value);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) {
return this.state.isDisjunctiveFacetRefined(facet, value);
};
/**
* Check if the string is a currently filtering tag.
* @param {string} tag tag to check
* @return {boolean}
*/
AlgoliaSearchHelper.prototype.hasTag = function(tag) {
return this.state.isTagRefined(tag);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag}
*/
AlgoliaSearchHelper.prototype.isTagRefined = function() {
return this.hasTagRefinements.apply(this, arguments);
};
/**
* Get the name of the currently used index.
* @return {string}
* @example
* helper.setIndex('highestPrice_products').getIndex();
* // returns 'highestPrice_products'
*/
AlgoliaSearchHelper.prototype.getIndex = function() {
return this.state.index;
};
function getCurrentPage() {
return this.state.page;
}
/**
* Get the currently selected page
* @deprecated
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage;
/**
* Get the currently selected page
* @function
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getPage = getCurrentPage;
/**
* Get all the tags currently set to filters the results.
*
* @return {string[]} The list of tags currently set.
*/
AlgoliaSearchHelper.prototype.getTags = function() {
return this.state.tagRefinements;
};
/**
* Get a parameter of the search by its name. It is possible that a parameter is directly
* defined in the index dashboard, but it will be undefined using this method.
*
* The complete list of parameters is
* available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters have their own API)
* @param {string} parameterName the parameter name
* @return {any} the parameter value
* @example
* var hitsPerPage = helper.getQueryParameter('hitsPerPage');
*/
AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) {
return this.state.getQueryParameter(parameterName);
};
/**
* Get the list of refinements for a given attribute. This method works with
* conjunctive, disjunctive, excluding and numerical filters.
*
* See also SearchResults#getRefinements
*
* @param {string} facetName attribute name used for faceting
* @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and
* a type. Numeric also contains an operator.
* @example
* helper.addNumericRefinement('price', '>', 100);
* helper.getRefinements('price');
* // [
* // {
* // "value": [
* // 100
* // ],
* // "operator": ">",
* // "type": "numeric"
* // }
* // ]
* @example
* helper.addFacetRefinement('color', 'blue');
* helper.addFacetExclusion('color', 'red');
* helper.getRefinements('color');
* // [
* // {
* // "value": "blue",
* // "type": "conjunctive"
* // },
* // {
* // "value": "red",
* // "type": "exclude"
* // }
* // ]
* @example
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* // [
* // {
* // "value": "plastic",
* // "type": "disjunctive"
* // }
* // ]
*/
AlgoliaSearchHelper.prototype.getRefinements = function(facetName) {
var refinements = [];
if (this.state.isConjunctiveFacet(facetName)) {
var conjRefinements = this.state.getConjunctiveRefinements(facetName);
forEach_1(conjRefinements, function(r) {
refinements.push({
value: r,
type: 'conjunctive'
});
});
var excludeRefinements = this.state.getExcludeRefinements(facetName);
forEach_1(excludeRefinements, function(r) {
refinements.push({
value: r,
type: 'exclude'
});
});
} else if (this.state.isDisjunctiveFacet(facetName)) {
var disjRefinements = this.state.getDisjunctiveRefinements(facetName);
forEach_1(disjRefinements, function(r) {
refinements.push({
value: r,
type: 'disjunctive'
});
});
}
var numericRefinements = this.state.getNumericRefinements(facetName);
forEach_1(numericRefinements, function(value, operator) {
refinements.push({
value: value,
operator: operator,
type: 'numeric'
});
});
return refinements;
};
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) {
return this.state.getNumericRefinement(attribute, operator);
};
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) {
return this.state.getHierarchicalFacetBreadcrumb(facetName);
};
// /////////// PRIVATE
/**
* Perform the underlying queries
* @private
* @return {undefined}
* @fires search
* @fires result
* @fires error
*/
AlgoliaSearchHelper.prototype._search = function() {
var state = this.state;
var mainQueries = requestBuilder_1._getQueries(state.index, state);
var states = [{
state: state,
queriesCount: mainQueries.length,
helper: this
}];
this.emit('search', state, this.lastResults);
var derivedQueries = map_1(this.derivedHelpers, function(derivedHelper) {
var derivedState = derivedHelper.getModifiedState(state);
var queries = requestBuilder_1._getQueries(derivedState.index, derivedState);
states.push({
state: derivedState,
queriesCount: queries.length,
helper: derivedHelper
});
derivedHelper.emit('search', derivedState, derivedHelper.lastResults);
return queries;
});
var queries = mainQueries.concat(flatten_1(derivedQueries));
var queryId = this._queryId++;
this._currentNbQueries++;
this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId));
};
/**
* Transform the responses as sent by the server and transform them into a user
* usable object that merge the results of all the batch requests. It will dispatch
* over the different helper + derived helpers (when there are some).
* @private
* @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>}
* state state used for to generate the request
* @param {number} queryId id of the current request
* @param {Error} err error if any, null otherwise
* @param {object} content content of the response
* @return {undefined}
*/
AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) {
// FIXME remove the number of outdated queries discarded instead of just one
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._currentNbQueries -= (queryId - this._lastQueryIdReceived);
this._lastQueryIdReceived = queryId;
if (err) {
this.emit('error', err);
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
} else {
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
var results = content.results;
forEach_1(states, function(s) {
var state = s.state;
var queriesCount = s.queriesCount;
var helper = s.helper;
var specificResults = results.splice(0, queriesCount);
var formattedResponse = helper.lastResults = new SearchResults_1(state, specificResults);
helper.emit('result', formattedResponse, state);
});
}
};
AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) {
return query ||
facetFilters.length !== 0 ||
numericFilters.length !== 0 ||
tagFilters.length !== 0;
};
/**
* Test if there are some disjunctive refinements on the facet
* @private
* @param {string} facet the attribute to test
* @return {boolean}
*/
AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) {
return this.state.disjunctiveRefinements[facet] &&
this.state.disjunctiveRefinements[facet].length > 0;
};
AlgoliaSearchHelper.prototype._change = function() {
this.emit('change', this.state, this.lastResults);
};
/**
* Clears the cache of the underlying Algolia client.
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.clearCache = function() {
this.client.clearCache();
return this;
};
/**
* Updates the internal client instance. If the reference of the clients
* are equal then no update is actually done.
* @param {AlgoliaSearch} newClient an AlgoliaSearch client
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.setClient = function(newClient) {
if (this.client === newClient) return this;
if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version$2);
this.client = newClient;
return this;
};
/**
* Gets the instance of the currently used client.
* @return {AlgoliaSearch}
*/
AlgoliaSearchHelper.prototype.getClient = function() {
return this.client;
};
/**
* Creates an derived instance of the Helper. A derived helper
* is a way to request other indices synchronised with the lifecycle
* of the main Helper. This mechanism uses the multiqueries feature
* of Algolia to aggregate all the requests in a single network call.
*
* This method takes a function that is used to create a new SearchParameter
* that will be used to create requests to Algolia. Those new requests
* are created just before the `search` event. The signature of the function
* is `SearchParameters -> SearchParameters`.
*
* This method returns a new DerivedHelper which is an EventEmitter
* that fires the same `search`, `result` and `error` events. Those
* events, however, will receive data specific to this DerivedHelper
* and the SearchParameters that is returned by the call of the
* parameter function.
* @param {function} fn SearchParameters -> SearchParameters
* @return {DerivedHelper}
*/
AlgoliaSearchHelper.prototype.derive = function(fn) {
var derivedHelper = new DerivedHelper_1(this, fn);
this.derivedHelpers.push(derivedHelper);
return derivedHelper;
};
/**
* This method detaches a derived Helper from the main one. Prefer using the one from the
* derived helper itself, to remove the event listeners too.
* @private
* @return {undefined}
* @throws Error
*/
AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) {
var pos = this.derivedHelpers.indexOf(derivedHelper);
if (pos === -1) throw new Error('Derived helper already detached');
this.derivedHelpers.splice(pos, 1);
};
/**
* This method returns true if there is currently at least one on-going search.
* @return {boolean} true if there is a search pending
*/
AlgoliaSearchHelper.prototype.hasPendingRequests = function() {
return this._currentNbQueries > 0;
};
/**
* @typedef AlgoliaSearchHelper.NumericRefinement
* @type {object}
* @property {number[]} value the numbers that are used for filtering this attribute with
* the operator specified.
* @property {string} operator the faceting data: value, number of entries
* @property {string} type will be 'numeric'
*/
/**
* @typedef AlgoliaSearchHelper.FacetRefinement
* @type {object}
* @property {string} value the string use to filter the attribute
* @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude'
*/
/*
* This function tests if the _ua parameter of the client
* already contains the JS Helper UA
*/
function doesClientAgentContainsHelper(client) {
// this relies on JS Client internal variable, this might break if implementation changes
var currentAgent = client._ua;
return !currentAgent ? false :
currentAgent.indexOf('JS Helper') !== -1;
}
var algoliasearch_helper = AlgoliaSearchHelper;
/**
* The algoliasearchHelper module is the function that will let its
* contains everything needed to use the Algoliasearch
* Helper. It is a also a function that instanciate the helper.
* To use the helper, you also need the Algolia JS client v3.
* @example
* //using the UMD build
* var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
* var helper = algoliasearchHelper(client, 'bestbuy', {
* facets: ['shipping'],
* disjunctiveFacets: ['category']
* });
* helper.on('result', function(result) {
* console.log(result);
* });
* helper.toggleRefine('Movies & TV Shows')
* .toggleRefine('Free shipping')
* .search();
* @example
* // The helper is an event emitter using the node API
* helper.on('result', updateTheResults);
* helper.once('result', updateTheResults);
* helper.removeListener('result', updateTheResults);
* helper.removeAllListeners('result');
* @module algoliasearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the name of the index to query
* @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
* @return {AlgoliaSearchHelper}
*/
function algoliasearchHelper(client, index, opts) {
return new algoliasearch_helper(client, index, opts);
}
/**
* The version currently used
* @member module:algoliasearchHelper.version
* @type {number}
*/
algoliasearchHelper.version = version$2;
/**
* Constructor for the Helper.
* @member module:algoliasearchHelper.AlgoliaSearchHelper
* @type {AlgoliaSearchHelper}
*/
algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper;
/**
* Constructor for the object containing all the parameters of the search.
* @member module:algoliasearchHelper.SearchParameters
* @type {SearchParameters}
*/
algoliasearchHelper.SearchParameters = SearchParameters_1;
/**
* Constructor for the object containing the results of the search.
* @member module:algoliasearchHelper.SearchResults
* @type {SearchResults}
*/
algoliasearchHelper.SearchResults = SearchResults_1;
/**
* URL tools to generate query string and parse them from/into
* SearchParameters
* @member module:algoliasearchHelper.url
* @type {object} {@link url}
*
*/
algoliasearchHelper.url = url;
var algoliasearchHelper_1 = algoliasearchHelper;
var algoliasearchHelper_4 = algoliasearchHelper_1.SearchParameters;
// From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js
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 getDisplayName(Component$$1) {
return Component$$1.displayName || Component$$1.name || 'UnknownComponent';
}
var resolved = Promise.resolve();
var defer = function defer(f) {
resolved.then(f);
};
function removeEmptyKey(obj) {
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (isEmpty_1(value) && isPlainObject_1(value)) {
delete obj[key];
} else if (isPlainObject_1(value)) {
removeEmptyKey(value);
}
});
return obj;
}
function createWidgetsManager(onWidgetsUpdate) {
var widgets = [];
// Is an update scheduled?
var scheduled = false;
// The state manager's updates need to be batched since more than one
// component can register or unregister widgets during the same tick.
function scheduleUpdate() {
if (scheduled) {
return;
}
scheduled = true;
defer(function () {
scheduled = false;
onWidgetsUpdate();
});
}
return {
registerWidget: function registerWidget(widget) {
widgets.push(widget);
scheduleUpdate();
return function unregisterWidget() {
widgets.splice(widgets.indexOf(widget), 1);
scheduleUpdate();
};
},
update: scheduleUpdate,
getWidgets: function getWidgets() {
return widgets;
}
};
}
function createStore(initialState) {
var state = initialState;
var listeners = [];
function dispatch() {
listeners.forEach(function (listener) {
return listener();
});
}
return {
getState: function getState() {
return state;
},
setState: function setState(nextState) {
state = nextState;
dispatch();
},
subscribe: function subscribe(listener) {
listeners.push(listener);
return function unsubcribe() {
listeners.splice(listeners.indexOf(listener), 1);
};
}
};
}
var highlightTags = {
highlightPreTag: "<ais-highlight-0000000000>",
highlightPostTag: "</ais-highlight-0000000000>"
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty$2 = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
/**
* Creates a new instance of the InstantSearchManager which controls the widgets and
* trigger the search when the widgets are updated.
* @param {string} indexName - the main index name
* @param {object} initialState - initial widget state
* @param {object} SearchParameters - optional additional parameters to send to the algolia API
* @param {number} stalledSearchDelay - time (in ms) after the search is stalled
* @return {InstantSearchManager} a new instance of InstantSearchManager
*/
function createInstantSearchManager(_ref) {
var indexName = _ref.indexName,
_ref$initialState = _ref.initialState,
initialState = _ref$initialState === undefined ? {} : _ref$initialState,
algoliaClient = _ref.algoliaClient,
_ref$searchParameters = _ref.searchParameters,
searchParameters = _ref$searchParameters === undefined ? {} : _ref$searchParameters,
resultsState = _ref.resultsState,
stalledSearchDelay = _ref.stalledSearchDelay;
var baseSP = new algoliasearchHelper_4(_extends({}, searchParameters, {
index: indexName
}, highlightTags));
var stalledSearchTimer = null;
var helper = algoliasearchHelper_1(algoliaClient, indexName, baseSP);
helper.on('result', handleSearchSuccess);
helper.on('error', handleSearchError);
helper.on('search', handleNewSearch);
var derivedHelpers = {};
var indexMapping = {}; // keep track of the original index where the parameters applied when sortBy is used.
var initialSearchParameters = helper.state;
var widgetsManager = createWidgetsManager(onWidgetsUpdate);
var store = createStore({
widgets: initialState,
metadata: [],
results: resultsState || null,
error: null,
searching: false,
isSearchStalled: true,
searchingForFacetValues: false
});
var skip = false;
function skipSearch() {
skip = true;
}
function updateClient(client) {
helper.setClient(client);
search();
}
function clearCache() {
helper.clearCache();
search();
}
function getMetadata(state) {
return widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getMetadata);
}).map(function (widget) {
return widget.getMetadata(state);
});
}
function getSearchParameters() {
indexMapping = {};
var sharedParameters = widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).filter(function (widget) {
return !widget.context.multiIndexContext && (widget.props.indexName === indexName || !widget.props.indexName);
}).reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, initialSearchParameters);
indexMapping[sharedParameters.index] = indexName;
var derivatedWidgets = widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).filter(function (widget) {
return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex !== indexName || widget.props.indexName && widget.props.indexName !== indexName;
}).reduce(function (indices, widget) {
var targetedIndex = widget.context.multiIndexContext ? widget.context.multiIndexContext.targetedIndex : widget.props.indexName;
var index = indices.find(function (i) {
return i.targetedIndex === targetedIndex;
});
if (index) {
index.widgets.push(widget);
} else {
indices.push({ targetedIndex: targetedIndex, widgets: [widget] });
}
return indices;
}, []);
var mainIndexParameters = widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).filter(function (widget) {
return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex === indexName || widget.props.indexName && widget.props.indexName === indexName;
}).reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, sharedParameters);
indexMapping[mainIndexParameters.index] = indexName;
return { sharedParameters: sharedParameters, mainIndexParameters: mainIndexParameters, derivatedWidgets: derivatedWidgets };
}
function search() {
if (!skip) {
var _getSearchParameters = getSearchParameters(helper.state),
sharedParameters = _getSearchParameters.sharedParameters,
mainIndexParameters = _getSearchParameters.mainIndexParameters,
derivatedWidgets = _getSearchParameters.derivatedWidgets;
Object.keys(derivedHelpers).forEach(function (key) {
return derivedHelpers[key].detach();
});
derivedHelpers = {};
helper.setState(sharedParameters);
derivatedWidgets.forEach(function (derivatedSearchParameters) {
var index = derivatedSearchParameters.targetedIndex;
var derivedHelper = helper.derive(function () {
var parameters = derivatedSearchParameters.widgets.reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, sharedParameters);
indexMapping[parameters.index] = index;
return parameters;
});
derivedHelper.on('result', handleSearchSuccess);
derivedHelper.on('error', handleSearchError);
derivedHelpers[index] = derivedHelper;
});
helper.setState(mainIndexParameters);
helper.search();
}
}
function handleSearchSuccess(content) {
var state = store.getState();
var results = state.results ? state.results : {};
/* if switching from mono index to multi index and vice versa,
results needs to reset to {}*/
results = !isEmpty_1(derivedHelpers) && results.getFacetByName ? {} : results;
if (!isEmpty_1(derivedHelpers)) {
results[indexMapping[content.index]] = content;
} else {
results = content;
}
var currentState = store.getState();
var nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
stalledSearchTimer = null;
nextIsSearchStalled = false;
}
var nextState = omit_1(_extends({}, currentState, {
results: results,
isSearchStalled: nextIsSearchStalled,
searching: false,
error: null
}), 'resultsFacetValues');
store.setState(nextState);
}
function handleSearchError(error) {
var currentState = store.getState();
var nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
nextIsSearchStalled = false;
}
var nextState = omit_1(_extends({}, currentState, {
isSearchStalled: nextIsSearchStalled,
error: error,
searching: false
}), 'resultsFacetValues');
store.setState(nextState);
}
function handleNewSearch() {
if (!stalledSearchTimer) {
stalledSearchTimer = setTimeout(function () {
var nextState = omit_1(_extends({}, store.getState(), {
isSearchStalled: true
}), 'resultsFacetValues');
store.setState(nextState);
}, stalledSearchDelay);
}
}
// Called whenever a widget has been rendered with new props.
function onWidgetsUpdate() {
var metadata = getMetadata(store.getState().widgets);
store.setState(_extends({}, store.getState(), {
metadata: metadata,
searching: true
}));
// Since the `getSearchParameters` method of widgets also depends on props,
// the result search parameters might have changed.
search();
}
function transitionState(nextSearchState) {
var searchState = store.getState().widgets;
return widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.transitionState);
}).reduce(function (res, widget) {
return widget.transitionState(searchState, res);
}, nextSearchState);
}
function onExternalStateUpdate(nextSearchState) {
var metadata = getMetadata(nextSearchState);
store.setState(_extends({}, store.getState(), {
widgets: nextSearchState,
metadata: metadata,
searching: true
}));
search();
}
function onSearchForFacetValues(nextSearchState) {
store.setState(_extends({}, store.getState(), {
searchingForFacetValues: true
}));
helper.searchForFacetValues(nextSearchState.facetName, nextSearchState.query).then(function (content) {
var _babelHelpers$extends;
store.setState(_extends({}, store.getState(), {
resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_babelHelpers$extends = {}, defineProperty$2(_babelHelpers$extends, nextSearchState.facetName, content.facetHits), defineProperty$2(_babelHelpers$extends, 'query', nextSearchState.query), _babelHelpers$extends)),
searchingForFacetValues: false
}));
}, function (error) {
store.setState(_extends({}, store.getState(), {
error: error,
searchingForFacetValues: false
}));
}).catch(function (error) {
// Since setState is synchronous, any error that occurs in the render of a
// component will be swallowed by this promise.
// This is a trick to make the error show up correctly in the console.
// See http://stackoverflow.com/a/30741722/969302
setTimeout(function () {
throw error;
});
});
}
function updateIndex(newIndex) {
initialSearchParameters = initialSearchParameters.setIndex(newIndex);
search();
}
function getWidgetsIds() {
return store.getState().metadata.reduce(function (res, meta) {
return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res;
}, []);
}
return {
store: store,
widgetsManager: widgetsManager,
getWidgetsIds: getWidgetsIds,
onExternalStateUpdate: onExternalStateUpdate,
transitionState: transitionState,
onSearchForFacetValues: onSearchForFacetValues,
updateClient: updateClient,
updateIndex: updateIndex,
clearCache: clearCache,
skipSearch: skipSearch
};
}
function validateNextProps(props, nextProps) {
if (!props.searchState && nextProps.searchState) {
throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled");
} else if (props.searchState && !nextProps.searchState) {
throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled");
}
}
/* eslint valid-jsdoc: 0 */
/**
* @description
* `<InstantSearch>` is the root component of all React InstantSearch implementations.
* It provides all the connected components (aka widgets) a means to interact
* with the searchState.
* @kind widget
* @name <InstantSearch>
* @requirements You will need to have an Algolia account to be able to use this widget.
* [Create one now](https://www.algolia.com/users/sign_up).
* @propType {string} appId - Your Algolia application id.
* @propType {string} apiKey - Your Algolia search-only API key.
* @propType {string} indexName - Main index in which to search.
* @propType {boolean} [refresh=false] - Flag to activate when the cache needs to be cleared so that the front-end is updated when a change occurs in the index.
* @propType {object} [algoliaClient] - Provide a custom Algolia client instead of the internal one.
* @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html).
* @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html).
* @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html).
* @propType {SearchResults|SearchResults[]} [resultsState] - Use this to inject the results that will be used at first rendering. Those results are found by using the `findResultsState` function. Useful for [Server Side Rendering](guide/Server-side_rendering.html).
* @propType {number} [stalledSearchDelay=200] - The amount of time before considering that the search takes too much time. The time is expressed in milliseconds.
* @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }`
* @example
* import {InstantSearch, SearchBox, Hits} from 'react-instantsearch/dom';
*
* export default function Search() {
* return (
* <InstantSearch
* appId="appId"
* apiKey="apiKey"
* indexName="indexName"
* >
* <SearchBox />
* <Hits />
* </InstantSearch>
* );
* }
*/
var InstantSearch$1 = function (_Component) {
inherits(InstantSearch, _Component);
function InstantSearch(props) {
classCallCheck(this, InstantSearch);
var _this = possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props));
_this.isControlled = Boolean(props.searchState);
var initialState = _this.isControlled ? props.searchState : {};
_this.isUnmounting = false;
_this.aisManager = createInstantSearchManager({
indexName: props.indexName,
searchParameters: props.searchParameters,
algoliaClient: props.algoliaClient,
initialState: initialState,
resultsState: props.resultsState,
stalledSearchDelay: props.stalledSearchDelay
});
return _this;
}
createClass(InstantSearch, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
validateNextProps(this.props, nextProps);
if (this.props.indexName !== nextProps.indexName) {
this.aisManager.updateIndex(nextProps.indexName);
}
if (this.props.refresh !== nextProps.refresh) {
if (nextProps.refresh) {
this.aisManager.clearCache();
}
}
if (this.props.algoliaClient !== nextProps.algoliaClient) {
this.aisManager.updateClient(nextProps.algoliaClient);
}
if (this.isControlled) {
this.aisManager.onExternalStateUpdate(nextProps.searchState);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.isUnmounting = true;
this.aisManager.skipSearch();
}
}, {
key: 'getChildContext',
value: function getChildContext() {
// If not already cached, cache the bound methods so that we can forward them as part
// of the context.
if (!this._aisContextCache) {
this._aisContextCache = {
ais: {
onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this),
createHrefForState: this.createHrefForState.bind(this),
onSearchForFacetValues: this.onSearchForFacetValues.bind(this),
onSearchStateChange: this.onSearchStateChange.bind(this),
onSearchParameters: this.onSearchParameters.bind(this)
}
};
}
return {
ais: _extends({}, this._aisContextCache.ais, {
store: this.aisManager.store,
widgetsManager: this.aisManager.widgetsManager,
mainTargetedIndex: this.props.indexName
})
};
}
}, {
key: 'createHrefForState',
value: function createHrefForState(searchState) {
searchState = this.aisManager.transitionState(searchState);
return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#';
}
}, {
key: 'onWidgetsInternalStateUpdate',
value: function onWidgetsInternalStateUpdate(searchState) {
searchState = this.aisManager.transitionState(searchState);
this.onSearchStateChange(searchState);
if (!this.isControlled) {
this.aisManager.onExternalStateUpdate(searchState);
}
}
}, {
key: 'onSearchStateChange',
value: function onSearchStateChange(searchState) {
if (this.props.onSearchStateChange && !this.isUnmounting) {
this.props.onSearchStateChange(searchState);
}
}
}, {
key: 'onSearchParameters',
value: function onSearchParameters(getSearchParameters, context, props) {
if (this.props.onSearchParameters) {
var searchState = this.props.searchState ? this.props.searchState : {};
this.props.onSearchParameters(getSearchParameters, context, props, searchState);
}
}
}, {
key: 'onSearchForFacetValues',
value: function onSearchForFacetValues(searchState) {
this.aisManager.onSearchForFacetValues(searchState);
}
}, {
key: 'getKnownKeys',
value: function getKnownKeys() {
return this.aisManager.getWidgetsIds();
}
}, {
key: 'render',
value: function render() {
var childrenCount = React.Children.count(this.props.children);
var _props$root = this.props.root,
Root = _props$root.Root,
props = _props$root.props;
if (childrenCount === 0) return null;else return React__default.createElement(
Root,
props,
this.props.children
);
}
}]);
return InstantSearch;
}(React.Component);
InstantSearch$1.defaultProps = {
stalledSearchDelay: 200
};
InstantSearch$1.propTypes = {
// @TODO: These props are currently constant.
indexName: propTypes.string.isRequired,
algoliaClient: propTypes.object.isRequired,
searchParameters: propTypes.object,
createURL: propTypes.func,
refresh: propTypes.bool.isRequired,
searchState: propTypes.object,
onSearchStateChange: propTypes.func,
onSearchParameters: propTypes.func,
resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]),
children: propTypes.node,
root: propTypes.shape({
Root: propTypes.oneOfType([propTypes.string, propTypes.func]),
props: propTypes.object
}).isRequired,
stalledSearchDelay: propTypes.number
};
InstantSearch$1.childContextTypes = {
// @TODO: more precise widgets manager propType
ais: propTypes.object.isRequired
};
var _name$version$descrip = {
name: 'react-instantsearch',
version: '4.4.0',
description: '\u26A1 Lightning-fast search for React and React Native apps, by Algolia',
keywords: ['algolia', 'components', 'fast', 'instantsearch', 'react', 'react-native', 'search'],
homepage: 'https://community.algolia.com/react-instantsearch',
license: 'MIT',
author: {
name: 'Algolia, Inc.',
url: 'https://www.algolia.com'
},
main: 'index.js',
module: 'es/index.js',
repository: {
type: 'git',
url: 'https://github.com/algolia/react-instantsearch'
},
scripts: {
build: './scripts/build.sh',
'build-and-publish': './scripts/build-and-publish.sh'
},
dependencies: {
algoliasearch: '^3.24.0',
'algoliasearch-helper': '^2.21.0',
classnames: '^2.2.5',
lodash: '^4.17.4',
'prop-types': '^15.5.10'
},
devDependencies: {
enzyme: '3.3.0',
'enzyme-adapter-react-16': '1.1.1',
react: '16.2.0',
'react-dom': '16.2.0',
'react-native': '0.51.0',
'react-test-renderer': '16.2.0'
}
};
var version = _name$version$descrip.version;
/**
* Creates a specialized root InstantSearch component. It accepts
* an algolia client and a specification of the root Element.
* @param {function} defaultAlgoliaClient - a function that builds an Algolia client
* @param {object} root - the defininition of the root of an InstantSearch sub tree.
* @returns {object} an InstantSearch root
*/
function createInstantSearch(defaultAlgoliaClient, root) {
var _class, _temp;
return _temp = _class = function (_Component) {
inherits(CreateInstantSearch, _Component);
function CreateInstantSearch() {
var _ref;
classCallCheck(this, CreateInstantSearch);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var _this = possibleConstructorReturn(this, (_ref = CreateInstantSearch.__proto__ || Object.getPrototypeOf(CreateInstantSearch)).call.apply(_ref, [this].concat(args)));
_this.client = _this.props.algoliaClient || defaultAlgoliaClient(_this.props.appId, _this.props.apiKey);
_this.client.addAlgoliaAgent('react-instantsearch ' + version);
return _this;
}
createClass(CreateInstantSearch, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var props = this.props;
if (nextProps.algoliaClient) {
this.client = nextProps.algoliaClient;
} else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) {
this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey);
}
this.client.addAlgoliaAgent('react-instantsearch ' + version);
}
}, {
key: 'render',
value: function render() {
return React__default.createElement(
InstantSearch$1,
{
createURL: this.props.createURL,
indexName: this.props.indexName,
searchParameters: this.props.searchParameters,
searchState: this.props.searchState,
onSearchStateChange: this.props.onSearchStateChange,
onSearchParameters: this.props.onSearchParameters,
root: this.props.root,
algoliaClient: this.client,
refresh: this.props.refresh,
resultsState: this.props.resultsState
},
this.props.children
);
}
}]);
return CreateInstantSearch;
}(React.Component), _class.propTypes = {
algoliaClient: propTypes.object,
appId: propTypes.string,
apiKey: propTypes.string,
children: propTypes.oneOfType([propTypes.arrayOf(propTypes.node), propTypes.node]),
indexName: propTypes.string.isRequired,
searchParameters: propTypes.object,
createURL: propTypes.func,
searchState: propTypes.object,
refresh: propTypes.bool.isRequired,
onSearchStateChange: propTypes.func,
onSearchParameters: propTypes.func,
resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]),
root: propTypes.shape({
Root: propTypes.oneOfType([propTypes.string, propTypes.func]).isRequired,
props: propTypes.object
})
}, _class.defaultProps = {
refresh: false,
root: root
}, _temp;
}
/* eslint valid-jsdoc: 0 */
/**
* @description
* `<Index>` is the component that allows you to apply widgets to a dedicated index. It's
* useful if you want to build an interface that targets multiple indices.
* @kind widget
* @name <Index>
* @propType {string} indexName - index in which to search.
* @example
* import {InstantSearch, Index, SearchBox, Hits, Configure} from 'react-instantsearch/dom';
*
* export default function Search() {
* return (
* <InstantSearch
appId=""
apiKey=""
indexName="index1">
<SearchBox/>
<Configure hitsPerPage={1} />
<Index indexName="index1">
<Hits />
</Index>
<Index indexName="index2">
<Hits />
</Index>
</InstantSearch>
* );
* }
*/
var Index$1 = function (_Component) {
inherits(Index, _Component);
function Index(props, context) {
classCallCheck(this, Index);
var _this = possibleConstructorReturn(this, (Index.__proto__ || Object.getPrototypeOf(Index)).call(this, props));
var widgetsManager = context.ais.widgetsManager;
/*
we want <Index> to be seen as a regular widget.
It means that with only <Index> present a new query will be sent to Algolia.
That way you don't need a virtual hits widget to use the connectAutoComplete.
*/
_this.unregisterWidget = widgetsManager.registerWidget(_this);
return _this;
}
createClass(Index, [{
key: 'componentWillMount',
value: function componentWillMount() {
this.context.ais.onSearchParameters(this.getSearchParameters, this.getChildContext(), this.props);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.props.indexName !== nextProps.indexName) {
this.context.ais.widgetsManager.update();
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.unregisterWidget();
}
}, {
key: 'getChildContext',
value: function getChildContext() {
return {
multiIndexContext: {
targetedIndex: this.props.indexName
}
};
}
}, {
key: 'getSearchParameters',
value: function getSearchParameters(searchParameters, props) {
return searchParameters.setIndex(this.props ? this.props.indexName : props.indexName);
}
}, {
key: 'render',
value: function render() {
var childrenCount = React.Children.count(this.props.children);
var _props$root = this.props.root,
Root = _props$root.Root,
props = _props$root.props;
if (childrenCount === 0) return null;else return React__default.createElement(
Root,
props,
this.props.children
);
}
}]);
return Index;
}(React.Component);
Index$1.propTypes = {
// @TODO: These props are currently constant.
indexName: propTypes.string.isRequired,
children: propTypes.node,
root: propTypes.shape({
Root: propTypes.oneOfType([propTypes.string, propTypes.func]),
props: propTypes.object
}).isRequired
};
Index$1.childContextTypes = {
multiIndexContext: propTypes.object.isRequired
};
Index$1.contextTypes = {
// @TODO: more precise widgets manager propType
ais: propTypes.object.isRequired
};
/**
* Creates a specialized root Index component. It accepts
* a specification of the root Element.
* @param {object} root - the defininition of the root of an Index sub tree.
* @returns {object} a Index root
*/
function createIndex(root) {
var _class, _temp;
return _temp = _class = function (_Component) {
inherits(CreateIndex, _Component);
function CreateIndex() {
classCallCheck(this, CreateIndex);
return possibleConstructorReturn(this, (CreateIndex.__proto__ || Object.getPrototypeOf(CreateIndex)).apply(this, arguments));
}
createClass(CreateIndex, [{
key: 'render',
value: function render() {
return React__default.createElement(
Index$1,
{ indexName: this.props.indexName, root: root },
this.props.children
);
}
}]);
return CreateIndex;
}(React.Component), _class.propTypes = {
children: propTypes.oneOfType([propTypes.arrayOf(propTypes.node), propTypes.node]),
indexName: propTypes.string.isRequired
}, _temp;
}
var inherits_browser$2 = createCommonjsModule(function (module) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
};
}
});
var hasOwn = Object.prototype.hasOwnProperty;
var toString$2 = Object.prototype.toString;
var foreach = function forEach (obj, fn, ctx) {
if (toString$2.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
// This file hosts our error definitions
// We use custom error "types" so that we can act on them when we need it
// e.g.: if error instanceof errors.UnparsableJSON then..
function AlgoliaSearchError(message, extraProperties) {
var forEach = foreach;
var error = this;
// try to get a stacktrace
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old';
}
this.name = 'AlgoliaSearchError';
this.message = message || 'Unknown error';
if (extraProperties) {
forEach(extraProperties, function addToErrorObject(value, key) {
error[key] = value;
});
}
}
inherits_browser$2(AlgoliaSearchError, Error);
function createCustomError(name, message) {
function AlgoliaSearchCustomError() {
var args = Array.prototype.slice.call(arguments, 0);
// custom message not set, use default
if (typeof args[0] !== 'string') {
args.unshift(message);
}
AlgoliaSearchError.apply(this, args);
this.name = 'AlgoliaSearch' + name + 'Error';
}
inherits_browser$2(AlgoliaSearchCustomError, AlgoliaSearchError);
return AlgoliaSearchCustomError;
}
// late exports to let various fn defs and inherits take place
var errors = {
AlgoliaSearchError: AlgoliaSearchError,
UnparsableJSON: createCustomError(
'UnparsableJSON',
'Could not parse the incoming response as JSON, see err.more for details'
),
RequestTimeout: createCustomError(
'RequestTimeout',
'Request timedout before getting a response'
),
Network: createCustomError(
'Network',
'Network issue, see err.more for details'
),
JSONPScriptFail: createCustomError(
'JSONPScriptFail',
'<script> was loaded but did not call our provided callback'
),
JSONPScriptError: createCustomError(
'JSONPScriptError',
'<script> unable to load due to an `error` event on it'
),
Unknown: createCustomError(
'Unknown',
'Unknown error occured'
)
};
// Parse cloud does not supports setTimeout
// We do not store a setTimeout reference in the client everytime
// We only fallback to a fake setTimeout when not available
// setTimeout cannot be override globally sadly
var exitPromise = function exitPromise(fn, _setTimeout) {
_setTimeout(fn, 0);
};
var buildSearchMethod_1 = buildSearchMethod;
/**
* Creates a search method to be used in clients
* @param {string} queryParam the name of the attribute used for the query
* @param {string} url the url
* @return {function} the search method
*/
function buildSearchMethod(queryParam, url) {
/**
* The search method. Prepares the data and send the query to Algolia.
* @param {string} query the string used for query search
* @param {object} args additional parameters to send with the search
* @param {function} [callback] the callback to be called with the client gets the answer
* @return {undefined|Promise} If the callback is not provided then this methods returns a Promise
*/
return function search(query, args, callback) {
// warn V2 users on how to search
if (typeof query === 'function' && typeof args === 'object' ||
typeof callback === 'object') {
// .search(query, params, cb)
// .search(cb, params)
throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)');
}
// Normalizing the function signature
if (arguments.length === 0 || typeof query === 'function') {
// Usage : .search(), .search(cb)
callback = query;
query = '';
} else if (arguments.length === 1 || typeof args === 'function') {
// Usage : .search(query/args), .search(query, cb)
callback = args;
args = undefined;
}
// At this point we have 3 arguments with values
// Usage : .search(args) // careful: typeof null === 'object'
if (typeof query === 'object' && query !== null) {
args = query;
query = undefined;
} else if (query === undefined || query === null) { // .search(undefined/null)
query = '';
}
var params = '';
if (query !== undefined) {
params += queryParam + '=' + encodeURIComponent(query);
}
var additionalUA;
if (args !== undefined) {
if (args.additionalUA) {
additionalUA = args.additionalUA;
delete args.additionalUA;
}
// `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if
params = this.as._getSearchParams(args, params);
}
return this._search(params, url, callback, additionalUA);
};
}
var deprecate = function deprecate(fn, message) {
var warned = false;
function deprecated() {
if (!warned) {
/* eslint no-console:0 */
console.warn(message);
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var deprecatedMessage = function deprecatedMessage(previousUsage, newUsage) {
var githubAnchorLink = previousUsage.toLowerCase()
.replace(/[\.\(\)]/g, '');
return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage +
'`. Please see https://github.com/algolia/algoliasearch-client-javascript/wiki/Deprecated#' + githubAnchorLink;
};
var merge$2 = function merge(destination/* , sources */) {
var sources = Array.prototype.slice.call(arguments);
foreach(sources, function(source) {
for (var keyName in source) {
if (source.hasOwnProperty(keyName)) {
if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') {
destination[keyName] = merge({}, destination[keyName], source[keyName]);
} else if (source[keyName] !== undefined) {
destination[keyName] = source[keyName];
}
}
}
});
return destination;
};
var clone = function clone(obj) {
return JSON.parse(JSON.stringify(obj));
};
var toStr$1 = Object.prototype.toString;
var isArguments$2 = function isArguments(value) {
var str = toStr$1.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr$1.call(value.callee) === '[object Function]';
}
return isArgs;
};
// modified from https://github.com/es-shims/es5-shim
var has$1 = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has$1.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArguments$2(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has$1.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has$1.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has$1.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArguments$2(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
var objectKeys = keysShim;
var omit$2 = function omit(obj, test) {
var keys = objectKeys;
var foreach$$2 = foreach;
var filtered = {};
foreach$$2(keys(obj), function doFilter(keyName) {
if (test(keyName) !== true) {
filtered[keyName] = obj[keyName];
}
});
return filtered;
};
var toString$3 = {}.toString;
var isarray = Array.isArray || function (arr) {
return toString$3.call(arr) == '[object Array]';
};
var map$2 = function map(arr, fn) {
var newArr = [];
foreach(arr, function(item, itemIndex) {
newArr.push(fn(item, itemIndex, arr));
});
return newArr;
};
var IndexCore_1 = IndexCore;
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
function IndexCore(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
// make sure every index instance has it's own cache
this.cache = {};
}
/*
* Clear all queries in cache
*/
IndexCore.prototype.clearCache = function() {
this.cache = {};
};
/*
* Search inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the full text query
* @param {object} [args] (optional) if set, contains an object with query parameters:
* - page: (integer) Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus,
* to retrieve the 10th page you need to set page=9
* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
* - attributesToRetrieve: a string that contains the list of object attributes
* you want to retrieve (let you minimize the answer size).
* Attributes are separated with a comma (for example "name,address").
* You can also use an array (for example ["name","address"]).
* By default, all attributes are retrieved. You can also use '*' to retrieve all
* values when an attributesToRetrieve setting is specified for your index.
* - attributesToHighlight: a string that contains the list of attributes you
* want to highlight according to the query.
* Attributes are separated by a comma. You can also use an array (for example ["name","address"]).
* If an attribute has no match for the query, the raw value is returned.
* By default all indexed text attributes are highlighted.
* You can use `*` if you want to highlight all textual attributes.
* Numerical attributes are not highlighted.
* A matchLevel is returned for each highlighted attribute and can contain:
* - full: if all the query terms were found in the attribute,
* - partial: if only some of the query terms were found,
* - none: if none of the query terms were found.
* - attributesToSnippet: a string that contains the list of attributes to snippet alongside
* the number of words to return (syntax is `attributeName:nbWords`).
* Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
* You can also use an array (Example: attributesToSnippet: ['name:10','content:10']).
* By default no snippet is computed.
* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters in a query word
* to accept two typos in this word. Defaults to 7.
* - getRankingInfo: if set to 1, the result hits will contain ranking
* information in _rankingInfo attribute.
* - aroundLatLng: search for entries around a given
* latitude/longitude (specified as two floats separated by a comma).
* For example aroundLatLng=47.316669,5.016670).
* You can specify the maximum distance in meters with the aroundRadius parameter (in meters)
* and the precision for ranking with aroundPrecision
* (for example if you set aroundPrecision=100, two objects that are distant of
* less than 100m will be considered as identical for "geo" ranking parameter).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - insideBoundingBox: search entries inside a given area defined by the two extreme points
* of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
* For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - numericFilters: a string that contains the list of numeric filters you want to
* apply separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value`.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
* You can also use an array (for example numericFilters: ["price>100","price<1000"]).
* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
* To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]]
* means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags** attribute
* of objects (for example {"_tags":["tag1","tag2"]}).
* - facetFilters: filter the query by a list of facets.
* Facets are separated by commas and each facet is encoded as `attributeName:value`.
* For example: `facetFilters=category:Book,author:John%20Doe`.
* You can also use an array (for example `["category:Book","author:John%20Doe"]`).
* - facets: List of object attributes that you want to use for faceting.
* Comma separated list: `"category,author"` or array `['category','author']`
* Only attributes that have been added in **attributesForFaceting** index setting
* can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
* - queryType: select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - optionalWords: a string that contains the list of words that should
* be considered as optional when found in the query.
* Comma separated and array are accepted.
* - distinct: If set to 1, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best
* one is kept and others are removed.
* - restrictSearchableAttributes: List of attributes you want to use for
* textual search (must be a subset of the attributesToIndex index setting)
* either comma separated or as an array
* @param {function} [callback] the result callback called with two arguments:
* error: null or Error('message'). If false, the content contains the error.
* content: the server answer that contains the list of results.
*/
IndexCore.prototype.search = buildSearchMethod_1('query');
/*
* -- BETA --
* Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the similar query
* @param {object} [args] (optional) if set, contains an object with query parameters.
* All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters
* are the two most useful to restrict the similar results and get more relevant content
*/
IndexCore.prototype.similarSearch = buildSearchMethod_1('similarQuery');
/*
* Browse index content. The response content will have a `cursor` property that you can use
* to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browse('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* }, callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browse = function(query, queryParameters, callback) {
var merge = merge$2;
var indexObj = this;
var page;
var hitsPerPage;
// we check variadic calls that are not the one defined
// .browse()/.browse(fn)
// => page = 0
if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') {
page = 0;
callback = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'number') {
// .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn)
page = arguments[0];
if (typeof arguments[1] === 'number') {
hitsPerPage = arguments[1];
} else if (typeof arguments[1] === 'function') {
callback = arguments[1];
hitsPerPage = undefined;
}
query = undefined;
queryParameters = undefined;
} else if (typeof arguments[0] === 'object') {
// .browse(queryParameters)/.browse(queryParameters, cb)
if (typeof arguments[1] === 'function') {
callback = arguments[1];
}
queryParameters = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
// .browse(query, cb)
callback = arguments[1];
queryParameters = undefined;
}
// otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb)
// get search query parameters combining various possible calls
// to .browse();
queryParameters = merge({}, queryParameters || {}, {
page: page,
hitsPerPage: hitsPerPage,
query: query
});
var params = this.as._getSearchParams(queryParameters, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse',
body: {params: params},
hostType: 'read',
callback: callback
});
};
/*
* Continue browsing from a previous position (cursor), obtained via a call to `.browse()`.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browseFrom('14lkfsakl32', callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browseFrom = function(cursor, callback) {
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse',
body: {cursor: cursor},
hostType: 'read',
callback: callback
});
};
/*
* Search for facet values
* https://www.algolia.com/doc/rest-api/search#search-for-facet-values
*
* @param {string} params.facetName Facet name, name of the attribute to search for values in.
* Must be declared as a facet
* @param {string} params.facetQuery Query for the facet search
* @param {string} [params.*] Any search parameter of Algolia,
* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
* @param callback (optional)
*/
IndexCore.prototype.searchForFacetValues = function(params, callback) {
var clone$$1 = clone;
var omit = omit$2;
var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])';
if (params.facetName === undefined || params.facetQuery === undefined) {
throw new Error(usage);
}
var facetName = params.facetName;
var filteredParams = omit(clone$$1(params), function(keyName) {
return keyName === 'facetName';
});
var searchParameters = this.as._getSearchParams(filteredParams, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' +
encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query',
hostType: 'read',
body: {params: searchParameters},
callback: callback
});
};
IndexCore.prototype.searchFacet = deprecate(function(params, callback) {
return this.searchForFacetValues(params, callback);
}, deprecatedMessage(
'index.searchFacet(params[, callback])',
'index.searchForFacetValues(params[, callback])'
));
IndexCore.prototype._search = function(params, url, callback, additionalUA) {
return this.as._jsonRequest({
cache: this.cache,
method: 'POST',
url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: {params: params},
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName),
body: {params: params}
},
callback: callback,
additionalUA: additionalUA
});
};
/*
* Get an object from this index
*
* @param objectID the unique identifier of the object to retrieve
* @param attrs (optional) if set, contains the array of attribute names to retrieve
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the object to retrieve or the error message if a failure occured
*/
IndexCore.prototype.getObject = function(objectID, attrs, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof attrs === 'function') {
callback = attrs;
attrs = undefined;
}
var params = '';
if (attrs !== undefined) {
params = '?attributes=';
for (var i = 0; i < attrs.length; ++i) {
if (i !== 0) {
params += ',';
}
params += attrs[i];
}
}
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
hostType: 'read',
callback: callback
});
};
/*
* Get several objects from this index
*
* @param objectIDs the array of unique identifier of objects to retrieve
*/
IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) {
var isArray = isarray;
var map = map$2;
var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
if (arguments.length === 1 || typeof attributesToRetrieve === 'function') {
callback = attributesToRetrieve;
attributesToRetrieve = undefined;
}
var body = {
requests: map(objectIDs, function prepareRequest(objectID) {
var request = {
indexName: indexObj.indexName,
objectID: objectID
};
if (attributesToRetrieve) {
request.attributesToRetrieve = attributesToRetrieve.join(',');
}
return request;
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/*/objects',
hostType: 'read',
body: body,
callback: callback
});
};
IndexCore.prototype.as = null;
IndexCore.prototype.indexName = null;
IndexCore.prototype.typeAheadArgs = null;
IndexCore.prototype.typeAheadValueOption = null;
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
var ms = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse$3(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse$3(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd';
}
if (ms >= h) {
return Math.round(ms / h) + 'h';
}
if (ms >= m) {
return Math.round(ms / m) + 'm';
}
if (ms >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return;
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name;
}
return Math.ceil(ms / n) + ' ' + name + 's';
}
var debug$1 = createCommonjsModule(function (module, exports) {
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = ms;
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms$$1 = curr - (prevTime || curr);
self.diff = ms$$1;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
exports.names = [];
exports.skips = [];
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
});
var debug_1 = debug$1.coerce;
var debug_2 = debug$1.disable;
var debug_3 = debug$1.enable;
var debug_4 = debug$1.enabled;
var debug_5 = debug$1.humanize;
var debug_6 = debug$1.names;
var debug_7 = debug$1.skips;
var debug_8 = debug$1.formatters;
var browser$1 = createCommonjsModule(function (module, exports) {
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug$1;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
});
var browser_1 = browser$1.log;
var browser_2 = browser$1.formatArgs;
var browser_3 = browser$1.save;
var browser_4 = browser$1.load;
var browser_5 = browser$1.useColors;
var browser_6 = browser$1.storage;
var browser_7 = browser$1.colors;
var debug = browser$1('algoliasearch:src/hostIndexState.js');
var localStorageNamespace = 'algoliasearch-client-js';
var store;
var moduleStore = {
state: {},
set: function(key, data) {
this.state[key] = data;
return this.state[key];
},
get: function(key) {
return this.state[key] || null;
}
};
var localStorageStore = {
set: function(key, data) {
moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure
try {
var namespace = JSON.parse(commonjsGlobal.localStorage[localStorageNamespace]);
namespace[key] = data;
commonjsGlobal.localStorage[localStorageNamespace] = JSON.stringify(namespace);
return namespace[key];
} catch (e) {
return localStorageFailure(key, e);
}
},
get: function(key) {
try {
return JSON.parse(commonjsGlobal.localStorage[localStorageNamespace])[key] || null;
} catch (e) {
return localStorageFailure(key, e);
}
}
};
function localStorageFailure(key, e) {
debug('localStorage failed with', e);
cleanup();
store = moduleStore;
return store.get(key);
}
store = supportsLocalStorage() ? localStorageStore : moduleStore;
var store_1 = {
get: getOrSet,
set: getOrSet,
supportsLocalStorage: supportsLocalStorage
};
function getOrSet(key, data) {
if (arguments.length === 1) {
return store.get(key);
}
return store.set(key, data);
}
function supportsLocalStorage() {
try {
if ('localStorage' in commonjsGlobal &&
commonjsGlobal.localStorage !== null) {
if (!commonjsGlobal.localStorage[localStorageNamespace]) {
// actual creation of the namespace
commonjsGlobal.localStorage.setItem(localStorageNamespace, JSON.stringify({}));
}
return true;
}
return false;
} catch (_) {
return false;
}
}
// In case of any error on localStorage, we clean our own namespace, this should handle
// quota errors when a lot of keys + data are used
function cleanup() {
try {
commonjsGlobal.localStorage.removeItem(localStorageNamespace);
} catch (_) {
// nothing to do
}
}
var AlgoliaSearchCore_1 = AlgoliaSearchCore;
// We will always put the API KEY in the JSON body in case of too long API KEY,
// to avoid query string being too long and failing in various conditions (our server limit, browser limit,
// proxies limit)
var MAX_API_KEY_LENGTH = 500;
var RESET_APP_DATA_TIMER =
process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) ||
60 * 2 * 1000; // after 2 minutes reset to first host
/*
* Algolia Search library initialization
* https://www.algolia.com/
*
* @param {string} applicationID - Your applicationID, found in your dashboard
* @param {string} apiKey - Your API key, found in your dashboard
* @param {Object} [opts]
* @param {number} [opts.timeout=2000] - The request timeout set in milliseconds,
* another request will be issued after this timeout
* @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API.
* Set to 'https:' to force using https.
* Default to document.location.protocol in browsers
* @param {Object|Array} [opts.hosts={
* read: [this.applicationID + '-dsn.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]),
* write: [this.applicationID + '.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]) - The hosts to use for Algolia Search API.
* If you provide them, you will less benefit from our HA implementation
*/
function AlgoliaSearchCore(applicationID, apiKey, opts) {
var debug = browser$1('algoliasearch');
var clone$$1 = clone;
var isArray = isarray;
var map = map$2;
var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)';
if (opts._allowEmptyCredentials !== true && !applicationID) {
throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage);
}
if (opts._allowEmptyCredentials !== true && !apiKey) {
throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage);
}
this.applicationID = applicationID;
this.apiKey = apiKey;
this.hosts = {
read: [],
write: []
};
opts = opts || {};
var protocol = opts.protocol || 'https:';
this._timeouts = opts.timeouts || {
connect: 1 * 1000, // 500ms connect is GPRS latency
read: 2 * 1000,
write: 30 * 1000
};
// backward compat, if opts.timeout is passed, we use it to configure all timeouts like before
if (opts.timeout) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout;
}
// while we advocate for colon-at-the-end values: 'http:' for `opts.protocol`
// we also accept `http` and `https`. It's a common error.
if (!/:$/.test(protocol)) {
protocol = protocol + ':';
}
if (opts.protocol !== 'http:' && opts.protocol !== 'https:') {
throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)');
}
this._checkAppIdData();
if (!opts.hosts) {
var defaultHosts = map(this._shuffleResult, function(hostNumber) {
return applicationID + '-' + hostNumber + '.algolianet.com';
});
// no hosts given, compute defaults
this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts);
this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts);
} else if (isArray(opts.hosts)) {
// when passing custom hosts, we need to have a different host index if the number
// of write/read hosts are different.
this.hosts.read = clone$$1(opts.hosts);
this.hosts.write = clone$$1(opts.hosts);
} else {
this.hosts.read = clone$$1(opts.hosts.read);
this.hosts.write = clone$$1(opts.hosts.write);
}
// add protocol and lowercase hosts
this.hosts.read = map(this.hosts.read, prepareHost(protocol));
this.hosts.write = map(this.hosts.write, prepareHost(protocol));
this.extraHeaders = {};
// In some situations you might want to warm the cache
this.cache = opts._cache || {};
this._ua = opts._ua;
this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache;
this._useFallback = opts.useFallback === undefined ? true : opts.useFallback;
this._setTimeout = opts._setTimeout;
debug('init done, %j', this);
}
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearchCore.prototype.initIndex = function(indexName) {
return new IndexCore_1(this, indexName);
};
/**
* Add an extra field to the HTTP request
*
* @param name the header field name
* @param value the header field value
*/
AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) {
this.extraHeaders[name.toLowerCase()] = value;
};
/**
* Get the value of an extra HTTP header
*
* @param name the header field name
*/
AlgoliaSearchCore.prototype.getExtraHeader = function(name) {
return this.extraHeaders[name.toLowerCase()];
};
/**
* Remove an extra field from the HTTP request
*
* @param name the header field name
*/
AlgoliaSearchCore.prototype.unsetExtraHeader = function(name) {
delete this.extraHeaders[name.toLowerCase()];
};
/**
* Augment sent x-algolia-agent with more data, each agent part
* is automatically separated from the others by a semicolon;
*
* @param algoliaAgent the agent to add
*/
AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) {
if (this._ua.indexOf(';' + algoliaAgent) === -1) {
this._ua += ';' + algoliaAgent;
}
};
/*
* Wrapper that try all hosts to maximize the quality of service
*/
AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) {
this._checkAppIdData();
var requestDebug = browser$1('algoliasearch:' + initialOpts.url);
var body;
var additionalUA = initialOpts.additionalUA || '';
var cache = initialOpts.cache;
var client = this;
var tries = 0;
var usingFallback = false;
var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback;
var headers;
if (
this.apiKey.length > MAX_API_KEY_LENGTH &&
initialOpts.body !== undefined &&
(initialOpts.body.params !== undefined || // index.search()
initialOpts.body.requests !== undefined) // client.search()
) {
initialOpts.body.apiKey = this.apiKey;
headers = this._computeRequestHeaders(additionalUA, false);
} else {
headers = this._computeRequestHeaders(additionalUA);
}
if (initialOpts.body !== undefined) {
body = safeJSONStringify(initialOpts.body);
}
requestDebug('request start');
var debugData = [];
function doRequest(requester, reqOpts) {
client._checkAppIdData();
var startTime = new Date();
var cacheID;
if (client._useCache) {
cacheID = initialOpts.url;
}
// as we sometime use POST requests to pass parameters (like query='aa'),
// the cacheID must also include the body to be different between calls
if (client._useCache && body) {
cacheID += '_body_' + reqOpts.body;
}
// handle cache existence
if (client._useCache && cache && cache[cacheID] !== undefined) {
requestDebug('serving response from cache');
return client._promise.resolve(JSON.parse(cache[cacheID]));
}
// if we reached max tries
if (tries >= client.hosts[initialOpts.hostType].length) {
if (!hasFallback || usingFallback) {
requestDebug('could not get any response');
// then stop
return client._promise.reject(new errors.AlgoliaSearchError(
'Cannot connect to the AlgoliaSearch API.' +
' Send an email to support@algolia.com to report and resolve the issue.' +
' Application id was: ' + client.applicationID, {debugData: debugData}
));
}
requestDebug('switching to fallback');
// let's try the fallback starting from here
tries = 0;
// method, url and body are fallback dependent
reqOpts.method = initialOpts.fallback.method;
reqOpts.url = initialOpts.fallback.url;
reqOpts.jsonBody = initialOpts.fallback.body;
if (reqOpts.jsonBody) {
reqOpts.body = safeJSONStringify(reqOpts.jsonBody);
}
// re-compute headers, they could be omitting the API KEY
headers = client._computeRequestHeaders(additionalUA);
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
client._setHostIndexByType(0, initialOpts.hostType);
usingFallback = true; // the current request is now using fallback
return doRequest(client._request.fallback, reqOpts);
}
var currentHost = client._getHostByType(initialOpts.hostType);
var url = currentHost + reqOpts.url;
var options = {
body: reqOpts.body,
jsonBody: reqOpts.jsonBody,
method: reqOpts.method,
headers: headers,
timeouts: reqOpts.timeouts,
debug: requestDebug
};
requestDebug('method: %s, url: %s, headers: %j, timeouts: %d',
options.method, url, options.headers, options.timeouts);
if (requester === client._request.fallback) {
requestDebug('using fallback');
}
// `requester` is any of this._request or this._request.fallback
// thus it needs to be called using the client as context
return requester.call(client, url, options).then(success, tryFallback);
function success(httpResponse) {
// compute the status of the response,
//
// When in browser mode, using XDR or JSONP, we have no statusCode available
// So we rely on our API response `status` property.
// But `waitTask` can set a `status` property which is not the statusCode (it's the task status)
// So we check if there's a `message` along `status` and it means it's an error
//
// That's the only case where we have a response.status that's not the http statusCode
var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status ||
// this is important to check the request statusCode AFTER the body eventual
// statusCode because some implementations (jQuery XDomainRequest transport) may
// send statusCode 200 while we had an error
httpResponse.statusCode ||
// When in browser mode, using XDR or JSONP
// we default to success when no error (no response.status && response.message)
// If there was a JSON.parse() error then body is null and it fails
httpResponse && httpResponse.body && 200;
requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j',
httpResponse.statusCode, status, httpResponse.headers);
var httpResponseOk = Math.floor(status / 100) === 2;
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime,
statusCode: status
});
if (httpResponseOk) {
if (client._useCache && cache) {
cache[cacheID] = httpResponse.responseText;
}
return httpResponse.body;
}
var shouldRetry = Math.floor(status / 100) !== 4;
if (shouldRetry) {
tries += 1;
return retryRequest();
}
requestDebug('unrecoverable error');
// no success and no retry => fail
var unrecoverableError = new errors.AlgoliaSearchError(
httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status}
);
return client._promise.reject(unrecoverableError);
}
function tryFallback(err) {
// error cases:
// While not in fallback mode:
// - CORS not supported
// - network error
// While in fallback mode:
// - timeout
// - network error
// - badly formatted JSONP (script loaded, did not call our callback)
// In both cases:
// - uncaught exception occurs (TypeError)
requestDebug('error: %s, stack: %s', err.message, err.stack);
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime
});
if (!(err instanceof errors.AlgoliaSearchError)) {
err = new errors.Unknown(err && err.message, err);
}
tries += 1;
// stop the request implementation when:
if (
// we did not generate this error,
// it comes from a throw in some other piece of code
err instanceof errors.Unknown ||
// server sent unparsable JSON
err instanceof errors.UnparsableJSON ||
// max tries and already using fallback or no fallback
tries >= client.hosts[initialOpts.hostType].length &&
(usingFallback || !hasFallback)) {
// stop request implementation for this command
err.debugData = debugData;
return client._promise.reject(err);
}
// When a timeout occured, retry by raising timeout
if (err instanceof errors.RequestTimeout) {
return retryRequestWithHigherTimeout();
}
return retryRequest();
}
function retryRequest() {
requestDebug('retrying request');
client._incrementHostIndex(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
function retryRequestWithHigherTimeout() {
requestDebug('retrying request with higher timeout');
client._incrementHostIndex(initialOpts.hostType);
client._incrementTimeoutMultipler();
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
}
var promise = doRequest(
client._request, {
url: initialOpts.url,
method: initialOpts.method,
body: body,
jsonBody: initialOpts.body,
timeouts: client._getTimeoutsForRequest(initialOpts.hostType)
}
);
// either we have a callback
// either we are using promises
if (typeof initialOpts.callback === 'function') {
promise.then(function okCb(content) {
exitPromise(function() {
initialOpts.callback(null, content);
}, client._setTimeout || setTimeout);
}, function nookCb(err) {
exitPromise(function() {
initialOpts.callback(err);
}, client._setTimeout || setTimeout);
});
} else {
return promise;
}
};
/*
* Transform search param object in query string
* @param {object} args arguments to add to the current query string
* @param {string} params current query string
* @return {string} the final query string
*/
AlgoliaSearchCore.prototype._getSearchParams = function(args, params) {
if (args === undefined || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) {
params += params === '' ? '' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]);
}
}
return params;
};
AlgoliaSearchCore.prototype._computeRequestHeaders = function(additionalUA, withAPIKey) {
var forEach = foreach;
var ua = additionalUA ?
this._ua + ';' + additionalUA :
this._ua;
var requestHeaders = {
'x-algolia-agent': ua,
'x-algolia-application-id': this.applicationID
};
// browser will inline headers in the url, node.js will use http headers
// but in some situations, the API KEY will be too long (big secured API keys)
// so if the request is a POST and the KEY is very long, we will be asked to not put
// it into headers but in the JSON body
if (withAPIKey !== false) {
requestHeaders['x-algolia-api-key'] = this.apiKey;
}
if (this.userToken) {
requestHeaders['x-algolia-usertoken'] = this.userToken;
}
if (this.securityTags) {
requestHeaders['x-algolia-tagfilters'] = this.securityTags;
}
forEach(this.extraHeaders, function addToRequestHeaders(value, key) {
requestHeaders[key] = value;
});
return requestHeaders;
};
/**
* Search through multiple indices at the same time
* @param {Object[]} queries An array of queries you want to run.
* @param {string} queries[].indexName The index name you want to target
* @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params`
* @param {Object} queries[].params Any search param like hitsPerPage, ..
* @param {Function} callback Callback to be called
* @return {Promise|undefined} Returns a promise if no callback given
*/
AlgoliaSearchCore.prototype.search = function(queries, opts, callback) {
var isArray = isarray;
var map = map$2;
var usage = 'Usage: client.search(arrayOfQueries[, callback])';
if (!isArray(queries)) {
throw new Error(usage);
}
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var client = this;
var postObj = {
requests: map(queries, function prepareRequest(query) {
var params = '';
// allow query.query
// so we are mimicing the index.search(query, params) method
// {indexName:, query:, params:}
if (query.query !== undefined) {
params += 'query=' + encodeURIComponent(query.query);
}
return {
indexName: query.indexName,
params: client._getSearchParams(query.params, params)
};
})
};
var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) {
return requestId + '=' +
encodeURIComponent(
'/1/indexes/' + encodeURIComponent(request.indexName) + '?' +
request.params
);
}).join('&');
var url = '/1/indexes/*/queries';
if (opts.strategy !== undefined) {
url += '?strategy=' + opts.strategy;
}
return this._jsonRequest({
cache: this.cache,
method: 'POST',
url: url,
body: postObj,
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/*',
body: {
params: JSONPParams
}
},
callback: callback
});
};
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
AlgoliaSearchCore.prototype.setSecurityTags = function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.securityTags = tags;
};
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
AlgoliaSearchCore.prototype.setUserToken = function(userToken) {
this.userToken = userToken;
};
/**
* Clear all queries in client's cache
* @return undefined
*/
AlgoliaSearchCore.prototype.clearCache = function() {
this.cache = {};
};
/**
* Set the number of milliseconds a request can take before automatically being terminated.
* @deprecated
* @param {Number} milliseconds
*/
AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) {
if (milliseconds) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds;
}
};
/**
* Set the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) {
this._timeouts = timeouts;
};
/**
* Get the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.getTimeouts = function() {
return this._timeouts;
};
AlgoliaSearchCore.prototype._getAppIdData = function() {
var data = store_1.get(this.applicationID);
if (data !== null) this._cacheAppIdData(data);
return data;
};
AlgoliaSearchCore.prototype._setAppIdData = function(data) {
data.lastChange = (new Date()).getTime();
this._cacheAppIdData(data);
return store_1.set(this.applicationID, data);
};
AlgoliaSearchCore.prototype._checkAppIdData = function() {
var data = this._getAppIdData();
var now = (new Date()).getTime();
if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) {
return this._resetInitialAppIdData(data);
}
return data;
};
AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) {
var newData = data || {};
newData.hostIndexes = {read: 0, write: 0};
newData.timeoutMultiplier = 1;
newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]);
return this._setAppIdData(newData);
};
AlgoliaSearchCore.prototype._cacheAppIdData = function(data) {
this._hostIndexes = data.hostIndexes;
this._timeoutMultiplier = data.timeoutMultiplier;
this._shuffleResult = data.shuffleResult;
};
AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) {
var foreach$$1 = foreach;
var currentData = this._getAppIdData();
foreach$$1(newData, function(value, key) {
currentData[key] = value;
});
return this._setAppIdData(currentData);
};
AlgoliaSearchCore.prototype._getHostByType = function(hostType) {
return this.hosts[hostType][this._getHostIndexByType(hostType)];
};
AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() {
return this._timeoutMultiplier;
};
AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) {
return this._hostIndexes[hostType];
};
AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) {
var clone$$1 = clone;
var newHostIndexes = clone$$1(this._hostIndexes);
newHostIndexes[hostType] = hostIndex;
this._partialAppIdDataUpdate({hostIndexes: newHostIndexes});
return hostIndex;
};
AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) {
return this._setHostIndexByType(
(this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType
);
};
AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() {
var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4);
return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier});
};
AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) {
return {
connect: this._timeouts.connect * this._timeoutMultiplier,
complete: this._timeouts[hostType] * this._timeoutMultiplier
};
};
function prepareHost(protocol) {
return function prepare(host) {
return protocol + '//' + host.toLowerCase();
};
}
// Prototype.js < 1.7, a widely used library, defines a weird
// Array.prototype.toJSON function that will fail to stringify our content
// appropriately
// refs:
// - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q
// - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c
// - http://stackoverflow.com/a/3148441/147079
function safeJSONStringify(obj) {
/* eslint no-extend-native:0 */
if (Array.prototype.toJSON === undefined) {
return JSON.stringify(obj);
}
var toJSON = Array.prototype.toJSON;
delete Array.prototype.toJSON;
var out = JSON.stringify(obj);
Array.prototype.toJSON = toJSON;
return out;
}
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function removeCredentials(headers) {
var newHeaders = {};
for (var headerName in headers) {
if (Object.prototype.hasOwnProperty.call(headers, headerName)) {
var value;
if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') {
value = '**hidden for security purposes**';
} else {
value = headers[headerName];
}
newHeaders[headerName] = value;
}
}
return newHeaders;
}
var win;
if (typeof window !== "undefined") {
win = window;
} else if (typeof commonjsGlobal !== "undefined") {
win = commonjsGlobal;
} else if (typeof self !== "undefined"){
win = self;
} else {
win = {};
}
var window_1 = win;
var es6Promise = createCommonjsModule(function (module, exports) {
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version 4.1.1
*/
(function (global, factory) {
module.exports = factory();
}(commonjsGlobal, (function () { function objectOrFunction(x) {
var type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = undefined;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
}
var isArray = _isArray;
var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var r = commonjsRequire;
var vertx = r('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof commonjsRequire === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var _arguments = arguments;
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
(function () {
var callback = _arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
})();
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve$1(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(16);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch (error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
try {
then$$1.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then$$1) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then$$1, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return resolve(promise, value);
}, function (reason) {
return reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$1) {
if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$1 === GET_THEN_ERROR) {
reject(promise, GET_THEN_ERROR.error);
GET_THEN_ERROR.error = null;
} else if (then$$1 === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$1)) {
handleForeignThenable(promise, maybeThenable, then$$1);
} else {
fulfill(promise, maybeThenable);
}
}
}
function resolve(promise, value) {
if (promise === value) {
reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = undefined,
callback = undefined,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = undefined,
error = undefined,
succeeded = undefined,
failed = undefined;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value.error = null;
} else {
succeeded = true;
}
if (promise === value) {
reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
resolve(promise, value);
}, function rejectPromise(reason) {
reject(promise, reason);
});
} catch (e) {
reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function Enumerator$1(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate(input);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
function validationError() {
return new Error('Array Methods must be provided an Array');
}
Enumerator$1.prototype._enumerate = function (input) {
for (var i = 0; this._state === PENDING && i < input.length; i++) {
this._eachEntry(input[i], i);
}
};
Enumerator$1.prototype._eachEntry = function (entry, i) {
var c = this._instanceConstructor;
var resolve$$1 = c.resolve;
if (resolve$$1 === resolve$1) {
var _then = getThen(entry);
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise$2) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, _then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$1) {
return resolve$$1(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$1(entry), i);
}
};
Enumerator$1.prototype._settledAt = function (state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator$1.prototype._willSettleAt = function (promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all$1(entries) {
return new Enumerator$1(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race$1(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject$1(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function Promise$2(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
}
}
Promise$2.all = all$1;
Promise$2.race = race$1;
Promise$2.resolve = resolve$1;
Promise$2.reject = reject$1;
Promise$2._setScheduler = setScheduler;
Promise$2._setAsap = setAsap;
Promise$2._asap = asap;
Promise$2.prototype = {
constructor: Promise$2,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: then,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function _catch(onRejection) {
return this.then(null, onRejection);
}
};
/*global self*/
function polyfill$1() {
var local = undefined;
if (typeof commonjsGlobal !== 'undefined') {
local = commonjsGlobal;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise$2;
}
// Strange compat..
Promise$2.polyfill = polyfill$1;
Promise$2.Promise = Promise$2;
return Promise$2;
})));
});
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
var encode$1 = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map$4(objectKeys$2(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray$2(obj[k])) {
return map$4(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray$2 = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map$4 (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys$2 = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
var inlineHeaders_1 = inlineHeaders;
function inlineHeaders(url, headers) {
if (/\?/.test(url)) {
url += '&';
} else {
url += '?';
}
return url + encode$1(headers);
}
var jsonpRequest_1 = jsonpRequest;
var JSONPCounter = 0;
function jsonpRequest(url, opts, cb) {
if (opts.method !== 'GET') {
cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
return;
}
opts.debug('JSONP: start');
var cbCalled = false;
var timedOut = false;
JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cbName = 'algoliaJSONP_' + JSONPCounter;
var done = false;
window[cbName] = function(data) {
removeGlobals();
if (timedOut) {
opts.debug('JSONP: Late answer, ignoring');
return;
}
cbCalled = true;
clean();
cb(null, {
body: data/* ,
// We do not send the statusCode, there's no statusCode in JSONP, it will be
// computed using data.status && data.message like with XDR
statusCode*/
});
};
// add callback by hand
url += '&callback=' + cbName;
// add body params manually
if (opts.jsonBody && opts.jsonBody.params) {
url += '&' + opts.jsonBody.params;
}
var ontimeout = setTimeout(timeout, opts.timeouts.complete);
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = readystatechange;
script.onload = success;
script.onerror = error;
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
function success() {
opts.debug('JSONP: success');
if (done || timedOut) {
return;
}
done = true;
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.debug('JSONP: Fail. Script loaded but did not call the callback');
clean();
cb(new errors.JSONPScriptFail());
}
}
function readystatechange() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
}
function clean() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
}
function removeGlobals() {
try {
delete window[cbName];
delete window[cbName + '_loaded'];
} catch (e) {
window[cbName] = window[cbName + '_loaded'] = undefined;
}
}
function timeout() {
opts.debug('JSONP: Script timeout');
timedOut = true;
clean();
cb(new errors.RequestTimeout());
}
function error() {
opts.debug('JSONP: Script error');
if (done || timedOut) {
return;
}
clean();
cb(new errors.JSONPScriptError());
}
}
var places = createPlacesClient;
function createPlacesClient(algoliasearch) {
return function places(appID, apiKey, opts) {
var cloneDeep = clone;
opts = opts && cloneDeep(opts) || {};
opts.hosts = opts.hosts || [
'places-dsn.algolia.net',
'places-1.algolianet.com',
'places-2.algolianet.com',
'places-3.algolianet.com'
];
// allow initPlaces() no arguments => community rate limited
if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) {
appID = '';
apiKey = '';
opts._allowEmptyCredentials = true;
}
var client = algoliasearch(appID, apiKey, opts);
var index = client.initIndex('places');
index.search = buildSearchMethod_1('query', '/1/places/query');
index.getObject = function(objectID, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/1/places/' + encodeURIComponent(objectID),
hostType: 'read',
callback: callback
});
};
return index;
};
}
var getDocumentProtocol_1 = getDocumentProtocol;
function getDocumentProtocol() {
var protocol = window.document.location.protocol;
// when in `file:` mode (local html file), default to `http:`
if (protocol !== 'http:' && protocol !== 'https:') {
protocol = 'http:';
}
return protocol;
}
var version$5 = '3.24.5';
var Promise$3 = window_1.Promise || es6Promise.Promise;
// This is the standalone browser build entry point
// Browser implementation of the Algolia Search JavaScript client,
// using XMLHttpRequest, XDomainRequest and JSONP as fallback
var createAlgoliasearch = function createAlgoliasearch(AlgoliaSearch, uaSuffix) {
var inherits = inherits_browser$2;
var errors$$2 = errors;
var inlineHeaders = inlineHeaders_1;
var jsonpRequest = jsonpRequest_1;
var places$$1 = places;
uaSuffix = uaSuffix || '';
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = clone;
var getDocumentProtocol = getDocumentProtocol_1;
opts = cloneDeep(opts || {});
if (opts.protocol === undefined) {
opts.protocol = getDocumentProtocol();
}
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchBrowser(applicationID, apiKey, opts);
}
algoliasearch.version = version$5;
algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version;
algoliasearch.initPlaces = places$$1(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
window_1.__algolia = {
debug: browser$1,
algoliasearch: algoliasearch
};
var support = {
hasXMLHttpRequest: 'XMLHttpRequest' in window_1,
hasXDomainRequest: 'XDomainRequest' in window_1
};
if (support.hasXMLHttpRequest) {
support.cors = 'withCredentials' in new XMLHttpRequest();
}
function AlgoliaSearchBrowser() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchBrowser, AlgoliaSearch);
AlgoliaSearchBrowser.prototype._request = function request(url, opts) {
return new Promise$3(function wrapRequest(resolve, reject) {
// no cors or XDomainRequest, no request
if (!support.cors && !support.hasXDomainRequest) {
// very old browser, not supported
reject(new errors$$2.Network('CORS not supported'));
return;
}
url = inlineHeaders(url, opts.headers);
var body = opts.body;
var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
var reqTimeout;
var timedOut;
var connected = false;
reqTimeout = setTimeout(onTimeout, opts.timeouts.connect);
// we set an empty onprogress listener
// so that XDomainRequest on IE9 is not aborted
// refs:
// - https://github.com/algolia/algoliasearch-client-js/issues/76
// - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
req.onprogress = onProgress;
if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange;
req.onload = onLoad;
req.onerror = onError;
// do not rely on default XHR async flag, as some analytics code like hotjar
// breaks it and set it to false by default
if (req instanceof XMLHttpRequest) {
req.open(opts.method, url, true);
} else {
req.open(opts.method, url);
}
// headers are meant to be sent after open
if (support.cors) {
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
} else {
req.setRequestHeader('content-type', 'application/json');
}
}
req.setRequestHeader('accept', 'application/json');
}
req.send(body);
// event object not received in IE8, at least
// but we do not use it, still important to note
function onLoad(/* event */) {
// When browser does not supports req.timeout, we can
// have both a load and timeout event, since handled by a dumb setTimeout
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
var out;
try {
out = {
body: JSON.parse(req.responseText),
responseText: req.responseText,
statusCode: req.status,
// XDomainRequest does not have any response headers
headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {}
};
} catch (e) {
out = new errors$$2.UnparsableJSON({
more: req.responseText
});
}
if (out instanceof errors$$2.UnparsableJSON) {
reject(out);
} else {
resolve(out);
}
}
function onError(event) {
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
// error event is trigerred both with XDR/XHR on:
// - DNS error
// - unallowed cross domain request
reject(
new errors$$2.Network({
more: event
})
);
}
function onTimeout() {
timedOut = true;
req.abort();
reject(new errors$$2.RequestTimeout());
}
function onConnect() {
connected = true;
clearTimeout(reqTimeout);
reqTimeout = setTimeout(onTimeout, opts.timeouts.complete);
}
function onProgress() {
if (!connected) onConnect();
}
function onReadyStateChange() {
if (!connected && req.readyState > 1) onConnect();
}
});
};
AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
return new Promise$3(function wrapJsonpRequest(resolve, reject) {
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
reject(err);
return;
}
resolve(content);
});
});
};
AlgoliaSearchBrowser.prototype._promise = {
reject: function rejectPromise(val) {
return Promise$3.reject(val);
},
resolve: function resolvePromise(val) {
return Promise$3.resolve(val);
},
delay: function delayPromise(ms) {
return new Promise$3(function resolveOnTimeout(resolve/* , reject*/) {
setTimeout(resolve, ms);
});
}
};
return algoliasearch;
};
var algoliasearchLite = createAlgoliasearch(AlgoliaSearchCore_1, '(lite) ');
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE$1 = 200;
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = _arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = _arrayMap(values, _baseUnary(iteratee));
}
if (comparator) {
includes = _arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE$1) {
includes = _cacheHas;
isCommon = false;
values = new _SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
var _baseDifference = baseDifference;
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = _baseRest(function(array, values) {
return isArrayLikeObject_1(array)
? _baseDifference(array, _baseFlatten(values, 1, isArrayLikeObject_1, true))
: [];
});
var difference_1 = difference;
/** Used for built-in method references. */
var objectProto$20 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$18 = objectProto$20.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$18.call(object, key);
}
var _baseHas = baseHas;
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has$2(object, path) {
return object != null && _hasPath(object, path, _baseHas);
}
var has_1 = has$2;
/**
* @typedef {object} ConnectorDescription
* @property {string} displayName - the displayName used by the wrapper
* @property {function} refine - a function to filter the local state
* @property {function} getSearchParameters - function transforming the local state to a SearchParameters
* @property {function} getMetadata - metadata of the widget
* @property {function} transitionState - hook after the state has changed
* @property {function} getProvidedProps - transform the state into props passed to the wrapped component.
* Receives (props, widgetStates, searchState, metadata) and returns the local state.
* @property {function} getId - Receives props and return the id that will be used to identify the widget
* @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state.
* @property {object} propTypes - PropTypes forwarded to the wrapped component.
* @property {object} defaultProps - default values for the props
*/
/**
* Connectors are the HOC used to transform React components
* into InstantSearch widgets.
* In order to simplify the construction of such connectors
* `createConnector` takes a description and transform it into
* a connector.
* @param {ConnectorDescription} connectorDesc the description of the connector
* @return {Connector} a function that wraps a component into
* an instantsearch connected one.
*/
function createConnector(connectorDesc) {
if (!connectorDesc.displayName) {
throw new Error('`createConnector` requires you to provide a `displayName` property.');
}
var hasRefine = has_1(connectorDesc, 'refine');
var hasSearchForFacetValues = has_1(connectorDesc, 'searchForFacetValues');
var hasSearchParameters = has_1(connectorDesc, 'getSearchParameters');
var hasMetadata = has_1(connectorDesc, 'getMetadata');
var hasTransitionState = has_1(connectorDesc, 'transitionState');
var hasCleanUp = has_1(connectorDesc, 'cleanUp');
var isWidget = hasSearchParameters || hasMetadata || hasTransitionState;
return function (Composed) {
var _class, _temp, _initialiseProps;
return _temp = _class = function (_Component) {
inherits(Connector, _Component);
function Connector(props, context) {
classCallCheck(this, Connector);
var _this = possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context));
_initialiseProps.call(_this);
var _context$ais = context.ais,
store = _context$ais.store,
widgetsManager = _context$ais.widgetsManager;
var canRender = false;
_this.state = {
props: _this.getProvidedProps(_extends({}, props, { canRender: canRender })),
canRender: canRender // use to know if a component is rendered (browser), or not (server).
};
_this.unsubscribe = store.subscribe(function () {
if (_this.state.canRender) {
_this.setState({
props: _this.getProvidedProps(_extends({}, _this.props, {
canRender: _this.state.canRender
}))
});
}
});
if (isWidget) {
_this.unregisterWidget = widgetsManager.registerWidget(_this);
}
return _this;
}
createClass(Connector, [{
key: 'getMetadata',
value: function getMetadata(nextWidgetsState) {
if (hasMetadata) {
return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState);
}
return {};
}
}, {
key: 'getSearchParameters',
value: function getSearchParameters(searchParameters) {
if (hasSearchParameters) {
return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.context.ais.store.getState().widgets);
}
return null;
}
}, {
key: 'transitionState',
value: function transitionState(prevWidgetsState, nextWidgetsState) {
if (hasTransitionState) {
return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState);
}
return nextWidgetsState;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.setState({
canRender: true
});
}
}, {
key: 'componentWillMount',
value: function componentWillMount() {
if (connectorDesc.getSearchParameters) {
this.context.ais.onSearchParameters(connectorDesc.getSearchParameters, this.context, this.props);
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (!isEqual_1(this.props, nextProps)) {
this.setState({
props: this.getProvidedProps(nextProps)
});
if (isWidget) {
// Since props might have changed, we need to re-run getSearchParameters
// and getMetadata with the new props.
this.context.ais.widgetsManager.update();
if (connectorDesc.transitionState) {
this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets));
}
}
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.unsubscribe();
if (isWidget) {
this.unregisterWidget(); // will schedule an update
if (hasCleanUp) {
var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets);
this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), {
widgets: newState
}));
this.context.ais.onSearchStateChange(removeEmptyKey(newState));
}
}
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
var propsEqual = shallowEqual(this.props, nextProps);
if (this.state.props === null || nextState.props === null) {
if (this.state.props === nextState.props) {
return !propsEqual;
}
return true;
}
return !propsEqual || !shallowEqual(this.state.props, nextState.props);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
if (this.state.props === null) {
return null;
}
var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {};
var searchForFacetValuesProps = hasSearchForFacetValues ? {
searchForItems: this.searchForFacetValues,
searchForFacetValues: function searchForFacetValues(facetName, query) {
_this2.searchForFacetValues(facetName, query);
}
} : {};
return React__default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps));
}
}]);
return Connector;
}(React.Component), _class.displayName = connectorDesc.displayName + '(' + getDisplayName(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = {
// @TODO: more precise state manager propType
ais: propTypes.object.isRequired,
multiIndexContext: propTypes.object
}, _initialiseProps = function _initialiseProps() {
var _this3 = this;
this.getProvidedProps = function (props) {
var store = _this3.context.ais.store;
var _store$getState = store.getState(),
results = _store$getState.results,
searching = _store$getState.searching,
error = _store$getState.error,
widgets = _store$getState.widgets,
metadata = _store$getState.metadata,
resultsFacetValues = _store$getState.resultsFacetValues,
searchingForFacetValues = _store$getState.searchingForFacetValues,
isSearchStalled = _store$getState.isSearchStalled;
var searchResults = {
results: results,
searching: searching,
error: error,
searchingForFacetValues: searchingForFacetValues,
isSearchStalled: isSearchStalled
};
return connectorDesc.getProvidedProps.call(_this3, props, widgets, searchResults, metadata, resultsFacetValues);
};
this.refine = function () {
var _connectorDesc$refine;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_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;
};
}
function getIndex(context) {
return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex;
}
function getResults(searchResults, context) {
if (searchResults.results && !searchResults.results.hits) {
return searchResults.results[getIndex(context)] ? searchResults.results[getIndex(context)] : null;
} else {
return searchResults.results ? searchResults.results : null;
}
}
function hasMultipleIndex(context) {
return context && context.multiIndexContext;
}
// eslint-disable-next-line max-params
function refineValue(searchState, nextRefinement, context, resetPage, namespace) {
if (hasMultipleIndex(context)) {
return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage);
} else {
// When we have a multi index page with shared widgets we should also
// reset their page to 1 if the resetPage is provided. Otherwise the
// indices will always be reset
// see: https://github.com/algolia/react-instantsearch/issues/310
// see: https://github.com/algolia/react-instantsearch/issues/637
if (searchState.indices && resetPage) {
Object.keys(searchState.indices).forEach(function (targetedIndex) {
searchState = refineValue(searchState, { page: 1 }, { multiIndexContext: { targetedIndex: targetedIndex } }, true, namespace);
});
}
return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage);
}
}
function refineMultiIndex(searchState, nextRefinement, context, resetPage) {
var page = resetPage ? { page: 1 } : undefined;
var index = getIndex(context);
var state = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], nextRefinement, page))) : _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, nextRefinement, page)));
return _extends({}, searchState, { indices: state });
}
function refineSingleIndex(searchState, nextRefinement, resetPage) {
var page = resetPage ? { page: 1 } : undefined;
return _extends({}, searchState, nextRefinement, page);
}
// eslint-disable-next-line max-params
function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) {
var _babelHelpers$extends3;
var index = getIndex(context);
var page = resetPage ? { page: 1 } : undefined;
var state = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], (_babelHelpers$extends3 = {}, defineProperty$2(_babelHelpers$extends3, namespace, _extends({}, searchState.indices[index][namespace], nextRefinement)), defineProperty$2(_babelHelpers$extends3, 'page', 1), _babelHelpers$extends3)))) : _extends({}, searchState.indices, defineProperty$2({}, index, _extends(defineProperty$2({}, namespace, nextRefinement), page)));
return _extends({}, searchState, { indices: state });
}
function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) {
var page = resetPage ? { page: 1 } : undefined;
return _extends({}, searchState, defineProperty$2({}, namespace, _extends({}, searchState[namespace], nextRefinement)), page);
}
function getNamespaceAndAttributeName(id) {
var parts = id.match(/^([^.]*)\.(.*)/);
var namespace = parts && parts[1];
var attributeName = parts && parts[2];
return { namespace: namespace, attributeName: attributeName };
}
// eslint-disable-next-line max-params
function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) {
var index = getIndex(context);
var _getNamespaceAndAttri = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri.namespace,
attributeName = _getNamespaceAndAttri.attributeName;
var refinements = hasMultipleIndex(context) && searchState.indices && namespace && searchState.indices['' + index] && has_1(searchState.indices['' + index][namespace], '' + attributeName) || hasMultipleIndex(context) && searchState.indices && has_1(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && namespace && has_1(searchState[namespace], attributeName) || !hasMultipleIndex(context) && has_1(searchState, id);
if (refinements) {
var currentRefinement = void 0;
if (hasMultipleIndex(context)) {
currentRefinement = namespace ? get_1(searchState.indices['' + index][namespace], attributeName) : get_1(searchState.indices[index], id);
} else {
currentRefinement = namespace ? get_1(searchState[namespace], attributeName) : get_1(searchState, id);
}
return refinementsCallback(currentRefinement);
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return defaultValue;
}
function cleanUpValue(searchState, context, id) {
var index = getIndex(context);
var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri2.namespace,
attributeName = _getNamespaceAndAttri2.attributeName;
if (hasMultipleIndex(context)) {
return namespace ? _extends({}, searchState, {
indices: _extends({}, searchState.indices, defineProperty$2({}, index, _extends({}, searchState.indices[index], defineProperty$2({}, namespace, omit_1(searchState.indices[index][namespace], '' + attributeName)))))
}) : omit_1(searchState, 'indices.' + index + '.' + id);
} else {
return namespace ? _extends({}, searchState, defineProperty$2({}, namespace, omit_1(searchState[namespace], '' + attributeName))) : omit_1(searchState, '' + id);
}
}
function getId() {
return 'configure';
}
var connectConfigure = createConnector({
displayName: 'AlgoliaConfigure',
getProvidedProps: function getProvidedProps() {
return {};
},
getSearchParameters: function getSearchParameters(searchParameters, props) {
var items = omit_1(props, 'children');
return searchParameters.setQueryParameters(items);
},
transitionState: function transitionState(props, prevSearchState, nextSearchState) {
var id = getId();
var items = omit_1(props, 'children');
var nonPresentKeys = this._props ? difference_1(keys_1(this._props), keys_1(props)) : [];
this._props = props;
var nextValue = defineProperty$2({}, id, _extends({}, omit_1(nextSearchState[id], nonPresentKeys), items));
return refineValue(nextSearchState, nextValue, this.context);
},
cleanUp: function cleanUp(props, searchState) {
var id = getId();
var index = getIndex(this.context);
var subState = hasMultipleIndex(this.context) && searchState.indices ? searchState.indices[index] : searchState;
var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : [];
var configureState = configureKeys.reduce(function (acc, item) {
if (!props[item]) {
acc[item] = subState[id][item];
}
return acc;
}, {});
var nextValue = defineProperty$2({}, id, configureState);
return refineValue(searchState, nextValue, this.context);
}
});
var Configure$1 = (function () {
return null;
});
/**
* Configure is a widget that lets you provide raw search parameters
* to the Algolia API.
*
* Any of the props added to this widget will be forwarded to Algolia. For more information
* on the different parameters that can be set, have a look at the
* [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters).
*
* This widget can be used either with react-dom and react-native. It will not render anything
* on screen, only configure some parameters.
*
* Read more in the [Search parameters](guide/Search_parameters.html) guide.
* @name Configure
* @kind widget
* @example
* import React from 'react';
*
* import { Configure, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Configure distinct={1} />
* </InstantSearch>
* );
* }
*/
var Configure = connectConfigure(Configure$1);
/**
* connectCurrentRefinements connector provides the logic to build a widget that will
* give the user the ability to remove all or some of the filters that were
* set.
* @name connectCurrentRefinements
* @kind connector
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {function} [clearsQuery=false] - Pass true to also clear the search query
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {array.<{label: string, attributeName: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attributeName` and `currentRefinement` are metadata containing row values.
* @providedPropType {string} query - the search query
*/
var connectCurrentRefinements = createConnector({
displayName: 'AlgoliaCurrentRefinements',
propTypes: {
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) {
var items = metadata.reduce(function (res, meta) {
if (typeof meta.items !== 'undefined') {
if (!props.clearsQuery && meta.id === 'query') {
return res;
} else {
if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') {
return res;
}
return res.concat(meta.items);
}
}
return res;
}, []);
return {
items: props.transformItems ? props.transformItems(items) : items,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, items) {
// `value` corresponds to our internal clear function computed in each connector metadata.
var refinementsToClear = items instanceof Array ? items.map(function (item) {
return item.value;
}) : [items];
return refinementsToClear.reduce(function (res, clear) {
return clear(res);
}, searchState);
}
});
var configManagerPropType = propTypes.shape({
register: propTypes.func.isRequired,
swap: propTypes.func.isRequired,
unregister: propTypes.func.isRequired
});
var stateManagerPropType = propTypes.shape({
createURL: propTypes.func.isRequired,
setState: propTypes.func.isRequired,
getState: propTypes.func.isRequired,
unlisten: propTypes.func.isRequired
});
var withKeysPropType = function withKeysPropType(keys) {
return function (props, propName, componentName) {
var prop = props[propName];
if (prop) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(prop)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
if (keys.indexOf(key) === -1) {
return new Error('Unknown `' + propName + '` key `' + key + '`. Check the render method ' + ('of `' + componentName + '`.'));
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
return undefined;
};
};
function translatable(defaultTranslations) {
return function (Composed) {
function Translatable(props) {
var translations = props.translations,
otherProps = objectWithoutProperties(props, ['translations']);
var translate = function translate(key) {
for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
var translation = translations && has_1(translations, key) ? translations[key] : defaultTranslations[key];
if (typeof translation === 'function') {
return translation.apply(undefined, params);
}
return translation;
};
return React__default.createElement(Composed, _extends({ translate: translate }, otherProps));
}
Translatable.displayName = 'Translatable(' + getDisplayName(Composed) + ')';
Translatable.propTypes = {
translations: withKeysPropType(Object.keys(defaultTranslations))
};
return Translatable;
};
}
var classnames = createCommonjsModule(function (module) {
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if ('object' !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (typeof undefined === 'function' && typeof undefined.amd === 'object' && undefined.amd) {
// register as 'classnames', consistent with npm package name
undefined('classnames', [], function () {
return classNames;
});
} else {
window.classNames = classNames;
}
}());
});
var prefix = 'ais';
function classNames(block) {
return function () {
for (var _len = arguments.length, elements = Array(_len), _key = 0; _key < _len; _key++) {
elements[_key] = arguments[_key];
}
return {
className: classnames(elements.filter(function (element) {
return element !== undefined && element !== false;
}).map(function (element) {
return prefix + '-' + block + '__' + element;
}))
};
};
}
var cx = classNames('CurrentRefinements');
var CurrentRefinements$1 = function (_Component) {
inherits(CurrentRefinements, _Component);
function CurrentRefinements() {
classCallCheck(this, CurrentRefinements);
return possibleConstructorReturn(this, (CurrentRefinements.__proto__ || Object.getPrototypeOf(CurrentRefinements)).apply(this, arguments));
}
createClass(CurrentRefinements, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
translate = _props.translate,
items = _props.items,
refine = _props.refine,
canRefine = _props.canRefine;
return React__default.createElement(
'div',
cx('root', !canRefine && 'noRefinement'),
React__default.createElement(
'div',
cx('items'),
items.map(function (item) {
return React__default.createElement(
'div',
_extends({ key: item.label }, cx('item', item.items && 'itemParent')),
React__default.createElement(
'span',
cx('itemLabel'),
item.label
),
item.items ? item.items.map(function (nestedItem) {
return React__default.createElement(
'div',
_extends({ key: nestedItem.label }, cx('item')),
React__default.createElement(
'span',
cx('itemLabel'),
nestedItem.label
),
React__default.createElement(
'button',
_extends({}, cx('itemClear'), {
onClick: function onClick() {
return refine(nestedItem.value);
}
}),
translate('clearFilter', nestedItem)
)
);
}) : React__default.createElement(
'button',
_extends({}, cx('itemClear'), { onClick: function onClick() {
return refine(item.value);
} }),
translate('clearFilter', item)
)
);
})
)
);
}
}]);
return CurrentRefinements;
}(React.Component);
CurrentRefinements$1.propTypes = {
translate: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string
})).isRequired,
refine: propTypes.func.isRequired,
canRefine: propTypes.bool.isRequired,
transformItems: propTypes.func
};
CurrentRefinements$1.contextTypes = {
canRefine: propTypes.func
};
var CurrentRefinementsComponent = translatable({
clearFilter: '✕'
})(CurrentRefinements$1);
/**
* The CurrentRefinements widget displays the list of currently applied filters.
*
* It allows the user to selectively remove them.
* @name CurrentRefinements
* @kind widget
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-CurrentRefinements__root - the root div of the widget
* @themeKey ais-CurrentRefinements__items - the container of the filters
* @themeKey ais-CurrentRefinements__item - a single filter
* @themeKey ais-CurrentRefinements__itemLabel - the label of a filter
* @themeKey ais-CurrentRefinements__itemClear - the trigger to remove the filter
* @themeKey ais-CurrentRefinements__noRefinement - present when there is no refinement
* @translationKey clearFilter - the remove filter button label
* @example
* import React from 'react';
*
* import { CurrentRefinements, RefinementList, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <CurrentRefinements />
* <RefinementList
attributeName="colors"
defaultRefinement={['Black']}
/>
* </InstantSearch>
* );
* }
*/
var CurrentRefinements = connectCurrentRefinements(CurrentRefinementsComponent);
var getId$1 = function getId(props) {
return props.attributes[0];
};
var namespace = 'hierarchicalMenu';
function getCurrentRefinement(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, namespace + '.' + getId$1(props), null, function (currentRefinement) {
if (currentRefinement === '') {
return null;
}
return currentRefinement;
});
}
function getValue$2(path, props, searchState, context) {
var id = props.id,
attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel;
var currentRefinement = getCurrentRefinement(props, searchState, context);
var nextRefinement = void 0;
if (currentRefinement === null) {
nextRefinement = path;
} else {
var tmpSearchParameters = new algoliasearchHelper_4({
hierarchicalFacets: [{
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}]
});
nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0];
}
return nextRefinement;
}
function transformValue(value, props, searchState, context) {
return value.map(function (v) {
return {
label: v.name,
value: getValue$2(v.path, props, searchState, context),
count: v.count,
isRefined: v.isRefined,
items: v.data && transformValue(v.data, props, searchState, context)
};
});
}
var truncate = function truncate() {
var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
return items.slice(0, limit).map(function () {
var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Array.isArray(item.items) ? _extends({}, item, {
items: truncate(item.items, limit)
}) : item;
});
};
function _refine(props, searchState, nextRefinement, context) {
var id = getId$1(props);
var nextValue = defineProperty$2({}, id, nextRefinement || '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return cleanUpValue(searchState, context, namespace + '.' + getId$1(props));
}
var sortBy = ['name:asc'];
/**
* connectHierarchicalMenu connector provides the logic to build a widget that will
* give the user the ability to explore a tree-like structure.
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
* @name connectHierarchicalMenu
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax.
* @propType {number} [limitMin=10] - The maximum number of items displayed.
* @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string[]} [rootPath=null] - The already selected and hidden path.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items.
*/
var connectHierarchicalMenu = createConnector({
displayName: 'AlgoliaHierarchicalMenu',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings');
}
return undefined;
},
separator: propTypes.string,
rootPath: propTypes.string,
showParentLevel: propTypes.bool,
defaultRefinement: propTypes.string,
showMore: propTypes.bool,
limitMin: propTypes.number,
limitMax: propTypes.number,
transformItems: propTypes.func
},
defaultProps: {
showMore: false,
limitMin: 10,
limitMax: 20,
separator: ' > ',
rootPath: null,
showParentLevel: true
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var id = getId$1(props);
var results = getResults(searchResults, this.context);
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: false
};
}
var limit = showMore ? limitMax : limitMin;
var value = results.getFacetValues(id, { sortBy: sortBy });
var items = value.data ? transformValue(value.data, props, searchState, this.context) : [];
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: truncate(transformedItems, limit),
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var id = getId$1(props);
var limit = showMore ? limitMax : limitMin;
searchParameters = searchParameters.addHierarchicalFacet({
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}).setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, limit)
});
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
if (currentRefinement !== null) {
searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var rootAttribute = props.attributes[0];
var id = getId$1(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return {
id: id,
index: getIndex(this.context),
items: !currentRefinement ? [] : [{
label: rootAttribute + ': ' + currentRefinement,
attributeName: rootAttribute,
value: function value(nextState) {
return _refine(props, nextState, '', _this.context);
},
currentRefinement: currentRefinement
}]
};
}
});
var cx$3 = classNames('SearchBox');
var DefaultLoadingIndicator = function DefaultLoadingIndicator() {
return React__default.createElement(
'svg',
{
width: '18',
height: '18',
viewBox: '0 0 38 38',
xmlns: 'http://www.w3.org/2000/svg',
stroke: '#BFC7D8'
},
React__default.createElement(
'g',
{ fill: 'none', fillRule: 'evenodd' },
React__default.createElement(
'g',
{ transform: 'translate(1 1)', strokeWidth: '2' },
React__default.createElement('circle', { strokeOpacity: '.5', cx: '18', cy: '18', r: '18' }),
React__default.createElement(
'path',
{ d: 'M36 18c0-9.94-8.06-18-18-18' },
React__default.createElement('animateTransform', {
attributeName: 'transform',
type: 'rotate',
from: '0 18 18',
to: '360 18 18',
dur: '1s',
repeatCount: 'indefinite'
})
)
)
)
);
};
var DefaultReset = function DefaultReset() {
return React__default.createElement(
'svg',
{ role: 'img', width: '1em', height: '1em' },
React__default.createElement('use', { xlinkHref: '#sbx-icon-clear-3' })
);
};
var DefaultSubmit = function DefaultSubmit() {
return React__default.createElement(
'svg',
{ role: 'img', width: '1em', height: '1em' },
React__default.createElement('use', { xlinkHref: '#sbx-icon-search-13' })
);
};
var SearchBox = function (_Component) {
inherits(SearchBox, _Component);
function SearchBox(props) {
classCallCheck(this, SearchBox);
var _this = possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this));
_this.getQuery = function () {
return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query;
};
_this.setQuery = function (val) {
var _this$props = _this.props,
refine = _this$props.refine,
searchAsYouType = _this$props.searchAsYouType;
if (searchAsYouType) {
refine(val);
} else {
_this.setState({
query: val
});
}
};
_this.onInputMount = function (input) {
_this.input = input;
if (_this.props.__inputRef) {
_this.props.__inputRef(input);
}
};
_this.onKeyDown = function (e) {
if (!_this.props.focusShortcuts) {
return;
}
var shortcuts = _this.props.focusShortcuts.map(function (key) {
return typeof key === 'string' ? key.toUpperCase().charCodeAt(0) : key;
});
var elt = e.target || e.srcElement;
var tagName = elt.tagName;
if (elt.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA') {
// already in an input
return;
}
var which = e.which || e.keyCode;
if (shortcuts.indexOf(which) === -1) {
// not the right shortcut
return;
}
_this.input.focus();
e.stopPropagation();
e.preventDefault();
};
_this.onSubmit = function (e) {
e.preventDefault();
e.stopPropagation();
_this.input.blur();
var _this$props2 = _this.props,
refine = _this$props2.refine,
searchAsYouType = _this$props2.searchAsYouType;
if (!searchAsYouType) {
refine(_this.getQuery());
}
return false;
};
_this.onChange = function (e) {
_this.setQuery(e.target.value);
if (_this.props.onChange) {
_this.props.onChange(e);
}
};
_this.onReset = function () {
_this.setQuery('');
_this.input.focus();
if (_this.props.onReset) {
_this.props.onReset();
}
};
_this.state = {
query: props.searchAsYouType ? null : props.currentRefinement
};
return _this;
}
createClass(SearchBox, [{
key: 'componentDidMount',
value: function componentDidMount() {
document.addEventListener('keydown', this.onKeyDown);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
document.removeEventListener('keydown', this.onKeyDown);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
// Reset query when the searchParameters query has changed.
// This is kind of an anti-pattern (props in state), but it works here
// since we know for sure that searchParameters having changed means a
// new search has been triggered.
if (!nextProps.searchAsYouType && nextProps.currentRefinement !== this.props.currentRefinement) {
this.setState({
query: nextProps.currentRefinement
});
}
}
// From https://github.com/algolia/autocomplete.js/pull/86
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props,
translate = _props.translate,
autoFocus = _props.autoFocus,
loadingIndicatorComponent = _props.loadingIndicatorComponent,
resetComponent = _props.resetComponent,
submitComponent = _props.submitComponent;
var query = this.getQuery();
var searchInputEvents = Object.keys(this.props).reduce(function (props, prop) {
if (['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) === -1 && prop.indexOf('on') === 0) {
return _extends({}, props, defineProperty$2({}, prop, _this2.props[prop]));
}
return props;
}, {});
var isSearchStalled = this.props.showLoadingIndicator && this.props.isSearchStalled;
/* eslint-disable max-len */
return React__default.createElement(
'form',
_extends({
noValidate: true,
onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit,
onReset: this.onReset
}, cx$3('root'), {
action: '',
role: 'search'
}),
React__default.createElement(
'svg',
{ xmlns: 'http://www.w3.org/2000/svg', style: { display: 'none' } },
React__default.createElement(
'symbol',
{
xmlns: 'http://www.w3.org/2000/svg',
id: 'sbx-icon-search-13',
viewBox: '0 0 40 40'
},
React__default.createElement('path', {
d: 'M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z',
fillRule: 'evenodd'
})
),
React__default.createElement(
'symbol',
{
xmlns: 'http://www.w3.org/2000/svg',
id: 'sbx-icon-clear-3',
viewBox: '0 0 20 20'
},
React__default.createElement('path', {
d: 'M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z',
fillRule: 'evenodd'
})
)
),
React__default.createElement(
'div',
_extends({
role: 'search'
}, cx$3('wrapper', isSearchStalled && 'stalled-search')),
React__default.createElement('input', _extends({
ref: this.onInputMount,
type: 'search',
placeholder: translate('placeholder'),
autoFocus: autoFocus,
autoComplete: 'off',
autoCorrect: 'off',
autoCapitalize: 'off',
spellCheck: 'false',
required: true,
maxLength: '512',
value: query,
onChange: this.onChange
}, searchInputEvents, cx$3('input'))),
this.props.showLoadingIndicator && React__default.createElement(
'div',
_extends({ hidden: !isSearchStalled }, cx$3('loading-indicator')),
loadingIndicatorComponent
),
React__default.createElement(
'button',
_extends({
type: 'submit',
title: translate('submitTitle'),
hidden: isSearchStalled
}, cx$3('submit')),
submitComponent
),
React__default.createElement(
'button',
_extends({
type: 'reset',
title: translate('resetTitle')
}, cx$3('reset'), {
onClick: this.onReset
}),
resetComponent
)
)
);
/* eslint-enable */
}
}]);
return SearchBox;
}(React.Component);
SearchBox.propTypes = {
currentRefinement: propTypes.string,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
loadingIndicatorComponent: propTypes.element,
resetComponent: propTypes.element,
submitComponent: propTypes.element,
focusShortcuts: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])),
autoFocus: propTypes.bool,
searchAsYouType: propTypes.bool,
onSubmit: propTypes.func,
onReset: propTypes.func,
onChange: propTypes.func,
isSearchStalled: propTypes.bool,
showLoadingIndicator: propTypes.bool,
// For testing purposes
__inputRef: propTypes.func
};
SearchBox.defaultProps = {
currentRefinement: '',
focusShortcuts: ['s', '/'],
autoFocus: false,
searchAsYouType: true,
showLoadingIndicator: false,
isSearchStalled: false,
loadingIndicatorComponent: React__default.createElement(DefaultLoadingIndicator, null),
submitComponent: React__default.createElement(DefaultSubmit, null),
resetComponent: React__default.createElement(DefaultReset, null)
};
var SearchBoxComponent = translatable({
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(SearchBox);
var itemsPropType$1 = propTypes.arrayOf(propTypes.shape({
value: propTypes.any,
label: propTypes.node.isRequired,
items: function items() {
return itemsPropType$1.apply(undefined, arguments);
}
}));
var List = function (_Component) {
inherits(List, _Component);
function List() {
classCallCheck(this, List);
var _this = possibleConstructorReturn(this, (List.__proto__ || Object.getPrototypeOf(List)).call(this));
_this.onShowMoreClick = function () {
_this.setState(function (state) {
return {
extended: !state.extended
};
});
};
_this.getLimit = function () {
var _this$props = _this.props,
limitMin = _this$props.limitMin,
limitMax = _this$props.limitMax;
var extended = _this.state.extended;
return extended ? limitMax : limitMin;
};
_this.resetQuery = function () {
_this.setState({ query: '' });
};
_this.renderItem = function (item, resetQuery) {
var items = item.items && React__default.createElement(
'div',
_this.props.cx('itemItems'),
item.items.slice(0, _this.getLimit()).map(function (child) {
return _this.renderItem(child, item);
})
);
return React__default.createElement(
'div',
_extends({
key: item.key || item.label
}, _this.props.cx('item', item.isRefined && 'itemSelected', item.noRefinement && 'itemNoRefinement', items && 'itemParent', items && item.isRefined && 'itemSelectedParent')),
_this.props.renderItem(item, resetQuery),
items
);
};
_this.state = {
extended: false,
query: ''
};
return _this;
}
createClass(List, [{
key: 'renderShowMore',
value: function renderShowMore() {
var _props = this.props,
showMore = _props.showMore,
translate = _props.translate,
cx = _props.cx;
var extended = this.state.extended;
var disabled = this.props.limitMin >= this.props.items.length;
if (!showMore) {
return null;
}
return React__default.createElement(
'button',
_extends({
disabled: disabled
}, cx('showMore', disabled && 'showMoreDisabled'), {
onClick: this.onShowMoreClick
}),
translate('showMore', extended)
);
}
}, {
key: 'renderSearchBox',
value: function renderSearchBox() {
var _this2 = this;
var _props2 = this.props,
cx = _props2.cx,
searchForItems = _props2.searchForItems,
isFromSearch = _props2.isFromSearch,
translate = _props2.translate,
items = _props2.items,
selectItem = _props2.selectItem;
var noResults = items.length === 0 && this.state.query !== '' ? React__default.createElement(
'div',
cx('noResults'),
translate('noResults')
) : null;
return React__default.createElement(
'div',
cx('SearchBox'),
React__default.createElement(SearchBoxComponent, {
currentRefinement: this.state.query,
refine: function refine(value) {
_this2.setState({ query: value });
searchForItems(value);
},
focusShortcuts: [],
translate: translate,
onSubmit: function onSubmit(e) {
e.preventDefault();
e.stopPropagation();
if (isFromSearch) {
selectItem(items[0], _this2.resetQuery);
}
}
}),
noResults
);
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var _props3 = this.props,
cx = _props3.cx,
items = _props3.items,
withSearchBox = _props3.withSearchBox,
canRefine = _props3.canRefine;
var searchBox = withSearchBox ? this.renderSearchBox() : null;
if (items.length === 0) {
return React__default.createElement(
'div',
cx('root', !canRefine && 'noRefinement'),
searchBox
);
}
// Always limit the number of items we show on screen, since the actual
// number of retrieved items might vary with the `maxValuesPerFacet` config
// option.
var limit = this.getLimit();
return React__default.createElement(
'div',
cx('root', !this.props.canRefine && 'noRefinement'),
searchBox,
React__default.createElement(
'div',
cx('items'),
items.slice(0, limit).map(function (item) {
return _this3.renderItem(item, _this3.resetQuery);
})
),
this.renderShowMore()
);
}
}]);
return List;
}(React.Component);
List.propTypes = {
cx: propTypes.func.isRequired,
// Only required with showMore.
translate: propTypes.func,
items: itemsPropType$1,
renderItem: propTypes.func.isRequired,
selectItem: propTypes.func,
showMore: propTypes.bool,
limitMin: propTypes.number,
limitMax: propTypes.number,
limit: propTypes.number,
show: propTypes.func,
searchForItems: propTypes.func,
withSearchBox: propTypes.bool,
isFromSearch: propTypes.bool,
canRefine: propTypes.bool
};
List.defaultProps = {
isFromSearch: false
};
var Link = function (_Component) {
inherits(Link, _Component);
function Link() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, Link);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Link.__proto__ || Object.getPrototypeOf(Link)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function (e) {
if (isSpecialClick(e)) {
return;
}
_this.props.onClick();
e.preventDefault();
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(Link, [{
key: 'render',
value: function render() {
return React__default.createElement('a', _extends({}, omit_1(this.props, 'onClick'), { onClick: this.onClick }));
}
}]);
return Link;
}(React.Component);
Link.propTypes = {
onClick: propTypes.func.isRequired
};
var cx$2 = classNames('HierarchicalMenu');
var itemsPropType = propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string,
count: propTypes.number.isRequired,
items: function items() {
return itemsPropType.apply(undefined, arguments);
}
}));
var HierarchicalMenu$1 = function (_Component) {
inherits(HierarchicalMenu, _Component);
function HierarchicalMenu() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, HierarchicalMenu);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = HierarchicalMenu.__proto__ || Object.getPrototypeOf(HierarchicalMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) {
var _this$props = _this.props,
createURL = _this$props.createURL,
refine = _this$props.refine;
return React__default.createElement(
Link,
_extends({}, cx$2('itemLink'), {
onClick: function onClick() {
return refine(item.value);
},
href: createURL(item.value)
}),
React__default.createElement(
'span',
cx$2('itemLabel'),
item.label
),
' ',
React__default.createElement(
'span',
cx$2('itemCount'),
item.count
)
);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(HierarchicalMenu, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
return React__default.createElement(List, _extends({
renderItem: this.renderItem,
cx: cx$2
}, pick_1(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isEmpty', 'canRefine'])));
}
}]);
return HierarchicalMenu;
}(React.Component);
HierarchicalMenu$1.propTypes = {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
canRefine: propTypes.bool.isRequired,
items: itemsPropType,
showMore: propTypes.bool,
limitMin: propTypes.number,
limitMax: propTypes.number,
transformItems: propTypes.func
};
HierarchicalMenu$1.contextTypes = {
canRefine: propTypes.func
};
var HierarchicalMenuComponent = translatable({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
}
})(HierarchicalMenu$1);
/**
* The hierarchical menu lets the user browse attributes using a tree-like structure.
*
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
*
* @name HierarchicalMenu
* @kind widget
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* [{
* "objectID": "321432",
* "name": "lemon",
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* },
* {
* "objectID": "8976987",
* "name": "orange",
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* }]
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "objectID": "321432",
* "name": "lemon",
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limitMin and limitMax.
* @propType {number} [limitMin=10] - The maximum number of items displayed.
* @propType {number} [limitMax=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string[]} [rootPath=null] - The already selected and hidden path.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-HierarchicalMenu__root - Container of the widget
* @themeKey ais-HierarchicalMenu__items - Container of the items
* @themeKey ais-HierarchicalMenu__item - Id for a single list item
* @themeKey ais-HierarchicalMenu__itemSelected - Id for the selected items in the list
* @themeKey ais-HierarchicalMenu__itemParent - Id for the elements that have a sub list displayed
* @themeKey ais-HierarchicalMenu__itemSelectedParent - Id for parents that have currently a child selected
* @themeKey ais-HierarchicalMenu__itemLink - the link containing the label and the count
* @themeKey ais-HierarchicalMenu__itemLabel - the label of the entry
* @themeKey ais-HierarchicalMenu__itemCount - the count of the entry
* @themeKey ais-HierarchicalMenu__itemItems - id representing a children
* @themeKey ais-HierarchicalMenu__showMore - container for the show more button
* @themeKey ais-HierarchicalMenu__noRefinement - present when there is no refinement
* @translationKey showMore - The label of the show more button. Accepts one parameter, a boolean that is true if the values are expanded
* @example
* import React from 'react';
* import { HierarchicalMenu, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <HierarchicalMenu
* id="categories"
* key="categories"
* attributes={[
* 'category',
* 'sub_category',
* 'sub_sub_category',
* ]}
* />
* </InstantSearch>
* );
* }
*/
var HierarchicalMenu = connectHierarchicalMenu(HierarchicalMenuComponent);
/**
* 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, isHighlighted: boolean}.
*/
function parseAlgoliaHit(_ref) {
var _ref$preTag = _ref.preTag,
preTag = _ref$preTag === undefined ? '<em>' : _ref$preTag,
_ref$postTag = _ref.postTag,
postTag = _ref$postTag === undefined ? '</em>' : _ref$postTag,
highlightProperty = _ref.highlightProperty,
attributeName = _ref.attributeName,
hit = _ref.hit;
if (!hit) throw new Error('`hit`, the matching record, must be provided');
var highlightObject = get_1(hit[highlightProperty], attributeName, {});
if (Array.isArray(highlightObject)) {
return highlightObject.map(function (item) {
return parseHighlightedAttribute({
preTag: preTag,
postTag: postTag,
highlightedValue: item.value
});
});
}
return parseHighlightedAttribute({
preTag: preTag,
postTag: postTag,
highlightedValue: highlightObject.value
});
}
/**
* 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,
_ref2$highlightedValu = _ref2.highlightedValue,
highlightedValue = _ref2$highlightedValu === undefined ? '' : _ref2$highlightedValu;
var splitByPreTag = highlightedValue.split(preTag);
var firstValue = splitByPreTag.shift();
var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }];
if (postTag === preTag) {
var isHighlighted = true;
splitByPreTag.forEach(function (split) {
elements.push({ value: split, isHighlighted: isHighlighted });
isHighlighted = !isHighlighted;
});
} else {
splitByPreTag.forEach(function (split) {
var splitByPostTag = split.split(postTag);
elements.push({
value: splitByPostTag[0],
isHighlighted: true
});
if (splitByPostTag[1] !== '') {
elements.push({
value: splitByPostTag[1],
isHighlighted: false
});
}
});
}
return elements;
}
var highlight = function highlight(_ref) {
var attributeName = _ref.attributeName,
hit = _ref.hit,
highlightProperty = _ref.highlightProperty;
return parseAlgoliaHit({
attributeName: attributeName,
hit: hit,
preTag: highlightTags.highlightPreTag,
postTag: highlightTags.highlightPostTag,
highlightProperty: highlightProperty
});
};
/**
* connectHighlight connector provides the logic to create an highlighter
* component that will retrieve, parse and render an highlighted attribute
* from an Algolia hit.
* @name connectHighlight
* @kind connector
* @category connector
* @providedPropType {function} highlight - function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attributes: `highlightProperty` which is the property that contains the highlight structure from the records, `attributeName` which is the name of the attribute (it can be either a string or an array of strings) to look for and `hit` which is the hit from Algolia. It returns an array of objects `{value: string, isHighlighted: boolean}. If the element that corresponds to the attributeName is an array of strings, it will return a nested array of objects.
* @example
* import React from 'react';
* import { connectHighlight } from 'react-instantsearch/connectors';
* import { InstantSearch, Hits } from 'react-instantsearch/dom';
*
* const CustomHighlight = connectHighlight(
* ({ highlight, attributeName, hit, highlightProperty }) => {
* const parsedHit = highlight({ attributeName, hit, highlightProperty: '_highlightResult' });
* const highlightedHits = parsedHit.map(part => {
* if (part.isHighlighted) return <mark>{part.value}</mark>;
* return part.value;
* });
* return <div>{highlightedHits}</div>;
* }
* );
*
* const Hit = ({hit}) =>
* <p>
* <CustomHighlight attributeName="description" hit={hit} />
* </p>;
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea">
* <Hits hitComponent={Hit} />
* </InstantSearch>
* );
* }
*/
var connectHighlight = createConnector({
displayName: 'AlgoliaHighlighter',
propTypes: {},
getProvidedProps: function getProvidedProps() {
return { highlight: highlight };
}
});
var cx$4 = classNames('Highlight');
function generateKey(i, value) {
return 'split-' + i + '-' + value;
}
var Highlight$2 = function Highlight(_ref) {
var value = _ref.value,
highlightedTagName = _ref.highlightedTagName,
isHighlighted = _ref.isHighlighted,
nonHighlightedTagName = _ref.nonHighlightedTagName;
var TagName = isHighlighted ? highlightedTagName : nonHighlightedTagName;
var className = isHighlighted ? 'highlighted' : 'nonHighlighted';
return React__default.createElement(
TagName,
cx$4(className),
value
);
};
Highlight$2.propTypes = {
value: propTypes.string.isRequired,
isHighlighted: propTypes.bool.isRequired,
highlightedTagName: propTypes.string.isRequired,
nonHighlightedTagName: propTypes.string.isRequired
};
function Highlighter(_ref2) {
var hit = _ref2.hit,
attributeName = _ref2.attributeName,
highlight = _ref2.highlight,
highlightProperty = _ref2.highlightProperty,
tagName = _ref2.tagName,
nonHighlightedTagName = _ref2.nonHighlightedTagName,
separator = _ref2.separator;
var parsedHighlightedValue = highlight({
hit: hit,
attributeName: attributeName,
highlightProperty: highlightProperty
});
return React__default.createElement(
'span',
{ className: 'ais-Highlight' },
parsedHighlightedValue.map(function (item, i) {
if (Array.isArray(item)) {
var isLast = i === parsedHighlightedValue.length - 1;
return React__default.createElement(
'span',
{ key: generateKey(i, hit[attributeName][i]) },
item.map(function (element, index) {
return React__default.createElement(Highlight$2, {
key: generateKey(index, element.value),
value: element.value,
highlightedTagName: tagName,
nonHighlightedTagName: nonHighlightedTagName,
isHighlighted: element.isHighlighted
});
}),
!isLast && React__default.createElement(
'span',
cx$4('separator'),
separator
)
);
}
return React__default.createElement(Highlight$2, {
key: generateKey(i, item.value),
value: item.value,
highlightedTagName: tagName,
nonHighlightedTagName: nonHighlightedTagName,
isHighlighted: item.isHighlighted
});
})
);
}
Highlighter.propTypes = {
hit: propTypes.object.isRequired,
attributeName: propTypes.string.isRequired,
highlight: propTypes.func.isRequired,
highlightProperty: propTypes.string.isRequired,
tagName: propTypes.string,
nonHighlightedTagName: propTypes.string,
separator: propTypes.node
};
Highlighter.defaultProps = {
tagName: 'em',
nonHighlightedTagName: 'span',
separator: ', '
};
function Highlight$1(props) {
return React__default.createElement(Highlighter, _extends({ highlightProperty: '_highlightResult' }, props));
}
Highlight$1.propTypes = {
hit: propTypes.object.isRequired,
attributeName: propTypes.string.isRequired,
highlight: propTypes.func.isRequired,
tagName: propTypes.string,
nonHighlightedTagName: propTypes.string,
separatorComponent: propTypes.node
};
/**
* Renders any attribute from a hit into its highlighted form when relevant.
*
* Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide.
* @name Highlight
* @kind widget
* @propType {string} attributeName - location of the highlighted attribute in the hit (the corresponding element can be either a string or an array of strings)
* @propType {object} hit - hit object containing the highlighted attribute
* @propType {string} [tagName='em'] - tag to be used for highlighted parts of the hit
* @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted
* @propType {React.Element} [separatorComponent=',<space>'] - symbol used to separate the elements of the array in case the attributeName points to an array of strings.
* @themeKey ais-Highlight - root of the component
* @themeKey ais-Highlight__highlighted - part of the text that is highlighted
* @themeKey ais-Highlight__nonHighlighted - part of the text that is non highlighted
* @example
* import React from 'react';
*
* import { connectHits, Highlight, InstantSearch } from 'react-instantsearch/dom';
*
* const CustomHits = connectHits(({ hits }) =>
* <div>
* {hits.map(hit =>
* <p key={hit.objectID}>
* <Highlight attributeName="description" hit={hit} />
* </p>
* )}
* </div>
* );
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <CustomHits />
* </InstantSearch>
* );
* }
*/
var Highlight = connectHighlight(Highlight$1);
function Snippet$1(props) {
return React__default.createElement(Highlighter, _extends({ highlightProperty: '_snippetResult' }, props));
}
Snippet$1.propTypes = {
hit: propTypes.object.isRequired,
attributeName: propTypes.string.isRequired,
highlight: propTypes.func.isRequired,
tagName: propTypes.string,
nonHighlightedTagName: propTypes.string,
separatorComponent: propTypes.node
};
/**
* Renders any attribute from an hit into its highlighted snippet form when relevant.
*
* Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide.
* @name Snippet
* @kind widget
* @requirements To use this widget, the attribute name passed to the `attributeName` prop must be
* present in "Attributes to snippet" on the Algolia dashboard or configured as `attributesToSnippet`
* via a set settings call to the Algolia API.
* @propType {string} attributeName - location of the highlighted snippet attribute in the hit (the corresponding element can be either a string or an array of strings)
* @propType {object} hit - hit object containing the highlighted snippet attribute
* @propType {string} [tagName='em'] - tag to be used for highlighted parts of the attribute
* @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted
* @propType {React.Element} [separatorComponent=',<space>'] - symbol used to separate the elements of the array in case the attributeName points to an array of strings.
* @example
* import React from 'react';
* import { Snippet, InstantSearch, Hits } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Hits
* hitComponent={({ hit }) => (
* <p key={hit.objectID}>
* <Snippet attributeName="description" hit={hit} />
* </p>
* )}
* />
* </InstantSearch>
* );
* }
*/
var Snippet = connectHighlight(Snippet$1);
/**
* connectHits connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* prop to a [Configure](guide/Search_parameters.html) widget.
*
* **Warning:** you will need to use the **objectID** property available on every hit as a key
* when iterating over them. This will ensure you have the best possible UI experience
* especially on slow networks.
* @name connectHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @example
* import React from 'react';
*
* import { Highlight, InstantSearch } from 'react-instantsearch/dom';
* import { connectHits } from 'react-instantsearch/connectors';
* const CustomHits = connectHits(({ hits }) =>
* <div>
* {hits.map(hit =>
* <p key={hit.objectID}>
* <Highlight attributeName="description" hit={hit} />
* </p>
* )}
* </div>
* );
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <CustomHits />
* </InstantSearch>
* );
* }
*/
var connectHits = createConnector({
displayName: 'AlgoliaHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, this.context);
var hits = results ? results.hits : [];
return { hits: hits };
},
/* Hits needs to be considered as a widget to trigger a search if no others widgets are used.
* To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState
* See createConnector.js
* */
getSearchParameters: function getSearchParameters(searchParameters) {
return searchParameters;
}
});
var cx$5 = classNames('Hits');
var Hits$1 = function Hits(_ref) {
var hits = _ref.hits,
HitComponent = _ref.hitComponent;
return (
// Spread the hit on HitComponent instead of passing the full object. BC.
// ex: <HitComponent {...hit} key={hit.objectID} />
React__default.createElement(
'div',
cx$5('root'),
hits.map(function (hit) {
return React__default.createElement(HitComponent, { key: hit.objectID, hit: hit });
})
)
);
};
Hits$1.propTypes = {
hits: propTypes.array,
hitComponent: propTypes.func.isRequired
};
Hits$1.defaultProps = {
hitComponent: function hitComponent(props) {
return React__default.createElement(
'div',
{
style: {
borderBottom: '1px solid #bbb',
paddingBottom: '5px',
marginBottom: '5px'
}
},
JSON.stringify(props).slice(0, 100),
'...'
);
}
};
/**
* Displays a list of hits.
*
* To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html).
*
* @name Hits
* @kind widget
* @propType {Component} [hitComponent] - Component used for rendering each hit from
* the results. If it is not provided the rendering defaults to displaying the
* hit in its JSON form. The component will be called with a `hit` prop.
* @themeKey ais-Hits__root - the root of the component
* @example
* import React from 'react';
* import { Hits, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Hits />
* </InstantSearch>
* );
* }
*/
var Hits = connectHits(Hits$1);
function getId$2() {
return 'hitsPerPage';
}
function getCurrentRefinement$1(props, searchState, context) {
var id = getId$2();
return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
/**
* connectHitsPerPage connector provides the logic to create connected
* components that will allow a user to choose to display more or less results from Algolia.
* @name connectHitsPerPage
* @kind connector
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {{value: number, label: string}[]} items - List of hits per page options.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
var connectHitsPerPage = createConnector({
displayName: 'AlgoliaHitsPerPage',
propTypes: {
defaultRefinement: propTypes.number.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string,
value: propTypes.number.isRequired
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement$1(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$2();
var nextValue = defineProperty$2({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, this.context, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, this.context, getId$2());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setHitsPerPage(getCurrentRefinement$1(props, searchState, this.context));
},
getMetadata: function getMetadata() {
return { id: getId$2() };
}
});
var Select = function (_Component) {
inherits(Select, _Component);
function Select() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, Select);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Select.__proto__ || Object.getPrototypeOf(Select)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) {
_this.props.onSelect(e.target.value);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(Select, [{
key: 'render',
value: function render() {
var _props = this.props,
cx = _props.cx,
items = _props.items,
selectedItem = _props.selectedItem;
return React__default.createElement(
'select',
_extends({}, cx('root'), { value: selectedItem, onChange: this.onChange }),
items.map(function (item) {
return React__default.createElement(
'option',
{
key: has_1(item, 'key') ? item.key : item.value,
disabled: item.disabled,
value: item.value
},
has_1(item, 'label') ? item.label : item.value
);
})
);
}
}]);
return Select;
}(React.Component);
Select.propTypes = {
cx: propTypes.func.isRequired,
onSelect: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
value: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired,
key: propTypes.oneOfType([propTypes.string, propTypes.number]),
label: propTypes.string,
disabled: propTypes.bool
})).isRequired,
selectedItem: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired
};
var cx$6 = classNames('HitsPerPage');
var HitsPerPage$1 = function (_Component) {
inherits(HitsPerPage, _Component);
function HitsPerPage() {
classCallCheck(this, HitsPerPage);
return possibleConstructorReturn(this, (HitsPerPage.__proto__ || Object.getPrototypeOf(HitsPerPage)).apply(this, arguments));
}
createClass(HitsPerPage, [{
key: 'render',
value: function render() {
var _props = this.props,
currentRefinement = _props.currentRefinement,
refine = _props.refine,
items = _props.items;
return React__default.createElement(Select, {
onSelect: refine,
selectedItem: currentRefinement,
items: items,
cx: cx$6
});
}
}]);
return HitsPerPage;
}(React.Component);
HitsPerPage$1.propTypes = {
refine: propTypes.func.isRequired,
currentRefinement: propTypes.number.isRequired,
transformItems: propTypes.func,
items: propTypes.arrayOf(propTypes.shape({
/**
* Number of hits to display.
*/
value: propTypes.number.isRequired,
/**
* Label to display on the option.
*/
label: propTypes.string
}))
};
/**
* The HitsPerPage widget displays a dropdown menu to let the user change the number
* of displayed hits.
*
* If you only want to configure the number of hits per page without
* displaying a widget, you should use the `<Configure hitsPerPage={20} />` widget. See [`<Configure /> documentation`](widgets/Configure.html)
*
* @name HitsPerPage
* @kind widget
* @propType {{value: number, label: string}[]} items - List of available options.
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-HitsPerPage__root - the root of the component.
* @example
* import React from 'react';
* import { HitsPerPage, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <HitsPerPage
* defaultRefinement={20}
* items={[{value: 20, label: 'Show 20 hits'}, {value: 50, label: 'Show 50 hits'}]}
* />
* </InstantSearch>
* );
* }
*/
var HitsPerPage = connectHitsPerPage(HitsPerPage$1);
function getId$3() {
return 'page';
}
function getCurrentRefinement$2(props, searchState, context) {
var id = getId$3();
var page = 1;
return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
currentRefinement = parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
/**
* InfiniteHits connector provides the logic to create connected
* components that will render an continuous list of results retrieved from
* Algolia. This connector provides a function to load more results.
* @name connectInfiniteHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @providedPropType {boolean} hasMore - indicates if there are more pages to load
* @providedPropType {function} refine - call to load more results
*/
var connectInfiniteHits = createConnector({
displayName: 'AlgoliaInfiniteHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, this.context);
if (!results) {
this._allResults = [];
return {
hits: this._allResults,
hasMore: false
};
}
var hits = results.hits,
page = results.page,
nbPages = results.nbPages;
// If it is the same page we do not touch the page result list
if (page === 0) {
this._allResults = hits;
} else if (page > this.previousPage) {
this._allResults = [].concat(toConsumableArray(this._allResults), toConsumableArray(hits));
} else if (page < this.previousPage) {
this._allResults = hits;
}
var lastPageIndex = nbPages - 1;
var hasMore = page < lastPageIndex;
this.previousPage = page;
return {
hits: this._allResults,
hasMore: hasMore
};
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQueryParameters({
page: getCurrentRefinement$2(props, searchState, this.context) - 1
});
},
refine: function refine(props, searchState) {
var id = getId$3();
var nextPage = getCurrentRefinement$2(props, searchState, this.context) + 1;
var nextValue = defineProperty$2({}, id, nextPage);
var resetPage = false;
return refineValue(searchState, nextValue, this.context, resetPage);
}
});
var cx$7 = classNames('InfiniteHits');
var InfiniteHits$1 = function (_Component) {
inherits(InfiniteHits, _Component);
function InfiniteHits() {
classCallCheck(this, InfiniteHits);
return possibleConstructorReturn(this, (InfiniteHits.__proto__ || Object.getPrototypeOf(InfiniteHits)).apply(this, arguments));
}
createClass(InfiniteHits, [{
key: 'render',
value: function render() {
var _props = this.props,
ItemComponent = _props.hitComponent,
hits = _props.hits,
hasMore = _props.hasMore,
refine = _props.refine,
translate = _props.translate;
var renderedHits = hits.map(function (hit) {
return React__default.createElement(ItemComponent, { key: hit.objectID, hit: hit });
});
var loadMoreButton = hasMore ? React__default.createElement(
'button',
_extends({}, cx$7('loadMore'), { onClick: function onClick() {
return refine();
} }),
translate('loadMore')
) : React__default.createElement(
'button',
_extends({}, cx$7('loadMore'), { disabled: true }),
translate('loadMore')
);
return React__default.createElement(
'div',
cx$7('root'),
renderedHits,
loadMoreButton
);
}
}]);
return InfiniteHits;
}(React.Component);
InfiniteHits$1.propTypes = {
hits: propTypes.array,
hitComponent: propTypes.oneOfType([propTypes.string, propTypes.func]).isRequired,
hasMore: propTypes.bool.isRequired,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired
};
/* eslint-disable react/display-name */
InfiniteHits$1.defaultProps = {
hitComponent: function hitComponent(hit) {
return React__default.createElement(
'div',
{
style: {
borderBottom: '1px solid #bbb',
paddingBottom: '5px',
marginBottom: '5px'
}
},
JSON.stringify(hit).slice(0, 100),
'...'
);
}
};
/* eslint-enable react/display-name */
var InfiniteHitsComponent = translatable({
loadMore: 'Load more'
})(InfiniteHits$1);
/**
* Displays an infinite list of hits along with a **load more** button.
*
* To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html).
*
* @name InfiniteHits
* @kind widget
* @propType {Component} hitComponent - Component used for rendering each hit from
* the results. If it is not provided the rendering defaults to displaying the
* hit in its JSON form. The component will be called with a `hit` prop.
* @themeKey ais-InfiniteHits__root - the root of the component
* @translationKey loadMore - the label of load more button
* @example
* import React from 'react';
* import { InfiniteHits, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <InfiniteHits />
* </InstantSearch>
* );
* }
*/
var InfiniteHits = connectInfiniteHits(InfiniteHitsComponent);
var namespace$1 = 'menu';
function getId$4(props) {
return props.attributeName;
}
function getCurrentRefinement$3(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, namespace$1 + '.' + getId$4(props), null, function (currentRefinement) {
if (currentRefinement === '') {
return null;
}
return currentRefinement;
});
}
function getValue$3(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement$3(props, searchState, context);
return name === currentRefinement ? '' : name;
}
function _refine$1(props, searchState, nextRefinement, context) {
var id = getId$4(props);
var nextValue = defineProperty$2({}, id, nextRefinement ? nextRefinement : '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$1);
}
function _cleanUp$1(props, searchState, context) {
return cleanUpValue(searchState, context, namespace$1 + '.' + getId$4(props));
}
var sortBy$1 = ['count:desc', 'name:asc'];
/**
* connectMenu connector provides the logic to build a widget that will
* give the user the ability to choose a single value for a specific facet.
* @name connectMenu
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @kind connector
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of diplayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {boolean} [withSearchBox=false] - allow search inside values
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
var connectMenu = createConnector({
displayName: 'AlgoliaMenu',
propTypes: {
attributeName: propTypes.string.isRequired,
showMore: propTypes.bool,
limitMin: propTypes.number,
limitMax: propTypes.number,
defaultRefinement: propTypes.string,
transformItems: propTypes.func,
withSearchBox: propTypes.bool,
searchForFacetValues: propTypes.bool // @deprecated
},
defaultProps: {
showMore: false,
limitMin: 10,
limitMax: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) {
var _this = this;
var attributeName = props.attributeName,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var results = getResults(searchResults, this.context);
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== '');
var withSearchBox = props.withSearchBox || props.searchForFacetValues;
if (props.withSearchBox && this.context.multiIndexContext) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement$3(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: canRefine
};
}
var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) {
return {
label: v.value,
value: getValue$3(v.value, props, searchState, _this.context),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attributeName, { sortBy: sortBy$1 }).map(function (v) {
return {
label: v.name,
value: getValue$3(v.name, props, searchState, _this.context),
count: v.count,
isRefined: v.isRefined
};
});
var sortedItems = withSearchBox && !isFromSearch ? orderBy_1(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items;
var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems;
return {
items: transformedItems.slice(0, limit),
currentRefinement: getCurrentRefinement$3(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$1(props, searchState, nextRefinement, this.context);
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return { facetName: props.attributeName, query: nextRefinement };
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$1(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$3(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$4(props);
var currentRefinement = getCurrentRefinement$3(props, searchState, this.context);
return {
id: id,
index: getIndex(this.context),
items: currentRefinement === null ? [] : [{
label: props.attributeName + ': ' + currentRefinement,
attributeName: props.attributeName,
value: function value(nextState) {
return _refine$1(props, nextState, '', _this2.context);
},
currentRefinement: currentRefinement
}]
};
}
});
var cx$8 = classNames('Menu');
var Menu$1 = function (_Component) {
inherits(Menu, _Component);
function Menu() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, Menu);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Menu.__proto__ || Object.getPrototypeOf(Menu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item, resetQuery) {
var createURL = _this.props.createURL;
var label = _this.props.isFromSearch ? React__default.createElement(Highlight, { attributeName: 'label', hit: item }) : item.label;
return React__default.createElement(
Link,
_extends({}, cx$8('itemLink', item.isRefined && 'itemLinkSelected'), {
onClick: function onClick() {
return _this.selectItem(item, resetQuery);
},
href: createURL(item.value)
}),
React__default.createElement(
'span',
cx$8('itemLabel', item.isRefined && 'itemLabelSelected'),
label
),
' ',
React__default.createElement(
'span',
cx$8('itemCount', item.isRefined && 'itemCountSelected'),
item.count
)
);
}, _this.selectItem = function (item, resetQuery) {
resetQuery();
_this.props.refine(item.value);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(Menu, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
return React__default.createElement(List, _extends({
renderItem: this.renderItem,
selectItem: this.selectItem,
cx: cx$8
}, pick_1(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine'])));
}
}]);
return Menu;
}(React.Component);
Menu$1.propTypes = {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
searchForItems: propTypes.func.isRequired,
withSearchBox: propTypes.bool,
createURL: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string.isRequired,
count: propTypes.number.isRequired,
isRefined: propTypes.bool.isRequired
})),
isFromSearch: propTypes.bool.isRequired,
canRefine: propTypes.bool.isRequired,
showMore: propTypes.bool,
limitMin: propTypes.number,
limitMax: propTypes.number,
transformItems: propTypes.func
};
Menu$1.contextTypes = {
canRefine: propTypes.func
};
var MenuComponent = translatable({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
},
noResults: 'No results',
submit: null,
reset: null,
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(Menu$1);
/**
* The Menu component displays a menu that lets the user choose a single value for a specific attribute.
* @name Menu
* @kind widget
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* If you are using the `withSearchBox` prop, you'll also need to make the attribute searchable using
* the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values).
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of diplayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/).
* @themeKey ais-Menu__root - the root of the component
* @themeKey ais-Menu__items - the container of all items in the menu
* @themeKey ais-Menu__item - a single item
* @themeKey ais-Menu__itemLinkSelected - the selected menu item
* @themeKey ais-Menu__itemLink - the item link
* @themeKey ais-Menu__itemLabelSelected - the selected item label
* @themeKey ais-Menu__itemLabel - the item label
* @themeKey ais-Menu__itemCount - the item count
* @themeKey ais-Menu__itemCountSelected - the selected item count
* @themeKey ais-Menu__noRefinement - present when there is no refinement
* @themeKey ais-Menu__showMore - the button that let the user toggle more results
* @themeKey ais-Menu__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded
* @translationkey noResults - The label of the no results text when no search for facet values results are found.
* @example
* import React from 'react';
*
* import { Menu, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Menu
* attributeName="category"
* />
* </InstantSearch>
* );
* }
*/
var Menu = connectMenu(MenuComponent);
var cx$9 = classNames('MenuSelect');
var MenuSelect$1 = function (_Component) {
inherits(MenuSelect, _Component);
function MenuSelect() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, MenuSelect);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = MenuSelect.__proto__ || Object.getPrototypeOf(MenuSelect)).call.apply(_ref, [this].concat(args))), _this), _this.handleSelectChange = function (_ref2) {
var value = _ref2.target.value;
_this.props.refine(value === 'ais__see__all__option' ? '' : value);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(MenuSelect, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
items = _props.items,
translate = _props.translate;
return React__default.createElement(
'select',
_extends({
value: this.selectedValue,
onChange: this.handleSelectChange
}, cx$9('select')),
React__default.createElement(
'option',
_extends({ value: 'ais__see__all__option' }, cx$9('option')),
translate('seeAllOption')
),
items.map(function (item) {
return React__default.createElement(
'option',
_extends({ key: item.value, value: item.value }, cx$9('option')),
item.label,
' (',
item.count,
')'
);
})
);
}
}, {
key: 'selectedValue',
get: function get() {
var _ref3 = find_1(this.props.items, { isRefined: true }) || {
value: 'ais__see__all__option'
},
value = _ref3.value;
return value;
}
}]);
return MenuSelect;
}(React.Component);
MenuSelect$1.propTypes = {
canRefine: propTypes.bool.isRequired,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string.isRequired,
count: propTypes.oneOfType([propTypes.number.isRequired, propTypes.string.isRequired]),
isRefined: propTypes.bool.isRequired
}))
};
MenuSelect$1.contextTypes = {
canRefine: propTypes.func
};
var MenuSelectComponent = translatable({
seeAllOption: 'See all'
})(MenuSelect$1);
/**
* The MenuSelect component displays a select that lets the user choose a single value for a specific attribute.
* @name MenuSelect
* @kind widget
* @requirements The attribute passed to the `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 {string} [defaultRefinement] - the value of the item selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-MenuSelect__select - the `<select>` DOM element.
* @themeKey ais-MenuSelect__option - the `<option>` DOM element for a single item
* @translationkey seeAllOption - The label of the option to select to remove the refinement
* @example
* import React from 'react';
*
* import { MenuSelect, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <MenuSelect
* attributeName="category"
* />
* </InstantSearch>
* );
* }
*/
var MenuSelect = connectMenu(MenuSelectComponent);
function stringifyItem(item) {
if (typeof item.start === 'undefined' && typeof item.end === 'undefined') {
return '';
}
return (item.start ? item.start : '') + ':' + (item.end ? item.end : '');
}
function parseItem(value) {
if (value.length === 0) {
return { start: null, end: null };
}
var _value$split = value.split(':'),
_value$split2 = slicedToArray(_value$split, 2),
startStr = _value$split2[0],
endStr = _value$split2[1];
return {
start: startStr.length > 0 ? parseInt(startStr, 10) : null,
end: endStr.length > 0 ? parseInt(endStr, 10) : null
};
}
var namespace$2 = 'multiRange';
function getId$5(props) {
return props.attributeName;
}
function getCurrentRefinement$4(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, namespace$2 + '.' + getId$5(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$2(props, searchState, nextRefinement, context) {
var nextValue = defineProperty$2({}, getId$5(props, searchState), nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$2);
}
function _cleanUp$2(props, searchState, context) {
return cleanUpValue(searchState, context, namespace$2 + '.' + getId$5(props));
}
/**
* connectMultiRange connector provides the logic to build a widget that will
* give the user the ability to select a range value for a numeric attribute.
* Ranges are defined statically.
* @name connectMultiRange
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @kind connector
* @propType {string} attributeName - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string.
* @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the MultiRange can display.
*/
var connectMultiRange = createConnector({
displayName: 'AlgoliaMultiRange',
propTypes: {
id: propTypes.string,
attributeName: propTypes.string.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.node,
start: propTypes.number,
end: propTypes.number
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attributeName = props.attributeName;
var currentRefinement = getCurrentRefinement$4(props, searchState, this.context);
var results = getResults(searchResults, this.context);
var items = props.items.map(function (item) {
var value = stringifyItem(item);
return {
label: item.label,
value: value,
isRefined: value === currentRefinement,
noRefinement: results ? itemHasRefinement(getId$5(props), results, value) : false
};
});
var stats = results && results.getFacetByName(attributeName) ? results.getFacetStats(attributeName) : null;
var refinedItem = find_1(items, function (item) {
return item.isRefined === true;
});
if (!items.some(function (item) {
return item.value === '';
})) {
items.push({
value: '',
isRefined: isEmpty_1(refinedItem),
noRefinement: !stats,
label: 'All'
});
}
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement,
canRefine: items.length > 0 && items.some(function (item) {
return item.noRefinement === false;
})
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$2(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$2(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName;
var _parseItem = parseItem(getCurrentRefinement$4(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$5(props);
var value = getCurrentRefinement$4(props, searchState, this.context);
var items = [];
var index = getIndex(this.context);
if (value !== '') {
var _find2 = find_1(props.items, function (item) {
return stringifyItem(item) === value;
}),
label = _find2.label;
items.push({
label: props.attributeName + ': ' + label,
attributeName: props.attributeName,
currentRefinement: label,
value: function value(nextState) {
return _refine$2(props, nextState, '', _this.context);
}
});
}
return { id: id, index: index, items: items };
}
});
var cx$10 = classNames('MultiRange');
var MultiRange$1 = function (_Component) {
inherits(MultiRange, _Component);
function MultiRange() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, MultiRange);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = MultiRange.__proto__ || Object.getPrototypeOf(MultiRange)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) {
var _this$props = _this.props,
refine = _this$props.refine,
translate = _this$props.translate;
var label = item.value === '' ? translate('all') : item.label;
return React__default.createElement(
'label',
cx$10(item.value === '' && 'itemAll'),
React__default.createElement('input', _extends({}, cx$10('itemRadio', item.isRefined && 'itemRadioSelected'), {
type: 'radio',
checked: item.isRefined,
disabled: item.noRefinement,
onChange: function onChange() {
return refine(item.value);
}
})),
React__default.createElement('span', cx$10('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')),
React__default.createElement(
'span',
cx$10('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'),
label
)
);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(MultiRange, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
items = _props.items,
canRefine = _props.canRefine;
return React__default.createElement(List, {
renderItem: this.renderItem,
showMore: false,
canRefine: canRefine,
cx: cx$10,
items: items.map(function (item) {
return _extends({}, item, { key: item.value });
})
});
}
}]);
return MultiRange;
}(React.Component);
MultiRange$1.propTypes = {
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.node.isRequired,
value: propTypes.string.isRequired,
isRefined: propTypes.bool.isRequired,
noRefinement: propTypes.bool.isRequired
})).isRequired,
refine: propTypes.func.isRequired,
transformItems: propTypes.func,
canRefine: propTypes.bool.isRequired,
translate: propTypes.func.isRequired
};
MultiRange$1.contextTypes = {
canRefine: propTypes.func
};
var MultiRangeComponent = translatable({
all: 'All'
})(MultiRange$1);
/**
* MultiRange is a widget used for selecting the range value of a numeric attribute.
* @name MultiRange
* @kind widget
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @propType {string} attributeName - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the format "min:max".
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-MultiRange__root - The root component of the widget
* @themeKey ais-MultiRange__items - The container of the items
* @themeKey ais-MultiRange__item - A single item
* @themeKey ais-MultiRange__itemSelected - The selected item
* @themeKey ais-MultiRange__itemLabel - The label of an item
* @themeKey ais-MultiRange__itemLabelSelected - The selected label item
* @themeKey ais-MultiRange__itemRadio - The radio of an item
* @themeKey ais-MultiRange__itemRadioSelected - The selected radio item
* @themeKey ais-MultiRange__noRefinement - present when there is no refinement for all ranges
* @themeKey ais-MultiRange__itemNoRefinement - present when there is no refinement for one range
* @themeKey ais-MultiRange__itemAll - indicate the range that will contain all the results
* @translationkey all - The label of the largest range added automatically by react instantsearch
* @example
* import React from 'react';
*
* import { MultiRange, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <MultiRange
* attributeName="price"
* items={[
* { end: 10, label: '<$10' },
* { start: 10, end: 100, label: '$10-$100' },
* { start: 100, end: 500, label: '$100-$500' },
* { start: 500, label: '>$500' },
* ]}
* />
* </InstantSearch>
* );
* }
*/
var MultiRange = connectMultiRange(MultiRangeComponent);
function getId$6() {
return 'page';
}
function getCurrentRefinement$5(props, searchState, context) {
var id = getId$6();
var page = 1;
return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
function _refine$3(props, searchState, nextPage, context) {
var id = getId$6();
var nextValue = defineProperty$2({}, id, nextPage);
var resetPage = false;
return refineValue(searchState, nextValue, context, resetPage);
}
/**
* connectPagination connector provides the logic to build a widget that will
* let the user displays hits corresponding to a certain page.
* @name connectPagination
* @kind connector
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [pagesPadding=3] - How many page links to display around the current page.
* @propType {number} [maxPages=Infinity] - Maximum number of pages to display.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {number} nbPages - the total of existing pages
* @providedPropType {number} currentRefinement - the page refinement currently applied
*/
var connectPagination = createConnector({
displayName: 'AlgoliaPagination',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, this.context);
if (!results) {
return null;
}
var nbPages = results.nbPages;
return {
nbPages: nbPages,
currentRefinement: getCurrentRefinement$5(props, searchState, this.context),
canRefine: nbPages > 1
};
},
refine: function refine(props, searchState, nextPage) {
return _refine$3(props, searchState, nextPage, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, this.context, getId$6());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setPage(getCurrentRefinement$5(props, searchState, this.context) - 1);
},
getMetadata: function getMetadata() {
return { id: getId$6() };
}
});
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil;
var nativeMax$7 = Math.max;
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax$7(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
var _baseRange = baseRange;
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && _isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite_1(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite_1(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite_1(step);
return _baseRange(start, end, step, fromRight);
};
}
var _createRange = createRange;
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
var range = _createRange();
var range_1 = range;
var LinkList = function (_Component) {
inherits(LinkList, _Component);
function LinkList() {
classCallCheck(this, LinkList);
return possibleConstructorReturn(this, (LinkList.__proto__ || Object.getPrototypeOf(LinkList)).apply(this, arguments));
}
createClass(LinkList, [{
key: 'render',
value: function render() {
var _props = this.props,
cx = _props.cx,
createURL = _props.createURL,
items = _props.items,
onSelect = _props.onSelect,
canRefine = _props.canRefine;
return React__default.createElement(
'ul',
cx('root', !canRefine && 'noRefinement'),
items.map(function (item) {
return React__default.createElement(
'li',
_extends({
key: has_1(item, 'key') ? item.key : item.value
}, cx('item', item.selected && !item.disabled && 'itemSelected', item.disabled && 'itemDisabled', item.modifier), {
disabled: item.disabled
}),
item.disabled ? React__default.createElement(
'span',
cx('itemLink', 'itemLinkDisabled'),
has_1(item, 'label') ? item.label : item.value
) : React__default.createElement(
Link,
_extends({}, cx('itemLink', item.selected && 'itemLinkSelected'), {
'aria-label': item.ariaLabel,
href: createURL(item.value),
onClick: function onClick() {
return onSelect(item.value);
}
}),
has_1(item, 'label') ? item.label : item.value
)
);
})
);
}
}]);
return LinkList;
}(React.Component);
LinkList.propTypes = {
cx: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
value: propTypes.oneOfType([propTypes.string, propTypes.number, propTypes.object]).isRequired,
key: propTypes.oneOfType([propTypes.string, propTypes.number]),
label: propTypes.node,
modifier: propTypes.string,
ariaLabel: propTypes.string,
disabled: propTypes.bool
})),
onSelect: propTypes.func.isRequired,
canRefine: propTypes.bool.isRequired
};
var cx$11 = classNames('Pagination');
// Determines the size of the widget (the number of pages displayed - that the user can directly click on)
function calculateSize(padding, maxPages) {
return Math.min(2 * padding + 1, maxPages);
}
function calculatePaddingLeft(currentPage, padding, maxPages, size) {
if (currentPage <= padding) {
return currentPage;
}
if (currentPage >= maxPages - padding) {
return size - (maxPages - currentPage);
}
return padding + 1;
}
// Retrieve the correct page range to populate the widget
function getPages(currentPage, maxPages, padding) {
var size = calculateSize(padding, maxPages);
// If the widget size is equal to the max number of pages, return the entire page range
if (size === maxPages) return range_1(1, maxPages + 1);
var paddingLeft = calculatePaddingLeft(currentPage, padding, maxPages, size);
var paddingRight = size - paddingLeft;
var first = currentPage - paddingLeft;
var last = currentPage + paddingRight;
return range_1(first + 1, last + 1);
}
var Pagination$1 = function (_Component) {
inherits(Pagination, _Component);
function Pagination() {
classCallCheck(this, Pagination);
return possibleConstructorReturn(this, (Pagination.__proto__ || Object.getPrototypeOf(Pagination)).apply(this, arguments));
}
createClass(Pagination, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'getItem',
value: function getItem(modifier, translationKey, value) {
var _props = this.props,
nbPages = _props.nbPages,
maxPages = _props.maxPages,
translate = _props.translate;
return {
key: modifier + '.' + value,
modifier: modifier,
disabled: value < 1 || value >= Math.min(maxPages, nbPages),
label: translate(translationKey, value),
value: value,
ariaLabel: translate('aria' + capitalize(translationKey), value)
};
}
}, {
key: 'render',
value: function render() {
var _props2 = this.props,
nbPages = _props2.nbPages,
maxPages = _props2.maxPages,
currentRefinement = _props2.currentRefinement,
pagesPadding = _props2.pagesPadding,
showFirst = _props2.showFirst,
showPrevious = _props2.showPrevious,
showNext = _props2.showNext,
showLast = _props2.showLast,
refine = _props2.refine,
createURL = _props2.createURL,
translate = _props2.translate,
ListComponent = _props2.listComponent,
otherProps = objectWithoutProperties(_props2, ['nbPages', 'maxPages', 'currentRefinement', 'pagesPadding', 'showFirst', 'showPrevious', 'showNext', 'showLast', 'refine', 'createURL', 'translate', 'listComponent']);
var totalPages = Math.min(nbPages, maxPages);
var lastPage = totalPages;
var items = [];
if (showFirst) {
items.push({
key: 'first',
modifier: 'itemFirst',
disabled: currentRefinement === 1,
label: translate('first'),
value: 1,
ariaLabel: translate('ariaFirst')
});
}
if (showPrevious) {
items.push({
key: 'previous',
modifier: 'itemPrevious',
disabled: currentRefinement === 1,
label: translate('previous'),
value: currentRefinement - 1,
ariaLabel: translate('ariaPrevious')
});
}
items = items.concat(getPages(currentRefinement, totalPages, pagesPadding).map(function (value) {
return {
key: value,
modifier: 'itemPage',
label: translate('page', value),
value: value,
selected: value === currentRefinement,
ariaLabel: translate('ariaPage', value)
};
}));
if (showNext) {
items.push({
key: 'next',
modifier: 'itemNext',
disabled: currentRefinement === lastPage || lastPage <= 1,
label: translate('next'),
value: currentRefinement + 1,
ariaLabel: translate('ariaNext')
});
}
if (showLast) {
items.push({
key: 'last',
modifier: 'itemLast',
disabled: currentRefinement === lastPage || lastPage <= 1,
label: translate('last'),
value: lastPage,
ariaLabel: translate('ariaLast')
});
}
return React__default.createElement(ListComponent, _extends({}, otherProps, {
cx: cx$11,
items: items,
onSelect: refine,
createURL: createURL
}));
}
}]);
return Pagination;
}(React.Component);
Pagination$1.propTypes = {
nbPages: propTypes.number.isRequired,
currentRefinement: propTypes.number.isRequired,
refine: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
canRefine: propTypes.bool.isRequired,
translate: propTypes.func.isRequired,
listComponent: propTypes.func,
showFirst: propTypes.bool,
showPrevious: propTypes.bool,
showNext: propTypes.bool,
showLast: propTypes.bool,
pagesPadding: propTypes.number,
maxPages: propTypes.number
};
Pagination$1.defaultProps = {
listComponent: LinkList,
showFirst: true,
showPrevious: true,
showNext: true,
showLast: false,
pagesPadding: 3,
maxPages: Infinity
};
Pagination$1.contextTypes = {
canRefine: propTypes.func
};
var PaginationComponent = translatable({
previous: '‹',
next: '›',
first: '«',
last: '»',
page: function page(currentRefinement) {
return currentRefinement.toString();
},
ariaPrevious: 'Previous page',
ariaNext: 'Next page',
ariaFirst: 'First page',
ariaLast: 'Last page',
ariaPage: function ariaPage(currentRefinement) {
return 'Page ' + currentRefinement.toString();
}
})(Pagination$1);
/**
* The Pagination widget displays a simple pagination system allowing the user to
* change the current page.
* @name Pagination
* @kind widget
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [pagesPadding=3] - How many page links to display around the current page.
* @propType {number} [maxPages=Infinity] - Maximum number of pages to display.
* @themeKey ais-Pagination__root - The root component of the widget
* @themeKey ais-Pagination__itemFirst - The first page link item
* @themeKey ais-Pagination__itemPrevious - The previous page link item
* @themeKey ais-Pagination__itemPage - The page link item
* @themeKey ais-Pagination__itemNext - The next page link item
* @themeKey ais-Pagination__itemLast - The last page link item
* @themeKey ais-Pagination__itemDisabled - a disabled item
* @themeKey ais-Pagination__itemSelected - a selected item
* @themeKey ais-Pagination__itemLink - The link of an item
* @themeKey ais-Pagination__noRefinement - present when there is no refinement
* @translationKey previous - Label value for the previous page link
* @translationKey next - Label value for the next page link
* @translationKey first - Label value for the first page link
* @translationKey last - Label value for the last page link
* @translationkey page - Label value for a page item. You get function(currentRefinement) and you need to return a string
* @translationKey ariaPrevious - Accessibility label value for the previous page link
* @translationKey ariaNext - Accessibility label value for the next page link
* @translationKey ariaFirst - Accessibility label value for the first page link
* @translationKey ariaLast - Accessibility label value for the last page link
* @translationkey ariaPage - Accessibility label value for a page item. You get function(currentRefinement) and you need to return a string
* @example
* import React from 'react';
*
* import { Pagination, InstantSearch } from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Pagination />
* </InstantSearch>
* );
* }
*/
var Pagination = connectPagination(PaginationComponent);
/**
* connectPoweredBy connector provides the logic to build a widget that
* will display a link to algolia.
* @name connectPoweredBy
* @kind connector
* @providedPropType {string} url - the url to redirect to algolia
*/
var connectPoweredBy = createConnector({
displayName: 'AlgoliaPoweredBy',
propTypes: {},
getProvidedProps: function getProvidedProps(props) {
var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + ('utm_content=' + (props.canRender ? location.hostname : '') + '&') + 'utm_campaign=poweredby';
return { url: url };
}
});
var cx$12 = classNames('PoweredBy');
/* eslint-disable max-len */
var AlgoliaLogo = function AlgoliaLogo() {
return React__default.createElement(
'svg',
{
xmlns: 'http://www.w3.org/2000/svg',
baseProfile: 'basic',
viewBox: '0 0 1366 362'
},
React__default.createElement(
'linearGradient',
{
id: 'g',
x1: '428.258',
x2: '434.145',
y1: '404.15',
y2: '409.85',
gradientUnits: 'userSpaceOnUse',
gradientTransform: 'matrix(94.045 0 0 -94.072 -40381.527 38479.52)'
},
React__default.createElement('stop', { offset: '0', stopColor: '#00AEFF' }),
React__default.createElement('stop', { offset: '1', stopColor: '#3369E7' })
),
React__default.createElement('path', {
d: 'M61.8 15.4h242.8c23.9 0 43.4 19.4 43.4 43.4v242.9c0 23.9-19.4 43.4-43.4 43.4H61.8c-23.9 0-43.4-19.4-43.4-43.4v-243c0-23.9 19.4-43.3 43.4-43.3z',
fill: 'url(#g)'
}),
React__default.createElement('path', {
d: 'M187 98.7c-51.4 0-93.1 41.7-93.1 93.2S135.6 285 187 285s93.1-41.7 93.1-93.2-41.6-93.1-93.1-93.1zm0 158.8c-36.2 0-65.6-29.4-65.6-65.6s29.4-65.6 65.6-65.6 65.6 29.4 65.6 65.6-29.3 65.6-65.6 65.6zm0-117.8v48.9c0 1.4 1.5 2.4 2.8 1.7l43.4-22.5c1-.5 1.3-1.7.8-2.7-9-15.8-25.7-26.6-45-27.3-1 0-2 .8-2 1.9zm-60.8-35.9l-5.7-5.7c-5.6-5.6-14.6-5.6-20.2 0l-6.8 6.8c-5.6 5.6-5.6 14.6 0 20.2l5.6 5.6c.9.9 2.2.7 3-.2 3.3-4.5 6.9-8.8 10.9-12.8 4.1-4.1 8.3-7.7 12.9-11 1-.6 1.1-2 .3-2.9zM217.5 89V77.7c0-7.9-6.4-14.3-14.3-14.3h-33.3c-7.9 0-14.3 6.4-14.3 14.3v11.6c0 1.3 1.2 2.2 2.5 1.9 9.3-2.7 19.1-4.1 29-4.1 9.5 0 18.9 1.3 28 3.8 1.2.3 2.4-.6 2.4-1.9z',
fill: '#FFFFFF'
}),
React__default.createElement('path', {
d: 'M842.5 267.6c0 26.7-6.8 46.2-20.5 58.6-13.7 12.4-34.6 18.6-62.8 18.6-10.3 0-31.7-2-48.8-5.8l6.3-31c14.3 3 33.2 3.8 43.1 3.8 15.7 0 26.9-3.2 33.6-9.6s10-15.9 10-28.5v-6.4c-3.9 1.9-9 3.8-15.3 5.8-6.3 1.9-13.6 2.9-21.8 2.9-10.8 0-20.6-1.7-29.5-5.1-8.9-3.4-16.6-8.4-22.9-15-6.3-6.6-11.3-14.9-14.8-24.8s-5.3-27.6-5.3-40.6c0-12.2 1.9-27.5 5.6-37.7 3.8-10.2 9.2-19 16.5-26.3 7.2-7.3 16-12.9 26.3-17s22.4-6.7 35.5-6.7c12.7 0 24.4 1.6 35.8 3.5 11.4 1.9 21.1 3.9 29 6.1v155.2zm-108.7-77.2c0 16.4 3.6 34.6 10.8 42.2 7.2 7.6 16.5 11.4 27.9 11.4 6.2 0 12.1-.9 17.6-2.6 5.5-1.7 9.9-3.7 13.4-6.1v-97.1c-2.8-.6-14.5-3-25.8-3.3-14.2-.4-25 5.4-32.6 14.7-7.5 9.3-11.3 25.6-11.3 40.8zm294.3 0c0 13.2-1.9 23.2-5.8 34.1s-9.4 20.2-16.5 27.9c-7.1 7.7-15.6 13.7-25.6 17.9s-25.4 6.6-33.1 6.6c-7.7-.1-23-2.3-32.9-6.6-9.9-4.3-18.4-10.2-25.5-17.9-7.1-7.7-12.6-17-16.6-27.9s-6-20.9-6-34.1c0-13.2 1.8-25.9 5.8-36.7 4-10.8 9.6-20 16.8-27.7s15.8-13.6 25.6-17.8c9.9-4.2 20.8-6.2 32.6-6.2s22.7 2.1 32.7 6.2c10 4.2 18.6 10.1 25.6 17.8 7.1 7.7 12.6 16.9 16.6 27.7 4.2 10.8 6.3 23.5 6.3 36.7zm-40 .1c0-16.9-3.7-31-10.9-40.8-7.2-9.9-17.3-14.8-30.2-14.8-12.9 0-23 4.9-30.2 14.8-7.2 9.9-10.7 23.9-10.7 40.8 0 17.1 3.6 28.6 10.8 38.5 7.2 10 17.3 14.9 30.2 14.9 12.9 0 23-5 30.2-14.9 7.2-10 10.8-21.4 10.8-38.5zm127.1 86.4c-64.1.3-64.1-51.8-64.1-60.1L1051 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9zm68.9 0h-39.3V108.1l39.3-6.2v175zm-19.7-193.5c13.1 0 23.8-10.6 23.8-23.7S1177.6 36 1164.4 36s-23.8 10.6-23.8 23.7 10.7 23.7 23.8 23.7zm117.4 18.6c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4s8.9 13.5 11.1 21.7c2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6s-25.9 2.7-41.1 2.7c-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.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-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18s13.7 5.3 23.6 5.3zm158.5 31.9c-64.1.3-64.1-51.8-64.1-60.1L610.6 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9z',
fill: '#182359'
})
);
};
/* eslint-enable max-len */
var PoweredBy$1 = function (_Component) {
inherits(PoweredBy, _Component);
function PoweredBy() {
classCallCheck(this, PoweredBy);
return possibleConstructorReturn(this, (PoweredBy.__proto__ || Object.getPrototypeOf(PoweredBy)).apply(this, arguments));
}
createClass(PoweredBy, [{
key: 'render',
value: function render() {
var _props = this.props,
translate = _props.translate,
url = _props.url;
return React__default.createElement(
'div',
cx$12('root'),
React__default.createElement(
'span',
cx$12('searchBy'),
translate('searchBy'),
' '
),
React__default.createElement(
'a',
_extends({
href: url,
target: '_blank'
}, cx$12('algoliaLink'), {
'aria-label': 'Algolia'
}),
React__default.createElement(AlgoliaLogo, null)
)
);
}
}]);
return PoweredBy;
}(React.Component);
PoweredBy$1.propTypes = {
url: propTypes.string.isRequired,
translate: propTypes.func.isRequired
};
var PoweredByComponent = translatable({
searchBy: 'Search by'
})(PoweredBy$1);
/**
* PoweredBy displays an Algolia logo.
*
* Algolia requires that you use this widget if you are on a [community or free plan](https://www.algolia.com/pricing).
* @name PoweredBy
* @kind widget
* @themeKey ais-PoweredBy__root - The root component of the widget
* @themeKey ais-PoweredBy__searchBy - The powered by label
* @themeKey ais-PoweredBy__algoliaLink - The algolia logo link
* @translationKey searchBy - Label value for the powered by
* @example
* import React from 'react';
*
* import { PoweredBy, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <PoweredBy />
* </InstantSearch>
* );
* }
*/
var PoweredBy = connectPoweredBy(PoweredByComponent);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsFinite = _root.isFinite;
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
*/
function isFinite$1(value) {
return typeof value == 'number' && nativeIsFinite(value);
}
var _isFinite = isFinite$1;
/**
* connectRange connector provides the logic to create connected
* components that will give the ability for a user to refine results using
* a numeric range.
* @name connectRange
* @kind connector
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @propType {string} attributeName - Name of the attribute for faceting
* @propType {{min: number, max: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [precision=2] - Number of digits after decimal point to use.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
*/
function getId$7(props) {
return props.attributeName;
}
var namespace$3 = 'range';
function getCurrentRange(boundaries, stats, precision) {
var pow = Math.pow(10, precision);
var min = void 0;
if (_isFinite(boundaries.min)) {
min = boundaries.min;
} else if (_isFinite(stats.min)) {
min = stats.min;
} else {
min = undefined;
}
var max = void 0;
if (_isFinite(boundaries.max)) {
max = boundaries.max;
} else if (_isFinite(stats.max)) {
max = stats.max;
} else {
max = undefined;
}
return {
min: min !== undefined ? Math.floor(min * pow) / pow : min,
max: max !== undefined ? Math.ceil(max * pow) / pow : max
};
}
function getCurrentRefinement$6(props, searchState, currentRange, context) {
var refinement = getCurrentRefinementValue(props, searchState, context, namespace$3 + '.' + getId$7(props), {}, function (currentRefinement) {
var min = currentRefinement.min,
max = currentRefinement.max;
if (typeof min === 'string') {
min = parseInt(min, 10);
}
if (typeof max === 'string') {
max = parseInt(max, 10);
}
return { min: min, max: max };
});
var hasMinBound = props.min !== undefined;
var hasMaxBound = props.max !== undefined;
var hasMinRefinment = refinement.min !== undefined;
var hasMaxRefinment = refinement.max !== undefined;
if (hasMinBound && hasMinRefinment && refinement.min < currentRange.min) {
throw Error("You can't provide min value lower than range.");
}
if (hasMaxBound && hasMaxRefinment && refinement.max > currentRange.max) {
throw Error("You can't provide max value greater than range.");
}
if (hasMinBound && !hasMinRefinment) {
refinement.min = currentRange.min;
}
if (hasMaxBound && !hasMaxRefinment) {
refinement.max = currentRange.max;
}
return refinement;
}
function nextValueForRefinement(hasBound, isReset, range, value) {
var next = void 0;
if (!hasBound && range === value) {
next = undefined;
} else if (hasBound && isReset) {
next = range;
} else {
next = value;
}
return next;
}
function _refine$4(props, searchState, nextRefinement, currentRange, context) {
var nextMin = nextRefinement.min,
nextMax = nextRefinement.max;
var currentMinRange = currentRange.min,
currentMaxRange = currentRange.max;
var isMinReset = nextMin === undefined || nextMin === '';
var isMaxReset = nextMax === undefined || nextMax === '';
var nextMinAsNumber = !isMinReset ? parseFloat(nextMin) : undefined;
var nextMaxAsNumber = !isMaxReset ? parseFloat(nextMax) : undefined;
var isNextMinValid = isMinReset || _isFinite(nextMinAsNumber);
var isNextMaxValid = isMaxReset || _isFinite(nextMaxAsNumber);
if (!isNextMinValid || !isNextMaxValid) {
throw Error("You can't provide non finite values to the range connector.");
}
if (nextMinAsNumber < currentMinRange) {
throw Error("You can't provide min value lower than range.");
}
if (nextMaxAsNumber > currentMaxRange) {
throw Error("You can't provide max value greater than range.");
}
var id = getId$7(props);
var resetPage = true;
var nextValue = defineProperty$2({}, id, {
min: nextValueForRefinement(props.min !== undefined, isMinReset, currentMinRange, nextMinAsNumber),
max: nextValueForRefinement(props.max !== undefined, isMaxReset, currentMaxRange, nextMaxAsNumber)
});
return refineValue(searchState, nextValue, context, resetPage, namespace$3);
}
function _cleanUp$3(props, searchState, context) {
return cleanUpValue(searchState, context, namespace$3 + '.' + getId$7(props));
}
var connectRange = createConnector({
displayName: 'AlgoliaRange',
propTypes: {
id: propTypes.string,
attributeName: propTypes.string.isRequired,
defaultRefinement: propTypes.shape({
min: propTypes.number.isRequired,
max: propTypes.number.isRequired
}),
min: propTypes.number,
max: propTypes.number,
precision: propTypes.number
},
defaultProps: {
precision: 2
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attributeName = props.attributeName,
precision = props.precision,
minBound = props.min,
maxBound = props.max;
var results = getResults(searchResults, this.context);
var stats = results ? results.getFacetStats(attributeName) || {} : {};
var count = results ? results.getFacetValues(attributeName).map(function (v) {
return {
value: v.name,
count: v.count
};
}) : [];
var _getCurrentRange = getCurrentRange({ min: minBound, max: maxBound }, stats, precision),
rangeMin = _getCurrentRange.min,
rangeMax = _getCurrentRange.max;
// The searchState is not always in sync with the helper state. For example
// when we set boundaries on the first render the searchState don't have
// the correct refinement. If this behaviour change in the upcoming version
// we could store the range inside the searchState instead of rely on `this`.
this._currentRange = {
min: rangeMin,
max: rangeMax
};
var _getCurrentRefinement = getCurrentRefinement$6(props, searchState, this._currentRange, this.context),
valueMin = _getCurrentRefinement.min,
valueMax = _getCurrentRefinement.max;
return {
min: rangeMin,
max: rangeMax,
canRefine: count.length > 0,
currentRefinement: {
min: valueMin === undefined ? rangeMin : valueMin,
max: valueMax === undefined ? rangeMax : valueMax
},
count: count,
precision: precision
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$4(props, searchState, nextRefinement, this._currentRange, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$3(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(params, props, searchState) {
var attributeName = props.attributeName;
var _getCurrentRefinement2 = getCurrentRefinement$6(props, searchState, this._currentRange, this.context),
min = _getCurrentRefinement2.min,
max = _getCurrentRefinement2.max;
params = params.addDisjunctiveFacet(attributeName);
if (min !== undefined) {
params = params.addNumericRefinement(attributeName, '>=', min);
}
if (max !== undefined) {
params = params.addNumericRefinement(attributeName, '<=', max);
}
return params;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var _currentRange = this._currentRange,
minRange = _currentRange.min,
maxRange = _currentRange.max;
var _getCurrentRefinement3 = getCurrentRefinement$6(props, searchState, this._currentRange, this.context),
minValue = _getCurrentRefinement3.min,
maxValue = _getCurrentRefinement3.max;
var items = [];
var hasMin = minValue !== undefined;
var hasMax = maxValue !== undefined;
var shouldDisplayMinLabel = hasMin && minValue !== minRange;
var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange;
if (shouldDisplayMinLabel || shouldDisplayMaxLabel) {
var fragments = [hasMin ? minValue + ' <= ' : '', props.attributeName, hasMax ? ' <= ' + maxValue : ''];
items.push({
label: fragments.join(''),
attributeName: props.attributeName,
value: function value(nextState) {
return _refine$4(props, nextState, {}, _this._currentRange, _this.context);
},
currentRefinement: {
min: minValue,
max: maxValue
}
});
}
return {
id: getId$7(props),
index: getIndex(this.context),
items: items
};
}
});
var cx$13 = classNames('RangeInput');
var RawRangeInput = function (_Component) {
inherits(RawRangeInput, _Component);
function RawRangeInput(props) {
classCallCheck(this, RawRangeInput);
var _this = possibleConstructorReturn(this, (RawRangeInput.__proto__ || Object.getPrototypeOf(RawRangeInput)).call(this, props));
_this.onSubmit = function (e) {
e.preventDefault();
_this.props.refine({
min: _this.state.from,
max: _this.state.to
});
};
_this.state = _this.normalizeStateForRendering(props);
return _this;
}
createClass(RawRangeInput, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) {
this.context.canRefine(this.props.canRefine);
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
// In react@16.0.0 the call to setState on the inputs trigger this lifecycle hook
// because the context has changed (for react). I don't think that the bug is related
// to react because I failed to reproduce it with a simple hierarchy of components.
// The workaround here is to check the differences between previous & next props in order
// to avoid to override current state when values are not yet refined. In the react documentation,
// they DON'T categorically say that setState never run componentWillReceiveProps.
// see: https://reactjs.org/docs/react-component.html#componentwillreceiveprops
if (nextProps.canRefine && (this.props.canRefine !== nextProps.canRefine || this.props.currentRefinement.min !== nextProps.currentRefinement.min || this.props.currentRefinement.max !== nextProps.currentRefinement.max)) {
this.setState(this.normalizeStateForRendering(nextProps));
}
if (this.context.canRefine && this.props.canRefine !== nextProps.canRefine) {
this.context.canRefine(nextProps.canRefine);
}
}
}, {
key: 'normalizeStateForRendering',
value: function normalizeStateForRendering(props) {
var canRefine = props.canRefine,
rangeMin = props.min,
rangeMax = props.max;
var _props$currentRefinem = props.currentRefinement,
valueMin = _props$currentRefinem.min,
valueMax = _props$currentRefinem.max;
return {
from: canRefine && valueMin !== undefined && valueMin !== rangeMin ? valueMin : '',
to: canRefine && valueMax !== undefined && valueMax !== rangeMax ? valueMax : ''
};
}
}, {
key: 'normalizeRangeForRendering',
value: function normalizeRangeForRendering(_ref) {
var canRefine = _ref.canRefine,
min = _ref.min,
max = _ref.max;
var hasMin = min !== undefined;
var hasMax = max !== undefined;
return {
min: canRefine && hasMin && hasMax ? min : '',
max: canRefine && hasMin && hasMax ? max : ''
};
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _state = this.state,
from = _state.from,
to = _state.to;
var _props = this.props,
precision = _props.precision,
translate = _props.translate,
canRefine = _props.canRefine;
var _normalizeRangeForRen = this.normalizeRangeForRendering(this.props),
min = _normalizeRangeForRen.min,
max = _normalizeRangeForRen.max;
var step = 1 / Math.pow(10, precision);
return React__default.createElement(
'form',
_extends({}, cx$13('root', !canRefine && 'noRefinement'), {
onSubmit: this.onSubmit
}),
React__default.createElement(
'fieldset',
_extends({ disabled: !canRefine }, cx$13('fieldset')),
React__default.createElement(
'label',
cx$13('labelMin'),
React__default.createElement('input', _extends({}, cx$13('inputMin'), {
type: 'number',
min: min,
max: max,
value: from,
step: step,
placeholder: min,
onChange: function onChange(e) {
return _this2.setState({ from: e.currentTarget.value });
}
}))
),
React__default.createElement(
'span',
cx$13('separator'),
translate('separator')
),
React__default.createElement(
'label',
cx$13('labelMax'),
React__default.createElement('input', _extends({}, cx$13('inputMax'), {
type: 'number',
min: min,
max: max,
value: to,
step: step,
placeholder: max,
onChange: function onChange(e) {
return _this2.setState({ to: e.currentTarget.value });
}
}))
),
React__default.createElement(
'button',
_extends({}, cx$13('submit'), { type: 'submit' }),
translate('submit')
)
)
);
}
}]);
return RawRangeInput;
}(React.Component);
RawRangeInput.propTypes = {
canRefine: propTypes.bool.isRequired,
precision: propTypes.number.isRequired,
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
min: propTypes.number,
max: propTypes.number,
currentRefinement: propTypes.shape({
min: propTypes.number,
max: propTypes.number
})
};
RawRangeInput.defaultProps = {
currentRefinement: {}
};
RawRangeInput.contextTypes = {
canRefine: propTypes.func
};
var RangeInputComponent = translatable({
submit: 'ok',
separator: 'to'
})(RawRangeInput);
/**
* RangeInput allows a user to select a numeric range using a minimum and maximum input.
* @name RangeInput
* @kind widget
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @propType {string} attributeName - the name of the attribute in the record
* @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [precision=2] - Number of digits after decimal point to use.
* @themeKey ais-RangeInput__root - The root component of the widget
* @themeKey ais-RangeInput__labelMin - The label for the min input
* @themeKey ais-RangeInput__inputMin - The min input
* @themeKey ais-RangeInput__separator - The separator between input
* @themeKey ais-RangeInput__labelMax - The label for the max input
* @themeKey ais-RangeInput__inputMax - The max input
* @themeKey ais-RangeInput__submit - The submit button
* @themeKey ais-RangeInput__noRefinement - present when there is no refinement
* @translationKey submit - Label value for the submit button
* @translationKey separator - Label value for the input separator
* @example
* import React from 'react';
*
* import { RangeInput, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <RangeInput attributeName="price"/>
* </InstantSearch>
* );
* }
*/
var RangeInput = connectRange(RangeInputComponent);
/**
* Since a lot of sliders already exist, we did not include one by default.
* However you can easily connect React InstantSearch to an existing one
* using the [connectRange connector](connectors/connectRange.html).
*
* @name RangeSlider
* @requirements To connect any slider to Algolia, the underlying attribute used must be holding numerical values.
* @kind widget
* @example
*
* // Here's an example showing how to connect the airbnb rheostat slider to React InstantSearch using the
* // range connector
import PropTypes from 'prop-types';
import React, {Component} from 'react';
import {connectRange} from 'react-instantsearch/connectors';
import Rheostat from 'rheostat';
class Range extends React.Component {
static propTypes = {
min: PropTypes.number,
max: PropTypes.number,
currentRefinement: PropTypes.object,
refine: PropTypes.func.isRequired,
canRefine: PropTypes.bool.isRequired,
};
state = {currentValues: {min: this.props.min, max: this.props.max}};
componentWillReceiveProps(sliderState) {
if (sliderState.canRefine) {
this.setState({currentValues: {min: sliderState.currentRefinement.min, max: sliderState.currentRefinement.max}});
}
}
onValuesUpdated = (sliderState) => {
this.setState({currentValues: {min: sliderState.values[0], max: sliderState.values[1]}});
};
onChange = (sliderState) => {
if (this.props.currentRefinement.min !== sliderState.values[0] ||
this.props.currentRefinement.max !== sliderState.values[1]) {
this.props.refine({min: sliderState.values[0], max: sliderState.values[1]});
}
};
render() {
const {min, max, currentRefinement} = this.props;
const {currentValues} = this.state;
return min !== max ?
<div>
<Rheostat
min={min}
max={max}
values={[currentRefinement.min, currentRefinement.max]}
onChange={this.onChange}
onValuesUpdated={this.onValuesUpdated}
/>
<div style={{display: 'flex', justifyContent: 'space-between'}}>
<div>{currentValues.min}</div>
<div>{currentValues.max}</div>
</div>
</div> : null;
}
}
const ConnectedRange = connectRange(Range);
*/
var RangeSlider = connectRange(function () {
return React__default.createElement(
'div',
null,
'We do not provide any Slider, see the documentation to learn how to connect one easily:',
React__default.createElement(
'a',
{
target: '_blank',
rel: 'noopener noreferrer',
href: 'https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html'
},
'https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html'
)
);
});
var cx$14 = classNames('StarRating');
var StarRating$1 = function (_Component) {
inherits(StarRating, _Component);
function StarRating() {
classCallCheck(this, StarRating);
return possibleConstructorReturn(this, (StarRating.__proto__ || Object.getPrototypeOf(StarRating)).apply(this, arguments));
}
createClass(StarRating, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'onClick',
value: function onClick(min, max, e) {
e.preventDefault();
e.stopPropagation();
if (min === this.props.currentRefinement.min && max === this.props.currentRefinement.max) {
this.props.refine({ min: this.props.min, max: this.props.max });
} else {
this.props.refine({ min: min, max: max });
}
}
}, {
key: 'buildItem',
value: function buildItem(_ref) {
var max = _ref.max,
lowerBound = _ref.lowerBound,
count = _ref.count,
translate = _ref.translate,
createURL = _ref.createURL,
isLastSelectableItem = _ref.isLastSelectableItem;
var disabled = !count;
var isCurrentMinLower = this.props.currentRefinement.min < lowerBound;
var selected = isLastSelectableItem && isCurrentMinLower || !disabled && lowerBound === this.props.currentRefinement.min && max === this.props.currentRefinement.max;
var icons = [];
for (var icon = 0; icon < max; icon++) {
var iconTheme = icon >= lowerBound ? 'ratingIconEmpty' : 'ratingIcon';
icons.push(React__default.createElement('span', _extends({
key: icon
}, cx$14(iconTheme, selected && iconTheme + 'Selected', disabled && iconTheme + 'Disabled'))));
}
// The last item of the list (the default item), should not
// be clickable if it is selected.
var isLastAndSelect = isLastSelectableItem && selected;
var StarsWrapper = isLastAndSelect ? 'div' : 'a';
var onClickHandler = isLastAndSelect ? {} : {
href: createURL({ min: lowerBound, max: max }),
onClick: this.onClick.bind(this, lowerBound, max)
};
return React__default.createElement(
StarsWrapper,
_extends({}, cx$14('ratingLink', selected && 'ratingLinkSelected', disabled && 'ratingLinkDisabled'), {
disabled: disabled,
key: lowerBound
}, onClickHandler),
icons,
React__default.createElement(
'span',
cx$14('ratingLabel', selected && 'ratingLabelSelected', disabled && 'ratingLabelDisabled'),
translate('ratingLabel')
),
React__default.createElement(
'span',
null,
' '
),
React__default.createElement(
'span',
cx$14('ratingCount', selected && 'ratingCountSelected', disabled && 'ratingCountDisabled'),
count
)
);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props,
translate = _props.translate,
refine = _props.refine,
min = _props.min,
max = _props.max,
count = _props.count,
createURL = _props.createURL,
canRefine = _props.canRefine;
var items = [];
var _loop = function _loop(i) {
var hasCount = !isEmpty_1(count.filter(function (item) {
return Number(item.value) === i;
}));
var lastSelectableItem = count.reduce(function (acc, item) {
return item.value < acc.value || !acc.value && hasCount ? item : acc;
}, {});
var itemCount = count.reduce(function (acc, item) {
return item.value >= i && hasCount ? acc + item.count : acc;
}, 0);
items.push(_this2.buildItem({
lowerBound: i,
max: max,
refine: refine,
count: itemCount,
translate: translate,
createURL: createURL,
isLastSelectableItem: i === Number(lastSelectableItem.value)
}));
};
for (var i = max; i >= min; i--) {
_loop(i);
}
return React__default.createElement(
'div',
cx$14('root', !canRefine && 'noRefinement'),
items
);
}
}]);
return StarRating;
}(React.Component);
StarRating$1.propTypes = {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
min: propTypes.number,
max: propTypes.number,
currentRefinement: propTypes.shape({
min: propTypes.number,
max: propTypes.number
}),
count: propTypes.arrayOf(propTypes.shape({
value: propTypes.string,
count: propTypes.number
})),
canRefine: propTypes.bool.isRequired
};
StarRating$1.contextTypes = {
canRefine: propTypes.func
};
var StarRatingComponent = translatable({
ratingLabel: ' & Up'
})(StarRating$1);
/**
* StarRating lets the user refine search results by clicking on stars.
*
* The stars are based on the selected `attributeName`.
* @requirements The attribute passed to the `attributeName` prop must be holding numerical values.
* @name StarRating
* @kind widget
* @propType {string} attributeName - the name of the attribute in the record
* @propType {number} [min] - Minimum value for the rating. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value for the rating. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the lower bound (end) and the max for the rating.
* @themeKey ais-StarRating__root - The root component of the widget
* @themeKey ais-StarRating__ratingLink - The item link
* @themeKey ais-StarRating__ratingLinkSelected - The selected link item
* @themeKey ais-StarRating__ratingLinkDisabled - The disabled link item
* @themeKey ais-StarRating__ratingIcon - The rating icon
* @themeKey ais-StarRating__ratingIconSelected - The selected rating icon
* @themeKey ais-StarRating__ratingIconDisabled - The disabled rating icon
* @themeKey ais-StarRating__ratingIconEmpty - The rating empty icon
* @themeKey ais-StarRating__ratingIconEmptySelected - The selected rating empty icon
* @themeKey ais-StarRating__ratingIconEmptyDisabled - The disabled rating empty icon
* @themeKey ais-StarRating__ratingLabel - The link label
* @themeKey ais-StarRating__ratingLabelSelected - The selected link label
* @themeKey ais-StarRating__ratingLabelDisabled - The disabled link label
* @themeKey ais-StarRating__ratingCount - The link count
* @themeKey ais-StarRating__ratingCountSelected - The selected link count
* @themeKey ais-StarRating__ratingCountDisabled - The disabled link count
* @themeKey ais-StarRating__noRefinement - present when there is no refinement
* @translationKey ratingLabel - Label value for the rating link
* @example
* import React from 'react';
*
* import { StarRating, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <StarRating attributeName="rating" />
* </InstantSearch>
* );
* }
*/
var StarRating = connectRange(StarRatingComponent);
var namespace$4 = 'refinementList';
function getId$8(props) {
return props.attributeName;
}
function getCurrentRefinement$7(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, namespace$4 + '.' + getId$8(props), [], function (currentRefinement) {
if (typeof currentRefinement === 'string') {
// All items were unselected
if (currentRefinement === '') {
return [];
}
// Only one item was in the searchState but we know it should be an array
return [currentRefinement];
}
return currentRefinement;
});
}
function getValue$4(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement$7(props, searchState, context);
var isAnewValue = currentRefinement.indexOf(name) === -1;
var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates
: currentRefinement.filter(function (selectedValue) {
return selectedValue !== name;
}); // cannot use .splice(), it mutates
return nextRefinement;
}
function _refine$5(props, searchState, nextRefinement, context) {
var id = getId$8(props);
// Setting the value to an empty string ensures that it is persisted in
// the URL as an empty value.
// This is necessary in the case where `defaultRefinement` contains one
// item and we try to deselect it. `nextSelected` would be an empty array,
// which would not be persisted to the URL.
// {foo: ['bar']} => "foo[0]=bar"
// {foo: []} => ""
var nextValue = defineProperty$2({}, id, nextRefinement.length > 0 ? nextRefinement : '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$4);
}
function _cleanUp$4(props, searchState, context) {
return cleanUpValue(searchState, context, namespace$4 + '.' + getId$8(props));
}
/**
* connectRefinementList connector provides the logic to build a widget that will
* give the user the ability to choose multiple values for a specific facet.
* @name connectRefinementList
* @kind connector
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [withSearchBox=false] - allow search inside values
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of displayed items
* @propType {number} [limitMax=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
var sortBy$2 = ['isRefined', 'count:desc', 'name:asc'];
var connectRefinementList = createConnector({
displayName: 'AlgoliaRefinementList',
propTypes: {
id: propTypes.string,
attributeName: propTypes.string.isRequired,
operator: propTypes.oneOf(['and', 'or']),
showMore: propTypes.bool,
limitMin: propTypes.number,
limitMax: propTypes.number,
defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])),
withSearchBox: propTypes.bool,
searchForFacetValues: propTypes.bool, // @deprecated
transformItems: propTypes.func
},
defaultProps: {
operator: 'or',
showMore: false,
limitMin: 10,
limitMax: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) {
var _this = this;
var attributeName = props.attributeName,
showMore = props.showMore,
limitMin = props.limitMin,
limitMax = props.limitMax;
var limit = showMore ? limitMax : limitMin;
var results = getResults(searchResults, this.context);
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attributeName));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attributeName] && searchForFacetValuesResults.query !== '');
var withSearchBox = props.withSearchBox || props.searchForFacetValues;
if (props.withSearchBox && this.context.multiIndexContext) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement$7(props, searchState, this.context),
canRefine: canRefine,
isFromSearch: isFromSearch,
withSearchBox: withSearchBox
};
}
var items = isFromSearch ? searchForFacetValuesResults[attributeName].map(function (v) {
return {
label: v.value,
value: getValue$4(v.value, props, searchState, _this.context),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attributeName, { sortBy: sortBy$2 }).map(function (v) {
return {
label: v.name,
value: getValue$4(v.name, props, searchState, _this.context),
count: v.count,
isRefined: v.isRefined
};
});
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, limit),
currentRefinement: getCurrentRefinement$7(props, searchState, this.context),
isFromSearch: isFromSearch,
withSearchBox: withSearchBox,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$5(props, searchState, nextRefinement, this.context);
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return { facetName: props.attributeName, query: nextRefinement };
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$4(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$7(props, searchState, this.context).reduce(function (res, val) {
return res[addRefinementKey](attributeName, val);
}, searchParameters);
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$8(props);
var context = this.context;
return {
id: id,
index: getIndex(this.context),
items: getCurrentRefinement$7(props, searchState, context).length > 0 ? [{
attributeName: props.attributeName,
label: props.attributeName + ': ',
currentRefinement: getCurrentRefinement$7(props, searchState, context),
value: function value(nextState) {
return _refine$5(props, nextState, [], context);
},
items: getCurrentRefinement$7(props, searchState, context).map(function (item) {
return {
label: '' + item,
value: function value(nextState) {
var nextSelectedItems = getCurrentRefinement$7(props, nextState, context).filter(function (other) {
return other !== item;
});
return _refine$5(props, searchState, nextSelectedItems, context);
}
};
})
}] : []
};
}
});
var cx$15 = classNames('RefinementList');
var RefinementList$4 = function (_Component) {
inherits(RefinementList, _Component);
function RefinementList(props) {
classCallCheck(this, RefinementList);
var _this = possibleConstructorReturn(this, (RefinementList.__proto__ || Object.getPrototypeOf(RefinementList)).call(this, props));
_this.selectItem = function (item, resetQuery) {
resetQuery();
_this.props.refine(item.value);
};
_this.renderItem = function (item, resetQuery) {
var label = _this.props.isFromSearch ? React__default.createElement(Highlight, { attributeName: 'label', hit: item }) : item.label;
return React__default.createElement(
'label',
null,
React__default.createElement('input', _extends({}, cx$15('itemCheckbox', item.isRefined && 'itemCheckboxSelected'), {
type: 'checkbox',
checked: item.isRefined,
onChange: function onChange() {
return _this.selectItem(item, resetQuery);
}
})),
React__default.createElement('span', cx$15('itemBox', 'itemBox', item.isRefined && 'itemBoxSelected')),
React__default.createElement(
'span',
cx$15('itemLabel', 'itemLabel', item.isRefined && 'itemLabelSelected'),
label
),
' ',
React__default.createElement(
'span',
cx$15('itemCount', item.isRefined && 'itemCountSelected'),
item.count.toLocaleString()
)
);
};
_this.state = { query: '' };
return _this;
}
createClass(RefinementList, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
return React__default.createElement(
'div',
null,
React__default.createElement(List, _extends({
renderItem: this.renderItem,
selectItem: this.selectItem,
cx: cx$15
}, pick_1(this.props, ['translate', 'items', 'showMore', 'limitMin', 'limitMax', 'isFromSearch', 'searchForItems', 'withSearchBox', 'canRefine']), {
query: this.state.query
}))
);
}
}]);
return RefinementList;
}(React.Component);
RefinementList$4.propTypes = {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
searchForItems: propTypes.func.isRequired,
withSearchBox: propTypes.bool,
createURL: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.arrayOf(propTypes.string).isRequired,
count: propTypes.number.isRequired,
isRefined: propTypes.bool.isRequired
})),
isFromSearch: propTypes.bool.isRequired,
canRefine: propTypes.bool.isRequired,
showMore: propTypes.bool,
limitMin: propTypes.number,
limitMax: propTypes.number,
transformItems: propTypes.func
};
RefinementList$4.contextTypes = {
canRefine: propTypes.func
};
var RefinementListComponent = translatable({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
},
noResults: 'No results',
submit: null,
reset: null,
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(RefinementList$4);
/**
* The RefinementList component displays a list that let the end user choose multiple values for a specific facet.
* @name RefinementList
* @kind widget
* @propType {string} attributeName - the name of the attribute in the record
* @propType {boolean} [withSearchBox=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/).
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limitMin=10] - the minimum number of displayed items
* @propType {number} [limitMax=20] - the maximum number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} [defaultRefinement] - the values of the items selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-RefinementList__root - the root of the component
* @themeKey ais-RefinementList__items - the container of all items in the list
* @themeKey ais-RefinementList__itemSelected - the selected list item
* @themeKey ais-RefinementList__itemCheckbox - the item checkbox
* @themeKey ais-RefinementList__itemCheckboxSelected - the selected item checkbox
* @themeKey ais-RefinementList__itemLabel - the item label
* @themeKey ais-RefinementList__itemLabelSelected - the selected item label
* @themeKey ais-RefinementList__itemCount - the item count
* @themeKey ais-RefinementList__itemCountSelected - the selected item count
* @themeKey ais-RefinementList__showMore - the button that let the user toggle more results
* @themeKey ais-RefinementList__noRefinement - present when there is no refinement
* @themeKey ais-RefinementList__SearchBox - the container of the search for facet values searchbox. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded
* @translationkey noResults - The label of the no results text when no search for facet values results are found.
* @requirements The attribute passed to the `attributeName` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* If you are using the `withSearchBox` prop, you'll also need to make the attribute searchable using
* the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values).
* @example
* import React from 'react';
*
* import { RefinementList, InstantSearch } from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <RefinementList attributeName="colors" />
* </InstantSearch>
* );
* }
*/
var RefinementList$3 = connectRefinementList(RefinementListComponent);
var cx$16 = classNames('ClearAll');
var ClearAll$1 = function (_Component) {
inherits(ClearAll, _Component);
function ClearAll() {
classCallCheck(this, ClearAll);
return possibleConstructorReturn(this, (ClearAll.__proto__ || Object.getPrototypeOf(ClearAll)).apply(this, arguments));
}
createClass(ClearAll, [{
key: 'render',
value: function render() {
var _props = this.props,
translate = _props.translate,
items = _props.items,
refine = _props.refine;
var isDisabled = items.length === 0;
if (isDisabled) {
return React__default.createElement(
'button',
_extends({}, cx$16('root'), { disabled: true }),
translate('reset')
);
}
return React__default.createElement(
'button',
_extends({}, cx$16('root'), { onClick: function onClick() {
return refine(items);
} }),
translate('reset')
);
}
}]);
return ClearAll;
}(React.Component);
ClearAll$1.propTypes = {
translate: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.object).isRequired,
refine: propTypes.func.isRequired
};
var ClearAllComponent = translatable({
reset: 'Clear all filters'
})(ClearAll$1);
/**
* The ClearAll widget displays a button that lets the user clean every refinement applied
* to the search.
* @name ClearAll
* @kind widget
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {boolean} [clearsQuery=false] - Pass true to also clear the search query
* @themeKey ais-ClearAll__root - the widget button
* @translationKey reset - the clear all button value
* @example
* import React from 'react';
*
* import { ClearAll, RefinementList, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <ClearAll />
* <RefinementList
attributeName="colors"
defaultRefinement={['Black']}
/>
* </InstantSearch>
* );
* }
*/
var ClearAll = connectCurrentRefinements(ClearAllComponent);
/**
* connectScrollTo connector provides the logic to build a widget that will
* let the page scroll to a certain point.
* @name connectScrollTo
* @kind connector
* @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget.
* @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo
* @providedPropType {boolean} hasNotChanged - indicates whether the refinement came from the scrollOn argument (for instance page by default)
*/
var connectScrollTo = createConnector({
displayName: 'AlgoliaScrollTo',
propTypes: {
scrollOn: propTypes.string
},
defaultProps: {
scrollOn: 'page'
},
getProvidedProps: function getProvidedProps(props, searchState) {
var id = props.scrollOn;
var value = getCurrentRefinementValue(props, searchState, this.context, id, null, function (currentRefinement) {
return currentRefinement;
});
if (!this._prevSearchState) {
this._prevSearchState = {};
}
/* Get the subpart of the state that interest us*/
if (hasMultipleIndex(this.context)) {
var index = getIndex(this.context);
searchState = searchState.indices ? searchState.indices[index] : {};
}
/*
if there is a change in the app that has been triggered by another element than
"props.scrollOn (id) or the Configure widget, we need to keep track of the search state to
know if there's a change in the app that was not triggered by the props.scrollOn (id)
or the Configure widget. This is useful when using ScrollTo in combination of Pagination.
As pagination can be change by every widget, we want to scroll only if it cames from the pagination
widget itself. We also remove the configure key from the search state to do this comparaison because for
now configure values are not present in the search state before a first refinement has been made
and will false the results.
See: https://github.com/algolia/react-instantsearch/issues/164
*/
var cleanedSearchState = omit_1(omit_1(searchState, 'configure'), id);
var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState);
this._prevSearchState = cleanedSearchState;
return { value: value, hasNotChanged: hasNotChanged };
}
});
var cx$17 = classNames('ScrollTo');
var ScrollTo$1 = function (_Component) {
inherits(ScrollTo, _Component);
function ScrollTo() {
classCallCheck(this, ScrollTo);
return possibleConstructorReturn(this, (ScrollTo.__proto__ || Object.getPrototypeOf(ScrollTo)).apply(this, arguments));
}
createClass(ScrollTo, [{
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
var _props = this.props,
value = _props.value,
hasNotChanged = _props.hasNotChanged;
if (value !== prevProps.value && hasNotChanged) {
this.el.scrollIntoView();
}
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
return React__default.createElement(
'div',
_extends({ ref: function ref(_ref) {
return _this2.el = _ref;
} }, cx$17('root')),
this.props.children
);
}
}]);
return ScrollTo;
}(React.Component);
ScrollTo$1.propTypes = {
value: propTypes.any,
children: propTypes.node,
hasNotChanged: propTypes.bool
};
/**
* The ScrollTo component will make the page scroll to the component wrapped by it when one of the
* [search state](guide/Search_state.html) prop is updated. By default when the page number changes,
* the scroll goes to the wrapped component.
*
* @name ScrollTo
* @kind widget
* @propType {string} [scrollOn="page"] - Widget state key on which to listen for changes.
* @example
* import React from 'react';
*
* import { ScrollTo, Hits, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <ScrollTo>
* <Hits />
* </ScrollTo>
* </InstantSearch>
* );
* }
*/
var ScrollTo = connectScrollTo(ScrollTo$1);
function getId$9() {
return 'query';
}
function getCurrentRefinement$8(props, searchState, context) {
var id = getId$9(props);
return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return '';
});
}
function _refine$6(props, searchState, nextRefinement, context) {
var id = getId$9();
var nextValue = defineProperty$2({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage);
}
function _cleanUp$5(props, searchState, context) {
return cleanUpValue(searchState, context, getId$9());
}
/**
* 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.
* @providedPropType {boolean} isSearchStalled - a flag that indicates if react-is has detected that searches are stalled.
*/
var connectSearchBox = createConnector({
displayName: 'AlgoliaSearchBox',
propTypes: {
defaultRefinement: propTypes.string
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
return {
currentRefinement: getCurrentRefinement$8(props, searchState, this.context),
isSearchStalled: searchResults.isSearchStalled
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$6(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$5(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement$8(props, searchState, this.context));
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId$9(props);
var currentRefinement = getCurrentRefinement$8(props, searchState, this.context);
return {
id: id,
index: getIndex(this.context),
items: currentRefinement === null ? [] : [{
label: id + ': ' + currentRefinement,
value: function value(nextState) {
return _refine$6(props, nextState, '', _this.context);
},
currentRefinement: currentRefinement
}]
};
}
});
/**
* The SearchBox component displays a search box that lets the user search for a specific query.
* @name SearchBox
* @kind widget
* @propType {string[]} [focusShortcuts=['s','/']] - List of keyboard shortcuts that focus the search box. Accepts key names and key codes.
* @propType {boolean} [autoFocus=false] - Should the search box be focused on render?
* @propType {boolean} [searchAsYouType=true] - Should we search on every change to the query? If you disable this option, new searches will only be triggered by clicking the search button or by pressing the enter key while the search box is focused.
* @propType {function} [onSubmit] - Intercept submit event sent from the SearchBox form container.
* @propType {function} [onReset] - Listen to `reset` event sent from the SearchBox form container.
* @propType {function} [on*] - Listen to any events sent form the search input itself.
* @propType {React.Element} [submitComponent] - Change the apparence of the default submit button (magnifying glass).
* @propType {React.Element} [resetComponent] - Change the apparence of the default reset button (cross).
* @propType {React.Element} [loadingIndicatorComponent] - Change the apparence of the default loading indicator (spinning circle).
* @propType {string} [defaultRefinement] - Provide default refinement value when component is mounted.
* @propType {boolean} [showLoadingIndicator=false] - Display that the search is loading. This only happens after a certain amount of time to avoid a blinking effect. This timer can be configured with `stalledSearchDelay` props on <InstantSearch>. By default, the value is 200ms.
* @themeKey ais-SearchBox__root - the root of the component
* @themeKey ais-SearchBox__wrapper - the search box wrapper
* @themeKey ais-SearchBox__input - the search box input
* @themeKey ais-SearchBox__submit - the submit button
* @themeKey ais-SearchBox__reset - the reset button
* @themeKey ais-SearchBox__loading-indicator - the loading indicator
* @translationkey submitTitle - The submit button title
* @translationkey resetTitle - The reset button title
* @translationkey placeholder - The label of the input placeholder
* @example
* import React from 'react';
*
* import { SearchBox, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SearchBox />
* </InstantSearch>
* );
* }
*/
var SearchBox$1 = connectSearchBox(SearchBoxComponent);
function getId$10() {
return 'sortBy';
}
function getCurrentRefinement$9(props, searchState, context) {
var id = getId$10(props);
return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return null;
});
}
/**
* The connectSortBy connector provides the logic to build a widget that will
* display a list of indices. This allows a user to change how the hits are being sorted.
* @name connectSortBy
* @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on
* the Algolia website.
* @kind connector
* @propType {string} defaultRefinement - The default selected index.
* @propType {{value: string, label: string}[]} items - The list of indexes to search in.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
var connectSortBy = createConnector({
displayName: 'AlgoliaSortBy',
propTypes: {
defaultRefinement: propTypes.string,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string,
value: propTypes.string.isRequired
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement$9(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$10();
var nextValue = defineProperty$2({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, this.context, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, this.context, getId$10());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var selectedIndex = getCurrentRefinement$9(props, searchState, this.context);
return searchParameters.setIndex(selectedIndex);
},
getMetadata: function getMetadata() {
return { id: getId$10() };
}
});
var cx$18 = classNames('SortBy');
var SortBy$1 = function (_Component) {
inherits(SortBy, _Component);
function SortBy() {
classCallCheck(this, SortBy);
return possibleConstructorReturn(this, (SortBy.__proto__ || Object.getPrototypeOf(SortBy)).apply(this, arguments));
}
createClass(SortBy, [{
key: 'render',
value: function render() {
var _props = this.props,
refine = _props.refine,
items = _props.items,
currentRefinement = _props.currentRefinement;
return React__default.createElement(Select, {
cx: cx$18,
selectedItem: currentRefinement,
onSelect: refine,
items: items
});
}
}]);
return SortBy;
}(React.Component);
SortBy$1.propTypes = {
refine: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string,
value: propTypes.string.isRequired
})).isRequired,
currentRefinement: propTypes.string.isRequired,
transformItems: propTypes.func
};
/**
* The SortBy component displays a list of indexes allowing a user to change the hits are sorting.
* @name SortBy
* @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on
* the Algolia website.
* @kind widget
* @propType {{value: string, label: string}[]} items - The list of indexes to search in.
* @propType {string} defaultRefinement - The default selected index.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-SortBy__root - the root of the component
* @example
* import React from 'react';
*
* import { SortBy, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SortBy
* items={[
* { value: 'ikea', label: 'Featured' },
* { value: 'ikea_price_asc', label: 'Price asc.' },
* { value: 'ikea_price_desc', label: 'Price desc.' },
* ]}
* defaultRefinement="ikea"
* />
* </InstantSearch>
* );
* }
*/
var SortBy = connectSortBy(SortBy$1);
/**
* connectStats connector provides the logic to build a widget that will
* displays algolia search statistics (hits number and processing time).
* @name connectStats
* @kind connector
* @providedPropType {number} nbHits - number of hits returned by Algolia.
* @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results.
*/
var connectStats = createConnector({
displayName: 'AlgoliaStats',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, this.context);
if (!results) {
return null;
}
return {
nbHits: results.nbHits,
processingTimeMS: results.processingTimeMS
};
}
});
var cx$19 = classNames('Stats');
var Stats$1 = function (_Component) {
inherits(Stats, _Component);
function Stats() {
classCallCheck(this, Stats);
return possibleConstructorReturn(this, (Stats.__proto__ || Object.getPrototypeOf(Stats)).apply(this, arguments));
}
createClass(Stats, [{
key: 'render',
value: function render() {
var _props = this.props,
translate = _props.translate,
nbHits = _props.nbHits,
processingTimeMS = _props.processingTimeMS;
return React__default.createElement(
'span',
cx$19('root'),
translate('stats', nbHits, processingTimeMS)
);
}
}]);
return Stats;
}(React.Component);
Stats$1.propTypes = {
translate: propTypes.func.isRequired,
nbHits: propTypes.number.isRequired,
processingTimeMS: propTypes.number.isRequired
};
var StatsComponent = translatable({
stats: function stats(n, ms) {
return n.toLocaleString() + ' results found in ' + ms.toLocaleString() + 'ms';
}
})(Stats$1);
/**
* The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server).
* @name Stats
* @kind widget
* @themeKey ais-Stats__root - the root of the component
* @translationkey stats - The string displayed by the stats widget. You get function(n, ms) and you need to return a string. n is a number of hits retrieved, ms is a processed time.
* @example
* import React from 'react';
*
* import { Stats, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Stats />
* </InstantSearch>
* );
* }
*/
var Stats = connectStats(StatsComponent);
function getId$11(props) {
return props.attributeName;
}
var namespace$5 = 'toggle';
function getCurrentRefinement$10(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, namespace$5 + '.' + getId$11(props), false, function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return false;
});
}
function _refine$7(props, searchState, nextRefinement, context) {
var id = getId$11(props);
var nextValue = defineProperty$2({}, id, nextRefinement ? nextRefinement : false);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$5);
}
function _cleanUp$6(props, searchState, context) {
return cleanUpValue(searchState, context, namespace$5 + '.' + getId$11(props));
}
/**
* connectToggle connector provides the logic to build a widget that will
* provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization.
* @name connectToggle
* @kind connector
* @requirements To use this widget, you'll need an attribute to toggle on.
*
* You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an
* extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details.
*
* @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {string} value - Value of the refinement to apply on `attributeName`.
* @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default?
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {boolean} currentRefinement - the refinement currently applied
*/
var connectToggle = createConnector({
displayName: 'AlgoliaToggle',
propTypes: {
label: propTypes.string,
filter: propTypes.func,
attributeName: propTypes.string,
value: propTypes.any,
defaultRefinement: propTypes.bool
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement$10(props, searchState, this.context);
return { currentRefinement: currentRefinement };
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$7(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$6(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributeName = props.attributeName,
value = props.value,
filter = props.filter;
var checked = getCurrentRefinement$10(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$11(props);
var checked = getCurrentRefinement$10(props, searchState, this.context);
var items = [];
var index = getIndex(this.context);
if (checked) {
items.push({
label: props.label,
currentRefinement: props.label,
attributeName: props.attributeName,
value: function value(nextState) {
return _refine$7(props, nextState, false, _this.context);
}
});
}
return { id: id, index: index, items: items };
}
});
var cx$20 = classNames('Toggle');
var Toggle$1 = function (_Component) {
inherits(Toggle, _Component);
function Toggle() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, Toggle);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Toggle.__proto__ || Object.getPrototypeOf(Toggle)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) {
_this.props.refine(e.target.checked);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(Toggle, [{
key: 'render',
value: function render() {
var _props = this.props,
currentRefinement = _props.currentRefinement,
label = _props.label;
return React__default.createElement(
'label',
cx$20('root'),
React__default.createElement('input', _extends({}, cx$20('checkbox'), {
type: 'checkbox',
checked: currentRefinement,
onChange: this.onChange
})),
React__default.createElement(
'span',
cx$20('label'),
label
)
);
}
}]);
return Toggle;
}(React.Component);
Toggle$1.propTypes = {
currentRefinement: propTypes.bool.isRequired,
refine: propTypes.func.isRequired,
label: propTypes.string.isRequired
};
/**
* The Toggle provides an on/off filtering feature based on an attribute value. Note that if you provide an “off” option, it will be refined at initialization.
* @name Toggle
* @kind widget
* @requirements To use this widget, you'll need an attribute to toggle on.
*
* You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an
* extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details.
*
* @propType {string} attributeName - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {any} value - Value of the refinement to apply on `attributeName` when checked.
* @propType {boolean} [defaultRefinement=false] - Default state of the widget. Should the toggle be checked by default?
* @themeKey ais-Toggle__root - the root of the component
* @themeKey ais-Toggle__checkbox - the toggle checkbox
* @themeKey ais-Toggle__label - the toggle label
* @example
* import React from 'react';
*
* import { Toggle, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Toggle
* attributeName="materials"
* label="Made with solid pine"
* value={'Solid pine'}
* />
* </InstantSearch>
* );
* }
*/
var Toggle = connectToggle(Toggle$1);
var cx$21 = classNames('Panel');
var Panel$1 = function (_Component) {
inherits(Panel, _Component);
createClass(Panel, [{
key: 'getChildContext',
value: function getChildContext() {
return { canRefine: this.canRefine };
}
}]);
function Panel(props) {
classCallCheck(this, Panel);
var _this = possibleConstructorReturn(this, (Panel.__proto__ || Object.getPrototypeOf(Panel)).call(this, props));
_this.canRefine = function (canRefine) {
_this.setState({ canRefine: canRefine });
};
_this.state = {
canRefine: true
};
return _this;
}
createClass(Panel, [{
key: 'render',
value: function render() {
return React__default.createElement(
'div',
cx$21('root', !this.state.canRefine && 'noRefinement'),
React__default.createElement(
'h5',
cx$21('title'),
this.props.title
),
this.props.children
);
}
}]);
return Panel;
}(React.Component);
Panel$1.propTypes = {
title: propTypes.string.isRequired,
children: propTypes.node
};
Panel$1.childContextTypes = {
canRefine: propTypes.func
};
var getId$12 = function getId(props) {
return props.attributes[0];
};
var namespace$6 = 'hierarchicalMenu';
function _refine$8(props, searchState, nextRefinement, context) {
var id = getId$12(props);
var nextValue = defineProperty$2({}, id, nextRefinement || '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$6);
}
function transformValue$1(values) {
return values.reduce(function (acc, item) {
if (item.isRefined) {
acc.push({
label: item.name,
// If dealing with a nested "items", "value" is equal to the previous value concatenated with the current label
// If dealing with the first level, "value" is equal to the current label
value: item.path
});
// Create a variable in order to keep the same acc for the recursion, otherwise "reduce" returns a new one
if (item.data) {
acc = acc.concat(transformValue$1(item.data, acc));
}
}
return acc;
}, []);
}
/**
* The breadcrumb component is s a type of secondary navigation scheme that
* reveals the user’s location in a website or web application.
*
* @name connectBreadcrumb
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a Breadcrumb of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {string} {React.Element} [separator=' > '] - Specifies the level separator used in the data.
* @propType {string} [rootURL=null] - The root element's URL (the originating page).
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display.
*/
var connectBreadcrumb = createConnector({
displayName: 'AlgoliaBreadcrumb',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings');
}
return undefined;
},
rootURL: propTypes.string,
separator: propTypes.oneOfType([propTypes.string, propTypes.element]),
transformItems: propTypes.func
},
defaultProps: {
rootURL: null,
separator: ' > '
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var id = getId$12(props);
var results = getResults(searchResults, this.context);
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
canRefine: false
};
}
var values = results.getFacetValues(id);
var items = values.data ? transformValue$1(values.data) : [];
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
canRefine: transformedItems.length > 0,
items: transformedItems
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$8(props, searchState, nextRefinement, this.context);
}
});
var cx$22 = classNames('Breadcrumb');
var itemsPropType$2 = propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string.isRequired
}));
var Breadcrumb$1 = function (_Component) {
inherits(Breadcrumb, _Component);
function Breadcrumb() {
classCallCheck(this, Breadcrumb);
return possibleConstructorReturn(this, (Breadcrumb.__proto__ || Object.getPrototypeOf(Breadcrumb)).apply(this, arguments));
}
createClass(Breadcrumb, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.canRefine) this.context.canRefine(this.props.canRefine);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.context.canRefine) this.context.canRefine(props.canRefine);
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
canRefine = _props.canRefine,
createURL = _props.createURL,
items = _props.items,
refine = _props.refine,
rootURL = _props.rootURL,
separator = _props.separator,
translate = _props.translate;
var rootPath = canRefine ? React__default.createElement(
'span',
cx$22('item'),
React__default.createElement(
Link,
_extends({}, cx$22('itemLink', 'itemLinkRoot'), {
onClick: function onClick() {
return !rootURL ? refine() : null;
},
href: rootURL ? rootURL : createURL()
}),
React__default.createElement(
'span',
cx$22('rootLabel'),
translate('rootLabel')
)
),
React__default.createElement(
'span',
cx$22('separator'),
separator
)
) : null;
var breadcrumb = items.map(function (item, idx) {
var isLast = idx === items.length - 1;
return !isLast ? React__default.createElement(
'span',
_extends({}, cx$22('item'), { key: idx }),
React__default.createElement(
Link,
_extends({}, cx$22('itemLink'), {
onClick: function onClick() {
return refine(item.value);
},
href: createURL(item.value),
key: idx
}),
React__default.createElement(
'span',
cx$22('itemLabel'),
item.label
)
),
React__default.createElement(
'span',
cx$22('separator'),
isLast ? '' : separator
)
) : React__default.createElement(
'span',
_extends({}, cx$22('itemLink', 'itemDisabled', 'item'), { key: idx }),
React__default.createElement(
'span',
cx$22('itemLabel'),
item.label
)
);
});
return React__default.createElement(
'div',
cx$22('root', !canRefine && 'noRefinement'),
rootPath,
breadcrumb
);
}
}]);
return Breadcrumb;
}(React.Component);
Breadcrumb$1.propTypes = {
canRefine: propTypes.bool.isRequired,
createURL: propTypes.func.isRequired,
items: itemsPropType$2,
refine: propTypes.func.isRequired,
rootURL: propTypes.string,
separator: propTypes.oneOfType([propTypes.string, propTypes.element]),
translate: propTypes.func.isRequired
};
Breadcrumb$1.contextTypes = {
canRefine: propTypes.func
};
var BreadcrumbComponent = translatable({
rootLabel: 'Home'
})(Breadcrumb$1);
/**
* A breadcrumb is a secondary navigation scheme that allows the user to see where the current page
* is in relation to the website or web application’s hierarchy.
* In terms of usability, using a breadcrumb reduces the number of actions a visitor needs to take in
* order to get to a higher-level page.
*
* If you want to select a specific refinement for your Breadcrumb component, you will need to use a Virtual Hierarchical Menu
* (https://community.algolia.com/react-instantsearch/guide/Virtual_widgets.html) and set its
* defaultRefinement that will be then used by the Breadcrumb.
*
* @name Breadcrumb
* @kind widget
* @requirements Breadcrumbs are used for websites with a large amount of content organised in a hierarchical manner.
* The typical example is an e-commerce website which has a large variety of products grouped into logical categories
* (with categories, subcategories which also have subcategories).To use this widget, your attributes must be formatted in a specific way.
*
* Keep in mind that breadcrumbs shouldn’t replace effective primary navigation menus:
* it is only an alternative way to navigate around the website.
*
* If, for instance, you would like to have a breadcrumb of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @propType {string} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow
* @propType {string} [separator='>'] - Symbol used for separating hyperlinks
* @propType {string} [rootURL=null] - The originating page (homepage)
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return
* @themeKey ais-Breadcrumb__root - The widget container
* @themeKey ais-Breadcrumb__itemLinkRoot - The root link (originating page)
* @themeKey ais-Breadcrumb__rootLabel - The root label
* @themeKey ais-Breadcrumb__item - Contains the link, the label and the separator
* @themeKey ais-Breadcrumb__itemLink - The link containing the label
* @themeKey ais-Breadcrumb__itemLabel - The link's label
* @themeKey ais-Breadcrumb__itemDisabled - For the last item of the breadcrumb which is not clickable
* @themeKey ais-Breadcrumb__separator - The separator
* @themeKey ais-Breadcrumb__noRefinement - present when there is no refinement
* @translationKey rootLabel - The root's label. Accepts a string
* @example
* import React from 'react';
* import { Breadcrumb, InstantSearch } from 'react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Breadcrumb
* attributes={[
* 'category',
* 'sub_category',
* 'sub_sub_category',
* ]}
* rootURL="www.algolia.com"
* separator=" / "
* />
* </InstantSearch>
* );
* }
*/
var Breadcrumb = connectBreadcrumb(BreadcrumbComponent);
var InstantSearch = createInstantSearch(algoliasearchLite, {
Root: 'div',
props: { className: 'ais-InstantSearch__root' }
});
var Index = createIndex({
Root: 'div',
props: { className: 'ais-MultiIndex__root' }
});
exports.InstantSearch = InstantSearch;
exports.Index = Index;
exports.Configure = Configure;
exports.CurrentRefinements = CurrentRefinements;
exports.HierarchicalMenu = HierarchicalMenu;
exports.Highlight = Highlight;
exports.Snippet = Snippet;
exports.Hits = Hits;
exports.HitsPerPage = HitsPerPage;
exports.InfiniteHits = InfiniteHits;
exports.Menu = Menu;
exports.MenuSelect = MenuSelect;
exports.MultiRange = MultiRange;
exports.Pagination = Pagination;
exports.PoweredBy = PoweredBy;
exports.RangeInput = RangeInput;
exports.RangeSlider = RangeSlider;
exports.StarRating = StarRating;
exports.RefinementList = RefinementList$3;
exports.ClearAll = ClearAll;
exports.ScrollTo = ScrollTo;
exports.SearchBox = SearchBox$1;
exports.SortBy = SortBy;
exports.Stats = Stats;
exports.Toggle = Toggle;
exports.Panel = Panel$1;
exports.Breadcrumb = Breadcrumb;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=Dom.js.map
|
ajax/libs/react-native-web/0.13.5/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/react-native-web/0.17.2/exports/ScrollView/index.js | cdnjs/cdnjs | function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import createReactClass from 'create-react-class';
import dismissKeyboard from '../../modules/dismissKeyboard';
import invariant from 'fbjs/lib/invariant';
import mergeRefs from '../../modules/mergeRefs';
import ScrollResponder from '../../modules/ScrollResponder';
import ScrollViewBase from './ScrollViewBase';
import StyleSheet from '../StyleSheet';
import View from '../View';
import React from 'react';
var emptyObject = {};
/* eslint-disable react/prefer-es6-class */
var ScrollView = createReactClass({
displayName: "ScrollView",
mixins: [ScrollResponder.Mixin],
getInitialState: function getInitialState() {
return this.scrollResponderMixinGetInitialState();
},
flashScrollIndicators: function flashScrollIndicators() {
this.scrollResponderFlashScrollIndicators();
},
/**
* Returns a reference to the underlying scroll responder, which supports
* operations like `scrollTo`. All ScrollView-like components should
* implement this method so that they can be composed while providing access
* to the underlying scroll responder's methods.
*/
getScrollResponder: function getScrollResponder() {
return this;
},
getScrollableNode: function getScrollableNode() {
return this._scrollNodeRef;
},
getInnerViewRef: function getInnerViewRef() {
return this._innerViewRef;
},
getInnerViewNode: function getInnerViewNode() {
return this._innerViewRef;
},
getNativeScrollRef: function getNativeScrollRef() {
return this._scrollNodeRef;
},
/**
* Scrolls to a given x, y offset, either immediately or with a smooth animation.
* Syntax:
*
* scrollTo(options: {x: number = 0; y: number = 0; animated: boolean = true})
*
* Note: The weird argument signature is due to the fact that, for historical reasons,
* the function also accepts separate arguments as as alternative to the options object.
* This is deprecated due to ambiguity (y before x), and SHOULD NOT BE USED.
*/
scrollTo: function scrollTo(y, x, animated) {
if (typeof y === 'number') {
console.warn('`scrollTo(y, x, animated)` is deprecated. Use `scrollTo({x: 5, y: 5, animated: true})` instead.');
} else {
var _ref = y || emptyObject;
x = _ref.x;
y = _ref.y;
animated = _ref.animated;
}
this.getScrollResponder().scrollResponderScrollTo({
x: x || 0,
y: y || 0,
animated: animated !== false
});
},
/**
* If this is a vertical ScrollView scrolls to the bottom.
* If this is a horizontal ScrollView scrolls to the right.
*
* Use `scrollToEnd({ animated: true })` for smooth animated scrolling,
* `scrollToEnd({ animated: false })` for immediate scrolling.
* If no options are passed, `animated` defaults to true.
*/
scrollToEnd: function scrollToEnd(options) {
// Default to true
var animated = (options && options.animated) !== false;
var horizontal = this.props.horizontal;
var scrollResponder = this.getScrollResponder();
var scrollResponderNode = scrollResponder.scrollResponderGetScrollableNode();
var x = horizontal ? scrollResponderNode.scrollWidth : 0;
var y = horizontal ? 0 : scrollResponderNode.scrollHeight;
scrollResponder.scrollResponderScrollTo({
x: x,
y: y,
animated: animated
});
},
render: function render() {
var _this$props = this.props,
contentContainerStyle = _this$props.contentContainerStyle,
horizontal = _this$props.horizontal,
onContentSizeChange = _this$props.onContentSizeChange,
refreshControl = _this$props.refreshControl,
stickyHeaderIndices = _this$props.stickyHeaderIndices,
pagingEnabled = _this$props.pagingEnabled,
forwardedRef = _this$props.forwardedRef,
keyboardDismissMode = _this$props.keyboardDismissMode,
onScroll = _this$props.onScroll,
other = _objectWithoutPropertiesLoose(_this$props, ["contentContainerStyle", "horizontal", "onContentSizeChange", "refreshControl", "stickyHeaderIndices", "pagingEnabled", "forwardedRef", "keyboardDismissMode", "onScroll"]);
if (process.env.NODE_ENV !== 'production' && this.props.style) {
var style = StyleSheet.flatten(this.props.style);
var childLayoutProps = ['alignItems', 'justifyContent'].filter(function (prop) {
return style && style[prop] !== undefined;
});
invariant(childLayoutProps.length === 0, "ScrollView child layout (" + JSON.stringify(childLayoutProps) + ") " + 'must be applied through the contentContainerStyle prop.');
}
var contentSizeChangeProps = {};
if (onContentSizeChange) {
contentSizeChangeProps = {
onLayout: this._handleContentOnLayout
};
}
var hasStickyHeaderIndices = !horizontal && Array.isArray(stickyHeaderIndices);
var children = hasStickyHeaderIndices || pagingEnabled ? React.Children.map(this.props.children, function (child, i) {
var isSticky = hasStickyHeaderIndices && stickyHeaderIndices.indexOf(i) > -1;
if (child != null && (isSticky || pagingEnabled)) {
return /*#__PURE__*/React.createElement(View, {
style: StyleSheet.compose(isSticky && styles.stickyHeader, pagingEnabled && styles.pagingEnabledChild)
}, child);
} else {
return child;
}
}) : this.props.children;
var contentContainer = /*#__PURE__*/React.createElement(View, _extends({}, contentSizeChangeProps, {
children: children,
collapsable: false,
ref: this._setInnerViewRef,
style: StyleSheet.compose(horizontal && styles.contentContainerHorizontal, contentContainerStyle)
}));
var baseStyle = horizontal ? styles.baseHorizontal : styles.baseVertical;
var pagingEnabledStyle = horizontal ? styles.pagingEnabledHorizontal : styles.pagingEnabledVertical;
var props = _objectSpread(_objectSpread({}, other), {}, {
style: [baseStyle, pagingEnabled && pagingEnabledStyle, this.props.style],
onTouchStart: this.scrollResponderHandleTouchStart,
onTouchMove: this.scrollResponderHandleTouchMove,
onTouchEnd: this.scrollResponderHandleTouchEnd,
onScrollBeginDrag: this.scrollResponderHandleScrollBeginDrag,
onScrollEndDrag: this.scrollResponderHandleScrollEndDrag,
onMomentumScrollBegin: this.scrollResponderHandleMomentumScrollBegin,
onMomentumScrollEnd: this.scrollResponderHandleMomentumScrollEnd,
onStartShouldSetResponder: this.scrollResponderHandleStartShouldSetResponder,
onStartShouldSetResponderCapture: this.scrollResponderHandleStartShouldSetResponderCapture,
onScrollShouldSetResponder: this.scrollResponderHandleScrollShouldSetResponder,
onScroll: this._handleScroll,
onResponderGrant: this.scrollResponderHandleResponderGrant,
onResponderTerminationRequest: this.scrollResponderHandleTerminationRequest,
onResponderTerminate: this.scrollResponderHandleTerminate,
onResponderRelease: this.scrollResponderHandleResponderRelease,
onResponderReject: this.scrollResponderHandleResponderReject
});
var ScrollViewClass = ScrollViewBase;
invariant(ScrollViewClass !== undefined, 'ScrollViewClass must not be undefined');
var scrollView = /*#__PURE__*/React.createElement(ScrollViewClass, _extends({}, props, {
ref: this._setScrollNodeRef
}), contentContainer);
if (refreshControl) {
return /*#__PURE__*/React.cloneElement(refreshControl, {
style: props.style
}, scrollView);
}
return scrollView;
},
_handleContentOnLayout: function _handleContentOnLayout(e) {
var _e$nativeEvent$layout = e.nativeEvent.layout,
width = _e$nativeEvent$layout.width,
height = _e$nativeEvent$layout.height;
this.props.onContentSizeChange(width, height);
},
_handleScroll: function _handleScroll(e) {
if (process.env.NODE_ENV !== 'production') {
if (this.props.onScroll && this.props.scrollEventThrottle == null) {
console.log('You specified `onScroll` on a <ScrollView> but not ' + '`scrollEventThrottle`. You will only receive one event. ' + 'Using `16` you get all the events but be aware that it may ' + "cause frame drops, use a bigger number if you don't need as " + 'much precision.');
}
}
if (this.props.keyboardDismissMode === 'on-drag') {
dismissKeyboard();
}
this.scrollResponderHandleScroll(e);
},
_setInnerViewRef: function _setInnerViewRef(node) {
this._innerViewRef = node;
},
_setScrollNodeRef: function _setScrollNodeRef(node) {
this._scrollNodeRef = node; // ScrollView needs to add more methods to the hostNode in addition to those
// added by `usePlatformMethods`. This is temporarily until an API like
// `ScrollView.scrollTo(hostNode, { x, y })` is added to React Native.
if (node != null) {
node.getScrollResponder = this.getScrollResponder;
node.getInnerViewNode = this.getInnerViewNode;
node.getInnerViewRef = this.getInnerViewRef;
node.getNativeScrollRef = this.getNativeScrollRef;
node.getScrollableNode = this.getScrollableNode;
node.scrollTo = this.scrollTo;
node.scrollToEnd = this.scrollToEnd;
node.flashScrollIndicators = this.flashScrollIndicators;
node.scrollResponderZoomTo = this.scrollResponderZoomTo;
node.scrollResponderScrollNativeHandleToKeyboard = this.scrollResponderScrollNativeHandleToKeyboard;
}
var ref = mergeRefs(this.props.forwardedRef);
ref(node);
}
});
var commonStyle = {
flexGrow: 1,
flexShrink: 1,
// Enable hardware compositing in modern browsers.
// Creates a new layer with its own backing surface that can significantly
// improve scroll performance.
transform: [{
translateZ: 0
}],
// iOS native scrolling
WebkitOverflowScrolling: 'touch'
};
var styles = StyleSheet.create({
baseVertical: _objectSpread(_objectSpread({}, commonStyle), {}, {
flexDirection: 'column',
overflowX: 'hidden',
overflowY: 'auto'
}),
baseHorizontal: _objectSpread(_objectSpread({}, commonStyle), {}, {
flexDirection: 'row',
overflowX: 'auto',
overflowY: 'hidden'
}),
contentContainerHorizontal: {
flexDirection: 'row'
},
stickyHeader: {
position: 'sticky',
top: 0,
zIndex: 10
},
pagingEnabledHorizontal: {
scrollSnapType: 'x mandatory'
},
pagingEnabledVertical: {
scrollSnapType: 'y mandatory'
},
pagingEnabledChild: {
scrollSnapAlign: 'start'
}
});
var ForwardedScrollView = /*#__PURE__*/React.forwardRef(function (props, forwardedRef) {
return /*#__PURE__*/React.createElement(ScrollView, _extends({}, props, {
forwardedRef: forwardedRef
}));
});
ForwardedScrollView.displayName = 'ScrollView';
export default ForwardedScrollView; |
ajax/libs/boardgame-io/0.47.6/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-0368a129.js';
import 'redux';
import './turn-order-0d61594c.js';
import 'immer';
import 'lodash.isplainobject';
import './reducer-77828ca8.js';
import 'rfc6902';
import './initialize-68f0dc41.js';
import './transport-0079de87.js';
import { C as Client$1 } from './client-d908fc95.js';
import 'flatted';
import './ai-f28cab02.js';
import React from 'react';
import PropTypes from 'prop-types';
var _excluded = ["matchID", "playerID"];
/**
* Client
*
* boardgame.io React Native client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React Native component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE.
*/
function Client(opts) {
var _class, _temp;
var game = opts.game,
numPlayers = opts.numPlayers,
board = opts.board,
multiplayer = opts.multiplayer,
enhancer = opts.enhancer;
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _temp = _class = /*#__PURE__*/function (_React$Component) {
_inherits(WrappedBoard, _React$Component);
var _super = _createSuper(WrappedBoard);
function WrappedBoard(props) {
var _this;
_classCallCheck(this, WrappedBoard);
_this = _super.call(this, props);
_this.client = Client$1({
game: game,
numPlayers: numPlayers,
multiplayer: multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
debug: false,
enhancer: enhancer
});
return _this;
}
_createClass(WrappedBoard, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
this.unsubscribe = this.client.subscribe(function () {
return _this2.forceUpdate();
});
this.client.start();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.matchID != this.props.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (prevProps.playerID != this.props.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (prevProps.credentials != this.props.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
}, {
key: "render",
value: function render() {
var _board = null;
var state = this.client.getState();
var _this$props = this.props,
matchID = _this$props.matchID,
playerID = _this$props.playerID,
rest = _objectWithoutProperties(_this$props, _excluded);
if (board) {
_board = /*#__PURE__*/React.createElement(board, _objectSpread2(_objectSpread2(_objectSpread2({}, state), rest), {}, {
matchID: matchID,
playerID: playerID,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
step: this.client.step,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages
}));
}
return _board;
}
}]);
return WrappedBoard;
}(React.Component), _defineProperty(_class, "propTypes", {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string
}), _defineProperty(_class, "defaultProps", {
matchID: 'default',
playerID: null,
credentials: null
}), _temp;
}
export { Client };
|
ajax/libs/primereact/7.0.0-rc.1/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;
} 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 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/7.0.0/breadcrumb/breadcrumb.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames, ObjectUtils } from 'primereact/utils';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} 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 BreadCrumb = /*#__PURE__*/function (_Component) {
_inherits(BreadCrumb, _Component);
var _super = _createSuper(BreadCrumb);
function BreadCrumb() {
_classCallCheck(this, BreadCrumb);
return _super.apply(this, arguments);
}
_createClass(BreadCrumb, [{
key: "itemClick",
value: function itemClick(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (!item.url) {
event.preventDefault();
}
if (item.command) {
item.command({
originalEvent: event,
item: item
});
}
}
}, {
key: "renderHome",
value: function renderHome() {
var _this = this;
if (this.props.home) {
var className = classNames('p-breadcrumb-home', {
'p-disabled': this.props.home.disabled
}, this.props.home.className);
var iconClassName = classNames('p-menuitem-icon', this.props.home.icon);
return /*#__PURE__*/React.createElement("li", {
className: className,
style: this.props.home.style
}, /*#__PURE__*/React.createElement("a", {
href: this.props.home.url || '#',
className: "p-menuitem-link",
"aria-disabled": this.props.home.disabled,
target: this.props.home.target,
onClick: function onClick(event) {
return _this.itemClick(event, _this.props.home);
}
}, /*#__PURE__*/React.createElement("span", {
className: iconClassName
})));
}
return null;
}
}, {
key: "renderSeparator",
value: function renderSeparator() {
return /*#__PURE__*/React.createElement("li", {
className: "p-breadcrumb-chevron pi pi-chevron-right"
});
}
}, {
key: "renderMenuitem",
value: function renderMenuitem(item) {
var _this2 = this;
var className = classNames(item.className, {
'p-disabled': item.disabled
});
var label = item.label && /*#__PURE__*/React.createElement("span", {
className: "p-menuitem-text"
}, item.label);
var content = /*#__PURE__*/React.createElement("a", {
href: item.url || '#',
className: "p-menuitem-link",
target: item.target,
onClick: function onClick(event) {
return _this2.itemClick(event, item);
},
"aria-disabled": item.disabled
}, label);
if (item.template) {
var defaultContentOptions = {
onClick: function onClick(event) {
return _this2.itemClick(event, item);
},
className: 'p-menuitem-link',
labelClassName: 'p-menuitem-text',
element: content,
props: this.props
};
content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions);
}
return /*#__PURE__*/React.createElement("li", {
className: className,
style: item.style
}, content);
}
}, {
key: "renderMenuitems",
value: function renderMenuitems() {
var _this3 = this;
if (this.props.model) {
var items = this.props.model.map(function (item, index) {
var menuitem = _this3.renderMenuitem(item);
var separator = index === _this3.props.model.length - 1 ? null : _this3.renderSeparator();
return /*#__PURE__*/React.createElement(React.Fragment, {
key: item.label + '_' + index
}, menuitem, separator);
});
return items;
}
return null;
}
}, {
key: "render",
value: function render() {
var className = classNames('p-breadcrumb p-component', this.props.className);
var home = this.renderHome();
var items = this.renderMenuitems();
var separator = this.renderSeparator();
return /*#__PURE__*/React.createElement("nav", {
id: this.props.id,
className: className,
style: this.props.style,
"aria-label": "Breadcrumb"
}, /*#__PURE__*/React.createElement("ul", null, home, separator, items));
}
}]);
return BreadCrumb;
}(Component);
_defineProperty(BreadCrumb, "defaultProps", {
id: null,
model: null,
home: null,
style: null,
className: null
});
export { BreadCrumb };
|
ajax/libs/primereact/7.2.0/accordion/accordion.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { UniqueComponentId, classNames, ObjectUtils, IconUtils } from 'primereact/utils';
import { CSSTransition } from 'primereact/csstransition';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _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 AccordionTab = /*#__PURE__*/function (_Component) {
_inherits(AccordionTab, _Component);
var _super = _createSuper(AccordionTab);
function AccordionTab() {
_classCallCheck(this, AccordionTab);
return _super.apply(this, arguments);
}
return _createClass(AccordionTab);
}(Component);
_defineProperty(AccordionTab, "defaultProps", {
header: null,
disabled: false,
style: null,
className: null,
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;
return _this;
}
_createClass(Accordion, [{
key: "shouldTabRender",
value: function shouldTabRender(tab) {
return tab && tab.type === AccordionTab;
}
}, {
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 _this2 = this;
var style = _objectSpread(_objectSpread({}, tab.props.headerStyle || {}), tab.props.style || {});
var className = classNames('p-accordion-header', {
'p-highlight': selected,
'p-disabled': tab.props.disabled
}, tab.props.headerClassName, tab.props.className);
var id = this.state.id + '_header_' + index;
var ariaControls = this.state.id + '_content_' + index;
var tabIndex = tab.props.disabled ? -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);
var icon = selected ? this.props.collapseIcon : this.props.expandIcon;
return /*#__PURE__*/React.createElement("div", {
className: className,
style: style
}, /*#__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
}, IconUtils.getJSXIcon(icon, {
className: 'p-accordion-toggle-icon'
}, {
props: this.props,
selected: selected
}), header));
}
}, {
key: "renderTabContent",
value: function renderTabContent(tab, selected, index) {
var style = _objectSpread(_objectSpread({}, tab.props.contentStyle || {}), tab.props.style || {});
var className = classNames('p-toggleable-content', tab.props.contentClassName, tab.props.className);
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: style,
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 (_this3.shouldTabRender(tab)) {
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/material-ui/4.9.4/es/FormControl/FormControlContext.js | cdnjs/cdnjs | import React from 'react';
/**
* @ignore - internal component.
*/
const FormControlContext = React.createContext();
if (process.env.NODE_ENV !== 'production') {
FormControlContext.displayName = 'FormControlContext';
}
export function useFormControl() {
return React.useContext(FormControlContext);
}
export default FormControlContext; |
ajax/libs/primereact/6.5.0/orderlist/orderlist.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { Button } from 'primereact/button';
import { ObjectUtils, DomHandler, classNames, Ripple } from 'primereact/core';
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$2() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var OrderListControls = /*#__PURE__*/function (_Component) {
_inherits(OrderListControls, _Component);
var _super = _createSuper$2(OrderListControls);
function OrderListControls() {
var _this;
_classCallCheck(this, OrderListControls);
_this = _super.call(this);
_this.moveUp = _this.moveUp.bind(_assertThisInitialized(_this));
_this.moveTop = _this.moveTop.bind(_assertThisInitialized(_this));
_this.moveDown = _this.moveDown.bind(_assertThisInitialized(_this));
_this.moveBottom = _this.moveBottom.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(OrderListControls, [{
key: "moveUp",
value: function moveUp(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = 0; i < this.props.selection.length; i++) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey);
if (selectedItemIndex !== 0) {
var movedItem = value[selectedItemIndex];
var temp = value[selectedItemIndex - 1];
value[selectedItemIndex - 1] = movedItem;
value[selectedItemIndex] = temp;
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'up'
});
}
}
}
}, {
key: "moveTop",
value: function moveTop(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = 0; i < this.props.selection.length; i++) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey);
if (selectedItemIndex !== 0) {
var movedItem = value.splice(selectedItemIndex, 1)[0];
value.unshift(movedItem);
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'top'
});
}
}
}
}, {
key: "moveDown",
value: function moveDown(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = this.props.selection.length - 1; i >= 0; i--) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey);
if (selectedItemIndex !== value.length - 1) {
var movedItem = value[selectedItemIndex];
var temp = value[selectedItemIndex + 1];
value[selectedItemIndex + 1] = movedItem;
value[selectedItemIndex] = temp;
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'down'
});
}
}
}
}, {
key: "moveBottom",
value: function moveBottom(event) {
if (this.props.selection) {
var value = _toConsumableArray(this.props.value);
for (var i = this.props.selection.length - 1; i >= 0; i--) {
var selectedItem = this.props.selection[i];
var selectedItemIndex = ObjectUtils.findIndexInList(selectedItem, value, this.props.dataKey);
if (selectedItemIndex !== value.length - 1) {
var movedItem = value.splice(selectedItemIndex, 1)[0];
value.push(movedItem);
} else {
break;
}
}
if (this.props.onReorder) {
this.props.onReorder({
originalEvent: event,
value: value,
direction: 'bottom'
});
}
}
}
}, {
key: "render",
value: function render() {
return /*#__PURE__*/React.createElement("div", {
className: "p-orderlist-controls"
}, /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-up",
onClick: this.moveUp
}), /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-double-up",
onClick: this.moveTop
}), /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-down",
onClick: this.moveDown
}), /*#__PURE__*/React.createElement(Button, {
type: "button",
icon: "pi pi-angle-double-down",
onClick: this.moveBottom
}));
}
}]);
return OrderListControls;
}(Component);
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var OrderListSubList = /*#__PURE__*/function (_Component) {
_inherits(OrderListSubList, _Component);
var _super = _createSuper$1(OrderListSubList);
function OrderListSubList(props) {
var _this;
_classCallCheck(this, OrderListSubList);
_this = _super.call(this, props);
_this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this));
_this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this));
_this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this));
_this.onListMouseMove = _this.onListMouseMove.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(OrderListSubList, [{
key: "isSelected",
value: function isSelected(item) {
return ObjectUtils.findIndexInList(item, this.props.selection, this.props.dataKey) !== -1;
}
}, {
key: "onDragStart",
value: function onDragStart(event, index) {
this.dragging = true;
this.draggedItemIndex = index;
if (this.props.dragdropScope) {
event.dataTransfer.setData('text', 'orderlist');
}
}
}, {
key: "onDragOver",
value: function onDragOver(event, index) {
if (this.draggedItemIndex !== index && this.draggedItemIndex + 1 !== index) {
this.dragOverItemIndex = index;
DomHandler.addClass(event.target, 'p-orderlist-droppoint-highlight');
event.preventDefault();
}
}
}, {
key: "onDragLeave",
value: function onDragLeave(event) {
this.dragOverItemIndex = null;
DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight');
}
}, {
key: "onDrop",
value: function onDrop(event) {
var dropIndex = this.draggedItemIndex > this.dragOverItemIndex ? this.dragOverItemIndex : this.dragOverItemIndex === 0 ? 0 : this.dragOverItemIndex - 1;
var value = _toConsumableArray(this.props.value);
ObjectUtils.reorderArray(value, this.draggedItemIndex, dropIndex);
this.dragOverItemIndex = null;
DomHandler.removeClass(event.target, 'p-orderlist-droppoint-highlight');
if (this.props.onChange) {
this.props.onChange({
originalEvent: event,
value: value
});
}
}
}, {
key: "onDragEnd",
value: function onDragEnd(event) {
this.dragging = false;
}
}, {
key: "onListMouseMove",
value: function onListMouseMove(event) {
if (this.dragging) {
var offsetY = this.listElement.getBoundingClientRect().top + DomHandler.getWindowScrollTop();
var bottomDiff = offsetY + this.listElement.clientHeight - event.pageY;
var topDiff = event.pageY - offsetY;
if (bottomDiff < 25 && bottomDiff > 0) this.listElement.scrollTop += 15;else if (topDiff < 25 && topDiff > 0) this.listElement.scrollTop -= 15;
}
}
}, {
key: "renderDropPoint",
value: function renderDropPoint(index, key) {
var _this2 = this;
return /*#__PURE__*/React.createElement("li", {
key: key,
className: "p-orderlist-droppoint",
onDragOver: function onDragOver(e) {
return _this2.onDragOver(e, index + 1);
},
onDragLeave: this.onDragLeave,
onDrop: this.onDrop
});
}
}, {
key: "render",
value: function render() {
var _this3 = this;
var header = null;
var items = null;
if (this.props.header) {
header = /*#__PURE__*/React.createElement("div", {
className: "p-orderlist-header"
}, this.props.header);
}
if (this.props.value) {
items = this.props.value.map(function (item, i) {
var content = _this3.props.itemTemplate ? _this3.props.itemTemplate(item) : item;
var itemClassName = classNames('p-orderlist-item', {
'p-highlight': _this3.isSelected(item)
}, _this3.props.className);
var key = JSON.stringify(item);
if (_this3.props.dragdrop) {
var _items = [_this3.renderDropPoint(i, key + '_droppoint'), /*#__PURE__*/React.createElement("li", {
key: key,
className: itemClassName,
onClick: function onClick(e) {
return _this3.props.onItemClick({
originalEvent: e,
value: item,
index: i
});
},
onKeyDown: function onKeyDown(e) {
return _this3.props.onItemKeyDown({
originalEvent: e,
value: item,
index: i
});
},
role: "option",
"aria-selected": _this3.isSelected(item),
draggable: "true",
onDragStart: function onDragStart(e) {
return _this3.onDragStart(e, i);
},
onDragEnd: _this3.onDragEnd,
tabIndex: _this3.props.tabIndex
}, content, /*#__PURE__*/React.createElement(Ripple, null))];
if (i === _this3.props.value.length - 1) {
_items.push(_this3.renderDropPoint(item, i, key + '_droppoint_end'));
}
return _items;
} else {
return /*#__PURE__*/React.createElement("li", {
key: JSON.stringify(item),
className: itemClassName,
role: "option",
"aria-selected": _this3.isSelected(item),
onClick: function onClick(e) {
return _this3.props.onItemClick({
originalEvent: e,
value: item,
index: i
});
},
onKeyDown: function onKeyDown(e) {
return _this3.props.onItemKeyDown({
originalEvent: e,
value: item,
index: i
});
},
tabIndex: _this3.props.tabIndex
}, content);
}
});
}
return /*#__PURE__*/React.createElement("div", {
className: "p-orderlist-list-container"
}, header, /*#__PURE__*/React.createElement("ul", {
ref: function ref(el) {
return _this3.listElement = el;
},
className: "p-orderlist-list",
style: this.props.listStyle,
onDragOver: this.onListMouseMove,
role: "listbox",
"aria-multiselectable": true
}, items));
}
}]);
return OrderListSubList;
}(Component);
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var OrderList = /*#__PURE__*/function (_Component) {
_inherits(OrderList, _Component);
var _super = _createSuper(OrderList);
function OrderList(props) {
var _this;
_classCallCheck(this, OrderList);
_this = _super.call(this, props);
_this.state = {
selection: []
};
_this.onItemClick = _this.onItemClick.bind(_assertThisInitialized(_this));
_this.onItemKeyDown = _this.onItemKeyDown.bind(_assertThisInitialized(_this));
_this.onReorder = _this.onReorder.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(OrderList, [{
key: "onItemClick",
value: function onItemClick(event) {
var metaKey = event.originalEvent.metaKey || event.originalEvent.ctrlKey;
var index = ObjectUtils.findIndexInList(event.value, this.state.selection, this.props.dataKey);
var selected = index !== -1;
var selection;
if (selected) {
if (metaKey) selection = this.state.selection.filter(function (val, i) {
return i !== index;
});else selection = [event.value];
} else {
if (metaKey) selection = [].concat(_toConsumableArray(this.state.selection), [event.value]);else selection = [event.value];
}
this.setState({
selection: selection
});
}
}, {
key: "onItemKeyDown",
value: function onItemKeyDown(event) {
var listItem = event.originalEvent.currentTarget;
switch (event.originalEvent.which) {
//down
case 40:
var nextItem = this.findNextItem(listItem);
if (nextItem) {
nextItem.focus();
}
event.originalEvent.preventDefault();
break;
//up
case 38:
var prevItem = this.findPrevItem(listItem);
if (prevItem) {
prevItem.focus();
}
event.originalEvent.preventDefault();
break;
//enter
case 13:
this.onItemClick(event);
event.originalEvent.preventDefault();
break;
}
}
}, {
key: "findNextItem",
value: function findNextItem(item) {
var nextItem = item.nextElementSibling;
if (nextItem) return !DomHandler.hasClass(nextItem, 'p-orderlist-item') ? this.findNextItem(nextItem) : nextItem;else return null;
}
}, {
key: "findPrevItem",
value: function findPrevItem(item) {
var prevItem = item.previousElementSibling;
if (prevItem) return !DomHandler.hasClass(prevItem, 'p-orderlist-item') ? this.findPrevItem(prevItem) : prevItem;else return null;
}
}, {
key: "onReorder",
value: function onReorder(event) {
if (this.props.onChange) {
this.props.onChange({
event: event.originalEvent,
value: event.value
});
}
this.reorderDirection = event.direction;
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
if (this.reorderDirection) {
this.updateListScroll();
this.reorderDirection = null;
}
}
}, {
key: "updateListScroll",
value: function updateListScroll() {
var listItems = DomHandler.find(this.subList.listElement, '.p-orderlist-item.p-highlight');
if (listItems && listItems.length) {
switch (this.reorderDirection) {
case 'up':
DomHandler.scrollInView(this.subList.listElement, listItems[0]);
break;
case 'top':
this.subList.listElement.scrollTop = 0;
break;
case 'down':
DomHandler.scrollInView(this.subList.listElement, listItems[listItems.length - 1]);
break;
case 'bottom':
this.subList.listElement.scrollTop = this.subList.listElement.scrollHeight;
break;
}
}
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var className = classNames('p-orderlist p-component', this.props.className);
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this2.element = el;
},
id: this.props.id,
className: className,
style: this.props.style
}, /*#__PURE__*/React.createElement(OrderListControls, {
value: this.props.value,
selection: this.state.selection,
onReorder: this.onReorder,
dataKey: this.props.dataKey
}), /*#__PURE__*/React.createElement(OrderListSubList, {
ref: function ref(el) {
return _this2.subList = el;
},
value: this.props.value,
selection: this.state.selection,
onItemClick: this.onItemClick,
onItemKeyDown: this.onItemKeyDown,
itemTemplate: this.props.itemTemplate,
header: this.props.header,
listStyle: this.props.listStyle,
dataKey: this.props.dataKey,
dragdrop: this.props.dragdrop,
onDragStart: this.onDragStart,
onDragEnter: this.onDragEnter,
onDragEnd: this.onDragEnd,
onDragLeave: this.onDragEnter,
onDrop: this.onDrop,
onChange: this.props.onChange,
tabIndex: this.props.tabIndex
}));
}
}]);
return OrderList;
}(Component);
_defineProperty(OrderList, "defaultProps", {
id: null,
value: null,
header: null,
style: null,
className: null,
listStyle: null,
dragdrop: false,
tabIndex: 0,
dataKey: null,
onChange: null,
itemTemplate: null
});
export { OrderList };
|
ajax/libs/primereact/6.5.1/tree/tree.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, ObjectUtils, classNames, Ripple } from 'primereact/core';
function _arrayLikeToArray$2(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray$2(arr);
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray$2(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray$2(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$2(arr) || _nonIterableSpread();
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createForOfIteratorHelper$1(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$1(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); }
function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct$1() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var UITreeNode = /*#__PURE__*/function (_Component) {
_inherits(UITreeNode, _Component);
var _super = _createSuper$1(UITreeNode);
function UITreeNode(props) {
var _this;
_classCallCheck(this, UITreeNode);
_this = _super.call(this, props);
_this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
_this.onDoubleClick = _this.onDoubleClick.bind(_assertThisInitialized(_this));
_this.onRightClick = _this.onRightClick.bind(_assertThisInitialized(_this));
_this.onTouchEnd = _this.onTouchEnd.bind(_assertThisInitialized(_this));
_this.onTogglerClick = _this.onTogglerClick.bind(_assertThisInitialized(_this));
_this.onNodeKeyDown = _this.onNodeKeyDown.bind(_assertThisInitialized(_this));
_this.propagateUp = _this.propagateUp.bind(_assertThisInitialized(_this));
_this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this));
_this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_this));
_this.onDragEnter = _this.onDragEnter.bind(_assertThisInitialized(_this));
_this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this));
_this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this));
_this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this));
_this.onDropPointDragOver = _this.onDropPointDragOver.bind(_assertThisInitialized(_this));
_this.onDropPointDragEnter = _this.onDropPointDragEnter.bind(_assertThisInitialized(_this));
_this.onDropPointDragLeave = _this.onDropPointDragLeave.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(UITreeNode, [{
key: "isLeaf",
value: function isLeaf() {
return this.props.isNodeLeaf(this.props.node);
}
}, {
key: "expand",
value: function expand(event) {
var expandedKeys = this.props.expandedKeys ? _objectSpread$1({}, this.props.expandedKeys) : {};
expandedKeys[this.props.node.key] = true;
this.props.onToggle({
originalEvent: event,
value: expandedKeys
});
this.invokeToggleEvents(event, true);
}
}, {
key: "collapse",
value: function collapse(event) {
var expandedKeys = _objectSpread$1({}, this.props.expandedKeys);
delete expandedKeys[this.props.node.key];
this.props.onToggle({
originalEvent: event,
value: expandedKeys
});
this.invokeToggleEvents(event, false);
}
}, {
key: "onTogglerClick",
value: function onTogglerClick(event) {
if (this.props.disabled) {
return;
}
if (this.isExpanded()) this.collapse(event);else this.expand(event);
}
}, {
key: "invokeToggleEvents",
value: function invokeToggleEvents(event, expanded) {
if (expanded) {
if (this.props.onExpand) {
this.props.onExpand({
originalEvent: event,
node: this.props.node
});
}
} else {
if (this.props.onCollapse) {
this.props.onCollapse({
originalEvent: event,
node: this.props.node
});
}
}
}
}, {
key: "isExpanded",
value: function isExpanded() {
return (this.props.expandedKeys ? this.props.expandedKeys[this.props.node.key] !== undefined : false) || this.props.node.expanded;
}
}, {
key: "onNodeKeyDown",
value: function onNodeKeyDown(event) {
if (this.props.disabled) {
return;
}
var nodeElement = event.target.parentElement;
if (!DomHandler.hasClass(nodeElement, 'p-treenode')) {
return;
}
switch (event.which) {
//down arrow
case 40:
var listElement = nodeElement.children[1];
if (listElement) {
this.focusNode(listElement.children[0]);
} else {
var nextNodeElement = nodeElement.nextElementSibling;
if (nextNodeElement) {
this.focusNode(nextNodeElement);
} else {
var nextSiblingAncestor = this.findNextSiblingOfAncestor(nodeElement);
if (nextSiblingAncestor) {
this.focusNode(nextSiblingAncestor);
}
}
}
event.preventDefault();
break;
//up arrow
case 38:
if (nodeElement.previousElementSibling) {
this.focusNode(this.findLastVisibleDescendant(nodeElement.previousElementSibling));
} else {
var parentNodeElement = this.getParentNodeElement(nodeElement);
if (parentNodeElement) {
this.focusNode(parentNodeElement);
}
}
event.preventDefault();
break;
//right arrow
case 39:
if (!this.isExpanded()) {
this.expand(event);
}
event.preventDefault();
break;
//left arrow
case 37:
if (this.isExpanded()) {
this.collapse(event);
}
event.preventDefault();
break;
//enter
case 13:
this.onClick(event);
event.preventDefault();
break;
}
}
}, {
key: "findNextSiblingOfAncestor",
value: function findNextSiblingOfAncestor(nodeElement) {
var parentNodeElement = this.getParentNodeElement(nodeElement);
if (parentNodeElement) {
if (parentNodeElement.nextElementSibling) return parentNodeElement.nextElementSibling;else return this.findNextSiblingOfAncestor(parentNodeElement);
} else {
return null;
}
}
}, {
key: "findLastVisibleDescendant",
value: function findLastVisibleDescendant(nodeElement) {
var childrenListElement = nodeElement.children[1];
if (childrenListElement) {
var lastChildElement = childrenListElement.children[childrenListElement.children.length - 1];
return this.findLastVisibleDescendant(lastChildElement);
} else {
return nodeElement;
}
}
}, {
key: "getParentNodeElement",
value: function getParentNodeElement(nodeElement) {
var parentNodeElement = nodeElement.parentElement.parentElement;
return DomHandler.hasClass(parentNodeElement, 'p-treenode') ? parentNodeElement : null;
}
}, {
key: "focusNode",
value: function focusNode(element) {
element.children[0].focus();
}
}, {
key: "onClick",
value: function onClick(event) {
if (this.props.onClick) {
this.props.onClick({
originalEvent: event,
node: this.props.node
});
}
if (event.target.className && event.target.className.constructor === String && event.target.className.indexOf('p-tree-toggler') === 0 || this.props.disabled) {
return;
}
if (this.props.selectionMode && this.props.node.selectable !== false) {
var selectionKeys;
if (this.isCheckboxSelectionMode()) {
var checked = this.isChecked();
selectionKeys = this.props.selectionKeys ? _objectSpread$1({}, this.props.selectionKeys) : {};
if (checked) {
if (this.props.propagateSelectionDown) this.propagateDown(this.props.node, false, selectionKeys);else delete selectionKeys[this.props.node.key];
if (this.props.propagateSelectionUp && this.props.onPropagateUp) {
this.props.onPropagateUp({
originalEvent: event,
check: false,
selectionKeys: selectionKeys
});
}
if (this.props.onUnselect) {
this.props.onUnselect({
originalEvent: event,
node: this.props.node
});
}
} else {
if (this.props.propagateSelectionDown) this.propagateDown(this.props.node, true, selectionKeys);else selectionKeys[this.props.node.key] = {
checked: true
};
if (this.props.propagateSelectionUp && this.props.onPropagateUp) {
this.props.onPropagateUp({
originalEvent: event,
check: true,
selectionKeys: selectionKeys
});
}
if (this.props.onSelect) {
this.props.onSelect({
originalEvent: event,
node: this.props.node
});
}
}
} else {
var selected = this.isSelected();
var metaSelection = this.nodeTouched ? false : this.props.metaKeySelection;
if (metaSelection) {
var metaKey = event.metaKey || event.ctrlKey;
if (selected && metaKey) {
if (this.isSingleSelectionMode()) {
selectionKeys = null;
} else {
selectionKeys = _objectSpread$1({}, this.props.selectionKeys);
delete selectionKeys[this.props.node.key];
}
if (this.props.onUnselect) {
this.props.onUnselect({
originalEvent: event,
node: this.props.node
});
}
} else {
if (this.isSingleSelectionMode()) {
selectionKeys = this.props.node.key;
} else if (this.isMultipleSelectionMode()) {
selectionKeys = !metaKey ? {} : this.props.selectionKeys ? _objectSpread$1({}, this.props.selectionKeys) : {};
selectionKeys[this.props.node.key] = true;
}
if (this.props.onSelect) {
this.props.onSelect({
originalEvent: event,
node: this.props.node
});
}
}
} else {
if (this.isSingleSelectionMode()) {
if (selected) {
selectionKeys = null;
if (this.props.onUnselect) {
this.props.onUnselect({
originalEvent: event,
node: this.props.node
});
}
} else {
selectionKeys = this.props.node.key;
if (this.props.onSelect) {
this.props.onSelect({
originalEvent: event,
node: this.props.node
});
}
}
} else {
if (selected) {
selectionKeys = _objectSpread$1({}, this.props.selectionKeys);
delete selectionKeys[this.props.node.key];
if (this.props.onUnselect) {
this.props.onUnselect({
originalEvent: event,
node: this.props.node
});
}
} else {
selectionKeys = this.props.selectionKeys ? _objectSpread$1({}, this.props.selectionKeys) : {};
selectionKeys[this.props.node.key] = true;
if (this.props.onSelect) {
this.props.onSelect({
originalEvent: event,
node: this.props.node
});
}
}
}
}
}
if (this.props.onSelectionChange) {
this.props.onSelectionChange({
originalEvent: event,
value: selectionKeys
});
}
}
this.nodeTouched = false;
}
}, {
key: "onDoubleClick",
value: function onDoubleClick(event) {
if (this.props.onDoubleClick) {
this.props.onDoubleClick({
originalEvent: event,
node: this.props.node
});
}
}
}, {
key: "onRightClick",
value: function onRightClick(event) {
if (this.props.disabled) {
return;
}
DomHandler.clearSelection();
if (this.props.onContextMenuSelectionChange) {
this.props.onContextMenuSelectionChange({
originalEvent: event,
value: this.props.node.key
});
}
if (this.props.onContextMenu) {
this.props.onContextMenu({
originalEvent: event,
node: this.props.node
});
}
}
}, {
key: "propagateUp",
value: function propagateUp(event) {
var check = event.check;
var selectionKeys = event.selectionKeys;
var checkedChildCount = 0;
var childPartialSelected = false;
var _iterator = _createForOfIteratorHelper$1(this.props.node.children),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var child = _step.value;
if (selectionKeys[child.key] && selectionKeys[child.key].checked) checkedChildCount++;else if (selectionKeys[child.key] && selectionKeys[child.key].partialChecked) childPartialSelected = true;
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
if (check && checkedChildCount === this.props.node.children.length) {
selectionKeys[this.props.node.key] = {
checked: true,
partialChecked: false
};
} else {
if (!check) {
delete selectionKeys[this.props.node.key];
}
if (childPartialSelected || checkedChildCount > 0 && checkedChildCount !== this.props.node.children.length) selectionKeys[this.props.node.key] = {
checked: false,
partialChecked: true
};else delete selectionKeys[this.props.node.key];
}
if (this.props.propagateSelectionUp && this.props.onPropagateUp) {
this.props.onPropagateUp(event);
}
}
}, {
key: "propagateDown",
value: function propagateDown(node, check, selectionKeys) {
if (check) selectionKeys[node.key] = {
checked: true,
partialChecked: false
};else delete selectionKeys[node.key];
if (node.children && node.children.length) {
for (var i = 0; i < node.children.length; i++) {
this.propagateDown(node.children[i], check, selectionKeys);
}
}
}
}, {
key: "isSelected",
value: function isSelected() {
if (this.props.selectionMode && this.props.selectionKeys) return this.isSingleSelectionMode() ? this.props.selectionKeys === this.props.node.key : this.props.selectionKeys[this.props.node.key] !== undefined;else return false;
}
}, {
key: "isChecked",
value: function isChecked() {
return this.props.selectionKeys ? this.props.selectionKeys[this.props.node.key] && this.props.selectionKeys[this.props.node.key].checked : false;
}
}, {
key: "isPartialChecked",
value: function isPartialChecked() {
return this.props.selectionKeys ? this.props.selectionKeys[this.props.node.key] && this.props.selectionKeys[this.props.node.key].partialChecked : false;
}
}, {
key: "isSingleSelectionMode",
value: function isSingleSelectionMode() {
return this.props.selectionMode && this.props.selectionMode === 'single';
}
}, {
key: "isMultipleSelectionMode",
value: function isMultipleSelectionMode() {
return this.props.selectionMode && this.props.selectionMode === 'multiple';
}
}, {
key: "isCheckboxSelectionMode",
value: function isCheckboxSelectionMode() {
return this.props.selectionMode && this.props.selectionMode === 'checkbox';
}
}, {
key: "onTouchEnd",
value: function onTouchEnd() {
this.nodeTouched = true;
}
}, {
key: "onDropPoint",
value: function onDropPoint(event, position) {
event.preventDefault();
if (this.props.node.droppable !== false) {
DomHandler.removeClass(event.target, 'p-treenode-droppoint-active');
if (this.props.onDropPoint) {
this.props.onDropPoint({
originalEvent: event,
path: this.props.path,
index: this.props.index,
position: position
});
}
}
}
}, {
key: "onDropPointDragOver",
value: function onDropPointDragOver(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) {
event.dataTransfer.dropEffect = 'move';
event.preventDefault();
}
}
}, {
key: "onDropPointDragEnter",
value: function onDropPointDragEnter(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) {
DomHandler.addClass(event.target, 'p-treenode-droppoint-active');
}
}
}, {
key: "onDropPointDragLeave",
value: function onDropPointDragLeave(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase()) {
DomHandler.removeClass(event.target, 'p-treenode-droppoint-active');
}
}
}, {
key: "onDrop",
value: function onDrop(event) {
if (this.props.dragdropScope && this.props.node.droppable !== false) {
DomHandler.removeClass(this.contentElement, 'p-treenode-dragover');
event.preventDefault();
event.stopPropagation();
if (this.props.onDrop) {
this.props.onDrop({
originalEvent: event,
path: this.props.path,
index: this.props.index
});
}
}
}
}, {
key: "onDragOver",
value: function onDragOver(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) {
event.dataTransfer.dropEffect = 'move';
event.preventDefault();
event.stopPropagation();
}
}
}, {
key: "onDragEnter",
value: function onDragEnter(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) {
DomHandler.addClass(this.contentElement, 'p-treenode-dragover');
}
}
}, {
key: "onDragLeave",
value: function onDragLeave(event) {
if (event.dataTransfer.types[1] === this.props.dragdropScope.toLocaleLowerCase() && this.props.node.droppable !== false) {
var rect = event.currentTarget.getBoundingClientRect();
if (event.nativeEvent.x > rect.left + rect.width || event.nativeEvent.x < rect.left || event.nativeEvent.y >= Math.floor(rect.top + rect.height) || event.nativeEvent.y < rect.top) {
DomHandler.removeClass(this.contentElement, 'p-treenode-dragover');
}
}
}
}, {
key: "onDragStart",
value: function onDragStart(event) {
event.dataTransfer.setData("text", this.props.dragdropScope);
event.dataTransfer.setData(this.props.dragdropScope, this.props.dragdropScope);
if (this.props.onDragStart) {
this.props.onDragStart({
originalEvent: event,
path: this.props.path,
index: this.props.index
});
}
}
}, {
key: "onDragEnd",
value: function onDragEnd(event) {
if (this.props.onDragEnd) {
this.props.onDragEnd({
originalEvent: event
});
}
}
}, {
key: "renderLabel",
value: function renderLabel() {
var content = /*#__PURE__*/React.createElement("span", {
className: "p-treenode-label"
}, this.props.node.label);
if (this.props.nodeTemplate) {
var defaultContentOptions = {
onTogglerClick: this.onTogglerClick,
className: 'p-treenode-label',
element: content,
props: this.props,
expanded: this.isExpanded()
};
content = ObjectUtils.getJSXElement(this.props.nodeTemplate, this.props.node, defaultContentOptions);
}
return content;
}
}, {
key: "renderCheckbox",
value: function renderCheckbox() {
if (this.isCheckboxSelectionMode() && this.props.node.selectable !== false) {
var checked = this.isChecked();
var partialChecked = this.isPartialChecked();
var className = classNames('p-checkbox-box', {
'p-highlight': checked,
'p-indeterminate': partialChecked,
'p-disabled': this.props.disabled
});
var icon = classNames('p-checkbox-icon p-c', {
'pi pi-check': checked,
'pi pi-minus': partialChecked
});
return /*#__PURE__*/React.createElement("div", {
className: "p-checkbox p-component"
}, /*#__PURE__*/React.createElement("div", {
className: className,
role: "checkbox",
"aria-checked": checked
}, /*#__PURE__*/React.createElement("span", {
className: icon
})));
}
return null;
}
}, {
key: "renderIcon",
value: function renderIcon(expanded) {
var icon = this.props.node.icon || (expanded ? this.props.node.expandedIcon : this.props.node.collapsedIcon);
if (icon) {
var className = classNames('p-treenode-icon', icon);
return /*#__PURE__*/React.createElement("span", {
className: className
});
}
return null;
}
}, {
key: "renderToggler",
value: function renderToggler(expanded) {
var iconClassName = classNames('p-tree-toggler-icon pi pi-fw', {
'pi-chevron-right': !expanded,
'pi-chevron-down': expanded
});
var content = /*#__PURE__*/React.createElement("button", {
type: "button",
className: "p-tree-toggler p-link",
tabIndex: -1,
onClick: this.onTogglerClick
}, /*#__PURE__*/React.createElement("span", {
className: iconClassName
}), /*#__PURE__*/React.createElement(Ripple, null));
if (this.props.togglerTemplate) {
var defaultContentOptions = {
onClick: this.onTogglerClick,
containerClassName: 'p-tree-toggler p-link',
iconClassName: 'p-tree-toggler-icon',
element: content,
props: this.props,
expanded: expanded
};
content = ObjectUtils.getJSXElement(this.props.togglerTemplate, this.props.node, defaultContentOptions);
}
return content;
}
}, {
key: "renderDropPoint",
value: function renderDropPoint(position) {
var _this2 = this;
if (this.props.dragdropScope) {
return /*#__PURE__*/React.createElement("li", {
className: "p-treenode-droppoint",
onDrop: function onDrop(event) {
return _this2.onDropPoint(event, position);
},
onDragOver: this.onDropPointDragOver,
onDragEnter: this.onDropPointDragEnter,
onDragLeave: this.onDropPointDragLeave
});
}
return null;
}
}, {
key: "renderContent",
value: function renderContent() {
var _this3 = this;
var selected = this.isSelected();
var checked = this.isChecked();
var className = classNames('p-treenode-content', this.props.node.className, {
'p-treenode-selectable': this.props.selectionMode && this.props.node.selectable !== false,
'p-highlight': this.isCheckboxSelectionMode() ? checked : selected,
'p-highlight-contextmenu': this.props.contextMenuSelectionKey && this.props.contextMenuSelectionKey === this.props.node.key,
'p-disabled': this.props.disabled
});
var expanded = this.isExpanded();
var toggler = this.renderToggler(expanded);
var checkbox = this.renderCheckbox();
var icon = this.renderIcon(expanded);
var label = this.renderLabel();
var tabIndex = this.props.disabled ? undefined : 0;
return /*#__PURE__*/React.createElement("div", {
ref: function ref(el) {
return _this3.contentElement = el;
},
className: className,
style: this.props.node.style,
onClick: this.onClick,
onDoubleClick: this.onDoubleClick,
onContextMenu: this.onRightClick,
onTouchEnd: this.onTouchEnd,
draggable: this.props.dragdropScope && this.props.node.draggable !== false && !this.props.disabled,
onDrop: this.onDrop,
onDragOver: this.onDragOver,
onDragEnter: this.onDragEnter,
onDragLeave: this.onDragLeave,
onDragStart: this.onDragStart,
onDragEnd: this.onDragEnd,
tabIndex: tabIndex,
onKeyDown: this.onNodeKeyDown,
role: "treeitem",
"aria-posinset": this.props.index + 1,
"aria-expanded": this.isExpanded(),
"aria-selected": checked || selected
}, toggler, checkbox, icon, label);
}
}, {
key: "renderChildren",
value: function renderChildren() {
var _this4 = this;
if (this.props.node.children && this.props.node.children.length && this.isExpanded()) {
return /*#__PURE__*/React.createElement("ul", {
className: "p-treenode-children",
role: "group"
}, this.props.node.children.map(function (childNode, index) {
return /*#__PURE__*/React.createElement(UITreeNode, {
key: childNode.key || childNode.label,
node: childNode,
parent: _this4.props.node,
index: index,
last: index === _this4.props.node.children.length - 1,
path: _this4.props.path + '-' + index,
disabled: _this4.props.disabled,
selectionMode: _this4.props.selectionMode,
selectionKeys: _this4.props.selectionKeys,
onSelectionChange: _this4.props.onSelectionChange,
metaKeySelection: _this4.props.metaKeySelection,
propagateSelectionDown: _this4.props.propagateSelectionDown,
propagateSelectionUp: _this4.props.propagateSelectionUp,
contextMenuSelectionKey: _this4.props.contextMenuSelectionKey,
onContextMenuSelectionChange: _this4.props.onContextMenuSelectionChange,
onContextMenu: _this4.props.onContextMenu,
onExpand: _this4.props.onExpand,
onCollapse: _this4.props.onCollapse,
onSelect: _this4.props.onSelect,
onUnselect: _this4.props.onUnselect,
expandedKeys: _this4.props.expandedKeys,
onToggle: _this4.props.onToggle,
onPropagateUp: _this4.propagateUp,
nodeTemplate: _this4.props.nodeTemplate,
togglerTemplate: _this4.props.togglerTemplate,
isNodeLeaf: _this4.props.isNodeLeaf,
dragdropScope: _this4.props.dragdropScope,
onDragStart: _this4.props.onDragStart,
onDragEnd: _this4.props.onDragEnd,
onDrop: _this4.props.onDrop,
onDropPoint: _this4.props.onDropPoint
});
}));
}
return null;
}
}, {
key: "renderNode",
value: function renderNode() {
var className = classNames('p-treenode', {
'p-treenode-leaf': this.isLeaf()
}, this.props.node.className);
var content = this.renderContent();
var children = this.renderChildren();
return /*#__PURE__*/React.createElement("li", {
className: className,
style: this.props.node.style
}, content, children);
}
}, {
key: "render",
value: function render() {
var node = this.renderNode();
if (this.props.dragdropScope && !this.props.disabled) {
var beforeDropPoint = this.renderDropPoint(-1);
var afterDropPoint = this.props.last ? this.renderDropPoint(1) : null;
return /*#__PURE__*/React.createElement(React.Fragment, null, beforeDropPoint, node, afterDropPoint);
} else {
return node;
}
}
}]);
return UITreeNode;
}(Component);
_defineProperty(UITreeNode, "defaultProps", {
node: null,
index: null,
last: null,
parent: null,
path: null,
disabled: false,
selectionMode: null,
selectionKeys: null,
contextMenuSelectionKey: null,
metaKeySelection: true,
expandedKeys: null,
propagateSelectionUp: true,
propagateSelectionDown: true,
dragdropScope: null,
ariaLabel: null,
ariaLabelledBy: null,
nodeTemplate: null,
togglerTemplate: null,
isNodeLeaf: null,
onSelect: null,
onUnselect: null,
onExpand: null,
onCollapse: null,
onToggle: null,
onSelectionChange: null,
onContextMenuSelectionChange: null,
onPropagateUp: null,
onDragStart: null,
onDragEnd: null,
onDrop: null,
onDropPoint: null,
onContextMenu: null,
onNodeClick: null,
onNodeDoubleClick: null
});
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Tree = /*#__PURE__*/function (_Component) {
_inherits(Tree, _Component);
var _super = _createSuper(Tree);
function Tree(props) {
var _this;
_classCallCheck(this, Tree);
_this = _super.call(this, props);
_this.state = {};
if (!_this.props.onFilterValueChange) {
_this.state['filterValue'] = '';
}
if (!_this.props.onToggle) {
_this.state['expandedKeys'] = _this.props.expandedKeys;
}
_this.isNodeLeaf = _this.isNodeLeaf.bind(_assertThisInitialized(_this));
_this.onToggle = _this.onToggle.bind(_assertThisInitialized(_this));
_this.onDragStart = _this.onDragStart.bind(_assertThisInitialized(_this));
_this.onDragEnd = _this.onDragEnd.bind(_assertThisInitialized(_this));
_this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this));
_this.onDropPoint = _this.onDropPoint.bind(_assertThisInitialized(_this));
_this.onFilterInputChange = _this.onFilterInputChange.bind(_assertThisInitialized(_this));
_this.onFilterInputKeyDown = _this.onFilterInputKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(Tree, [{
key: "getFilterValue",
value: function getFilterValue() {
return this.props.onFilterValueChange ? this.props.filterValue : this.state.filterValue;
}
}, {
key: "getExpandedKeys",
value: function getExpandedKeys() {
return this.props.onToggle ? this.props.expandedKeys : this.state.expandedKeys;
}
}, {
key: "getRootNode",
value: function getRootNode() {
return this.props.filter && this.filteredNodes ? this.filteredNodes : this.props.value;
}
}, {
key: "onToggle",
value: function onToggle(event) {
if (this.props.onToggle) {
this.props.onToggle(event);
} else {
this.setState({
expandedKeys: event.value
});
}
}
}, {
key: "onDragStart",
value: function onDragStart(event) {
this.dragState = {
path: event.path,
index: event.index
};
}
}, {
key: "onDragEnd",
value: function onDragEnd() {
this.dragState = null;
}
}, {
key: "onDrop",
value: function onDrop(event) {
if (this.validateDropNode(this.dragState.path, event.path)) {
var value = JSON.parse(JSON.stringify(this.props.value));
var dragPaths = this.dragState.path.split('-');
dragPaths.pop();
var dragNodeParent = this.findNode(value, dragPaths);
var dragNode = dragNodeParent ? dragNodeParent.children[this.dragState.index] : value[this.dragState.index];
var dropNode = this.findNode(value, event.path.split('-'));
if (dropNode.children) dropNode.children.push(dragNode);else dropNode.children = [dragNode];
if (dragNodeParent) dragNodeParent.children.splice(this.dragState.index, 1);else value.splice(this.dragState.index, 1);
if (this.props.onDragDrop) {
this.props.onDragDrop({
originalEvent: event.originalEvent,
value: value,
dragNode: dragNode,
dropNode: dropNode,
dropIndex: event.index
});
}
}
}
}, {
key: "onDropPoint",
value: function onDropPoint(event) {
if (this.validateDropPoint(event)) {
var value = JSON.parse(JSON.stringify(this.props.value));
var dragPaths = this.dragState.path.split('-');
dragPaths.pop();
var dropPaths = event.path.split('-');
dropPaths.pop();
var dragNodeParent = this.findNode(value, dragPaths);
var dropNodeParent = this.findNode(value, dropPaths);
var dragNode = dragNodeParent ? dragNodeParent.children[this.dragState.index] : value[this.dragState.index];
var siblings = this.areSiblings(this.dragState.path, event.path);
if (dragNodeParent) dragNodeParent.children.splice(this.dragState.index, 1);else value.splice(this.dragState.index, 1);
if (event.position < 0) {
var dropIndex = siblings ? this.dragState.index > event.index ? event.index : event.index - 1 : event.index;
if (dropNodeParent) dropNodeParent.children.splice(dropIndex, 0, dragNode);else value.splice(dropIndex, 0, dragNode);
} else {
if (dropNodeParent) dropNodeParent.children.push(dragNode);else value.push(dragNode);
}
if (this.props.onDragDrop) {
this.props.onDragDrop({
originalEvent: event.originalEvent,
value: value,
dragNode: dragNode,
dropNode: dropNodeParent,
dropIndex: event.index
});
}
}
}
}, {
key: "validateDrop",
value: function validateDrop(dragPath, dropPath) {
if (!dragPath) {
return false;
} else {
//same node
if (dragPath === dropPath) {
return false;
} //parent dropped on an descendant
if (dropPath.indexOf(dragPath) === 0) {
return false;
}
return true;
}
}
}, {
key: "validateDropNode",
value: function validateDropNode(dragPath, dropPath) {
var validateDrop = this.validateDrop(dragPath, dropPath);
if (validateDrop) {
//child dropped on parent
if (dragPath.indexOf('-') > 0 && dragPath.substring(0, dragPath.lastIndexOf('-')) === dropPath) {
return false;
}
return true;
} else {
return false;
}
}
}, {
key: "validateDropPoint",
value: function validateDropPoint(event) {
var validateDrop = this.validateDrop(this.dragState.path, event.path);
if (validateDrop) {
//child dropped to next sibling's drop point
if (event.position === -1 && this.areSiblings(this.dragState.path, event.path) && this.dragState.index + 1 === event.index) {
return false;
}
return true;
} else {
return false;
}
}
}, {
key: "areSiblings",
value: function areSiblings(path1, path2) {
if (path1.length === 1 && path2.length === 1) return true;else return path1.substring(0, path1.lastIndexOf('-')) === path2.substring(0, path2.lastIndexOf('-'));
}
}, {
key: "findNode",
value: function findNode(value, path) {
if (path.length === 0) {
return null;
} else {
var index = parseInt(path[0], 10);
var nextSearchRoot = value.children ? value.children[index] : value[index];
if (path.length === 1) {
return nextSearchRoot;
} else {
path.shift();
return this.findNode(nextSearchRoot, path);
}
}
}
}, {
key: "isNodeLeaf",
value: function isNodeLeaf(node) {
return node.leaf === false ? false : !(node.children && node.children.length);
}
}, {
key: "onFilterInputKeyDown",
value: function onFilterInputKeyDown(event) {
//enter
if (event.which === 13) {
event.preventDefault();
}
}
}, {
key: "onFilterInputChange",
value: function onFilterInputChange(event) {
this.filterChanged = true;
var filterValue = event.target.value;
if (this.props.onFilterValueChange) {
this.props.onFilterValueChange({
originalEvent: event,
value: filterValue
});
} else {
this.setState({
filterValue: filterValue
});
}
}
}, {
key: "filter",
value: function filter(value) {
this.setState({
filterValue: ObjectUtils.isNotEmpty(value) ? value : ''
}, this._filter);
}
}, {
key: "_filter",
value: function _filter() {
if (!this.filterChanged) {
return;
}
var filterValue = this.getFilterValue();
if (ObjectUtils.isEmpty(filterValue)) {
this.filteredNodes = this.props.value;
} else {
this.filteredNodes = [];
var searchFields = this.props.filterBy.split(',');
var filterText = filterValue.toLocaleLowerCase(this.props.filterLocale);
var isStrictMode = this.props.filterMode === 'strict';
var _iterator = _createForOfIteratorHelper(this.props.value),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var node = _step.value;
var copyNode = _objectSpread({}, node);
var paramsWithoutNode = {
searchFields: searchFields,
filterText: filterText,
isStrictMode: isStrictMode
};
if (isStrictMode && (this.findFilteredNodes(copyNode, paramsWithoutNode) || this.isFilterMatched(copyNode, paramsWithoutNode)) || !isStrictMode && (this.isFilterMatched(copyNode, paramsWithoutNode) || this.findFilteredNodes(copyNode, paramsWithoutNode))) {
this.filteredNodes.push(copyNode);
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
this.filterChanged = false;
}
}, {
key: "findFilteredNodes",
value: function findFilteredNodes(node, paramsWithoutNode) {
if (node) {
var matched = false;
if (node.children) {
var childNodes = _toConsumableArray(node.children);
node.children = [];
var _iterator2 = _createForOfIteratorHelper(childNodes),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var childNode = _step2.value;
var copyChildNode = _objectSpread({}, childNode);
if (this.isFilterMatched(copyChildNode, paramsWithoutNode)) {
matched = true;
node.children.push(copyChildNode);
}
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
if (matched) {
node.expanded = true;
return true;
}
}
}
}, {
key: "isFilterMatched",
value: function isFilterMatched(node, _ref) {
var searchFields = _ref.searchFields,
filterText = _ref.filterText,
isStrictMode = _ref.isStrictMode;
var matched = false;
var _iterator3 = _createForOfIteratorHelper(searchFields),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var field = _step3.value;
var fieldValue = String(ObjectUtils.resolveFieldData(node, field)).toLocaleLowerCase(this.props.filterLocale);
if (fieldValue.indexOf(filterText) > -1) {
matched = true;
}
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
if (!matched || isStrictMode && !this.isNodeLeaf(node)) {
matched = this.findFilteredNodes(node, {
searchFields: searchFields,
filterText: filterText,
isStrictMode: isStrictMode
}) || matched;
}
return matched;
}
}, {
key: "renderRootChild",
value: function renderRootChild(node, index, last) {
return /*#__PURE__*/React.createElement(UITreeNode, {
key: node.key || node.label,
node: node,
index: index,
last: last,
path: String(index),
disabled: this.props.disabled,
selectionMode: this.props.selectionMode,
selectionKeys: this.props.selectionKeys,
onSelectionChange: this.props.onSelectionChange,
metaKeySelection: this.props.metaKeySelection,
contextMenuSelectionKey: this.props.contextMenuSelectionKey,
onContextMenuSelectionChange: this.props.onContextMenuSelectionChange,
onContextMenu: this.props.onContextMenu,
propagateSelectionDown: this.props.propagateSelectionDown,
propagateSelectionUp: this.props.propagateSelectionUp,
onExpand: this.props.onExpand,
onCollapse: this.props.onCollapse,
onSelect: this.props.onSelect,
onUnselect: this.props.onUnselect,
expandedKeys: this.getExpandedKeys(),
onToggle: this.onToggle,
nodeTemplate: this.props.nodeTemplate,
togglerTemplate: this.props.togglerTemplate,
isNodeLeaf: this.isNodeLeaf,
dragdropScope: this.props.dragdropScope,
onDragStart: this.onDragStart,
onDragEnd: this.onDragEnd,
onDrop: this.onDrop,
onDropPoint: this.onDropPoint,
onNodeClick: this.props.onNodeClick,
onNodeDoubleClick: this.props.onNodeDoubleClick
});
}
}, {
key: "renderRootChildren",
value: function renderRootChildren() {
var _this2 = this;
if (this.props.filter) {
this.filterChanged = true;
this._filter();
}
var value = this.getRootNode();
return value.map(function (node, index) {
return _this2.renderRootChild(node, index, index === value.length - 1);
});
}
}, {
key: "renderModel",
value: function renderModel() {
if (this.props.value) {
var rootNodes = this.renderRootChildren();
var contentClass = classNames('p-tree-container', this.props.contentClassName);
return /*#__PURE__*/React.createElement("ul", {
className: contentClass,
role: "tree",
"aria-label": this.props.ariaLabel,
"aria-labelledby": this.props.ariaLabelledBy,
style: this.props.contentStyle
}, rootNodes);
}
return null;
}
}, {
key: "renderLoader",
value: function renderLoader() {
if (this.props.loading) {
var icon = classNames('p-tree-loading-icon pi-spin', this.props.loadingIcon);
return /*#__PURE__*/React.createElement("div", {
className: "p-tree-loading-overlay p-component-overlay"
}, /*#__PURE__*/React.createElement("i", {
className: icon
}));
}
return null;
}
}, {
key: "renderFilter",
value: function renderFilter() {
if (this.props.filter) {
var filterValue = this.getFilterValue();
filterValue = ObjectUtils.isNotEmpty(filterValue) ? filterValue : '';
return /*#__PURE__*/React.createElement("div", {
className: "p-tree-filter-container"
}, /*#__PURE__*/React.createElement("input", {
type: "text",
value: filterValue,
autoComplete: "off",
className: "p-tree-filter p-inputtext p-component",
placeholder: this.props.filterPlaceholder,
onKeyDown: this.onFilterInputKeyDown,
onChange: this.onFilterInputChange,
disabled: this.props.disabled
}), /*#__PURE__*/React.createElement("span", {
className: "p-tree-filter-icon pi pi-search"
}));
}
return null;
}
}, {
key: "renderHeader",
value: function renderHeader() {
if (this.props.showHeader) {
var filterElement = this.renderFilter();
var content = filterElement;
if (this.props.header) {
var defaultContentOptions = {
filterContainerClassName: 'p-tree-filter-container',
filterIconClasssName: 'p-tree-filter-icon pi pi-search',
filterInput: {
className: 'p-tree-filter p-inputtext p-component',
onKeyDown: this.onFilterInputKeyDown,
onChange: this.onFilterInputChange
},
filterElement: filterElement,
element: content,
props: this.props
};
content = ObjectUtils.getJSXElement(this.props.header, defaultContentOptions);
}
return /*#__PURE__*/React.createElement("div", {
className: "p-tree-header"
}, content);
}
return null;
}
}, {
key: "renderFooter",
value: function renderFooter() {
var content = ObjectUtils.getJSXElement(this.props.footer, this.props);
return /*#__PURE__*/React.createElement("div", {
className: "p-tree-footer"
}, content);
}
}, {
key: "render",
value: function render() {
var className = classNames('p-tree p-component', this.props.className, {
'p-tree-selectable': this.props.selectionMode,
'p-tree-loading': this.props.loading,
'p-disabled': this.props.disabled
});
var loader = this.renderLoader();
var content = this.renderModel();
var header = this.renderHeader();
var footer = this.renderFooter();
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
className: className,
style: this.props.style
}, loader, header, content, footer);
}
}]);
return Tree;
}(Component);
_defineProperty(Tree, "defaultProps", {
id: null,
value: null,
disabled: false,
selectionMode: null,
selectionKeys: null,
onSelectionChange: null,
contextMenuSelectionKey: null,
onContextMenuSelectionChange: null,
expandedKeys: null,
style: null,
className: null,
contentStyle: null,
contentClassName: null,
metaKeySelection: true,
propagateSelectionUp: true,
propagateSelectionDown: true,
loading: false,
loadingIcon: 'pi pi-spinner',
dragdropScope: null,
header: null,
footer: null,
showHeader: true,
filter: false,
filterValue: null,
filterBy: 'label',
filterMode: 'lenient',
filterPlaceholder: null,
filterLocale: undefined,
nodeTemplate: null,
togglerTemplate: null,
onSelect: null,
onUnselect: null,
onExpand: null,
onCollapse: null,
onToggle: null,
onDragDrop: null,
onContextMenu: null,
onFilterValueChange: null,
onNodeClick: null,
onNodeDoubleClick: null
});
export { Tree };
|
ajax/libs/material-ui/4.9.2/esm/SnackbarContent/SnackbarContent.js | cdnjs/cdnjs | import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import Paper from '../Paper';
import { emphasize } from '../styles/colorManipulator';
export var styles = function styles(theme) {
var emphasis = theme.palette.type === 'light' ? 0.8 : 0.98;
var backgroundColor = emphasize(theme.palette.background.default, emphasis);
return {
/* Styles applied to the root element. */
root: _extends({}, theme.typography.body2, _defineProperty({
color: theme.palette.getContrastText(backgroundColor),
backgroundColor: backgroundColor,
display: 'flex',
alignItems: 'center',
flexWrap: 'wrap',
padding: '6px 16px',
borderRadius: theme.shape.borderRadius,
flexGrow: 1
}, theme.breakpoints.up('sm'), {
flexGrow: 'initial',
minWidth: 288
})),
/* Styles applied to the message wrapper element. */
message: {
padding: '8px 0'
},
/* Styles applied to the action wrapper element if `action` is provided. */
action: {
display: 'flex',
alignItems: 'center',
marginLeft: 'auto',
paddingLeft: 16,
marginRight: -8
}
};
};
var SnackbarContent = React.forwardRef(function SnackbarContent(props, ref) {
var action = props.action,
classes = props.classes,
className = props.className,
message = props.message,
_props$role = props.role,
role = _props$role === void 0 ? 'alert' : _props$role,
other = _objectWithoutProperties(props, ["action", "classes", "className", "message", "role"]);
return React.createElement(Paper, _extends({
role: role,
square: true,
elevation: 6,
className: clsx(classes.root, className),
ref: ref
}, other), React.createElement("div", {
className: classes.message
}, message), action ? React.createElement("div", {
className: classes.action
}, action) : null);
});
process.env.NODE_ENV !== "production" ? SnackbarContent.propTypes = {
/**
* The action to display. It renders after the message, at the end of the snackbar.
*/
action: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The message to display.
*/
message: PropTypes.node,
/**
* The ARIA role attribute of the element.
*/
role: PropTypes.string
} : void 0;
export default withStyles(styles, {
name: 'MuiSnackbarContent'
})(SnackbarContent); |
ajax/libs/material-ui/4.11.3-deprecations.0/RootRef/RootRef.js | cdnjs/cdnjs | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var React = _interopRequireWildcard(require("react"));
var ReactDOM = _interopRequireWildcard(require("react-dom"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _utils = require("@material-ui/utils");
var _setRef = _interopRequireDefault(require("../utils/setRef"));
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
var warnedOnce = false;
/**
* ⚠️⚠️⚠️
* If you want the DOM element of a Material-UI component check out
* [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element)
* first.
*
* This component uses `findDOMNode` which is deprecated in React.StrictMode.
*
* Helper component to allow attaching a ref to a
* wrapped element to access the underlying DOM element.
*
* It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801.
* For example:
* ```jsx
* import React from 'react';
* import RootRef from '@material-ui/core/RootRef';
*
* function MyComponent() {
* const domRef = React.useRef();
*
* React.useEffect(() => {
* console.log(domRef.current); // DOM node
* }, []);
*
* return (
* <RootRef rootRef={domRef}>
* <SomeChildComponent />
* </RootRef>
* );
* }
* ```
*
* @deprecated
*/
var RootRef = /*#__PURE__*/function (_React$Component) {
(0, _inherits2.default)(RootRef, _React$Component);
var _super = _createSuper(RootRef);
function RootRef() {
(0, _classCallCheck2.default)(this, RootRef);
return _super.apply(this, arguments);
}
(0, _createClass2.default)(RootRef, [{
key: "componentDidMount",
value: function componentDidMount() {
this.ref = ReactDOM.findDOMNode(this);
(0, _setRef.default)(this.props.rootRef, this.ref);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
var ref = ReactDOM.findDOMNode(this);
if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) {
if (prevProps.rootRef !== this.props.rootRef) {
(0, _setRef.default)(prevProps.rootRef, null);
}
this.ref = ref;
(0, _setRef.default)(this.props.rootRef, this.ref);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.ref = null;
(0, _setRef.default)(this.props.rootRef, null);
}
}, {
key: "render",
value: function render() {
if (process.env.NODE_ENV !== 'production') {
if (!warnedOnce) {
warnedOnce = true;
console.warn(['Material-UI: The RootRef component is deprecated.', 'The component relies on the ReactDOM.findDOMNode API which is deprecated in React.StrictMode.', 'Instead, you can get a reference to the underlying DOM node of the components via the `ref` prop.'].join('/n'));
}
}
return this.props.children;
}
}]);
return RootRef;
}(React.Component);
process.env.NODE_ENV !== "production" ? RootRef.propTypes = {
/**
* The wrapped element.
*/
children: _propTypes.default.element.isRequired,
/**
* A ref that points to the first DOM node of the wrapped element.
*/
rootRef: _utils.refType.isRequired
} : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== "production" ? RootRef.propTypes = (0, _utils.exactProp)(RootRef.propTypes) : void 0;
}
var _default = RootRef;
exports.default = _default; |
ajax/libs/primereact/7.0.0/skeleton/skeleton.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames } from 'primereact/utils';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Skeleton = /*#__PURE__*/function (_Component) {
_inherits(Skeleton, _Component);
var _super = _createSuper(Skeleton);
function Skeleton() {
_classCallCheck(this, Skeleton);
return _super.apply(this, arguments);
}
_createClass(Skeleton, [{
key: "skeletonStyle",
value: function skeletonStyle() {
if (this.props.size) return {
width: this.props.size,
height: this.props.size,
borderRadius: this.props.borderRadius
};else return {
width: this.props.width,
height: this.props.height,
borderRadius: this.props.borderRadius
};
}
}, {
key: "render",
value: function render() {
var skeletonClassName = classNames('p-skeleton p-component', {
'p-skeleton-circle': this.props.shape === 'circle',
'p-skeleton-none': this.props.animation === 'none'
}, this.props.className);
var style = this.skeletonStyle();
return /*#__PURE__*/React.createElement("div", {
style: style,
className: skeletonClassName
});
}
}]);
return Skeleton;
}(Component);
_defineProperty(Skeleton, "defaultProps", {
shape: 'rectangle',
size: null,
width: '100%',
height: '1rem',
borderRadius: null,
animation: 'wave',
style: null,
className: null
});
export { Skeleton };
|
ajax/libs/react-instantsearch/5.0.1/Dom.js | cdnjs/cdnjs | /*! ReactInstantSearch 5.0.1 | © Algolia, inc. | https://community.algolia.com/react-instantsearch */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Dom = {}),global.React));
}(this, (function (exports,React) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
// shim for using process in browser
// based off https://github.com/defunctzombie/node-process/blob/master/browser.js
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout() {
throw new Error('clearTimeout has not been defined');
}
var cachedSetTimeout = defaultSetTimout;
var cachedClearTimeout = defaultClearTimeout;
if (typeof global$1.setTimeout === 'function') {
cachedSetTimeout = setTimeout;
}
if (typeof global$1.clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
}
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e) {
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e) {
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while (len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
function nextTick(fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
}
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
var title = 'browser';
var platform = 'browser';
var browser = true;
var env = {};
var argv = [];
var version = ''; // empty string to avoid regexp issues
var versions = {};
var release = {};
var config = {};
function noop() {}
var on = noop;
var addListener = noop;
var once = noop;
var off = noop;
var removeListener = noop;
var removeAllListeners = noop;
var emit = noop;
function binding(name) {
throw new Error('process.binding is not supported');
}
function cwd() {
return '/';
}
function chdir(dir) {
throw new Error('process.chdir is not supported');
}function umask() {
return 0;
}
// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
var performance = global$1.performance || {};
var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () {
return new Date().getTime();
};
// generate timestamp or delta
// see http://nodejs.org/api/process.html#process_process_hrtime
function hrtime(previousTimestamp) {
var clocktime = performanceNow.call(performance) * 1e-3;
var seconds = Math.floor(clocktime);
var nanoseconds = Math.floor(clocktime % 1 * 1e9);
if (previousTimestamp) {
seconds = seconds - previousTimestamp[0];
nanoseconds = nanoseconds - previousTimestamp[1];
if (nanoseconds < 0) {
seconds--;
nanoseconds += 1e9;
}
}
return [seconds, nanoseconds];
}
var startTime = new Date();
function uptime() {
var currentTime = new Date();
var dif = currentTime - startTime;
return dif / 1000;
}
var process = {
nextTick: nextTick,
title: title,
browser: browser,
env: env,
argv: argv,
version: version,
versions: versions,
on: on,
addListener: addListener,
once: once,
off: off,
removeListener: removeListener,
removeAllListeners: removeAllListeners,
emit: emit,
binding: binding,
cwd: cwd,
chdir: chdir,
umask: umask,
hrtime: hrtime,
platform: platform,
release: release,
config: config,
uptime: uptime
};
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
var emptyFunction_1 = emptyFunction;
function invariant(condition, format, a, b, c, d, e, f) {
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
var invariant_1 = invariant;
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret_1) {
// It is still safe when called from React.
return;
}
invariant_1(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
} shim.isRequired = shim;
function getShim() {
return shim;
} // Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim
};
ReactPropTypes.checkPropTypes = emptyFunction_1;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = factoryWithThrowingShims();
}
});
/** 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;
}
var _isPrototype = isPrototype;
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
var _overArg = overArg;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = _overArg(Object.keys, Object);
var _nativeKeys = nativeKeys;
/** Used for built-in method references. */
var objectProto$1 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$1 = objectProto$1.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$1.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
var _baseKeys = baseKeys;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
var _freeGlobal = freeGlobal;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = _freeGlobal || freeSelf || Function('return this')();
var _root = root;
/** Built-in value references. */
var Symbol$1 = _root.Symbol;
var _Symbol = Symbol$1;
/** Used for built-in method references. */
var objectProto$2 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto$2.toString;
/** Built-in value references. */
var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty$2.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
var _getRawTag = getRawTag;
/** Used for built-in method references. */
var objectProto$3 = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString$1 = objectProto$3.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString$1.call(value);
}
var _objectToString = objectToString;
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag$1 && symToStringTag$1 in Object(value))
? _getRawTag(value)
: _objectToString(value);
}
var _baseGetTag = baseGetTag;
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
var isObject_1 = isObject;
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject_1(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = _baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
var isFunction_1 = isFunction;
/** Used to detect overreaching core-js shims. */
var coreJsData = _root['__core-js_shared__'];
var _coreJsData = coreJsData;
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
var _isMasked = isMasked;
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
var _toSource = toSource;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto$1 = Function.prototype,
objectProto$4 = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString$1 = funcProto$1.toString;
/** Used to check objects for own properties. */
var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString$1.call(hasOwnProperty$3).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject_1(value) || _isMasked(value)) {
return false;
}
var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
return pattern.test(_toSource(value));
}
var _baseIsNative = baseIsNative;
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
var _getValue = getValue;
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = _getValue(object, key);
return _baseIsNative(value) ? value : undefined;
}
var _getNative = getNative;
/* Built-in method references that are verified to be native. */
var DataView = _getNative(_root, 'DataView');
var _DataView = DataView;
/* Built-in method references that are verified to be native. */
var Map = _getNative(_root, 'Map');
var _Map = Map;
/* Built-in method references that are verified to be native. */
var Promise$1 = _getNative(_root, 'Promise');
var _Promise = Promise$1;
/* Built-in method references that are verified to be native. */
var Set = _getNative(_root, 'Set');
var _Set = Set;
/* Built-in method references that are verified to be native. */
var WeakMap = _getNative(_root, 'WeakMap');
var _WeakMap = WeakMap;
/** `Object#toString` result references. */
var mapTag = '[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;
};
}
var _getTag = getTag;
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
var isObjectLike_1 = isObjectLike;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
}
var _baseIsArguments = baseIsArguments;
/** Used for built-in method references. */
var objectProto$5 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto$5.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
return isObjectLike_1(value) && hasOwnProperty$4.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
var isArguments_1 = isArguments;
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
var isArray_1 = isArray;
/** 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;
}
var isLength_1 = isLength;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength_1(value.length) && !isFunction_1(value);
}
var isArrayLike_1 = isArrayLike;
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
var stubFalse_1 = stubFalse;
var isBuffer_1 = createCommonjsModule(function (module, exports) {
/** Detect free variable `exports`. */
var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? _root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse_1;
module.exports = isBuffer;
});
/** `Object#toString` result references. */
var argsTag$1 = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag$1 = '[object Function]',
mapTag$1 = '[object Map]',
numberTag = '[object Number]',
objectTag$1 = '[object Object]',
regexpTag = '[object RegExp]',
setTag$1 = '[object Set]',
stringTag = '[object String]',
weakMapTag$1 = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag$1 = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag$1] =
typedArrayTags[mapTag$1] = typedArrayTags[numberTag] =
typedArrayTags[objectTag$1] = typedArrayTags[regexpTag] =
typedArrayTags[setTag$1] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag$1] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike_1(value) &&
isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
}
var _baseIsTypedArray = baseIsTypedArray;
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
var _baseUnary = baseUnary;
var _nodeUtil = createCommonjsModule(function (module, exports) {
/** Detect free variable `exports`. */
var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && _freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
});
/* Node.js helper references. */
var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
var isTypedArray_1 = isTypedArray;
/** `Object#toString` result references. */
var mapTag$2 = '[object Map]',
setTag$2 = '[object Set]';
/** Used for built-in method references. */
var objectProto$6 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike_1(value) &&
(isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) {
return !value.length;
}
var tag = _getTag(value);
if (tag == mapTag$2 || tag == setTag$2) {
return !value.size;
}
if (_isPrototype(value)) {
return !_baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty$5.call(value, key)) {
return false;
}
}
return true;
}
var isEmpty_1 = isEmpty;
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
var _arrayMap = arrayMap;
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
var _listCacheClear = listCacheClear;
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
var eq_1 = eq;
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq_1(array[length][0], key)) {
return length;
}
}
return -1;
}
var _assocIndexOf = assocIndexOf;
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = _assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
var _listCacheDelete = listCacheDelete;
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = _assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
var _listCacheGet = listCacheGet;
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return _assocIndexOf(this.__data__, key) > -1;
}
var _listCacheHas = listCacheHas;
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = _assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
var _listCacheSet = listCacheSet;
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = _listCacheClear;
ListCache.prototype['delete'] = _listCacheDelete;
ListCache.prototype.get = _listCacheGet;
ListCache.prototype.has = _listCacheHas;
ListCache.prototype.set = _listCacheSet;
var _ListCache = ListCache;
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new _ListCache;
this.size = 0;
}
var _stackClear = stackClear;
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
var _stackDelete = stackDelete;
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
var _stackGet = stackGet;
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
var _stackHas = stackHas;
/* Built-in method references that are verified to be native. */
var nativeCreate = _getNative(Object, 'create');
var _nativeCreate = nativeCreate;
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
this.size = 0;
}
var _hashClear = hashClear;
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
var _hashDelete = hashDelete;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto$7 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (_nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty$6.call(data, key) ? data[key] : undefined;
}
var _hashGet = hashGet;
/** Used for built-in method references. */
var objectProto$8 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$7 = objectProto$8.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key);
}
var _hashHas = hashHas;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
return this;
}
var _hashSet = hashSet;
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = _hashClear;
Hash.prototype['delete'] = _hashDelete;
Hash.prototype.get = _hashGet;
Hash.prototype.has = _hashHas;
Hash.prototype.set = _hashSet;
var _Hash = Hash;
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new _Hash,
'map': new (_Map || _ListCache),
'string': new _Hash
};
}
var _mapCacheClear = mapCacheClear;
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
var _isKeyable = isKeyable;
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return _isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
var _getMapData = getMapData;
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = _getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
var _mapCacheDelete = mapCacheDelete;
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return _getMapData(this, key).get(key);
}
var _mapCacheGet = mapCacheGet;
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return _getMapData(this, key).has(key);
}
var _mapCacheHas = mapCacheHas;
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = _getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
var _mapCacheSet = mapCacheSet;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = _mapCacheClear;
MapCache.prototype['delete'] = _mapCacheDelete;
MapCache.prototype.get = _mapCacheGet;
MapCache.prototype.has = _mapCacheHas;
MapCache.prototype.set = _mapCacheSet;
var _MapCache = MapCache;
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof _ListCache) {
var pairs = data.__data__;
if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new _MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
var _stackSet = stackSet;
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new _ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = _stackClear;
Stack.prototype['delete'] = _stackDelete;
Stack.prototype.get = _stackGet;
Stack.prototype.has = _stackHas;
Stack.prototype.set = _stackSet;
var _Stack = Stack;
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
var _arrayEach = arrayEach;
var defineProperty = (function() {
try {
var func = _getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
var _defineProperty = defineProperty;
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && _defineProperty) {
_defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
var _baseAssignValue = baseAssignValue;
/** Used for built-in method references. */
var objectProto$9 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$8 = objectProto$9.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty$8.call(object, key) && eq_1(objValue, value)) ||
(value === undefined && !(key in object))) {
_baseAssignValue(object, key, value);
}
}
var _assignValue = assignValue;
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
_baseAssignValue(object, key, newValue);
} else {
_assignValue(object, key, newValue);
}
}
return object;
}
var _copyObject = copyObject;
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
var _baseTimes = baseTimes;
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER$1 = 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$1 : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
var _isIndex = isIndex;
/** Used for built-in method references. */
var objectProto$10 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$9 = objectProto$10.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray_1(value),
isArg = !isArr && isArguments_1(value),
isBuff = !isArr && !isArg && isBuffer_1(value),
isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? _baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty$9.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
_isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
var _arrayLikeKeys = arrayLikeKeys;
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
}
var keys_1 = keys;
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && _copyObject(source, keys_1(source), object);
}
var _baseAssign = baseAssign;
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
var _nativeKeysIn = nativeKeysIn;
/** Used for built-in method references. */
var objectProto$11 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$10 = objectProto$11.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject_1(object)) {
return _nativeKeysIn(object);
}
var isProto = _isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty$10.call(object, key)))) {
result.push(key);
}
}
return result;
}
var _baseKeysIn = baseKeysIn;
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn$1(object) {
return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
}
var keysIn_1 = keysIn$1;
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && _copyObject(source, keysIn_1(source), object);
}
var _baseAssignIn = baseAssignIn;
var _cloneBuffer = createCommonjsModule(function (module, exports) {
/** Detect free variable `exports`. */
var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? _root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
module.exports = cloneBuffer;
});
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
var _copyArray = copyArray;
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
var _arrayFilter = arrayFilter;
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
var stubArray_1 = stubArray;
/** Used for built-in method references. */
var objectProto$12 = Object.prototype;
/** Built-in value references. */
var propertyIsEnumerable$1 = objectProto$12.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return _arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable$1.call(object, symbol);
});
};
var _getSymbols = getSymbols;
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return _copyObject(source, _getSymbols(source), object);
}
var _copySymbols = copySymbols;
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
var _arrayPush = arrayPush;
/** Built-in value references. */
var getPrototype = _overArg(Object.getPrototypeOf, Object);
var _getPrototype = getPrototype;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
var result = [];
while (object) {
_arrayPush(result, _getSymbols(object));
object = _getPrototype(object);
}
return result;
};
var _getSymbolsIn = getSymbolsIn;
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return _copyObject(source, _getSymbolsIn(source), object);
}
var _copySymbolsIn = copySymbolsIn;
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
}
var _baseGetAllKeys = baseGetAllKeys;
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return _baseGetAllKeys(object, keys_1, _getSymbols);
}
var _getAllKeys = getAllKeys;
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
}
var _getAllKeysIn = getAllKeysIn;
/** Used for built-in method references. */
var objectProto$13 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$11 = objectProto$13.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$11.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
var _initCloneArray = initCloneArray;
/** Built-in value references. */
var Uint8Array = _root.Uint8Array;
var _Uint8Array = Uint8Array;
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
return result;
}
var _cloneArrayBuffer = cloneArrayBuffer;
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
var _cloneDataView = cloneDataView;
/**
* Adds the key-value `pair` to `map`.
*
* @private
* @param {Object} map The map to modify.
* @param {Array} pair The key-value pair to add.
* @returns {Object} Returns `map`.
*/
function addMapEntry(map, pair) {
// Don't return `map.set` because it's not chainable in IE 11.
map.set(pair[0], pair[1]);
return map;
}
var _addMapEntry = addMapEntry;
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
var _arrayReduce = arrayReduce;
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
var _mapToArray = mapToArray;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 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);
}
var _cloneMap = cloneMap;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
var _cloneRegExp = cloneRegExp;
/**
* Adds `value` to `set`.
*
* @private
* @param {Object} set The set to modify.
* @param {*} value The value to add.
* @returns {Object} Returns `set`.
*/
function addSetEntry(set, value) {
// Don't return `set.add` because it's not chainable in IE 11.
set.add(value);
return set;
}
var _addSetEntry = addSetEntry;
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
var _setToArray = setToArray;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$1 = 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$1) : _setToArray(set);
return _arrayReduce(array, _addSetEntry, new set.constructor);
}
var _cloneSet = cloneSet;
/** Used to convert symbols to primitives and strings. */
var symbolProto = _Symbol ? _Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
var _cloneSymbol = cloneSymbol;
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
var _cloneTypedArray = cloneTypedArray;
/** `Object#toString` result references. */
var boolTag$1 = '[object Boolean]',
dateTag$1 = '[object Date]',
mapTag$3 = '[object Map]',
numberTag$1 = '[object Number]',
regexpTag$1 = '[object RegExp]',
setTag$3 = '[object Set]',
stringTag$1 = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag$1 = '[object ArrayBuffer]',
dataViewTag$2 = '[object DataView]',
float32Tag$1 = '[object Float32Array]',
float64Tag$1 = '[object Float64Array]',
int8Tag$1 = '[object Int8Array]',
int16Tag$1 = '[object Int16Array]',
int32Tag$1 = '[object Int32Array]',
uint8Tag$1 = '[object Uint8Array]',
uint8ClampedTag$1 = '[object Uint8ClampedArray]',
uint16Tag$1 = '[object Uint16Array]',
uint32Tag$1 = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `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$1:
return _cloneArrayBuffer(object);
case boolTag$1:
case dateTag$1:
return new Ctor(+object);
case dataViewTag$2:
return _cloneDataView(object, isDeep);
case float32Tag$1: case float64Tag$1:
case int8Tag$1: case int16Tag$1: case int32Tag$1:
case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
return _cloneTypedArray(object, isDeep);
case mapTag$3:
return _cloneMap(object, isDeep, cloneFunc);
case numberTag$1:
case stringTag$1:
return new Ctor(object);
case regexpTag$1:
return _cloneRegExp(object);
case setTag$3:
return _cloneSet(object, isDeep, cloneFunc);
case symbolTag:
return _cloneSymbol(object);
}
}
var _initCloneByTag = initCloneByTag;
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject_1(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
var _baseCreate = baseCreate;
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !_isPrototype(object))
? _baseCreate(_getPrototype(object))
: {};
}
var _initCloneObject = initCloneObject;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$2 = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var argsTag$2 = '[object Arguments]',
arrayTag$1 = '[object Array]',
boolTag$2 = '[object Boolean]',
dateTag$2 = '[object Date]',
errorTag$1 = '[object Error]',
funcTag$2 = '[object Function]',
genTag$1 = '[object GeneratorFunction]',
mapTag$4 = '[object Map]',
numberTag$2 = '[object Number]',
objectTag$2 = '[object Object]',
regexpTag$2 = '[object RegExp]',
setTag$4 = '[object Set]',
stringTag$2 = '[object String]',
symbolTag$1 = '[object Symbol]',
weakMapTag$2 = '[object WeakMap]';
var arrayBufferTag$2 = '[object ArrayBuffer]',
dataViewTag$3 = '[object DataView]',
float32Tag$2 = '[object Float32Array]',
float64Tag$2 = '[object Float64Array]',
int8Tag$2 = '[object Int8Array]',
int16Tag$2 = '[object Int16Array]',
int32Tag$2 = '[object Int32Array]',
uint8Tag$2 = '[object Uint8Array]',
uint8ClampedTag$2 = '[object Uint8ClampedArray]',
uint16Tag$2 = '[object Uint16Array]',
uint32Tag$2 = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag$2] = cloneableTags[arrayTag$1] =
cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$3] =
cloneableTags[boolTag$2] = cloneableTags[dateTag$2] =
cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] =
cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] =
cloneableTags[int32Tag$2] = cloneableTags[mapTag$4] =
cloneableTags[numberTag$2] = cloneableTags[objectTag$2] =
cloneableTags[regexpTag$2] = cloneableTags[setTag$4] =
cloneableTags[stringTag$2] = cloneableTags[symbolTag$1] =
cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] =
cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true;
cloneableTags[errorTag$1] = cloneableTags[funcTag$2] =
cloneableTags[weakMapTag$2] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG$2,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject_1(value)) {
return value;
}
var isArr = isArray_1(value);
if (isArr) {
result = _initCloneArray(value);
if (!isDeep) {
return _copyArray(value, result);
}
} else {
var tag = _getTag(value),
isFunc = tag == funcTag$2 || tag == genTag$1;
if (isBuffer_1(value)) {
return _cloneBuffer(value, isDeep);
}
if (tag == objectTag$2 || tag == argsTag$2 || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : _initCloneObject(value);
if (!isDeep) {
return isFlat
? _copySymbolsIn(value, _baseAssignIn(result, value))
: _copySymbols(value, _baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = _initCloneByTag(value, tag, baseClone, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new _Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
var keysFunc = isFull
? (isFlat ? _getAllKeysIn : _getAllKeys)
: (isFlat ? keysIn : keys_1);
var props = isArr ? undefined : keysFunc(value);
_arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
_assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
var _baseClone = baseClone;
/** `Object#toString` result references. */
var symbolTag$2 = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike_1(value) && _baseGetTag(value) == symbolTag$2);
}
var isSymbol_1 = isSymbol;
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray_1(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol_1(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
var _isKey = isKey;
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || _MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = _MapCache;
var memoize_1 = memoize;
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize_1(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
var _memoizeCapped = memoizeCapped;
/** Used to match property names within property paths. */
var reLeadingDot = /^\./,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = _memoizeCapped(function(string) {
var result = [];
if (reLeadingDot.test(string)) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
var _stringToPath = stringToPath;
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray_1(value)) {
// Recursively convert values (susceptible to call stack limits).
return _arrayMap(value, baseToString) + '';
}
if (isSymbol_1(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
var _baseToString = baseToString;
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : _baseToString(value);
}
var toString_1 = toString;
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray_1(value)) {
return value;
}
return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
}
var _castPath = castPath;
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
var last_1 = last;
/** Used as references for various `Number` constants. */
var INFINITY$1 = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol_1(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
}
var _toKey = toKey;
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = _castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[_toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
var _baseGet = baseGet;
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
var _baseSlice = baseSlice;
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1));
}
var _parent = parent;
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = _castPath(path, object);
object = _parent(object, path);
return object == null || delete object[_toKey(last_1(path))];
}
var _baseUnset = baseUnset;
/** `Object#toString` result references. */
var objectTag$3 = '[object Object]';
/** Used for built-in method references. */
var funcProto$2 = Function.prototype,
objectProto$14 = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString$2 = funcProto$2.toString;
/** Used to check objects for own properties. */
var hasOwnProperty$12 = objectProto$14.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString$2.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) {
return false;
}
var proto = _getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty$12.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString$2.call(Ctor) == objectCtorString;
}
var isPlainObject_1 = isPlainObject;
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject_1(value) ? undefined : value;
}
var _customOmitClone = customOmitClone;
/** Built-in value references. */
var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray_1(value) || isArguments_1(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
var _isFlattenable = isFlattenable;
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = _isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
_arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
var _baseFlatten = baseFlatten;
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? _baseFlatten(array, 1) : [];
}
var flatten_1 = flatten;
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
var _apply = apply;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return _apply(func, this, otherArgs);
};
}
var _overRest = overRest;
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
var constant_1 = constant;
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
var identity_1 = identity;
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !_defineProperty ? identity_1 : function(func, string) {
return _defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant_1(string),
'writable': true
});
};
var _baseSetToString = baseSetToString;
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
var _shortOut = shortOut;
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = _shortOut(_baseSetToString);
var _setToString = setToString;
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return _setToString(_overRest(func, undefined, flatten_1), func + '');
}
var _flatRest = flatRest;
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG$3 = 1,
CLONE_FLAT_FLAG$1 = 2,
CLONE_SYMBOLS_FLAG$1 = 4;
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = _flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = _arrayMap(paths, function(path) {
path = _castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
_copyObject(object, _getAllKeysIn(object), result);
if (isDeep) {
result = _baseClone(result, CLONE_DEEP_FLAG$3 | CLONE_FLAT_FLAG$1 | CLONE_SYMBOLS_FLAG$1, _customOmitClone);
}
var length = paths.length;
while (length--) {
_baseUnset(result, paths[length]);
}
return result;
});
var omit_1 = omit;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED$2);
return this;
}
var _setCacheAdd = setCacheAdd;
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
var _setCacheHas = setCacheHas;
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new _MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
SetCache.prototype.has = _setCacheHas;
var _SetCache = SetCache;
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
var _baseFindIndex = baseFindIndex;
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
var _baseIsNaN = baseIsNaN;
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
var _strictIndexOf = strictIndexOf;
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? _strictIndexOf(array, value, fromIndex)
: _baseFindIndex(array, _baseIsNaN, fromIndex);
}
var _baseIndexOf = baseIndexOf;
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && _baseIndexOf(array, value, 0) > -1;
}
var _arrayIncludes = arrayIncludes;
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
var _arrayIncludesWith = arrayIncludesWith;
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
var _cacheHas = cacheHas;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/
function baseIntersection(arrays, iteratee, comparator) {
var includes = comparator ? _arrayIncludesWith : _arrayIncludes,
length = arrays[0].length,
othLength = arrays.length,
othIndex = othLength,
caches = Array(othLength),
maxLength = Infinity,
result = [];
while (othIndex--) {
var array = arrays[othIndex];
if (othIndex && iteratee) {
array = _arrayMap(array, _baseUnary(iteratee));
}
maxLength = nativeMin(array.length, maxLength);
caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
? new _SetCache(othIndex && array)
: undefined;
}
array = arrays[0];
var index = -1,
seen = caches[0];
outer:
while (++index < length && result.length < maxLength) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (!(seen
? _cacheHas(seen, computed)
: includes(result, computed, comparator)
)) {
othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if (!(cache
? _cacheHas(cache, computed)
: includes(arrays[othIndex], computed, comparator))
) {
continue outer;
}
}
if (seen) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
var _baseIntersection = baseIntersection;
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return _setToString(_overRest(func, start, identity_1), func + '');
}
var _baseRest = baseRest;
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike_1(value) && isArrayLike_1(value);
}
var isArrayLikeObject_1 = isArrayLikeObject;
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject_1(value) ? value : [];
}
var _castArrayLikeObject = castArrayLikeObject;
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/
var intersection = _baseRest(function(arrays) {
var mapped = _arrayMap(arrays, _castArrayLikeObject);
return (mapped.length && mapped[0] === arrays[0])
? _baseIntersection(mapped)
: [];
});
var intersection_1 = intersection;
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
var _createBaseFor = createBaseFor;
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = _createBaseFor();
var _baseFor = baseFor;
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && _baseFor(object, iteratee, keys_1);
}
var _baseForOwn = baseForOwn;
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity_1;
}
var _castFunction = castFunction;
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forOwn(object, iteratee) {
return object && _baseForOwn(object, _castFunction(iteratee));
}
var forOwn_1 = forOwn;
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike_1(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
var _createBaseEach = createBaseEach;
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = _createBaseEach(_baseForOwn);
var _baseEach = baseEach;
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray_1(collection) ? _arrayEach : _baseEach;
return func(collection, _castFunction(iteratee));
}
var forEach_1 = forEach;
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
_baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
var _baseFilter = baseFilter;
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
var _arraySome = arraySome;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked && stack.get(other)) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!_arraySome(other, function(othValue, othIndex) {
if (!_cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
var _equalArrays = equalArrays;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$1 = 1,
COMPARE_UNORDERED_FLAG$1 = 2;
/** `Object#toString` result references. */
var boolTag$3 = '[object Boolean]',
dateTag$3 = '[object Date]',
errorTag$2 = '[object Error]',
mapTag$5 = '[object Map]',
numberTag$3 = '[object Number]',
regexpTag$3 = '[object RegExp]',
setTag$5 = '[object Set]',
stringTag$3 = '[object String]',
symbolTag$3 = '[object Symbol]';
var arrayBufferTag$3 = '[object ArrayBuffer]',
dataViewTag$4 = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined,
symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag$4:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag$3:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
return false;
}
return true;
case boolTag$3:
case dateTag$3:
case numberTag$3:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq_1(+object, +other);
case errorTag$2:
return object.name == other.name && object.message == other.message;
case regexpTag$3:
case stringTag$3:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag$5:
var convert = _mapToArray;
case setTag$5:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
convert || (convert = _setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG$1;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag$3:
if (symbolValueOf$1) {
return symbolValueOf$1.call(object) == symbolValueOf$1.call(other);
}
}
return false;
}
var _equalByTag = equalByTag;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$2 = 1;
/** Used for built-in method references. */
var objectProto$15 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$13 = objectProto$15.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
objProps = _getAllKeys(object),
objLength = objProps.length,
othProps = _getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty$13.call(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked && stack.get(other)) {
return stacked == other;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
var _equalObjects = equalObjects;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$3 = 1;
/** `Object#toString` result references. */
var argsTag$3 = '[object Arguments]',
arrayTag$2 = '[object Array]',
objectTag$4 = '[object Object]';
/** Used for built-in method references. */
var objectProto$16 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$14 = objectProto$16.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray_1(object),
othIsArr = isArray_1(other),
objTag = objIsArr ? arrayTag$2 : _getTag(object),
othTag = othIsArr ? arrayTag$2 : _getTag(other);
objTag = objTag == argsTag$3 ? objectTag$4 : objTag;
othTag = othTag == argsTag$3 ? objectTag$4 : othTag;
var objIsObj = objTag == objectTag$4,
othIsObj = othTag == objectTag$4,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer_1(object)) {
if (!isBuffer_1(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new _Stack);
return (objIsArr || isTypedArray_1(object))
? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
var objIsWrapped = objIsObj && hasOwnProperty$14.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty$14.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new _Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new _Stack);
return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
var _baseIsEqualDeep = baseIsEqualDeep;
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) {
return value !== value && other !== other;
}
return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
var _baseIsEqual = baseIsEqual;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$4 = 1,
COMPARE_UNORDERED_FLAG$2 = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new _Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
var _baseIsMatch = baseIsMatch;
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject_1(value);
}
var _isStrictComparable = isStrictComparable;
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys_1(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, _isStrictComparable(value)];
}
return result;
}
var _getMatchData = getMatchData;
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
var _matchesStrictComparable = matchesStrictComparable;
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = _getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || _baseIsMatch(object, source, matchData);
};
}
var _baseMatches = baseMatches;
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : _baseGet(object, path);
return result === undefined ? defaultValue : result;
}
var get_1 = get;
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
var _baseHasIn = baseHasIn;
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = _castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = _toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength_1(length) && _isIndex(key, length) &&
(isArray_1(object) || isArguments_1(object));
}
var _hasPath = hasPath;
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && _hasPath(object, path, _baseHasIn);
}
var hasIn_1 = hasIn;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG$5 = 1,
COMPARE_UNORDERED_FLAG$3 = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (_isKey(path) && _isStrictComparable(srcValue)) {
return _matchesStrictComparable(_toKey(path), srcValue);
}
return function(object) {
var objValue = get_1(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn_1(object, path)
: _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
};
}
var _baseMatchesProperty = baseMatchesProperty;
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
var _baseProperty = baseProperty;
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return _baseGet(object, path);
};
}
var _basePropertyDeep = basePropertyDeep;
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
}
var property_1 = property;
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity_1;
}
if (typeof value == 'object') {
return isArray_1(value)
? _baseMatchesProperty(value[0], value[1])
: _baseMatches(value);
}
return property_1(value);
}
var _baseIteratee = baseIteratee;
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*/
function filter(collection, predicate) {
var func = isArray_1(collection) ? _arrayFilter : _baseFilter;
return func(collection, _baseIteratee(predicate, 3));
}
var filter_1 = filter;
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike_1(collection) ? Array(collection.length) : [];
_baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
var _baseMap = baseMap;
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray_1(collection) ? _arrayMap : _baseMap;
return func(collection, _baseIteratee(iteratee, 3));
}
var map_1 = map;
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
var _baseReduce = baseReduce;
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray_1(collection) ? _arrayReduce : _baseReduce,
initAccum = arguments.length < 3;
return func(collection, _baseIteratee(iteratee, 4), accumulator, initAccum, _baseEach);
}
var reduce_1 = reduce;
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol_1(value)) {
return NAN;
}
if (isObject_1(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject_1(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
var toNumber_1 = toNumber;
/** Used as references for various `Number` constants. */
var INFINITY$2 = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber_1(value);
if (value === INFINITY$2 || value === -INFINITY$2) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
var toFinite_1 = toFinite;
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite_1(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
var toInteger_1 = toInteger;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$1 = Math.max;
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger_1(fromIndex);
if (index < 0) {
index = nativeMax$1(length + index, 0);
}
return _baseIndexOf(array, value, index);
}
var indexOf_1 = indexOf;
/** `Object#toString` result references. */
var numberTag$4 = '[object Number]';
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike_1(value) && _baseGetTag(value) == numberTag$4);
}
var isNumber_1 = isNumber;
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN$1(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber_1(value) && value != +value;
}
var _isNaN = isNaN$1;
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return _baseIsEqual(value, other);
}
var isEqual_1 = isEqual;
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
var isUndefined_1 = isUndefined;
/** `Object#toString` result references. */
var stringTag$4 = '[object String]';
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$4);
}
var isString_1 = isString;
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike_1(collection)) {
var iteratee = _baseIteratee(predicate, 3);
collection = keys_1(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
var _createFind = createFind;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$2 = Math.max;
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger_1(fromIndex);
if (index < 0) {
index = nativeMax$2(length + index, 0);
}
return _baseFindIndex(array, _baseIteratee(predicate, 3), index);
}
var findIndex_1 = findIndex;
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find = _createFind(findIndex_1);
var find_1 = find;
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : _baseSlice(array, start, end);
}
var _castSlice = castSlice;
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
var _charsEndIndex = charsEndIndex;
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
var _charsStartIndex = charsStartIndex;
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
var _asciiToArray = asciiToArray;
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsZWJ = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
var _hasUnicode = hasUnicode;
/** Used to compose unicode character classes. */
var rsAstralRange$1 = '\\ud800-\\udfff',
rsComboMarksRange$1 = '\\u0300-\\u036f',
reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f',
rsComboSymbolsRange$1 = '\\u20d0-\\u20ff',
rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1,
rsVarRange$1 = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange$1 + ']',
rsCombo = '[' + rsComboRange$1 + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange$1 + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsZWJ$1 = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange$1 + ']?',
rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
var _unicodeToArray = unicodeToArray;
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return _hasUnicode(string)
? _unicodeToArray(string)
: _asciiToArray(string);
}
var _stringToArray = stringToArray;
/** Used to match leading and trailing whitespace. */
var reTrim$1 = /^\s+|\s+$/g;
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString_1(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrim$1, '');
}
if (!string || !(chars = _baseToString(chars))) {
return string;
}
var strSymbols = _stringToArray(string),
chrSymbols = _stringToArray(chars),
start = _charsStartIndex(strSymbols, chrSymbols),
end = _charsEndIndex(strSymbols, chrSymbols) + 1;
return _castSlice(strSymbols, start, end).join('');
}
var trim_1 = trim;
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject_1(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike_1(object) && _isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq_1(object[index], value);
}
return false;
}
var _isIterateeCall = isIterateeCall;
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return _baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && _isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
var _createAssigner = createAssigner;
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = _createAssigner(function(object, source, srcIndex, customizer) {
_copyObject(source, keysIn_1(source), object, customizer);
});
var assignInWith_1 = assignInWith;
/** Used for built-in method references. */
var objectProto$17 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$15 = objectProto$17.hasOwnProperty;
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq_1(objValue, objectProto$17[key]) && !hasOwnProperty$15.call(object, key))) {
return srcValue;
}
return objValue;
}
var _customDefaultsAssignIn = customDefaultsAssignIn;
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = _baseRest(function(args) {
args.push(undefined, _customDefaultsAssignIn);
return _apply(assignInWith_1, undefined, args);
});
var defaults_1 = defaults;
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq_1(object[key], value)) ||
(value === undefined && !(key in object))) {
_baseAssignValue(object, key, value);
}
}
var _assignMergeValue = assignMergeValue;
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return _copyObject(value, keysIn_1(value));
}
var toPlainObject_1 = toPlainObject;
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = object[key],
srcValue = source[key],
stacked = stack.get(srcValue);
if (stacked) {
_assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray_1(srcValue),
isBuff = !isArr && isBuffer_1(srcValue),
isTyped = !isArr && !isBuff && isTypedArray_1(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray_1(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject_1(objValue)) {
newValue = _copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = _cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = _cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject_1(srcValue) || isArguments_1(srcValue)) {
newValue = objValue;
if (isArguments_1(objValue)) {
newValue = toPlainObject_1(objValue);
}
else if (!isObject_1(objValue) || (srcIndex && isFunction_1(objValue))) {
newValue = _initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
_assignMergeValue(object, key, newValue);
}
var _baseMergeDeep = baseMergeDeep;
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
_baseFor(source, function(srcValue, key) {
if (isObject_1(srcValue)) {
stack || (stack = new _Stack);
_baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(object[key], srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
_assignMergeValue(object, key, newValue);
}
}, keysIn_1);
}
var _baseMerge = baseMerge;
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = _createAssigner(function(object, source, srcIndex) {
_baseMerge(object, source, srcIndex);
});
var merge_1 = merge;
function valToNumber(v) {
if (isNumber_1(v)) {
return v;
} else if (isString_1(v)) {
return parseFloat(v);
} else if (isArray_1(v)) {
return map_1(v, valToNumber);
}
throw new Error('The value should be a number, a parseable string or an array of those.');
}
var valToNumber_1 = valToNumber;
function filterState(state, filters) {
var partialState = {};
var attributeFilters = filter_1(filters, function(f) { return f.indexOf('attribute:') !== -1; });
var attributes = map_1(attributeFilters, function(aF) { return aF.split(':')[1]; });
if (indexOf_1(attributes, '*') === -1) {
forEach_1(attributes, function(attr) {
if (state.isConjunctiveFacet(attr) && state.isFacetRefined(attr)) {
if (!partialState.facetsRefinements) partialState.facetsRefinements = {};
partialState.facetsRefinements[attr] = state.facetsRefinements[attr];
}
if (state.isDisjunctiveFacet(attr) && state.isDisjunctiveFacetRefined(attr)) {
if (!partialState.disjunctiveFacetsRefinements) partialState.disjunctiveFacetsRefinements = {};
partialState.disjunctiveFacetsRefinements[attr] = state.disjunctiveFacetsRefinements[attr];
}
if (state.isHierarchicalFacet(attr) && state.isHierarchicalFacetRefined(attr)) {
if (!partialState.hierarchicalFacetsRefinements) partialState.hierarchicalFacetsRefinements = {};
partialState.hierarchicalFacetsRefinements[attr] = state.hierarchicalFacetsRefinements[attr];
}
var numericRefinements = state.getNumericRefinements(attr);
if (!isEmpty_1(numericRefinements)) {
if (!partialState.numericRefinements) partialState.numericRefinements = {};
partialState.numericRefinements[attr] = state.numericRefinements[attr];
}
});
} else {
if (!isEmpty_1(state.numericRefinements)) {
partialState.numericRefinements = state.numericRefinements;
}
if (!isEmpty_1(state.facetsRefinements)) partialState.facetsRefinements = state.facetsRefinements;
if (!isEmpty_1(state.disjunctiveFacetsRefinements)) {
partialState.disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements;
}
if (!isEmpty_1(state.hierarchicalFacetsRefinements)) {
partialState.hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements;
}
}
var searchParameters = filter_1(
filters,
function(f) {
return f.indexOf('attribute:') === -1;
}
);
forEach_1(
searchParameters,
function(parameterKey) {
partialState[parameterKey] = state[parameterKey];
}
);
return partialState;
}
var filterState_1 = filterState;
/**
* Functions to manipulate refinement lists
*
* The RefinementList is not formally defined through a prototype but is based
* on a specific structure.
*
* @module SearchParameters.refinementList
*
* @typedef {string[]} SearchParameters.refinementList.Refinements
* @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList
*/
var lib = {
/**
* Adds a refinement to a RefinementList
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement, if the value is not a string it will be converted
* @return {RefinementList} a new and updated refinement list
*/
addRefinement: function addRefinement(refinementList, attribute, value) {
if (lib.isRefined(refinementList, attribute, value)) {
return refinementList;
}
var valueAsString = '' + value;
var facetRefinement = !refinementList[attribute] ?
[valueAsString] :
refinementList[attribute].concat(valueAsString);
var mod = {};
mod[attribute] = facetRefinement;
return defaults_1({}, mod, refinementList);
},
/**
* Removes refinement(s) for an attribute:
* - if the value is specified removes the refinement for the value on the attribute
* - if no value is specified removes all the refinements for this attribute
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} [value] the value of the refinement
* @return {RefinementList} a new and updated refinement lst
*/
removeRefinement: function removeRefinement(refinementList, attribute, value) {
if (isUndefined_1(value)) {
return lib.clearRefinement(refinementList, attribute);
}
var valueAsString = '' + value;
return lib.clearRefinement(refinementList, function(v, f) {
return attribute === f && valueAsString === v;
});
},
/**
* Toggles the refinement value for an attribute.
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement
* @return {RefinementList} a new and updated list
*/
toggleRefinement: function toggleRefinement(refinementList, attribute, value) {
if (isUndefined_1(value)) throw new Error('toggleRefinement should be used with a value');
if (lib.isRefined(refinementList, attribute, value)) {
return lib.removeRefinement(refinementList, attribute, value);
}
return lib.addRefinement(refinementList, attribute, value);
},
/**
* Clear all or parts of a RefinementList. Depending on the arguments, three
* kinds of behavior can happen:
* - if no attribute is provided: clears the whole list
* - if an attribute is provided as a string: clears the list for the specific attribute
* - if an attribute is provided as a function: discards the elements for which the function returns true
* @param {RefinementList} refinementList the initial list
* @param {string} [attribute] the attribute or function to discard
* @param {string} [refinementType] optional parameter to give more context to the attribute function
* @return {RefinementList} a new and updated refinement list
*/
clearRefinement: function clearRefinement(refinementList, attribute, refinementType) {
if (isUndefined_1(attribute)) {
return {};
} else if (isString_1(attribute)) {
return omit_1(refinementList, attribute);
} else if (isFunction_1(attribute)) {
return reduce_1(refinementList, function(memo, values, key) {
var facetList = filter_1(values, function(value) {
return !attribute(value, key, refinementType);
});
if (!isEmpty_1(facetList)) memo[key] = facetList;
return memo;
}, {});
}
},
/**
* Test if the refinement value is used for the attribute. If no refinement value
* is provided, test if the refinementList contains any refinement for the
* given attribute.
* @param {RefinementList} refinementList the list of refinement
* @param {string} attribute name of the attribute
* @param {string} [refinementValue] value of the filter/refinement
* @return {boolean}
*/
isRefined: function isRefined(refinementList, attribute, refinementValue) {
var indexOf = indexOf_1;
var containsRefinements = !!refinementList[attribute] &&
refinementList[attribute].length > 0;
if (isUndefined_1(refinementValue) || !containsRefinements) {
return containsRefinements;
}
var refinementValueAsString = '' + refinementValue;
return indexOf(refinementList[attribute], refinementValueAsString) !== -1;
}
};
var RefinementList = lib;
/**
* like _.find but using _.isEqual to be able to use it
* to find arrays.
* @private
* @param {any[]} array array to search into
* @param {any} searchedValue the value we're looking for
* @return {any} the searched value or undefined
*/
function findArray(array, searchedValue) {
return find_1(array, function(currentValue) {
return isEqual_1(currentValue, searchedValue);
});
}
/**
* The facet list is the structure used to store the list of values used to
* filter a single attribute.
* @typedef {string[]} SearchParameters.FacetList
*/
/**
* Structure to store numeric filters with the operator as the key. The supported operators
* are `=`, `>`, `<`, `>=`, `<=` and `!=`.
* @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList
*/
/**
* SearchParameters is the data structure that contains all the information
* usable for making a search to Algolia API. It doesn't do the search itself,
* nor does it contains logic about the parameters.
* It is an immutable object, therefore it has been created in a way that each
* changes does not change the object itself but returns a copy with the
* modification.
* This object should probably not be instantiated outside of the helper. It will
* be provided when needed. This object is documented for reference as you'll
* get it from events generated by the {@link AlgoliaSearchHelper}.
* If need be, instantiate the Helper from the factory function {@link SearchParameters.make}
* @constructor
* @classdesc contains all the parameters of a search
* @param {object|SearchParameters} newParameters existing parameters or partial object
* for the properties of a new SearchParameters
* @see SearchParameters.make
* @example <caption>SearchParameters of the first query in
* <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption>
{
"query": "",
"disjunctiveFacets": [
"customerReviewCount",
"category",
"salePrice_range",
"manufacturer"
],
"maxValuesPerFacet": 30,
"page": 0,
"hitsPerPage": 10,
"facets": [
"type",
"shipping"
]
}
*/
function SearchParameters(newParameters) {
var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {};
/**
* Targeted index. This parameter is mandatory.
* @member {string}
*/
this.index = params.index || '';
// Query
/**
* Query string of the instant search. The empty string is a valid query.
* @member {string}
* @see https://www.algolia.com/doc/rest#param-query
*/
this.query = params.query || '';
// Facets
/**
* This attribute contains the list of all the conjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.facets = params.facets || [];
/**
* This attribute contains the list of all the disjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.disjunctiveFacets = params.disjunctiveFacets || [];
/**
* This attribute contains the list of all the hierarchical facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* Hierarchical facets are a sub type of disjunctive facets that
* let you filter faceted attributes hierarchically.
* @member {string[]|object[]}
*/
this.hierarchicalFacets = params.hierarchicalFacets || [];
// Refinements
/**
* This attribute contains all the filters that need to be
* applied on the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsRefinements = params.facetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* excluded from the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters excluded for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsExcludes = params.facetsExcludes || {};
/**
* This attribute contains all the filters that need to be
* applied on the disjunctive facets. Each facet must be properly
* defined in the `disjunctiveFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* applied on the numeric attributes.
*
* The key is the name of the attribute, and the value is the
* filters to apply to this attribute.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `numericFilters` attribute.
* @member {Object.<string, SearchParameters.OperatorList>}
*/
this.numericRefinements = params.numericRefinements || {};
/**
* This attribute contains all the tags used to refine the query.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `tagFilters` attribute.
* @member {string[]}
*/
this.tagRefinements = params.tagRefinements || [];
/**
* This attribute contains all the filters that need to be
* applied on the hierarchical facets. Each facet must be properly
* defined in the `hierarchicalFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name. The FacetList values
* are structured as a string that contain the values for each level
* separated by the configured separator.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {};
/**
* Contains the numeric filters in the raw format of the Algolia API. Setting
* this parameter is not compatible with the usage of numeric filters methods.
* @see https://www.algolia.com/doc/javascript#numericFilters
* @member {string}
*/
this.numericFilters = params.numericFilters;
/**
* Contains the tag filters in the raw format of the Algolia API. Setting this
* parameter is not compatible with the of the add/remove/toggle methods of the
* tag api.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.tagFilters = params.tagFilters;
/**
* Contains the optional tag filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalTagFilters = params.optionalTagFilters;
/**
* Contains the optional facet filters in the raw format of the Algolia API.
* @see https://www.algolia.com/doc/rest#param-tagFilters
* @member {string}
*/
this.optionalFacetFilters = params.optionalFacetFilters;
// Misc. parameters
/**
* Number of hits to be returned by the search API
* @member {number}
* @see https://www.algolia.com/doc/rest#param-hitsPerPage
*/
this.hitsPerPage = params.hitsPerPage;
/**
* Number of values for each faceted attribute
* @member {number}
* @see https://www.algolia.com/doc/rest#param-maxValuesPerFacet
*/
this.maxValuesPerFacet = params.maxValuesPerFacet;
/**
* The current page number
* @member {number}
* @see https://www.algolia.com/doc/rest#param-page
*/
this.page = params.page || 0;
/**
* How the query should be treated by the search engine.
* Possible values: prefixAll, prefixLast, prefixNone
* @see https://www.algolia.com/doc/rest#param-queryType
* @member {string}
*/
this.queryType = params.queryType;
/**
* How the typo tolerance behave in the search engine.
* Possible values: true, false, min, strict
* @see https://www.algolia.com/doc/rest#param-typoTolerance
* @member {string}
*/
this.typoTolerance = params.typoTolerance;
/**
* Number of characters to wait before doing one character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor1Typo
* @member {number}
*/
this.minWordSizefor1Typo = params.minWordSizefor1Typo;
/**
* Number of characters to wait before doing a second character replacement.
* @see https://www.algolia.com/doc/rest#param-minWordSizefor2Typos
* @member {number}
*/
this.minWordSizefor2Typos = params.minWordSizefor2Typos;
/**
* Configure the precision of the proximity ranking criterion
* @see https://www.algolia.com/doc/rest#param-minProximity
*/
this.minProximity = params.minProximity;
/**
* Should the engine allow typos on numerics.
* @see https://www.algolia.com/doc/rest#param-allowTyposOnNumericTokens
* @member {boolean}
*/
this.allowTyposOnNumericTokens = params.allowTyposOnNumericTokens;
/**
* Should the plurals be ignored
* @see https://www.algolia.com/doc/rest#param-ignorePlurals
* @member {boolean}
*/
this.ignorePlurals = params.ignorePlurals;
/**
* Restrict which attribute is searched.
* @see https://www.algolia.com/doc/rest#param-restrictSearchableAttributes
* @member {string}
*/
this.restrictSearchableAttributes = params.restrictSearchableAttributes;
/**
* Enable the advanced syntax.
* @see https://www.algolia.com/doc/rest#param-advancedSyntax
* @member {boolean}
*/
this.advancedSyntax = params.advancedSyntax;
/**
* Enable the analytics
* @see https://www.algolia.com/doc/rest#param-analytics
* @member {boolean}
*/
this.analytics = params.analytics;
/**
* Tag of the query in the analytics.
* @see https://www.algolia.com/doc/rest#param-analyticsTags
* @member {string}
*/
this.analyticsTags = params.analyticsTags;
/**
* Enable the synonyms
* @see https://www.algolia.com/doc/rest#param-synonyms
* @member {boolean}
*/
this.synonyms = params.synonyms;
/**
* Should the engine replace the synonyms in the highlighted results.
* @see https://www.algolia.com/doc/rest#param-replaceSynonymsInHighlight
* @member {boolean}
*/
this.replaceSynonymsInHighlight = params.replaceSynonymsInHighlight;
/**
* Add some optional words to those defined in the dashboard
* @see https://www.algolia.com/doc/rest#param-optionalWords
* @member {string}
*/
this.optionalWords = params.optionalWords;
/**
* Possible values are "lastWords" "firstWords" "allOptional" "none" (default)
* @see https://www.algolia.com/doc/rest#param-removeWordsIfNoResults
* @member {string}
*/
this.removeWordsIfNoResults = params.removeWordsIfNoResults;
/**
* List of attributes to retrieve
* @see https://www.algolia.com/doc/rest#param-attributesToRetrieve
* @member {string}
*/
this.attributesToRetrieve = params.attributesToRetrieve;
/**
* List of attributes to highlight
* @see https://www.algolia.com/doc/rest#param-attributesToHighlight
* @member {string}
*/
this.attributesToHighlight = params.attributesToHighlight;
/**
* Code to be embedded on the left part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPreTag
* @member {string}
*/
this.highlightPreTag = params.highlightPreTag;
/**
* Code to be embedded on the right part of the highlighted results
* @see https://www.algolia.com/doc/rest#param-highlightPostTag
* @member {string}
*/
this.highlightPostTag = params.highlightPostTag;
/**
* List of attributes to snippet
* @see https://www.algolia.com/doc/rest#param-attributesToSnippet
* @member {string}
*/
this.attributesToSnippet = params.attributesToSnippet;
/**
* Enable the ranking informations in the response, set to 1 to activate
* @see https://www.algolia.com/doc/rest#param-getRankingInfo
* @member {number}
*/
this.getRankingInfo = params.getRankingInfo;
/**
* Remove duplicates based on the index setting attributeForDistinct
* @see https://www.algolia.com/doc/rest#param-distinct
* @member {boolean|number}
*/
this.distinct = params.distinct;
/**
* Center of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundLatLng
* @member {string}
*/
this.aroundLatLng = params.aroundLatLng;
/**
* Center of the search, retrieve from the user IP.
* @see https://www.algolia.com/doc/rest#param-aroundLatLngViaIP
* @member {boolean}
*/
this.aroundLatLngViaIP = params.aroundLatLngViaIP;
/**
* Radius of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundRadius
* @member {number}
*/
this.aroundRadius = params.aroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-aroundPrecision
* @member {number}
*/
this.minimumAroundRadius = params.minimumAroundRadius;
/**
* Precision of the geo search.
* @see https://www.algolia.com/doc/rest#param-minimumAroundRadius
* @member {number}
*/
this.aroundPrecision = params.aroundPrecision;
/**
* Geo search inside a box.
* @see https://www.algolia.com/doc/rest#param-insideBoundingBox
* @member {string}
*/
this.insideBoundingBox = params.insideBoundingBox;
/**
* Geo search inside a polygon.
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.insidePolygon = params.insidePolygon;
/**
* Allows to specify an ellipsis character for the snippet when we truncate the text
* (added before and after if truncated).
* The default value is an empty string and we recommend to set it to "…"
* @see https://www.algolia.com/doc/rest#param-insidePolygon
* @member {string}
*/
this.snippetEllipsisText = params.snippetEllipsisText;
/**
* Allows to specify some attributes name on which exact won't be applied.
* Attributes are separated with a comma (for example "name,address" ), you can also use a
* JSON string array encoding (for example encodeURIComponent('["name","address"]') ).
* By default the list is empty.
* @see https://www.algolia.com/doc/rest#param-disableExactOnAttributes
* @member {string|string[]}
*/
this.disableExactOnAttributes = params.disableExactOnAttributes;
/**
* Applies 'exact' on single word queries if the word contains at least 3 characters
* and is not a stop word.
* Can take two values: true or false.
* By default, its set to false.
* @see https://www.algolia.com/doc/rest#param-enableExactOnSingleWordQuery
* @member {boolean}
*/
this.enableExactOnSingleWordQuery = params.enableExactOnSingleWordQuery;
// Undocumented parameters, still needed otherwise we fail
this.offset = params.offset;
this.length = params.length;
var self = this;
forOwn_1(params, function checkForUnknownParameter(paramValue, paramName) {
if (SearchParameters.PARAMETERS.indexOf(paramName) === -1) {
self[paramName] = paramValue;
}
});
}
/**
* List all the properties in SearchParameters and therefore all the known Algolia properties
* This doesn't contain any beta/hidden features.
* @private
*/
SearchParameters.PARAMETERS = keys_1(new SearchParameters());
/**
* @private
* @param {object} partialState full or part of a state
* @return {object} a new object with the number keys as number
*/
SearchParameters._parseNumbers = function(partialState) {
// Do not reparse numbers in SearchParameters, they ought to be parsed already
if (partialState instanceof SearchParameters) return partialState;
var numbers = {};
var numberKeys = [
'aroundPrecision',
'aroundRadius',
'getRankingInfo',
'minWordSizefor2Typos',
'minWordSizefor1Typo',
'page',
'maxValuesPerFacet',
'distinct',
'minimumAroundRadius',
'hitsPerPage',
'minProximity'
];
forEach_1(numberKeys, function(k) {
var value = partialState[k];
if (isString_1(value)) {
var parsedValue = parseFloat(value);
numbers[k] = _isNaN(parsedValue) ? value : parsedValue;
}
});
if (partialState.numericRefinements) {
var numericRefinements = {};
forEach_1(partialState.numericRefinements, function(operators, attribute) {
numericRefinements[attribute] = {};
forEach_1(operators, function(values, operator) {
var parsedValues = map_1(values, function(v) {
if (isArray_1(v)) {
return map_1(v, function(vPrime) {
if (isString_1(vPrime)) {
return parseFloat(vPrime);
}
return vPrime;
});
} else if (isString_1(v)) {
return parseFloat(v);
}
return v;
});
numericRefinements[attribute][operator] = parsedValues;
});
});
numbers.numericRefinements = numericRefinements;
}
return merge_1({}, partialState, numbers);
};
/**
* Factory for SearchParameters
* @param {object|SearchParameters} newParameters existing parameters or partial
* object for the properties of a new SearchParameters
* @return {SearchParameters} frozen instance of SearchParameters
*/
SearchParameters.make = function makeSearchParameters(newParameters) {
var instance = new SearchParameters(newParameters);
forEach_1(newParameters.hierarchicalFacets, function(facet) {
if (facet.rootPath) {
var currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) {
instance = instance.clearRefinements(facet.name);
}
// get it again in case it has been cleared
currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length === 0) {
instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath);
}
}
});
return instance;
};
/**
* Validates the new parameters based on the previous state
* @param {SearchParameters} currentState the current state
* @param {object|SearchParameters} parameters the new parameters to set
* @return {Error|null} Error if the modification is invalid, null otherwise
*/
SearchParameters.validate = function(currentState, parameters) {
var params = parameters || {};
if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) {
return new Error(
'[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' +
'an error, if it is really what you want, you should first clear the tags with clearTags method.');
}
if (currentState.tagRefinements.length > 0 && params.tagFilters) {
return new Error(
'[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' +
'an error, if it is not, you should first clear the tags with clearTags method.');
}
if (currentState.numericFilters && params.numericRefinements && !isEmpty_1(params.numericRefinements)) {
return new Error(
"[Numeric filters] Can't switch from the advanced to the managed API. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
if (!isEmpty_1(currentState.numericRefinements) && params.numericFilters) {
return new Error(
"[Numeric filters] Can't switch from the managed API to the advanced. It" +
' is probably an error, if this is really what you want, you have to first' +
' clear the numeric filters.');
}
return null;
};
SearchParameters.prototype = {
constructor: SearchParameters,
/**
* Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)
* @method
* @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {SearchParameters}
*/
clearRefinements: function clearRefinements(attribute) {
var clear = RefinementList.clearRefinement;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(attribute),
facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'),
facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'),
disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'),
hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet')
});
},
/**
* Remove all the refined tags from the SearchParameters
* @method
* @return {SearchParameters}
*/
clearTags: function clearTags() {
if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this;
return this.setQueryParameters({
tagFilters: undefined,
tagRefinements: []
});
},
/**
* Set the index.
* @method
* @param {string} index the index name
* @return {SearchParameters}
*/
setIndex: function setIndex(index) {
if (index === this.index) return this;
return this.setQueryParameters({
index: index
});
},
/**
* Query setter
* @method
* @param {string} newQuery value for the new query
* @return {SearchParameters}
*/
setQuery: function setQuery(newQuery) {
if (newQuery === this.query) return this;
return this.setQueryParameters({
query: newQuery
});
},
/**
* Page setter
* @method
* @param {number} newPage new page number
* @return {SearchParameters}
*/
setPage: function setPage(newPage) {
if (newPage === this.page) return this;
return this.setQueryParameters({
page: newPage
});
},
/**
* Facets setter
* The facets are the simple facets, used for conjunctive (and) faceting.
* @method
* @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting
* @return {SearchParameters}
*/
setFacets: function setFacets(facets) {
return this.setQueryParameters({
facets: facets
});
},
/**
* Disjunctive facets setter
* Change the list of disjunctive (or) facets the helper chan handle.
* @method
* @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting
* @return {SearchParameters}
*/
setDisjunctiveFacets: function setDisjunctiveFacets(facets) {
return this.setQueryParameters({
disjunctiveFacets: facets
});
},
/**
* HitsPerPage setter
* Hits per page represents the number of hits retrieved for this query
* @method
* @param {number} n number of hits retrieved per page of results
* @return {SearchParameters}
*/
setHitsPerPage: function setHitsPerPage(n) {
if (this.hitsPerPage === n) return this;
return this.setQueryParameters({
hitsPerPage: n
});
},
/**
* typoTolerance setter
* Set the value of typoTolerance
* @method
* @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict")
* @return {SearchParameters}
*/
setTypoTolerance: function setTypoTolerance(typoTolerance) {
if (this.typoTolerance === typoTolerance) return this;
return this.setQueryParameters({
typoTolerance: typoTolerance
});
},
/**
* Add a numeric filter for a given attribute
* When value is an array, they are combined with OR
* When value is a single value, it will combined with AND
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number | number[]} value value of the filter
* @return {SearchParameters}
* @example
* // for price = 50 or 40
* searchparameter.addNumericRefinement('price', '=', [50, 40]);
* @example
* // for size = 38 and 40
* searchparameter.addNumericRefinement('size', '=', 38);
* searchparameter.addNumericRefinement('size', '=', 40);
*/
addNumericRefinement: function(attribute, operator, v) {
var value = valToNumber_1(v);
if (this.isNumericRefined(attribute, operator, value)) return this;
var mod = merge_1({}, this.numericRefinements);
mod[attribute] = merge_1({}, mod[attribute]);
if (mod[attribute][operator]) {
// Array copy
mod[attribute][operator] = mod[attribute][operator].slice();
// Add the element. Concat can't be used here because value can be an array.
mod[attribute][operator].push(value);
} else {
mod[attribute][operator] = [value];
}
return this.setQueryParameters({
numericRefinements: mod
});
},
/**
* Get the list of conjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getConjunctiveRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsRefinements[facetName] || [];
},
/**
* Get the list of disjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getDisjunctiveRefinements: function(facetName) {
if (!this.isDisjunctiveFacet(facetName)) {
throw new Error(
facetName + ' is not defined in the disjunctiveFacets attribute of the helper configuration'
);
}
return this.disjunctiveFacetsRefinements[facetName] || [];
},
/**
* Get the list of hierarchical refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getHierarchicalRefinement: function(facetName) {
// we send an array but we currently do not support multiple
// hierarchicalRefinements for a hierarchicalFacet
return this.hierarchicalFacetsRefinements[facetName] || [];
},
/**
* Get the list of exclude refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getExcludeRefinements: function(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
throw new Error(facetName + ' is not defined in the facets attribute of the helper configuration');
}
return this.facetsExcludes[facetName] || [];
},
/**
* Remove all the numeric filter for a given (attribute, operator)
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number} [number] the value to be removed
* @return {SearchParameters}
*/
removeNumericRefinement: function(attribute, operator, paramValue) {
if (paramValue !== undefined) {
var paramValueAsNumber = valToNumber_1(paramValue);
if (!this.isNumericRefined(attribute, operator, paramValueAsNumber)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator && isEqual_1(value.val, paramValueAsNumber);
})
});
} else if (operator !== undefined) {
if (!this.isNumericRefined(attribute, operator)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute && value.op === operator;
})
});
}
if (!this.isNumericRefined(attribute)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function(value, key) {
return key === attribute;
})
});
},
/**
* Get the list of numeric refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {SearchParameters.OperatorList[]} list of refinements
*/
getNumericRefinements: function(facetName) {
return this.numericRefinements[facetName] || {};
},
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
getNumericRefinement: function(attribute, operator) {
return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator];
},
/**
* Clear numeric filters.
* @method
* @private
* @param {string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {Object.<string, OperatorList>}
*/
_clearNumericRefinements: function _clearNumericRefinements(attribute) {
if (isUndefined_1(attribute)) {
return {};
} else if (isString_1(attribute)) {
return omit_1(this.numericRefinements, attribute);
} else if (isFunction_1(attribute)) {
return reduce_1(this.numericRefinements, function(memo, operators, key) {
var operatorList = {};
forEach_1(operators, function(values, operator) {
var outValues = [];
forEach_1(values, function(value) {
var predicateResult = attribute({val: value, op: operator}, key, 'numeric');
if (!predicateResult) outValues.push(value);
});
if (!isEmpty_1(outValues)) operatorList[operator] = outValues;
});
if (!isEmpty_1(operatorList)) memo[key] = operatorList;
return memo;
}, {});
}
},
/**
* Add a facet to the facets attribute of the helper configuration, if it
* isn't already present.
* @method
* @param {string} facet facet name to add
* @return {SearchParameters}
*/
addFacet: function addFacet(facet) {
if (this.isConjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
facets: this.facets.concat([facet])
});
},
/**
* Add a disjunctive facet to the disjunctiveFacets attribute of the helper
* configuration, if it isn't already present.
* @method
* @param {string} facet disjunctive facet name to add
* @return {SearchParameters}
*/
addDisjunctiveFacet: function addDisjunctiveFacet(facet) {
if (this.isDisjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
disjunctiveFacets: this.disjunctiveFacets.concat([facet])
});
},
/**
* Add a hierarchical facet to the hierarchicalFacets attribute of the helper
* configuration.
* @method
* @param {object} hierarchicalFacet hierarchical facet to add
* @return {SearchParameters}
* @throws will throw an error if a hierarchical facet with the same name was already declared
*/
addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) {
if (this.isHierarchicalFacet(hierarchicalFacet.name)) {
throw new Error(
'Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`');
}
return this.setQueryParameters({
hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet])
});
},
/**
* Add a refinement on a "normal" facet
* @method
* @param {string} facet attribute to apply the faceting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addFacetRefinement: function addFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Exclude a value from a "normal" facet
* @method
* @param {string} facet attribute to apply the exclusion on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addExcludeRefinement: function addExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Adds a refinement on a disjunctive facet.
* @method
* @param {string} facet attribute to apply the faceting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.addRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* addTagRefinement adds a tag to the list used to filter the results
* @param {string} tag tag to be added
* @return {SearchParameters}
*/
addTagRefinement: function addTagRefinement(tag) {
if (this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: this.tagRefinements.concat(tag)
};
return this.setQueryParameters(modification);
},
/**
* Remove a facet from the facets attribute of the helper configuration, if it
* is present.
* @method
* @param {string} facet facet name to remove
* @return {SearchParameters}
*/
removeFacet: function removeFacet(facet) {
if (!this.isConjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
facets: filter_1(this.facets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a disjunctive facet from the disjunctiveFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet disjunctive facet name to remove
* @return {SearchParameters}
*/
removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) {
if (!this.isDisjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
disjunctiveFacets: filter_1(this.disjunctiveFacets, function(f) {
return f !== facet;
})
});
},
/**
* Remove a hierarchical facet from the hierarchicalFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet hierarchical facet name to remove
* @return {SearchParameters}
*/
removeHierarchicalFacet: function removeHierarchicalFacet(facet) {
if (!this.isHierarchicalFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
hierarchicalFacets: filter_1(this.hierarchicalFacets, function(f) {
return f.name !== facet;
})
});
},
/**
* Remove a refinement set on facet. If a value is provided, it will clear the
* refinement for the given value, otherwise it will clear all the refinement
* values for the faceted attribute.
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} [value] value used to filter
* @return {SearchParameters}
*/
removeFacetRefinement: function removeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Remove a negative refinement on a facet
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeExcludeRefinement: function removeExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Remove a refinement on a disjunctive facet
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.removeRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Remove a tag from the list of tag refinements
* @method
* @param {string} tag the tag to remove
* @return {SearchParameters}
*/
removeTagRefinement: function removeTagRefinement(tag) {
if (!this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: filter_1(this.tagRefinements, function(t) { return t !== tag; })
};
return this.setQueryParameters(modification);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
* @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement}
*/
toggleRefinement: function toggleRefinement(facet, value) {
return this.toggleFacetRefinement(facet, value);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
*/
toggleFacetRefinement: function toggleFacetRefinement(facet, value) {
if (this.isHierarchicalFacet(facet)) {
return this.toggleHierarchicalFacetRefinement(facet, value);
} else if (this.isConjunctiveFacet(facet)) {
return this.toggleConjunctiveFacetRefinement(facet, value);
} else if (this.isDisjunctiveFacet(facet)) {
return this.toggleDisjunctiveFacetRefinement(facet, value);
}
throw new Error('Cannot refine the undeclared facet ' + facet +
'; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets');
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.toggleRefinement(
this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet));
var mod = {};
var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined &&
this.hierarchicalFacetsRefinements[facet].length > 0 && (
// remove current refinement:
// refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0] === value ||
// remove a parent refinement of the current refinement:
// - refinement was 'beer > IPA > Flying dog'
// - call is toggleRefine('beer > IPA')
// - refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0
);
if (upOneOrMultipleLevel) {
if (value.indexOf(separator) === -1) {
// go back to root level
mod[facet] = [];
} else {
mod[facet] = [value.slice(0, value.lastIndexOf(separator))];
}
} else {
mod[facet] = [value];
}
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Adds a refinement on a hierarchical facet.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is refined
*/
addHierarchicalFacetRefinement: function(facet, path) {
if (this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is already refined.');
}
var mod = {};
mod[facet] = [path];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is not refined
*/
removeHierarchicalFacetRefinement: function(facet) {
if (!this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is not refined.');
}
var mod = {};
mod[facet] = [];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaults_1({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Switch the tag refinement
* @method
* @param {string} tag the tag to remove or add
* @return {SearchParameters}
*/
toggleTagRefinement: function toggleTagRefinement(tag) {
if (this.isTagRefined(tag)) {
return this.removeTagRefinement(tag);
}
return this.addTagRefinement(tag);
},
/**
* Test if the facet name is from one of the disjunctive facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isDisjunctiveFacet: function(facet) {
return indexOf_1(this.disjunctiveFacets, facet) > -1;
},
/**
* Test if the facet name is from one of the hierarchical facets
* @method
* @param {string} facetName facet name to test
* @return {boolean}
*/
isHierarchicalFacet: function(facetName) {
return this.getHierarchicalFacetByName(facetName) !== undefined;
},
/**
* Test if the facet name is from one of the conjunctive/normal facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isConjunctiveFacet: function(facet) {
return indexOf_1(this.facets, facet) > -1;
},
/**
* Returns true if the facet is refined, either for a specific value or in
* general.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value, optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isFacetRefined: function isFacetRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsRefinements, facet, value);
},
/**
* Returns true if the facet contains exclusions or if a specific value is
* excluded.
*
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isExcludeRefined: function isExcludeRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return RefinementList.isRefined(this.facetsExcludes, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value optional, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(
facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value optional, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(
facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var refinements = this.getHierarchicalRefinement(facet);
if (!value) {
return refinements.length > 0;
}
return indexOf_1(refinements, value) !== -1;
},
/**
* Test if the triple (attribute, operator, value) is already refined.
* If only the attribute and the operator are provided, it tests if the
* contains any refinement value.
* @method
* @param {string} attribute attribute for which the refinement is applied
* @param {string} [operator] operator of the refinement
* @param {string} [value] value of the refinement
* @return {boolean} true if it is refined
*/
isNumericRefined: function isNumericRefined(attribute, operator, value) {
if (isUndefined_1(value) && isUndefined_1(operator)) {
return !!this.numericRefinements[attribute];
}
var isOperatorDefined = this.numericRefinements[attribute] &&
!isUndefined_1(this.numericRefinements[attribute][operator]);
if (isUndefined_1(value) || !isOperatorDefined) {
return isOperatorDefined;
}
var parsedValue = valToNumber_1(value);
var isAttributeValueDefined = !isUndefined_1(
findArray(this.numericRefinements[attribute][operator], parsedValue)
);
return isOperatorDefined && isAttributeValueDefined;
},
/**
* Returns true if the tag refined, false otherwise
* @method
* @param {string} tag the tag to check
* @return {boolean}
*/
isTagRefined: function isTagRefined(tag) {
return indexOf_1(this.tagRefinements, tag) !== -1;
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() {
// attributes used for numeric filter can also be disjunctive
var disjunctiveNumericRefinedFacets = intersection_1(
keys_1(this.numericRefinements),
this.disjunctiveFacets
);
return keys_1(this.disjunctiveFacetsRefinements)
.concat(disjunctiveNumericRefinedFacets)
.concat(this.getRefinedHierarchicalFacets());
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() {
return intersection_1(
// enforce the order between the two arrays,
// so that refinement name index === hierarchical facet index
map_1(this.hierarchicalFacets, 'name'),
keys_1(this.hierarchicalFacetsRefinements)
);
},
/**
* Returned the list of all disjunctive facets not refined
* @method
* @return {string[]}
*/
getUnrefinedDisjunctiveFacets: function() {
var refinedFacets = this.getRefinedDisjunctiveFacets();
return filter_1(this.disjunctiveFacets, function(f) {
return indexOf_1(refinedFacets, f) === -1;
});
},
managedParameters: [
'index',
'facets', 'disjunctiveFacets', 'facetsRefinements',
'facetsExcludes', 'disjunctiveFacetsRefinements',
'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'
],
getQueryParams: function getQueryParams() {
var managedParameters = this.managedParameters;
var queryParams = {};
forOwn_1(this, function(paramValue, paramName) {
if (indexOf_1(managedParameters, paramName) === -1 && paramValue !== undefined) {
queryParams[paramName] = paramValue;
}
});
return queryParams;
},
/**
* Let the user retrieve any parameter value from the SearchParameters
* @param {string} paramName name of the parameter
* @return {any} the value of the parameter
*/
getQueryParameter: function getQueryParameter(paramName) {
if (!this.hasOwnProperty(paramName)) {
throw new Error(
"Parameter '" + paramName + "' is not an attribute of SearchParameters " +
'(http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)');
}
return this[paramName];
},
/**
* Let the user set a specific value for a given parameter. Will return the
* same instance if the parameter is invalid or if the value is the same as the
* previous one.
* @method
* @param {string} parameter the parameter name
* @param {any} value the value to be set, must be compliant with the definition
* of the attribute on the object
* @return {SearchParameters} the updated state
*/
setQueryParameter: function setParameter(parameter, value) {
if (this[parameter] === value) return this;
var modification = {};
modification[parameter] = value;
return this.setQueryParameters(modification);
},
/**
* Let the user set any of the parameters with a plain object.
* @method
* @param {object} params all the keys and the values to be updated
* @return {SearchParameters} a new updated instance
*/
setQueryParameters: function setQueryParameters(params) {
if (!params) return this;
var error = SearchParameters.validate(this, params);
if (error) {
throw error;
}
var parsedParams = SearchParameters._parseNumbers(params);
return this.mutateMe(function mergeWith(newInstance) {
var ks = keys_1(params);
forEach_1(ks, function(k) {
newInstance[k] = parsedParams[k];
});
return newInstance;
});
},
/**
* Returns an object with only the selected attributes.
* @param {string[]} filters filters to retrieve only a subset of the state. It
* accepts strings that can be either attributes of the SearchParameters (e.g. hitsPerPage)
* or attributes of the index with the notation 'attribute:nameOfMyAttribute'
* @return {object}
*/
filter: function(filters) {
return filterState_1(this, filters);
},
/**
* Helper function to make it easier to build new instances from a mutating
* function
* @private
* @param {function} fn newMutableState -> previousState -> () function that will
* change the value of the newMutable to the desired state
* @return {SearchParameters} a new instance with the specified modifications applied
*/
mutateMe: function mutateMe(fn) {
var newState = new this.constructor(this);
fn(newState, this);
return newState;
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSortBy: function(hierarchicalFacet) {
return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc'];
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSeparator: function(hierarchicalFacet) {
return hierarchicalFacet.separator || ' > ';
},
/**
* Helper function to get the hierarchicalFacet prefix path or null
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.rootPath or null as default
*/
_getHierarchicalRootPath: function(hierarchicalFacet) {
return hierarchicalFacet.rootPath || null;
},
/**
* Helper function to check if we show the parent level of the hierarchicalFacet
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.showParentLevel or true as default
*/
_getHierarchicalShowParentLevel: function(hierarchicalFacet) {
if (typeof hierarchicalFacet.showParentLevel === 'boolean') {
return hierarchicalFacet.showParentLevel;
}
return true;
},
/**
* Helper function to get the hierarchicalFacet by it's name
* @param {string} hierarchicalFacetName
* @return {object} a hierarchicalFacet
*/
getHierarchicalFacetByName: function(hierarchicalFacetName) {
return find_1(
this.hierarchicalFacets,
{name: hierarchicalFacetName}
);
},
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
getHierarchicalFacetBreadcrumb: function(facetName) {
if (!this.isHierarchicalFacet(facetName)) {
throw new Error(
'Cannot get the breadcrumb of an unknown hierarchical facet: `' + facetName + '`');
}
var refinement = this.getHierarchicalRefinement(facetName)[0];
if (!refinement) return [];
var separator = this._getHierarchicalFacetSeparator(
this.getHierarchicalFacetByName(facetName)
);
var path = refinement.split(separator);
return map_1(path, trim_1);
}
};
/**
* Callback used for clearRefinement method
* @callback SearchParameters.clearCallback
* @param {OperatorList|FacetList} value the value of the filter
* @param {string} key the current attribute name
* @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude`
* depending on the type of facet
* @return {boolean} `true` if the element should be removed. `false` otherwise.
*/
var SearchParameters_1 = SearchParameters;
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
var compact_1 = compact;
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(array, iteratee) {
var result,
index = -1,
length = array.length;
while (++index < length) {
var current = iteratee(array[index]);
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}
}
return result;
}
var _baseSum = baseSum;
/**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/
function sumBy(array, iteratee) {
return (array && array.length)
? _baseSum(array, _baseIteratee(iteratee, 2))
: 0;
}
var sumBy_1 = sumBy;
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return _arrayMap(props, function(key) {
return object[key];
});
}
var _baseValues = baseValues;
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : _baseValues(object, keys_1(object));
}
var values_1 = values;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$3 = Math.max;
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike_1(collection) ? collection : values_1(collection);
fromIndex = (fromIndex && !guard) ? toInteger_1(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax$3(length + fromIndex, 0);
}
return isString_1(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && _baseIndexOf(collection, value, fromIndex) > -1);
}
var includes_1 = includes;
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
var _baseSortBy = baseSortBy;
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol_1(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol_1(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
var _compareAscending = compareAscending;
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = _compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
var _compareMultiple = compareMultiple;
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
var index = -1;
iteratees = _arrayMap(iteratees.length ? iteratees : [identity_1], _baseUnary(_baseIteratee));
var result = _baseMap(collection, function(value, key, collection) {
var criteria = _arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return _baseSortBy(result, function(object, other) {
return _compareMultiple(object, other, orders);
});
}
var _baseOrderBy = baseOrderBy;
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray_1(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray_1(orders)) {
orders = orders == null ? [] : [orders];
}
return _baseOrderBy(collection, iteratees, orders);
}
var orderBy_1 = orderBy;
/** Used to store function metadata. */
var metaMap = _WeakMap && new _WeakMap;
var _metaMap = metaMap;
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !_metaMap ? identity_1 : function(func, data) {
_metaMap.set(func, data);
return func;
};
var _baseSetData = baseSetData;
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = _baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject_1(result) ? result : thisBinding;
};
}
var _createCtor = createCtor;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1;
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = _createCtor(func);
function wrapper() {
var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
var _createBind = createBind;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$4 = Math.max;
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax$4(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
var _composeArgs = composeArgs;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$5 = Math.max;
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax$5(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
return result;
}
var _composeArgsRight = composeArgsRight;
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
var _countHolders = countHolders;
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
var _baseLodash = baseLodash;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = _baseCreate(_baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
var _LazyWrapper = LazyWrapper;
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop$1() {
// No operation performed.
}
var noop_1 = noop$1;
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !_metaMap ? noop_1 : function(func) {
return _metaMap.get(func);
};
var _getData = getData;
/** Used to lookup unminified function names. */
var realNames = {};
var _realNames = realNames;
/** Used for built-in method references. */
var objectProto$18 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$16 = objectProto$18.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$16.call(_realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
var _getFuncName = getFuncName;
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
LodashWrapper.prototype = _baseCreate(_baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
var _LodashWrapper = LodashWrapper;
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof _LazyWrapper) {
return wrapper.clone();
}
var result = new _LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = _copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
var _wrapperClone = wrapperClone;
/** Used for built-in method references. */
var objectProto$19 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$17 = objectProto$19.hasOwnProperty;
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike_1(value) && !isArray_1(value) && !(value instanceof _LazyWrapper)) {
if (value instanceof _LodashWrapper) {
return value;
}
if (hasOwnProperty$17.call(value, '__wrapped__')) {
return _wrapperClone(value);
}
}
return new _LodashWrapper(value);
}
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = _baseLodash.prototype;
lodash.prototype.constructor = lodash;
var wrapperLodash = lodash;
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = _getFuncName(func),
other = wrapperLodash[funcName];
if (typeof other != 'function' || !(funcName in _LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = _getData(other);
return !!data && func === data[0];
}
var _isLaziable = isLaziable;
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = _shortOut(_baseSetData);
var _setData = setData;
/** Used to match wrap detail comments. */
var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
var _getWrapDetails = getWrapDetails;
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
var _insertWrapDetails = insertWrapDetails;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$1 = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256,
WRAP_FLIP_FLAG = 512;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG$1],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
_arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !_arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
var _updateWrapDetails = updateWrapDetails;
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/
function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return _setToString(wrapper, _insertWrapDetails(source, _updateWrapDetails(_getWrapDetails(source), bitmask)));
}
var _setWrapToString = setWrapToString;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$2 = 1,
WRAP_BIND_KEY_FLAG$1 = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG$1 = 8,
WRAP_PARTIAL_FLAG$1 = 32,
WRAP_PARTIAL_RIGHT_FLAG$1 = 64;
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG$1,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$1 : WRAP_PARTIAL_RIGHT_FLAG$1);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$1 : WRAP_PARTIAL_FLAG$1);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG$2 | WRAP_BIND_KEY_FLAG$1);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (_isLaziable(func)) {
_setData(result, newData);
}
result.placeholder = placeholder;
return _setWrapToString(result, func, bitmask);
}
var _createRecurry = createRecurry;
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = func;
return object.placeholder;
}
var _getHolder = getHolder;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin$1 = Math.min;
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin$1(indexes.length, arrLength),
oldArray = _copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = _isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
var _reorder = reorder;
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
var _replaceHolders = replaceHolders;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$3 = 1,
WRAP_BIND_KEY_FLAG$2 = 2,
WRAP_CURRY_FLAG$2 = 8,
WRAP_CURRY_RIGHT_FLAG$1 = 16,
WRAP_ARY_FLAG$1 = 128,
WRAP_FLIP_FLAG$1 = 512;
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG$1,
isBind = bitmask & WRAP_BIND_FLAG$3,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2,
isCurried = bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1),
isFlip = bitmask & WRAP_FLIP_FLAG$1,
Ctor = isBindKey ? undefined : _createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = _getHolder(wrapper),
holdersCount = _countHolders(args, placeholder);
}
if (partials) {
args = _composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = _composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = _replaceHolders(args, placeholder);
return _createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = _reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== _root && this instanceof wrapper) {
fn = Ctor || _createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
var _createHybrid = createHybrid;
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = _createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = _getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: _replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return _createRecurry(
func, bitmask, _createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
return _apply(fn, this, args);
}
return wrapper;
}
var _createCurry = createCurry;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$4 = 1;
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG$4,
Ctor = _createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== _root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return _apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
var _createPartial = createPartial;
/** Used as the internal argument placeholder. */
var PLACEHOLDER$1 = '__lodash_placeholder__';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$5 = 1,
WRAP_BIND_KEY_FLAG$3 = 2,
WRAP_CURRY_BOUND_FLAG$1 = 4,
WRAP_CURRY_FLAG$3 = 8,
WRAP_ARY_FLAG$2 = 128,
WRAP_REARG_FLAG$1 = 256;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin$2 = Math.min;
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG$5 | WRAP_BIND_KEY_FLAG$3 | WRAP_ARY_FLAG$2);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_CURRY_FLAG$3)) ||
((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_REARG_FLAG$1) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$1)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$3));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG$5) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG$5 ? 0 : WRAP_CURRY_BOUND_FLAG$1;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? _composeArgs(partials, value, source[4]) : value;
data[4] = partials ? _replaceHolders(data[3], PLACEHOLDER$1) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? _composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? _replaceHolders(data[5], PLACEHOLDER$1) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG$2) {
data[8] = data[8] == null ? source[8] : nativeMin$2(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
var _mergeData = mergeData;
/** Error message constants. */
var FUNC_ERROR_TEXT$1 = 'Expected a function';
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$6 = 1,
WRAP_BIND_KEY_FLAG$4 = 2,
WRAP_CURRY_FLAG$4 = 8,
WRAP_CURRY_RIGHT_FLAG$2 = 16,
WRAP_PARTIAL_FLAG$2 = 32,
WRAP_PARTIAL_RIGHT_FLAG$2 = 64;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax$6 = Math.max;
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG$4;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT$1);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG$2 | WRAP_PARTIAL_RIGHT_FLAG$2);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax$6(toInteger_1(ary), 0);
arity = arity === undefined ? arity : toInteger_1(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG$2) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : _getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
_mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax$6(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2)) {
bitmask &= ~(WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG$6) {
var result = _createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG$4 || bitmask == WRAP_CURRY_RIGHT_FLAG$2) {
result = _createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG$2 || bitmask == (WRAP_BIND_FLAG$6 | WRAP_PARTIAL_FLAG$2)) && !holders.length) {
result = _createPartial(func, bitmask, thisArg, partials);
} else {
result = _createHybrid.apply(undefined, newData);
}
var setter = data ? _baseSetData : _setData;
return _setWrapToString(setter(result, newData), func, bitmask);
}
var _createWrap = createWrap;
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_FLAG$3 = 32;
/**
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = _baseRest(function(func, partials) {
var holders = _replaceHolders(partials, _getHolder(partial));
return _createWrap(func, WRAP_PARTIAL_FLAG$3, undefined, partials, holders);
});
// Assign default placeholders.
partial.placeholder = {};
var partial_1 = partial;
/** Used to compose bitmasks for function metadata. */
var WRAP_PARTIAL_RIGHT_FLAG$3 = 64;
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = _baseRest(function(func, partials) {
var holders = _replaceHolders(partials, _getHolder(partialRight));
return _createWrap(func, WRAP_PARTIAL_RIGHT_FLAG$3, undefined, partials, holders);
});
// Assign default placeholders.
partialRight.placeholder = {};
var partialRight_1 = partialRight;
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
var _baseClamp = baseClamp;
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString_1(string);
position = position == null
? 0
: _baseClamp(toInteger_1(position), 0, string.length);
target = _baseToString(target);
return string.slice(position, position + target.length) == target;
}
var startsWith_1 = startsWith;
/**
* Transform sort format from user friendly notation to lodash format
* @param {string[]} sortBy array of predicate of the form "attribute:order"
* @return {array.<string[]>} array containing 2 elements : attributes, orders
*/
var formatSort = function formatSort(sortBy, defaults) {
return reduce_1(sortBy, function preparePredicate(out, sortInstruction) {
var sortInstructions = sortInstruction.split(':');
if (defaults && sortInstructions.length === 1) {
var similarDefault = find_1(defaults, function(predicate) {
return startsWith_1(predicate, sortInstruction[0]);
});
if (similarDefault) {
sortInstructions = similarDefault.split(':');
}
}
out[0].push(sortInstructions[0]);
out[1].push(sortInstructions[1]);
return out;
}, [[], []]);
};
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject_1(object)) {
return object;
}
path = _castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = _toKey(path[index]),
newValue = value;
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject_1(objValue)
? objValue
: (_isIndex(path[index + 1]) ? [] : {});
}
}
_assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
var _baseSet = baseSet;
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = _baseGet(object, path);
if (predicate(value, path)) {
_baseSet(result, _castPath(path, object), value);
}
}
return result;
}
var _basePickBy = basePickBy;
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = _arrayMap(_getAllKeysIn(object), function(prop) {
return [prop];
});
predicate = _baseIteratee(predicate);
return _basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
var pickBy_1 = pickBy;
var generateHierarchicalTree_1 = generateTrees;
function generateTrees(state) {
return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) {
var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex];
var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] &&
state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || '';
var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet);
var sortBy = formatSort(state._getHierarchicalFacetSortBy(hierarchicalFacet));
var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, hierarchicalFacetRefinement);
var results = hierarchicalFacetResult;
if (hierarchicalRootPath) {
results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length);
}
return reduce_1(results, generateTreeFn, {
name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
count: null, // root level, no count
isRefined: true, // root level, always refined
path: null, // root level, no path
data: null
});
};
}
function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel, currentRefinement) {
return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) {
var parent = hierarchicalTree;
if (currentHierarchicalLevel > 0) {
var level = 0;
parent = hierarchicalTree;
while (level < currentHierarchicalLevel) {
parent = parent && find_1(parent.data, {isRefined: true});
level++;
}
}
// we found a refined parent, let's add current level data under it
if (parent) {
// filter values in case an object has multiple categories:
// {
// categories: {
// level0: ['beers', 'bières'],
// level1: ['beers > IPA', 'bières > Belges']
// }
// }
//
// If parent refinement is `beers`, then we do not want to have `bières > Belges`
// showing up
var onlyMatchingValuesFn = filterFacetValues(parent.path || hierarchicalRootPath,
currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel);
parent.data = orderBy_1(
map_1(
pickBy_1(hierarchicalFacetResult.data, onlyMatchingValuesFn),
formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement)
),
sortBy[0], sortBy[1]
);
}
return hierarchicalTree;
};
}
function filterFacetValues(parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath,
hierarchicalShowParentLevel) {
return function(facetCount, facetValue) {
// we want the facetValue is a child of hierarchicalRootPath
if (hierarchicalRootPath &&
(facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) {
return false;
}
// we always want root levels (only when there is no prefix path)
return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 ||
// if there is a rootPath, being root level mean 1 level under rootPath
hierarchicalRootPath &&
facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 ||
// if current refinement is a root level and current facetValue is a root level,
// keep the facetValue
facetValue.indexOf(hierarchicalSeparator) === -1 &&
currentRefinement.indexOf(hierarchicalSeparator) === -1 ||
// currentRefinement is a child of the facet value
currentRefinement.indexOf(facetValue) === 0 ||
// facetValue is a child of the current parent, add it
facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 &&
(hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0);
};
}
function formatHierarchicalFacetValue(hierarchicalSeparator, currentRefinement) {
return function format(facetCount, facetValue) {
return {
name: trim_1(last_1(facetValue.split(hierarchicalSeparator))),
path: facetValue,
count: facetCount,
isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0,
data: null
};
};
}
/**
* @typedef SearchResults.Facet
* @type {object}
* @property {string} name name of the attribute in the record
* @property {object} data the faceting data: value, number of entries
* @property {object} stats undefined unless facet_stats is retrieved from algolia
*/
/**
* @typedef SearchResults.HierarchicalFacet
* @type {object}
* @property {string} name name of the current value given the hierarchical level, trimmed.
* If root node, you get the facet name
* @property {number} count number of objects matching this hierarchical value
* @property {string} path the current hierarchical value full path
* @property {boolean} isRefined `true` if the current value was refined, `false` otherwise
* @property {HierarchicalFacet[]} data sub values for the current level
*/
/**
* @typedef SearchResults.FacetValue
* @type {object}
* @property {string} name the facet value itself
* @property {number} count times this facet appears in the results
* @property {boolean} isRefined is the facet currently selected
* @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets)
*/
/**
* @typedef Refinement
* @type {object}
* @property {string} type the type of filter used:
* `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical`
* @property {string} attributeName name of the attribute used for filtering
* @property {string} name the value of the filter
* @property {number} numericValue the value as a number. Only for numeric filters.
* @property {string} operator the operator used. Only for numeric filters.
* @property {number} count the number of computed hits for this filter. Only on facets.
* @property {boolean} exhaustive if the count is exhaustive
*/
function getIndices(obj) {
var indices = {};
forEach_1(obj, function(val, idx) { indices[val] = idx; });
return indices;
}
function assignFacetStats(dest, facetStats, key) {
if (facetStats && facetStats[key]) {
dest.stats = facetStats[key];
}
}
function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) {
return find_1(
hierarchicalFacets,
function facetKeyMatchesAttribute(hierarchicalFacet) {
return includes_1(hierarchicalFacet.attributes, hierarchicalAttributeName);
}
);
}
/*eslint-disable */
/**
* Constructor for SearchResults
* @class
* @classdesc SearchResults contains the results of a query to Algolia using the
* {@link AlgoliaSearchHelper}.
* @param {SearchParameters} state state that led to the response
* @param {array.<object>} results the results from algolia client
* @example <caption>SearchResults of the first query in
* <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption>
{
"hitsPerPage": 10,
"processingTimeMS": 2,
"facets": [
{
"name": "type",
"data": {
"HardGood": 6627,
"BlackTie": 550,
"Music": 665,
"Software": 131,
"Game": 456,
"Movie": 1571
},
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"Free shipping": 5507
},
"name": "shipping"
}
],
"hits": [
{
"thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
"_highlightResult": {
"shortDescription": {
"matchLevel": "none",
"value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"matchedWords": []
},
"category": {
"matchLevel": "none",
"value": "Computer Security Software",
"matchedWords": []
},
"manufacturer": {
"matchedWords": [],
"value": "Webroot",
"matchLevel": "none"
},
"name": {
"value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"matchedWords": [],
"matchLevel": "none"
}
},
"image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
"shipping": "Free shipping",
"bestSellingRank": 4,
"shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
"name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"category": "Computer Security Software",
"salePrice_range": "1 - 50",
"objectID": "1688832",
"type": "Software",
"customerReviewCount": 5980,
"salePrice": 49.99,
"manufacturer": "Webroot"
},
....
],
"nbHits": 10000,
"disjunctiveFacets": [
{
"exhaustive": false,
"data": {
"5": 183,
"12": 112,
"7": 149,
...
},
"name": "customerReviewCount",
"stats": {
"max": 7461,
"avg": 157.939,
"min": 1
}
},
{
"data": {
"Printer Ink": 142,
"Wireless Speakers": 60,
"Point & Shoot Cameras": 48,
...
},
"name": "category",
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"> 5000": 2,
"1 - 50": 6524,
"501 - 2000": 566,
"201 - 500": 1501,
"101 - 200": 1360,
"2001 - 5000": 47
},
"name": "salePrice_range"
},
{
"data": {
"Dynex™": 202,
"Insignia™": 230,
"PNY": 72,
...
},
"name": "manufacturer",
"exhaustive": false
}
],
"query": "",
"nbPages": 100,
"page": 0,
"index": "bestbuy"
}
**/
/*eslint-enable */
function SearchResults(state, results) {
var mainSubResponse = results[0];
this._rawResults = results;
/**
* query used to generate the results
* @member {string}
*/
this.query = mainSubResponse.query;
/**
* The query as parsed by the engine given all the rules.
* @member {string}
*/
this.parsedQuery = mainSubResponse.parsedQuery;
/**
* all the records that match the search parameters. Each record is
* augmented with a new attribute `_highlightResult`
* which is an object keyed by attribute and with the following properties:
* - `value` : the value of the facet highlighted (html)
* - `matchLevel`: full, partial or none depending on how the query terms match
* @member {object[]}
*/
this.hits = mainSubResponse.hits;
/**
* index where the results come from
* @member {string}
*/
this.index = mainSubResponse.index;
/**
* number of hits per page requested
* @member {number}
*/
this.hitsPerPage = mainSubResponse.hitsPerPage;
/**
* total number of hits of this query on the index
* @member {number}
*/
this.nbHits = mainSubResponse.nbHits;
/**
* total number of pages with respect to the number of hits per page and the total number of hits
* @member {number}
*/
this.nbPages = mainSubResponse.nbPages;
/**
* current page
* @member {number}
*/
this.page = mainSubResponse.page;
/**
* sum of the processing time of all the queries
* @member {number}
*/
this.processingTimeMS = sumBy_1(results, 'processingTimeMS');
/**
* The position if the position was guessed by IP.
* @member {string}
* @example "48.8637,2.3615",
*/
this.aroundLatLng = mainSubResponse.aroundLatLng;
/**
* The radius computed by Algolia.
* @member {string}
* @example "126792922",
*/
this.automaticRadius = mainSubResponse.automaticRadius;
/**
* String identifying the server used to serve this request.
* @member {string}
* @example "c7-use-2.algolia.net",
*/
this.serverUsed = mainSubResponse.serverUsed;
/**
* Boolean that indicates if the computation of the counts did time out.
* @deprecated
* @member {boolean}
*/
this.timeoutCounts = mainSubResponse.timeoutCounts;
/**
* Boolean that indicates if the computation of the hits did time out.
* @deprecated
* @member {boolean}
*/
this.timeoutHits = mainSubResponse.timeoutHits;
/**
* True if the counts of the facets is exhaustive
* @member {boolean}
*/
this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount;
/**
* True if the number of hits is exhaustive
* @member {boolean}
*/
this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits;
/**
* Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/).
* @member {object[]}
*/
this.userData = mainSubResponse.userData;
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
this.disjunctiveFacets = [];
/**
* disjunctive facets results
* @member {SearchResults.HierarchicalFacet[]}
*/
this.hierarchicalFacets = map_1(state.hierarchicalFacets, function initFutureTree() {
return [];
});
/**
* other facets results
* @member {SearchResults.Facet[]}
*/
this.facets = [];
var disjunctiveFacets = state.getRefinedDisjunctiveFacets();
var facetsIndices = getIndices(state.facets);
var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets);
var nextDisjunctiveResult = 1;
var self = this;
// Since we send request only for disjunctive facets that have been refined,
// we get the facets informations from the first, general, response.
forEach_1(mainSubResponse.facets, function(facetValueObject, facetKey) {
var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName(
state.hierarchicalFacets,
facetKey
);
if (hierarchicalFacet) {
// Place the hierarchicalFacet data at the correct index depending on
// the attributes order that was defined at the helper initialization
var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey);
var idxAttributeName = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name});
self.hierarchicalFacets[idxAttributeName][facetIndex] = {
attribute: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
} else {
var isFacetDisjunctive = indexOf_1(state.disjunctiveFacets, facetKey) !== -1;
var isFacetConjunctive = indexOf_1(state.facets, facetKey) !== -1;
var position;
if (isFacetDisjunctive) {
position = disjunctiveFacetsIndices[facetKey];
self.disjunctiveFacets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey);
}
if (isFacetConjunctive) {
position = facetsIndices[facetKey];
self.facets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey);
}
}
});
// Make sure we do not keep holes within the hierarchical facets
this.hierarchicalFacets = compact_1(this.hierarchicalFacets);
// aggregate the refined disjunctive facets
forEach_1(disjunctiveFacets, function(disjunctiveFacet) {
var result = results[nextDisjunctiveResult];
var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet);
// There should be only item in facets.
forEach_1(result.facets, function(facetResults, dfacet) {
var position;
if (hierarchicalFacet) {
position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
self.hierarchicalFacets[position][attributeIndex].data = merge_1(
{},
self.hierarchicalFacets[position][attributeIndex].data,
facetResults
);
} else {
position = disjunctiveFacetsIndices[dfacet];
var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {};
self.disjunctiveFacets[position] = {
name: dfacet,
data: defaults_1({}, facetResults, dataFromMainRequest),
exhaustive: result.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet);
if (state.disjunctiveFacetsRefinements[dfacet]) {
forEach_1(state.disjunctiveFacetsRefinements[dfacet], function(refinementValue) {
// add the disjunctive refinements if it is no more retrieved
if (!self.disjunctiveFacets[position].data[refinementValue] &&
indexOf_1(state.disjunctiveFacetsRefinements[dfacet], refinementValue) > -1) {
self.disjunctiveFacets[position].data[refinementValue] = 0;
}
});
}
}
});
nextDisjunctiveResult++;
});
// if we have some root level values for hierarchical facets, merge them
forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are already at a root refinement (or no refinement at all), there is no
// root level values request
if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) {
return;
}
var result = results[nextDisjunctiveResult];
forEach_1(result.facets, function(facetResults, dfacet) {
var position = findIndex_1(state.hierarchicalFacets, {name: hierarchicalFacet.name});
var attributeIndex = findIndex_1(self.hierarchicalFacets[position], {attribute: dfacet});
// previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
// when we always get root levels, if the hits refinement is `beers > IPA` (count: 5),
// then the disjunctive values will be `beers` (count: 100),
// but we do not want to display
// | beers (100)
// > IPA (5)
// We want
// | beers (5)
// > IPA (5)
var defaultData = {};
if (currentRefinement.length > 0) {
var root = currentRefinement[0].split(separator)[0];
defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root];
}
self.hierarchicalFacets[position][attributeIndex].data = defaults_1(
defaultData,
facetResults,
self.hierarchicalFacets[position][attributeIndex].data
);
});
nextDisjunctiveResult++;
});
// add the excludes
forEach_1(state.facetsExcludes, function(excludes, facetName) {
var position = facetsIndices[facetName];
self.facets[position] = {
name: facetName,
data: mainSubResponse.facets[facetName],
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
forEach_1(excludes, function(facetValue) {
self.facets[position] = self.facets[position] || {name: facetName};
self.facets[position].data = self.facets[position].data || {};
self.facets[position].data[facetValue] = 0;
});
});
this.hierarchicalFacets = map_1(this.hierarchicalFacets, generateHierarchicalTree_1(state));
this.facets = compact_1(this.facets);
this.disjunctiveFacets = compact_1(this.disjunctiveFacets);
this._state = state;
}
/**
* Get a facet object with its name
* @deprecated
* @param {string} name name of the faceted attribute
* @return {SearchResults.Facet} the facet object
*/
SearchResults.prototype.getFacetByName = function(name) {
var predicate = {name: name};
return find_1(this.facets, predicate) ||
find_1(this.disjunctiveFacets, predicate) ||
find_1(this.hierarchicalFacets, predicate);
};
/**
* Get the facet values of a specified attribute from a SearchResults object.
* @private
* @param {SearchResults} results the search results to search in
* @param {string} attribute name of the faceted attribute to search for
* @return {array|object} facet values. For the hierarchical facets it is an object.
*/
function extractNormalizedFacetValues(results, attribute) {
var predicate = {name: attribute};
if (results._state.isConjunctiveFacet(attribute)) {
var facet = find_1(results.facets, predicate);
if (!facet) return [];
return map_1(facet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isFacetRefined(attribute, k),
isExcluded: results._state.isExcludeRefined(attribute, k)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find_1(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return map_1(disjunctiveFacet.data, function(v, k) {
return {
name: k,
count: v,
isRefined: results._state.isDisjunctiveFacetRefined(attribute, k)
};
});
} else if (results._state.isHierarchicalFacet(attribute)) {
return find_1(results.hierarchicalFacets, predicate);
}
}
/**
* Sort nodes of a hierarchical facet results
* @private
* @param {HierarchicalFacet} node node to upon which we want to apply the sort
*/
function recSort(sortFn, node) {
if (!node.data || node.data.length === 0) {
return node;
}
var children = map_1(node.data, partial_1(recSort, sortFn));
var sortedChildren = sortFn(children);
var newNode = merge_1({}, node, {data: sortedChildren});
return newNode;
}
SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc'];
function vanillaSortFn(order, data) {
return data.sort(order);
}
/**
* Get a the list of values for a given facet attribute. Those values are sorted
* refinement first, descending count (bigger value on top), and name ascending
* (alphabetical order). The sort formula can overridden using either string based
* predicates or a function.
*
* This method will return all the values returned by the Algolia engine plus all
* the values already refined. This means that it can happen that the
* `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet)
* might not be respected if you have facet values that are already refined.
* @param {string} attribute attribute name
* @param {object} opts configuration options.
* @param {Array.<string> | function} opts.sortBy
* When using strings, it consists of
* the name of the [FacetValue](#SearchResults.FacetValue) or the
* [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the
* order (`asc` or `desc`). For example to order the value by count, the
* argument would be `['count:asc']`.
*
* If only the attribute name is specified, the ordering defaults to the one
* specified in the default value for this attribute.
*
* When not specified, the order is
* ascending. This parameter can also be a function which takes two facet
* values and should return a number, 0 if equal, 1 if the first argument is
* bigger or -1 otherwise.
*
* The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']`
* @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('results', function(content){
* //get values ordered only by name ascending using the string predicate
* content.getFacetValues('city', {sortBy: ['name:asc']});
* //get values ordered only by count ascending using a function
* content.getFacetValues('city', {
* // this is equivalent to ['count:asc']
* sortBy: function(a, b) {
* if (a.count === b.count) return 0;
* if (a.count > b.count) return 1;
* if (b.count > a.count) return -1;
* }
* });
* });
*/
SearchResults.prototype.getFacetValues = function(attribute, opts) {
var facetValues = extractNormalizedFacetValues(this, attribute);
if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.');
var options = defaults_1({}, opts, {sortBy: SearchResults.DEFAULT_SORT});
if (isArray_1(options.sortBy)) {
var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT);
if (isArray_1(facetValues)) {
return orderBy_1(facetValues, order[0], order[1]);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partialRight_1(orderBy_1, order[0], order[1]), facetValues);
} else if (isFunction_1(options.sortBy)) {
if (isArray_1(facetValues)) {
return facetValues.sort(options.sortBy);
}
// If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(partial_1(vanillaSortFn, options.sortBy), facetValues);
}
throw new Error(
'options.sortBy is optional but if defined it must be ' +
'either an array of string (predicates) or a sorting function'
);
};
/**
* Returns the facet stats if attribute is defined and the facet contains some.
* Otherwise returns undefined.
* @param {string} attribute name of the faceted attribute
* @return {object} The stats of the facet
*/
SearchResults.prototype.getFacetStats = function(attribute) {
if (this._state.isConjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.facets, attribute);
} else if (this._state.isDisjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute);
}
throw new Error(attribute + ' is not present in `facets` or `disjunctiveFacets`');
};
function getFacetStatsIfAvailable(facetList, facetName) {
var data = find_1(facetList, {name: facetName});
return data && data.stats;
}
/**
* Returns all refinements for all filters + tags. It also provides
* additional information: count and exhausistivity for each filter.
*
* See the [refinement type](#Refinement) for an exhaustive view of the available
* data.
*
* @return {Array.<Refinement>} all the refinements
*/
SearchResults.prototype.getRefinements = function() {
var state = this._state;
var results = this;
var res = [];
forEach_1(state.facetsRefinements, function(refinements, attributeName) {
forEach_1(refinements, function(name) {
res.push(getRefinement(state, 'facet', attributeName, name, results.facets));
});
});
forEach_1(state.facetsExcludes, function(refinements, attributeName) {
forEach_1(refinements, function(name) {
res.push(getRefinement(state, 'exclude', attributeName, name, results.facets));
});
});
forEach_1(state.disjunctiveFacetsRefinements, function(refinements, attributeName) {
forEach_1(refinements, function(name) {
res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets));
});
});
forEach_1(state.hierarchicalFacetsRefinements, function(refinements, attributeName) {
forEach_1(refinements, function(name) {
res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets));
});
});
forEach_1(state.numericRefinements, function(operators, attributeName) {
forEach_1(operators, function(values, operator) {
forEach_1(values, function(value) {
res.push({
type: 'numeric',
attributeName: attributeName,
name: value,
numericValue: value,
operator: operator
});
});
});
});
forEach_1(state.tagRefinements, function(name) {
res.push({type: 'tag', attributeName: '_tags', name: name});
});
return res;
};
function getRefinement(state, type, attributeName, name, resultsFacets) {
var facet = find_1(resultsFacets, {name: attributeName});
var count = get_1(facet, 'data[' + name + ']');
var exhaustive = get_1(facet, 'exhaustive');
return {
type: type,
attributeName: attributeName,
name: name,
count: count || 0,
exhaustive: exhaustive || false
};
}
function getHierarchicalRefinement(state, attributeName, name, resultsFacets) {
var facet = find_1(resultsFacets, {name: attributeName});
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var splitted = name.split(facetDeclaration.separator);
var configuredName = splitted[splitted.length - 1];
for (var i = 0; facet !== undefined && i < splitted.length; ++i) {
facet = find_1(facet.data, {name: splitted[i]});
}
var count = get_1(facet, 'count');
var exhaustive = get_1(facet, 'exhaustive');
return {
type: 'hierarchical',
attributeName: attributeName,
name: configuredName,
count: count || 0,
exhaustive: exhaustive || false
};
}
var SearchResults_1 = SearchResults;
var isBufferBrowser = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
};
var inherits_browser = createCommonjsModule(function (module) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
};
}
});
var util = createCommonjsModule(function (module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(commonjsGlobal.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = isBufferBrowser;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = inherits_browser;
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
});
var util_1 = util.format;
var util_2 = util.deprecate;
var util_3 = util.debuglog;
var util_4 = util.inspect;
var util_5 = util.isArray;
var util_6 = util.isBoolean;
var util_7 = util.isNull;
var util_8 = util.isNullOrUndefined;
var util_9 = util.isNumber;
var util_10 = util.isString;
var util_11 = util.isSymbol;
var util_12 = util.isUndefined;
var util_13 = util.isRegExp;
var util_14 = util.isObject;
var util_15 = util.isDate;
var util_16 = util.isError;
var util_17 = util.isFunction;
var util_18 = util.isPrimitive;
var util_19 = util.isBuffer;
var util_20 = util.log;
var util_21 = util.inherits;
var util_22 = util._extend;
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
var events = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber$1(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject$1(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined$1(handler))
return false;
if (isFunction$1(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject$1(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction$1(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction$1(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject$1(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject$1(this._events[type]) && !this._events[type].warned) {
if (!isUndefined$1(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction$1(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction$1(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction$1(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject$1(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction$1(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction$1(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction$1(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction$1(arg) {
return typeof arg === 'function';
}
function isNumber$1(arg) {
return typeof arg === 'number';
}
function isObject$1(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined$1(arg) {
return arg === void 0;
}
/**
* A DerivedHelper is a way to create sub requests to
* Algolia from a main helper.
* @class
* @classdesc The DerivedHelper provides an event based interface for search callbacks:
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
*/
function DerivedHelper(mainHelper, fn) {
this.main = mainHelper;
this.fn = fn;
this.lastResults = null;
}
util.inherits(DerivedHelper, events.EventEmitter);
/**
* Detach this helper from the main helper
* @return {undefined}
* @throws Error if the derived helper is already detached
*/
DerivedHelper.prototype.detach = function() {
this.removeAllListeners();
this.main.detachDerivedHelper(this);
};
DerivedHelper.prototype.getModifiedState = function(parameters) {
return this.fn(parameters);
};
var DerivedHelper_1 = DerivedHelper;
var requestBuilder = {
/**
* Get all the queries to send to the client, those queries can used directly
* with the Algolia client.
* @private
* @return {object[]} The queries
*/
_getQueries: function getQueries(index, state) {
var queries = [];
// One query for the hits
queries.push({
indexName: index,
params: requestBuilder._getHitsSearchParams(state)
});
// One for each disjunctive facets
forEach_1(state.getRefinedDisjunctiveFacets(), function(refinedFacet) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet)
});
});
// maybe more to get the root level of hierarchical facets when activated
forEach_1(state.getRefinedHierarchicalFacets(), function(refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet);
// if we are deeper than level 0 (starting from `beer > IPA`)
// we want to get the root values
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true)
});
}
});
return queries;
},
/**
* Build search parameters used to fetch hits
* @private
* @return {object.<string, any>}
*/
_getHitsSearchParams: function(state) {
var facets = state.facets
.concat(state.disjunctiveFacets)
.concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state));
var facetFilters = requestBuilder._getFacetFilters(state);
var numericFilters = requestBuilder._getNumericFilters(state);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
facets: facets,
tagFilters: tagFilters
};
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
return merge_1(state.getQueryParams(), additionalParams);
},
/**
* Build search parameters used to fetch a disjunctive facet
* @private
* @param {string} facet the associated facet name
* @param {boolean} hierarchicalRootLevel ?? FIXME
* @return {object}
*/
_getDisjunctiveFacetSearchParams: function(state, facet, hierarchicalRootLevel) {
var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel);
var numericFilters = requestBuilder._getNumericFilters(state, facet);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
hitsPerPage: 1,
page: 0,
attributesToRetrieve: [],
attributesToHighlight: [],
attributesToSnippet: [],
tagFilters: tagFilters,
analytics: false
};
var hierarchicalFacet = state.getHierarchicalFacetByName(facet);
if (hierarchicalFacet) {
additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute(
state,
hierarchicalFacet,
hierarchicalRootLevel
);
} else {
additionalParams.facets = facet;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
return merge_1(state.getQueryParams(), additionalParams);
},
/**
* Return the numeric filters in an algolia request fashion
* @private
* @param {string} [facetName] the name of the attribute for which the filters should be excluded
* @return {string[]} the numeric filters in the algolia format
*/
_getNumericFilters: function(state, facetName) {
if (state.numericFilters) {
return state.numericFilters;
}
var numericFilters = [];
forEach_1(state.numericRefinements, function(operators, attribute) {
forEach_1(operators, function(values, operator) {
if (facetName !== attribute) {
forEach_1(values, function(value) {
if (isArray_1(value)) {
var vs = map_1(value, function(v) {
return attribute + operator + v;
});
numericFilters.push(vs);
} else {
numericFilters.push(attribute + operator + value);
}
});
}
});
});
return numericFilters;
},
/**
* Return the tags filters depending
* @private
* @return {string}
*/
_getTagFilters: function(state) {
if (state.tagFilters) {
return state.tagFilters;
}
return state.tagRefinements.join(',');
},
/**
* Build facetFilters parameter based on current refinements. The array returned
* contains strings representing the facet filters in the algolia format.
* @private
* @param {string} [facet] if set, the current disjunctive facet
* @return {array.<string>}
*/
_getFacetFilters: function(state, facet, hierarchicalRootLevel) {
var facetFilters = [];
forEach_1(state.facetsRefinements, function(facetValues, facetName) {
forEach_1(facetValues, function(facetValue) {
facetFilters.push(facetName + ':' + facetValue);
});
});
forEach_1(state.facetsExcludes, function(facetValues, facetName) {
forEach_1(facetValues, function(facetValue) {
facetFilters.push(facetName + ':-' + facetValue);
});
});
forEach_1(state.disjunctiveFacetsRefinements, function(facetValues, facetName) {
if (facetName === facet || !facetValues || facetValues.length === 0) return;
var orFilters = [];
forEach_1(facetValues, function(facetValue) {
orFilters.push(facetName + ':' + facetValue);
});
facetFilters.push(orFilters);
});
forEach_1(state.hierarchicalFacetsRefinements, function(facetValues, facetName) {
var facetValue = facetValues[0];
if (facetValue === undefined) {
return;
}
var hierarchicalFacet = state.getHierarchicalFacetByName(facetName);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeToRefine;
var attributesIndex;
// we ask for parent facet values only when the `facet` is the current hierarchical facet
if (facet === facetName) {
// if we are at the root level already, no need to ask for facet values, we get them from
// the hits query
if (facetValue.indexOf(separator) === -1 || (!rootPath && hierarchicalRootLevel === true) ||
(rootPath && rootPath.split(separator).length === facetValue.split(separator).length)) {
return;
}
if (!rootPath) {
attributesIndex = facetValue.split(separator).length - 2;
facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator));
} else {
attributesIndex = rootPath.split(separator).length - 1;
facetValue = rootPath;
}
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
} else {
attributesIndex = facetValue.split(separator).length - 1;
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
}
if (attributeToRefine) {
facetFilters.push([attributeToRefine + ':' + facetValue]);
}
});
return facetFilters;
},
_getHitsHierarchicalFacetsAttributes: function(state) {
var out = [];
return reduce_1(
state.hierarchicalFacets,
// ask for as much levels as there's hierarchical refinements
function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) {
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0];
// if no refinement, ask for root level
if (!hierarchicalRefinement) {
allAttributes.push(hierarchicalFacet.attributes[0]);
return allAttributes;
}
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var level = hierarchicalRefinement.split(separator).length;
var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1);
return allAttributes.concat(newAttributes);
}, out);
},
_getDisjunctiveHierarchicalFacetAttribute: function(state, hierarchicalFacet, rootLevel) {
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (rootLevel === true) {
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeIndex = 0;
if (rootPath) {
attributeIndex = rootPath.split(separator).length;
}
return [hierarchicalFacet.attributes[attributeIndex]];
}
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || '';
// if refinement is 'beers > IPA > Flying dog',
// then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values)
var parentLevel = hierarchicalRefinement.split(separator).length - 1;
return hierarchicalFacet.attributes.slice(0, parentLevel + 1);
},
getSearchForFacetQuery: function(facetName, query, maxFacetHits, state) {
var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ?
state.clearRefinements(facetName) :
state;
var searchForFacetSearchParameters = {
facetQuery: query,
facetName: facetName
};
if (typeof maxFacetHits === 'number') {
searchForFacetSearchParameters.maxFacetHits = maxFacetHits;
}
var queries = merge_1(requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters);
return queries;
}
};
var requestBuilder_1 = requestBuilder;
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
_baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
var _baseInverter = baseInverter;
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return _baseInverter(object, setter, toIteratee(iteratee), {});
};
}
var _createInverter = createInverter;
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = _createInverter(function(result, value, key) {
result[value] = key;
}, constant_1(identity_1));
var invert_1 = invert;
var keys2Short = {
advancedSyntax: 'aS',
allowTyposOnNumericTokens: 'aTONT',
analyticsTags: 'aT',
analytics: 'a',
aroundLatLngViaIP: 'aLLVIP',
aroundLatLng: 'aLL',
aroundPrecision: 'aP',
aroundRadius: 'aR',
attributesToHighlight: 'aTH',
attributesToRetrieve: 'aTR',
attributesToSnippet: 'aTS',
disjunctiveFacetsRefinements: 'dFR',
disjunctiveFacets: 'dF',
distinct: 'd',
facetsExcludes: 'fE',
facetsRefinements: 'fR',
facets: 'f',
getRankingInfo: 'gRI',
hierarchicalFacetsRefinements: 'hFR',
hierarchicalFacets: 'hF',
highlightPostTag: 'hPoT',
highlightPreTag: 'hPrT',
hitsPerPage: 'hPP',
ignorePlurals: 'iP',
index: 'idx',
insideBoundingBox: 'iBB',
insidePolygon: 'iPg',
length: 'l',
maxValuesPerFacet: 'mVPF',
minimumAroundRadius: 'mAR',
minProximity: 'mP',
minWordSizefor1Typo: 'mWS1T',
minWordSizefor2Typos: 'mWS2T',
numericFilters: 'nF',
numericRefinements: 'nR',
offset: 'o',
optionalWords: 'oW',
page: 'p',
queryType: 'qT',
query: 'q',
removeWordsIfNoResults: 'rWINR',
replaceSynonymsInHighlight: 'rSIH',
restrictSearchableAttributes: 'rSA',
synonyms: 's',
tagFilters: 'tF',
tagRefinements: 'tR',
typoTolerance: 'tT',
optionalTagFilters: 'oTF',
optionalFacetFilters: 'oFF',
snippetEllipsisText: 'sET',
disableExactOnAttributes: 'dEOA',
enableExactOnSingleWordQuery: 'eEOSWQ'
};
var short2Keys = invert_1(keys2Short);
var shortener = {
/**
* All the keys of the state, encoded.
* @const
*/
ENCODED_PARAMETERS: keys_1(short2Keys),
/**
* Decode a shorten attribute
* @param {string} shortKey the shorten attribute
* @return {string} the decoded attribute, undefined otherwise
*/
decode: function(shortKey) {
return short2Keys[shortKey];
},
/**
* Encode an attribute into a short version
* @param {string} key the attribute
* @return {string} the shorten attribute
*/
encode: function(key) {
return keys2Short[key];
}
};
var utils = createCommonjsModule(function (module, exports) {
var has = Object.prototype.hasOwnProperty;
var hexTable = (function () {
var array = [];
for (var i = 0; i < 256; ++i) {
array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
}
return array;
}());
var compactQueue = function compactQueue(queue) {
var obj;
while (queue.length) {
var item = queue.pop();
obj = item.obj[item.prop];
if (Array.isArray(obj)) {
var compacted = [];
for (var j = 0; j < obj.length; ++j) {
if (typeof obj[j] !== 'undefined') {
compacted.push(obj[j]);
}
}
item.obj[item.prop] = compacted;
}
}
return obj;
};
exports.arrayToObject = function arrayToObject(source, options) {
var obj = options && options.plainObjects ? Object.create(null) : {};
for (var i = 0; i < source.length; ++i) {
if (typeof source[i] !== 'undefined') {
obj[i] = source[i];
}
}
return obj;
};
exports.merge = function merge(target, source, options) {
if (!source) {
return target;
}
if (typeof source !== 'object') {
if (Array.isArray(target)) {
target.push(source);
} else if (typeof target === 'object') {
if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) {
target[source] = true;
}
} else {
return [target, source];
}
return target;
}
if (typeof target !== 'object') {
return [target].concat(source);
}
var mergeTarget = target;
if (Array.isArray(target) && !Array.isArray(source)) {
mergeTarget = exports.arrayToObject(target, options);
}
if (Array.isArray(target) && Array.isArray(source)) {
source.forEach(function (item, i) {
if (has.call(target, i)) {
if (target[i] && typeof target[i] === 'object') {
target[i] = exports.merge(target[i], item, options);
} else {
target.push(item);
}
} else {
target[i] = item;
}
});
return target;
}
return Object.keys(source).reduce(function (acc, key) {
var value = source[key];
if (has.call(acc, key)) {
acc[key] = exports.merge(acc[key], value, options);
} else {
acc[key] = value;
}
return acc;
}, mergeTarget);
};
exports.assign = function assignSingleSource(target, source) {
return Object.keys(source).reduce(function (acc, key) {
acc[key] = source[key];
return acc;
}, target);
};
exports.decode = function (str) {
try {
return decodeURIComponent(str.replace(/\+/g, ' '));
} catch (e) {
return str;
}
};
exports.encode = function encode(str) {
// This code was originally written by Brian White (mscdex) for the io.js core querystring library.
// It has been adapted here for stricter adherence to RFC 3986
if (str.length === 0) {
return str;
}
var string = typeof str === 'string' ? str : String(str);
var out = '';
for (var i = 0; i < string.length; ++i) {
var c = string.charCodeAt(i);
if (
c === 0x2D // -
|| c === 0x2E // .
|| c === 0x5F // _
|| c === 0x7E // ~
|| (c >= 0x30 && c <= 0x39) // 0-9
|| (c >= 0x41 && c <= 0x5A) // a-z
|| (c >= 0x61 && c <= 0x7A) // A-Z
) {
out += string.charAt(i);
continue;
}
if (c < 0x80) {
out = out + hexTable[c];
continue;
}
if (c < 0x800) {
out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
if (c < 0xD800 || c >= 0xE000) {
out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
continue;
}
i += 1;
c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
out += hexTable[0xF0 | (c >> 18)]
+ hexTable[0x80 | ((c >> 12) & 0x3F)]
+ hexTable[0x80 | ((c >> 6) & 0x3F)]
+ hexTable[0x80 | (c & 0x3F)];
}
return out;
};
exports.compact = function compact(value) {
var queue = [{ obj: { o: value }, prop: 'o' }];
var refs = [];
for (var i = 0; i < queue.length; ++i) {
var item = queue[i];
var obj = item.obj[item.prop];
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
var val = obj[key];
if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
queue.push({ obj: obj, prop: key });
refs.push(val);
}
}
}
return compactQueue(queue);
};
exports.isRegExp = function isRegExp(obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
};
exports.isBuffer = function isBuffer(obj) {
if (obj === null || typeof obj === 'undefined') {
return false;
}
return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
};
});
var utils_1 = utils.arrayToObject;
var utils_2 = utils.merge;
var utils_3 = utils.assign;
var utils_4 = utils.decode;
var utils_5 = utils.encode;
var utils_6 = utils.compact;
var utils_7 = utils.isRegExp;
var utils_8 = utils.isBuffer;
var replace = String.prototype.replace;
var percentTwenties = /%20/g;
var formats = {
'default': 'RFC3986',
formatters: {
RFC1738: function (value) {
return replace.call(value, percentTwenties, '+');
},
RFC3986: function (value) {
return value;
}
},
RFC1738: 'RFC1738',
RFC3986: 'RFC3986'
};
var arrayPrefixGenerators = {
brackets: function brackets(prefix) { // eslint-disable-line func-name-matching
return prefix + '[]';
},
indices: function indices(prefix, key) { // eslint-disable-line func-name-matching
return prefix + '[' + key + ']';
},
repeat: function repeat(prefix) { // eslint-disable-line func-name-matching
return prefix;
}
};
var toISO = Date.prototype.toISOString;
var defaults$1 = {
delimiter: '&',
encode: true,
encoder: utils.encode,
encodeValuesOnly: false,
serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching
return toISO.call(date);
},
skipNulls: false,
strictNullHandling: false
};
var stringify = function stringify( // eslint-disable-line func-name-matching
object,
prefix,
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly
) {
var obj = object;
if (typeof filter === 'function') {
obj = filter(prefix, obj);
} else if (obj instanceof Date) {
obj = serializeDate(obj);
} else if (obj === null) {
if (strictNullHandling) {
return encoder && !encodeValuesOnly ? encoder(prefix, defaults$1.encoder) : prefix;
}
obj = '';
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
if (encoder) {
var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults$1.encoder);
return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults$1.encoder))];
}
return [formatter(prefix) + '=' + formatter(String(obj))];
}
var values = [];
if (typeof obj === 'undefined') {
return values;
}
var objKeys;
if (Array.isArray(filter)) {
objKeys = filter;
} else {
var keys = Object.keys(obj);
objKeys = sort ? keys.sort(sort) : keys;
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
if (Array.isArray(obj)) {
values = values.concat(stringify(
obj[key],
generateArrayPrefix(prefix, key),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly
));
} else {
values = values.concat(stringify(
obj[key],
prefix + (allowDots ? '.' + key : '[' + key + ']'),
generateArrayPrefix,
strictNullHandling,
skipNulls,
encoder,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly
));
}
}
return values;
};
var stringify_1 = function (object, opts) {
var obj = object;
var options = opts ? utils.assign({}, opts) : {};
if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
throw new TypeError('Encoder has to be a function.');
}
var delimiter = typeof options.delimiter === 'undefined' ? defaults$1.delimiter : options.delimiter;
var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$1.strictNullHandling;
var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults$1.skipNulls;
var encode = typeof options.encode === 'boolean' ? options.encode : defaults$1.encode;
var encoder = typeof options.encoder === 'function' ? options.encoder : defaults$1.encoder;
var sort = typeof options.sort === 'function' ? options.sort : null;
var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults$1.serializeDate;
var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults$1.encodeValuesOnly;
if (typeof options.format === 'undefined') {
options.format = formats['default'];
} else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
throw new TypeError('Unknown format option provided.');
}
var formatter = formats.formatters[options.format];
var objKeys;
var filter;
if (typeof options.filter === 'function') {
filter = options.filter;
obj = filter('', obj);
} else if (Array.isArray(options.filter)) {
filter = options.filter;
objKeys = filter;
}
var keys = [];
if (typeof obj !== 'object' || obj === null) {
return '';
}
var arrayFormat;
if (options.arrayFormat in arrayPrefixGenerators) {
arrayFormat = options.arrayFormat;
} else if ('indices' in options) {
arrayFormat = options.indices ? 'indices' : 'repeat';
} else {
arrayFormat = 'indices';
}
var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
if (!objKeys) {
objKeys = Object.keys(obj);
}
if (sort) {
objKeys.sort(sort);
}
for (var i = 0; i < objKeys.length; ++i) {
var key = objKeys[i];
if (skipNulls && obj[key] === null) {
continue;
}
keys = keys.concat(stringify(
obj[key],
key,
generateArrayPrefix,
strictNullHandling,
skipNulls,
encode ? encoder : null,
filter,
sort,
allowDots,
serializeDate,
formatter,
encodeValuesOnly
));
}
var joined = keys.join(delimiter);
var prefix = options.addQueryPrefix === true ? '?' : '';
return joined.length > 0 ? prefix + joined : '';
};
var has = Object.prototype.hasOwnProperty;
var defaults$2 = {
allowDots: false,
allowPrototypes: false,
arrayLimit: 20,
decoder: utils.decode,
delimiter: '&',
depth: 5,
parameterLimit: 1000,
plainObjects: false,
strictNullHandling: false
};
var parseValues = function parseQueryStringValues(str, options) {
var obj = {};
var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
var parts = cleanStr.split(options.delimiter, limit);
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
var bracketEqualsPos = part.indexOf(']=');
var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
var key, val;
if (pos === -1) {
key = options.decoder(part, defaults$2.decoder);
val = options.strictNullHandling ? null : '';
} else {
key = options.decoder(part.slice(0, pos), defaults$2.decoder);
val = options.decoder(part.slice(pos + 1), defaults$2.decoder);
}
if (has.call(obj, key)) {
obj[key] = [].concat(obj[key]).concat(val);
} else {
obj[key] = val;
}
}
return obj;
};
var parseObject = function (chain, val, options) {
var leaf = val;
for (var i = chain.length - 1; i >= 0; --i) {
var obj;
var root = chain[i];
if (root === '[]') {
obj = [];
obj = obj.concat(leaf);
} else {
obj = options.plainObjects ? Object.create(null) : {};
var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
var index = parseInt(cleanRoot, 10);
if (
!isNaN(index)
&& root !== cleanRoot
&& String(index) === cleanRoot
&& index >= 0
&& (options.parseArrays && index <= options.arrayLimit)
) {
obj = [];
obj[index] = leaf;
} else {
obj[cleanRoot] = leaf;
}
}
leaf = obj;
}
return leaf;
};
var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
if (!givenKey) {
return;
}
// Transform dot notation to bracket notation
var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
// The regex chunks
var brackets = /(\[[^[\]]*])/;
var child = /(\[[^[\]]*])/g;
// Get the parent
var segment = brackets.exec(key);
var parent = segment ? key.slice(0, segment.index) : key;
// Stash the parent if it exists
var keys = [];
if (parent) {
// If we aren't using plain objects, optionally prefix keys
// that would overwrite object prototype properties
if (!options.plainObjects && has.call(Object.prototype, parent)) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(parent);
}
// Loop through children appending to the array until we hit depth
var i = 0;
while ((segment = child.exec(key)) !== null && i < options.depth) {
i += 1;
if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
if (!options.allowPrototypes) {
return;
}
}
keys.push(segment[1]);
}
// If there's a remainder, just add whatever is left
if (segment) {
keys.push('[' + key.slice(segment.index) + ']');
}
return parseObject(keys, val, options);
};
var parse = function (str, opts) {
var options = opts ? utils.assign({}, opts) : {};
if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
throw new TypeError('Decoder has to be a function.');
}
options.ignoreQueryPrefix = options.ignoreQueryPrefix === true;
options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults$2.delimiter;
options.depth = typeof options.depth === 'number' ? options.depth : defaults$2.depth;
options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults$2.arrayLimit;
options.parseArrays = options.parseArrays !== false;
options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults$2.decoder;
options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults$2.allowDots;
options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults$2.plainObjects;
options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults$2.allowPrototypes;
options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults$2.parameterLimit;
options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults$2.strictNullHandling;
if (str === '' || str === null || typeof str === 'undefined') {
return options.plainObjects ? Object.create(null) : {};
}
var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
var obj = options.plainObjects ? Object.create(null) : {};
// Iterate over the keys and setup the new object
var keys = Object.keys(tempObj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var newObj = parseKeys(key, tempObj[key], options);
obj = utils.merge(obj, newObj, options);
}
return utils.compact(obj);
};
var lib$1 = {
formats: formats,
parse: parse,
stringify: stringify_1
};
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG$7 = 1,
WRAP_PARTIAL_FLAG$4 = 32;
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = _baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG$7;
if (partials.length) {
var holders = _replaceHolders(partials, _getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG$4;
}
return _createWrap(func, bitmask, thisArg, partials, holders);
});
// Assign default placeholders.
bind.placeholder = {};
var bind_1 = bind;
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return _basePickBy(object, paths, function(value, path) {
return hasIn_1(object, path);
});
}
var _basePick = basePick;
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = _flatRest(function(object, paths) {
return object == null ? {} : _basePick(object, paths);
});
var pick_1 = pick;
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/
function mapKeys(object, iteratee) {
var result = {};
iteratee = _baseIteratee(iteratee, 3);
_baseForOwn(object, function(value, key, object) {
_baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
var mapKeys_1 = mapKeys;
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = _baseIteratee(iteratee, 3);
_baseForOwn(object, function(value, key, object) {
_baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
var mapValues_1 = mapValues;
/**
* Module containing the functions to serialize and deserialize
* {SearchParameters} in the query string format
* @module algoliasearchHelper.url
*/
var encode = utils.encode;
function recursiveEncode(input) {
if (isPlainObject_1(input)) {
return mapValues_1(input, recursiveEncode);
}
if (isArray_1(input)) {
return map_1(input, recursiveEncode);
}
if (isString_1(input)) {
return encode(input);
}
return input;
}
var refinementsParameters = ['dFR', 'fR', 'nR', 'hFR', 'tR'];
var stateKeys = shortener.ENCODED_PARAMETERS;
function sortQueryStringValues(prefixRegexp, invertedMapping, a, b) {
if (prefixRegexp !== null) {
a = a.replace(prefixRegexp, '');
b = b.replace(prefixRegexp, '');
}
a = invertedMapping[a] || a;
b = invertedMapping[b] || b;
if (stateKeys.indexOf(a) !== -1 || stateKeys.indexOf(b) !== -1) {
if (a === 'q') return -1;
if (b === 'q') return 1;
var isARefinements = refinementsParameters.indexOf(a) !== -1;
var isBRefinements = refinementsParameters.indexOf(b) !== -1;
if (isARefinements && !isBRefinements) {
return 1;
} else if (isBRefinements && !isARefinements) {
return -1;
}
}
return a.localeCompare(b);
}
/**
* Read a query string and return an object containing the state
* @param {string} queryString the query string that will be decoded
* @param {object} [options] accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
*/
var getStateFromQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var invertedMapping = invert_1(mapping);
var partialStateWithPrefix = lib$1.parse(queryString);
var prefixRegexp = new RegExp('^' + prefixForParameters);
var partialState = mapKeys_1(
partialStateWithPrefix,
function(v, k) {
var hasPrefix = prefixForParameters && prefixRegexp.test(k);
var unprefixedKey = hasPrefix ? k.replace(prefixRegexp, '') : k;
var decodedKey = shortener.decode(invertedMapping[unprefixedKey] || unprefixedKey);
return decodedKey || unprefixedKey;
}
);
var partialStateWithParsedNumbers = SearchParameters_1._parseNumbers(partialState);
return pick_1(partialStateWithParsedNumbers, SearchParameters_1.PARAMETERS);
};
/**
* Retrieve an object of all the properties that are not understandable as helper
* parameters.
* @param {string} queryString the query string to read
* @param {object} [options] the options
* - prefixForParameters : prefix used for the helper configuration keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
var getUnrecognizedParametersInQueryString = function(queryString, options) {
var prefixForParameters = options && options.prefix;
var mapping = options && options.mapping || {};
var invertedMapping = invert_1(mapping);
var foreignConfig = {};
var config = lib$1.parse(queryString);
if (prefixForParameters) {
var prefixRegexp = new RegExp('^' + prefixForParameters);
forEach_1(config, function(v, key) {
if (!prefixRegexp.test(key)) foreignConfig[key] = v;
});
} else {
forEach_1(config, function(v, key) {
if (!shortener.decode(invertedMapping[key] || key)) foreignConfig[key] = v;
});
}
return foreignConfig;
};
/**
* Generate a query string for the state passed according to the options
* @param {SearchParameters} state state to serialize
* @param {object} [options] May contain the following parameters :
* - prefix : prefix in front of the keys
* - mapping : map short attributes to another value e.g. {q: 'query'}
* - moreAttributes : more values to be added in the query string. Those values
* won't be prefixed.
* - safe : get safe urls for use in emails, chat apps or any application auto linking urls.
* All parameters and values will be encoded in a way that it's safe to share them.
* Default to false for legacy reasons ()
* @return {string} the query string
*/
var getQueryStringFromState = function(state, options) {
var moreAttributes = options && options.moreAttributes;
var prefixForParameters = options && options.prefix || '';
var mapping = options && options.mapping || {};
var safe = options && options.safe || false;
var invertedMapping = invert_1(mapping);
var stateForUrl = safe ? state : recursiveEncode(state);
var encodedState = mapKeys_1(
stateForUrl,
function(v, k) {
var shortK = shortener.encode(k);
return prefixForParameters + (mapping[shortK] || shortK);
}
);
var prefixRegexp = prefixForParameters === '' ? null : new RegExp('^' + prefixForParameters);
var sort = bind_1(sortQueryStringValues, null, prefixRegexp, invertedMapping);
if (!isEmpty_1(moreAttributes)) {
var stateQs = lib$1.stringify(encodedState, {encode: safe, sort: sort});
var moreQs = lib$1.stringify(moreAttributes, {encode: safe});
if (!stateQs) return moreQs;
return stateQs + '&' + moreQs;
}
return lib$1.stringify(encodedState, {encode: safe, sort: sort});
};
var url = {
getStateFromQueryString: getStateFromQueryString,
getUnrecognizedParametersInQueryString: getUnrecognizedParametersInQueryString,
getQueryStringFromState: getQueryStringFromState
};
var version$1 = '2.22.0';
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {SearchParameters} state the current parameters with the latest changes applied
* @property {SearchResults} lastResults the previous results received from Algolia. `null` before
* the first request
* @example
* helper.on('change', function(state, lastResults) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when a main search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {SearchParameters} state the parameters used for this search
* @property {SearchResults} lastResults the results from the previous search. `null` if
* it is the first search.
* @example
* helper.on('search', function(state, lastResults) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when a search using `searchForFacetValues` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchForFacetValues
* @property {SearchParameters} state the parameters used for this search
* it is the first search.
* @property {string} facet the facet searched into
* @property {string} query the query used to search in the facets
* @example
* helper.on('searchForFacetValues', function(state, facet, query) {
* console.log('searchForFacetValues sent');
* });
*/
/**
* Event triggered when a search using `searchOnce` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchOnce
* @property {SearchParameters} state the parameters used for this search
* it is the first search.
* @example
* helper.on('searchOnce', function(state) {
* console.log('searchOnce sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {SearchResults} results the results received from Algolia
* @property {SearchParameters} state the parameters used to query Algolia. Those might
* be different from the one in the helper instance (for example if the network is unreliable).
* @example
* helper.on('result', function(results, state) {
* console.log('Search results received');
* });
*/
/**
* Event triggered when Algolia sends back an error. For example, if an unknown parameter is
* used, the error can be caught using this event.
* @event AlgoliaSearchHelper#event:error
* @property {Error} error the error returned by the Algolia.
* @example
* helper.on('error', function(error) {
* console.log('Houston we got a problem.');
* });
*/
/**
* Event triggered when the queue of queries have been depleted (with any result or outdated queries)
* @event AlgoliaSearchHelper#event:searchQueueEmpty
* @example
* helper.on('searchQueueEmpty', function() {
* console.log('No more search pending');
* // This is received before the result event if we're not expecting new results
* });
*
* helper.search();
*/
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
* search. It provides an event based interface for search callbacks:
* - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the
* {@link SearchResults} of the last result if any.
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial
* config of the search. It doesn't have to be a {SearchParameters},
* just an object containing the properties you need from it.
*/
function AlgoliaSearchHelper(client, index, options) {
if (!client.addAlgoliaAgent) console.log('Please upgrade to the newest version of the JS Client.'); // eslint-disable-line
else if (!doesClientAgentContainsHelper(client)) client.addAlgoliaAgent('JS Helper ' + version$1);
this.setClient(client);
var opts = options || {};
opts.index = index;
this.state = SearchParameters_1.make(opts);
this.lastResults = null;
this._queryId = 0;
this._lastQueryIdReceived = -1;
this.derivedHelpers = [];
this._currentNbQueries = 0;
}
util.inherits(AlgoliaSearchHelper, events.EventEmitter);
/**
* Start the search with the parameters set in the state. When the
* method is called, it triggers a `search` event. The results will
* be available through the `result` event. If an error occurs, an
* `error` will be fired instead.
* @return {AlgoliaSearchHelper}
* @fires search
* @fires result
* @fires error
* @chainable
*/
AlgoliaSearchHelper.prototype.search = function() {
this._search();
return this;
};
/**
* Gets the search query parameters that would be sent to the Algolia Client
* for the hits
* @return {object} Query Parameters
*/
AlgoliaSearchHelper.prototype.getQuery = function() {
var state = this.state;
return requestBuilder_1._getHitsSearchParams(state);
};
/**
* Start a search using a modified version of the current state. This method does
* not trigger the helper lifecycle and does not modify the state kept internally
* by the helper. This second aspect means that the next search call will be the
* same as a search call before calling searchOnce.
* @param {object} options can contain all the parameters that can be set to SearchParameters
* plus the index
* @param {function} [callback] optional callback executed when the response from the
* server is back.
* @return {promise|undefined} if a callback is passed the method returns undefined
* otherwise it returns a promise containing an object with two keys :
* - content with a SearchResults
* - state with the state used for the query as a SearchParameters
* @example
* // Changing the number of records returned per page to 1
* // This example uses the callback API
* var state = helper.searchOnce({hitsPerPage: 1},
* function(error, content, state) {
* // if an error occurred it will be passed in error, otherwise its value is null
* // content contains the results formatted as a SearchResults
* // state is the instance of SearchParameters used for this search
* });
* @example
* // Changing the number of records returned per page to 1
* // This example uses the promise API
* var state1 = helper.searchOnce({hitsPerPage: 1})
* .then(promiseHandler);
*
* function promiseHandler(res) {
* // res contains
* // {
* // content : SearchResults
* // state : SearchParameters (the one used for this specific search)
* // }
* }
*/
AlgoliaSearchHelper.prototype.searchOnce = function(options, cb) {
var tempState = !options ? this.state : this.state.setQueryParameters(options);
var queries = requestBuilder_1._getQueries(tempState.index, tempState);
var self = this;
this._currentNbQueries++;
this.emit('searchOnce', tempState);
if (cb) {
return this.client.search(
queries,
function(err, content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
if (err) cb(err, null, tempState);
else cb(err, new SearchResults_1(tempState, content.results), tempState);
}
);
}
return this.client.search(queries).then(function(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
return {
content: new SearchResults_1(tempState, content.results),
state: tempState,
_originalResponse: content
};
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Structure of each result when using
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* @typedef FacetSearchHit
* @type {object}
* @property {string} value the facet value
* @property {string} highlighted the facet value highlighted with the query string
* @property {number} count number of occurrence of this facet value
* @property {boolean} isRefined true if the value is already refined
*/
/**
* Structure of the data resolved by the
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* promise.
* @typedef FacetSearchResult
* @type {object}
* @property {FacetSearchHit} facetHits the results for this search for facet values
* @property {number} processingTimeMS time taken by the query inside the engine
*/
/**
* Search for facet values based on an query and the name of a faceted attribute. This
* triggers a search and will return a promise. On top of using the query, it also sends
* the parameters from the state so that the search is narrowed down to only the possible values.
*
* See the description of [FacetSearchResult](reference.html#FacetSearchResult)
* @param {string} facet the name of the faceted attribute
* @param {string} query the string query for the search
* @param {number} maxFacetHits the maximum number values returned. Should be > 0 and <= 100
* @return {promise<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper.prototype.searchForFacetValues = function(facet, query, maxFacetHits) {
var state = this.state;
var index = this.client.initIndex(this.state.index);
var isDisjunctive = state.isDisjunctiveFacet(facet);
var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, this.state);
this._currentNbQueries++;
var self = this;
this.emit('searchForFacetValues', state, facet, query);
return index.searchForFacetValues(algoliaQuery).then(function addIsRefined(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
content.facetHits = forEach_1(content.facetHits, function(f) {
f.isRefined = isDisjunctive ?
state.isDisjunctiveFacetRefined(facet, f.value) :
state.isFacetRefined(facet, f.value);
});
return content;
}, function(e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Sets the text query used for the search.
*
* This method resets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setQuery = function(q) {
this.state = this.state.setPage(0).setQuery(q);
this._change();
return this;
};
/**
* Remove all the types of refinements except tags. A string can be provided to remove
* only the refinements of a specific attribute. For more advanced use case, you can
* provide a function instead. This function should follow the
* [clearCallback definition](#SearchParameters.clearCallback).
*
* This method resets the current page to 0.
* @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* // Removing all the refinements
* helper.clearRefinements().search();
* @example
* // Removing all the filters on a the category attribute.
* helper.clearRefinements('category').search();
* @example
* // Removing only the exclude filters on the category facet.
* helper.clearRefinements(function(value, attribute, type) {
* return type === 'exclude' && attribute === 'category';
* }).search();
*/
AlgoliaSearchHelper.prototype.clearRefinements = function(name) {
this.state = this.state.setPage(0).clearRefinements(name);
this._change();
return this;
};
/**
* Remove all the tag filters.
*
* This method resets the current page to 0.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.clearTags = function() {
this.state = this.state.setPage(0).clearTags();
this._change();
return this;
};
/**
* Adds a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function() {
return this.addDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Adds a refinement on a hierarchical facet. It will throw
* an exception if the facet is not defined or if the facet
* is already refined.
*
* This method resets the current page to 0.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is refined
* @chainable
* @fires change
*/
AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addHierarchicalFacetRefinement(facet, value);
this._change();
return this;
};
/**
* Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} operator the operator of the filter
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).addNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Adds a filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).addFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addRefine = function() {
return this.addFacetRefinement.apply(this, arguments);
};
/**
* Adds a an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).addExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion}
*/
AlgoliaSearchHelper.prototype.addExclude = function() {
return this.addFacetExclusion.apply(this, arguments);
};
/**
* Adds a tag filter with the `tag` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addTag = function(tag) {
this.state = this.state.setPage(0).addTagRefinement(tag);
this._change();
return this;
};
/**
* Removes an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* Some parameters are optional, triggering different behavior:
* - if the value is not provided, then all the numeric value will be removed for the
* specified attribute/operator couple.
* - if the operator is not provided either, then all the numeric filter on this attribute
* will be removed.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} [operator] the operator of the filter
* @param {number} [value] the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeNumericRefinement = function(attribute, operator, value) {
this.state = this.state.setPage(0).removeNumericRefinement(attribute, operator, value);
this._change();
return this;
};
/**
* Removes a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeDisjunctiveFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function() {
return this.removeDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is not refined
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function(facet) {
this.state = this.state.setPage(0).removeHierarchicalFacetRefinement(facet);
this._change();
return this;
};
/**
* Removes a filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).removeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeRefine = function() {
return this.removeFacetRefinement.apply(this, arguments);
};
/**
* Removes an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).removeExcludeRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion}
*/
AlgoliaSearchHelper.prototype.removeExclude = function() {
return this.removeFacetExclusion.apply(this, arguments);
};
/**
* Removes a tag filter with the `tag` provided. If the
* filter is not set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeTag = function(tag) {
this.state = this.state.setPage(0).removeTagRefinement(tag);
this._change();
return this;
};
/**
* Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetExclusion = function(facet, value) {
this.state = this.state.setPage(0).toggleExcludeFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion}
*/
AlgoliaSearchHelper.prototype.toggleExclude = function() {
return this.toggleFacetExclusion.apply(this, arguments);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
* @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefinement = function(facet, value) {
return this.toggleFacetRefinement(facet, value);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetRefinement = function(facet, value) {
this.state = this.state.setPage(0).toggleFacetRefinement(facet, value);
this._change();
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefine = function() {
return this.toggleFacetRefinement.apply(this, arguments);
};
/**
* Adds or removes a tag filter with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleTag = function(tag) {
this.state = this.state.setPage(0).toggleTagRefinement(tag);
this._change();
return this;
};
/**
* Increments the page number by one.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setPage(0).nextPage().getPage();
* // returns 1
*/
AlgoliaSearchHelper.prototype.nextPage = function() {
return this.setPage(this.state.page + 1);
};
/**
* Decrements the page number by one.
* @fires change
* @return {AlgoliaSearchHelper}
* @chainable
* @example
* helper.setPage(1).previousPage().getPage();
* // returns 0
*/
AlgoliaSearchHelper.prototype.previousPage = function() {
return this.setPage(this.state.page - 1);
};
/**
* @private
*/
function setCurrentPage(page) {
if (page < 0) throw new Error('Page requested below 0.');
this.state = this.state.setPage(page);
this._change();
return this;
}
/**
* Change the current page
* @deprecated
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage;
/**
* Updates the current page.
* @function
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setPage = setCurrentPage;
/**
* Updates the name of the index that will be targeted by the query.
*
* This method resets the current page to 0.
* @param {string} name the index name
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setIndex = function(name) {
this.state = this.state.setPage(0).setIndex(name);
this._change();
return this;
};
/**
* Update a parameter of the search. This method reset the page
*
* The complete list of parameters is available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters and facets have their own API)
*
* This method resets the current page to 0.
* @param {string} parameter name of the parameter to update
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setQueryParameter('hitsPerPage', 20).search();
*/
AlgoliaSearchHelper.prototype.setQueryParameter = function(parameter, value) {
var newState = this.state.setPage(0).setQueryParameter(parameter, value);
if (this.state === newState) return this;
this.state = newState;
this._change();
return this;
};
/**
* Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setState = function(newState) {
this.state = SearchParameters_1.make(newState);
this._change();
return this;
};
/**
* Get the current search state stored in the helper. This object is immutable.
* @param {string[]} [filters] optional filters to retrieve only a subset of the state
* @return {SearchParameters|object} if filters is specified a plain object is
* returned containing only the requested fields, otherwise return the unfiltered
* state
* @example
* // Get the complete state as stored in the helper
* helper.getState();
* @example
* // Get a part of the state with all the refinements on attributes and the query
* helper.getState(['query', 'attribute:category']);
*/
AlgoliaSearchHelper.prototype.getState = function(filters) {
if (filters === undefined) return this.state;
return this.state.filter(filters);
};
/**
* DEPRECATED Get part of the state as a query string. By default, the output keys will not
* be prefixed and will only take the applied refinements and the query.
* @deprecated
* @param {object} [options] May contain the following parameters :
*
* **filters** : possible values are all the keys of the [SearchParameters](#searchparameters), `index` for
* the index, all the refinements with `attribute:*` or for some specific attributes with
* `attribute:theAttribute`
*
* **prefix** : prefix in front of the keys
*
* **moreAttributes** : more values to be added in the query string. Those values
* won't be prefixed.
* @return {string} the query string
*/
AlgoliaSearchHelper.prototype.getStateAsQueryString = function getStateAsQueryString(options) {
var filters = options && options.filters || ['query', 'attribute:*'];
var partialState = this.getState(filters);
return url.getQueryStringFromState(partialState, options);
};
/**
* DEPRECATED Read a query string and return an object containing the state. Use
* url module.
* @deprecated
* @static
* @param {string} queryString the query string that will be decoded
* @param {object} options accepted options :
* - prefix : the prefix used for the saved attributes, you have to provide the
* same that was used for serialization
* @return {object} partial search parameters object (same properties than in the
* SearchParameters but not exhaustive)
* @see {@link url#getStateFromQueryString}
*/
AlgoliaSearchHelper.getConfigurationFromQueryString = url.getStateFromQueryString;
/**
* DEPRECATED Retrieve an object of all the properties that are not understandable as helper
* parameters. Use url module.
* @deprecated
* @static
* @param {string} queryString the query string to read
* @param {object} options the options
* - prefixForParameters : prefix used for the helper configuration keys
* @return {object} the object containing the parsed configuration that doesn't
* to the helper
*/
AlgoliaSearchHelper.getForeignConfigurationInQueryString = url.getUnrecognizedParametersInQueryString;
/**
* DEPRECATED Overrides part of the state with the properties stored in the provided query
* string.
* @deprecated
* @param {string} queryString the query string containing the informations to url the state
* @param {object} options optional parameters :
* - prefix : prefix used for the algolia parameters
* - triggerChange : if set to true the state update will trigger a change event
*/
AlgoliaSearchHelper.prototype.setStateFromQueryString = function(queryString, options) {
var triggerChange = options && options.triggerChange || false;
var configuration = url.getStateFromQueryString(queryString, options);
var updatedState = this.state.setQueryParameters(configuration);
if (triggerChange) this.setState(updatedState);
else this.overrideStateWithoutTriggeringChangeEvent(updatedState);
};
/**
* Override the current state without triggering a change event.
* Do not use this method unless you know what you are doing. (see the example
* for a legit use case)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @example
* helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
* updateYourURL(state)
* })
* window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
* helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
* @chainable
*/
AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function(newState) {
this.state = new SearchParameters_1(newState);
return this;
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isRefined = function(facet, value) {
if (this.state.isConjunctiveFacet(facet)) {
return this.state.isFacetRefined(facet, value);
} else if (this.state.isDisjunctiveFacet(facet)) {
return this.state.isDisjunctiveFacetRefined(facet, value);
}
throw new Error(facet +
' is not properly defined in this helper configuration' +
'(use the facets or disjunctiveFacets keys to configure it)');
};
/**
* Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
* @example
* // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
* helper.hasRefinements('price'); // false
* helper.addNumericRefinement('price', '>', 100);
* helper.hasRefinements('price'); // true
*
* helper.hasRefinements('color'); // false
* helper.addFacetRefinement('color', 'blue');
* helper.hasRefinements('color'); // true
*
* helper.hasRefinements('material'); // false
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* helper.hasRefinements('material'); // true
*
* helper.hasRefinements('categories'); // false
* helper.toggleFacetRefinement('categories', 'kitchen > knife');
* helper.hasRefinements('categories'); // true
*
*/
AlgoliaSearchHelper.prototype.hasRefinements = function(attribute) {
if (!isEmpty_1(this.state.getNumericRefinements(attribute))) {
return true;
} else if (this.state.isConjunctiveFacet(attribute)) {
return this.state.isFacetRefined(attribute);
} else if (this.state.isDisjunctiveFacet(attribute)) {
return this.state.isDisjunctiveFacetRefined(attribute);
} else if (this.state.isHierarchicalFacet(attribute)) {
return this.state.isHierarchicalFacetRefined(attribute);
}
// there's currently no way to know that the user did call `addNumericRefinement` at some point
// thus we cannot distinguish if there once was a numeric refinement that was cleared
// so we will return false in every other situations to be consistent
// while what we should do here is throw because we did not find the attribute in any type
// of refinement
return false;
};
/**
* Check if a value is excluded for a specific faceted attribute. If the value
* is omitted then the function checks if there is any excluding refinements.
*
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} true if refined
* @example
* helper.isExcludeRefined('color'); // false
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // false
*
* helper.addFacetExclusion('color', 'red');
*
* helper.isExcludeRefined('color'); // true
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // true
*/
AlgoliaSearchHelper.prototype.isExcluded = function(facet, value) {
return this.state.isExcludeRefined(facet, value);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function(facet, value) {
return this.state.isDisjunctiveFacetRefined(facet, value);
};
/**
* Check if the string is a currently filtering tag.
* @param {string} tag tag to check
* @return {boolean}
*/
AlgoliaSearchHelper.prototype.hasTag = function(tag) {
return this.state.isTagRefined(tag);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag}
*/
AlgoliaSearchHelper.prototype.isTagRefined = function() {
return this.hasTagRefinements.apply(this, arguments);
};
/**
* Get the name of the currently used index.
* @return {string}
* @example
* helper.setIndex('highestPrice_products').getIndex();
* // returns 'highestPrice_products'
*/
AlgoliaSearchHelper.prototype.getIndex = function() {
return this.state.index;
};
function getCurrentPage() {
return this.state.page;
}
/**
* Get the currently selected page
* @deprecated
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage;
/**
* Get the currently selected page
* @function
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getPage = getCurrentPage;
/**
* Get all the tags currently set to filters the results.
*
* @return {string[]} The list of tags currently set.
*/
AlgoliaSearchHelper.prototype.getTags = function() {
return this.state.tagRefinements;
};
/**
* Get a parameter of the search by its name. It is possible that a parameter is directly
* defined in the index dashboard, but it will be undefined using this method.
*
* The complete list of parameters is
* available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters have their own API)
* @param {string} parameterName the parameter name
* @return {any} the parameter value
* @example
* var hitsPerPage = helper.getQueryParameter('hitsPerPage');
*/
AlgoliaSearchHelper.prototype.getQueryParameter = function(parameterName) {
return this.state.getQueryParameter(parameterName);
};
/**
* Get the list of refinements for a given attribute. This method works with
* conjunctive, disjunctive, excluding and numerical filters.
*
* See also SearchResults#getRefinements
*
* @param {string} facetName attribute name used for faceting
* @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and
* a type. Numeric also contains an operator.
* @example
* helper.addNumericRefinement('price', '>', 100);
* helper.getRefinements('price');
* // [
* // {
* // "value": [
* // 100
* // ],
* // "operator": ">",
* // "type": "numeric"
* // }
* // ]
* @example
* helper.addFacetRefinement('color', 'blue');
* helper.addFacetExclusion('color', 'red');
* helper.getRefinements('color');
* // [
* // {
* // "value": "blue",
* // "type": "conjunctive"
* // },
* // {
* // "value": "red",
* // "type": "exclude"
* // }
* // ]
* @example
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* // [
* // {
* // "value": "plastic",
* // "type": "disjunctive"
* // }
* // ]
*/
AlgoliaSearchHelper.prototype.getRefinements = function(facetName) {
var refinements = [];
if (this.state.isConjunctiveFacet(facetName)) {
var conjRefinements = this.state.getConjunctiveRefinements(facetName);
forEach_1(conjRefinements, function(r) {
refinements.push({
value: r,
type: 'conjunctive'
});
});
var excludeRefinements = this.state.getExcludeRefinements(facetName);
forEach_1(excludeRefinements, function(r) {
refinements.push({
value: r,
type: 'exclude'
});
});
} else if (this.state.isDisjunctiveFacet(facetName)) {
var disjRefinements = this.state.getDisjunctiveRefinements(facetName);
forEach_1(disjRefinements, function(r) {
refinements.push({
value: r,
type: 'disjunctive'
});
});
}
var numericRefinements = this.state.getNumericRefinements(facetName);
forEach_1(numericRefinements, function(value, operator) {
refinements.push({
value: value,
operator: operator,
type: 'numeric'
});
});
return refinements;
};
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute of the record
* @param {string} operator applied
* @return {number} value of the refinement
*/
AlgoliaSearchHelper.prototype.getNumericRefinement = function(attribute, operator) {
return this.state.getNumericRefinement(attribute, operator);
};
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function(facetName) {
return this.state.getHierarchicalFacetBreadcrumb(facetName);
};
// /////////// PRIVATE
/**
* Perform the underlying queries
* @private
* @return {undefined}
* @fires search
* @fires result
* @fires error
*/
AlgoliaSearchHelper.prototype._search = function() {
var state = this.state;
var mainQueries = requestBuilder_1._getQueries(state.index, state);
var states = [{
state: state,
queriesCount: mainQueries.length,
helper: this
}];
this.emit('search', state, this.lastResults);
var derivedQueries = map_1(this.derivedHelpers, function(derivedHelper) {
var derivedState = derivedHelper.getModifiedState(state);
var queries = requestBuilder_1._getQueries(derivedState.index, derivedState);
states.push({
state: derivedState,
queriesCount: queries.length,
helper: derivedHelper
});
derivedHelper.emit('search', derivedState, derivedHelper.lastResults);
return queries;
});
var queries = mainQueries.concat(flatten_1(derivedQueries));
var queryId = this._queryId++;
this._currentNbQueries++;
this.client.search(queries, this._dispatchAlgoliaResponse.bind(this, states, queryId));
};
/**
* Transform the responses as sent by the server and transform them into a user
* usable object that merge the results of all the batch requests. It will dispatch
* over the different helper + derived helpers (when there are some).
* @private
* @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>}
* state state used for to generate the request
* @param {number} queryId id of the current request
* @param {Error} err error if any, null otherwise
* @param {object} content content of the response
* @return {undefined}
*/
AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function(states, queryId, err, content) {
// FIXME remove the number of outdated queries discarded instead of just one
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._currentNbQueries -= (queryId - this._lastQueryIdReceived);
this._lastQueryIdReceived = queryId;
if (err) {
this.emit('error', err);
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
} else {
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
var results = content.results;
forEach_1(states, function(s) {
var state = s.state;
var queriesCount = s.queriesCount;
var helper = s.helper;
var specificResults = results.splice(0, queriesCount);
var formattedResponse = helper.lastResults = new SearchResults_1(state, specificResults);
helper.emit('result', formattedResponse, state);
});
}
};
AlgoliaSearchHelper.prototype.containsRefinement = function(query, facetFilters, numericFilters, tagFilters) {
return query ||
facetFilters.length !== 0 ||
numericFilters.length !== 0 ||
tagFilters.length !== 0;
};
/**
* Test if there are some disjunctive refinements on the facet
* @private
* @param {string} facet the attribute to test
* @return {boolean}
*/
AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function(facet) {
return this.state.disjunctiveRefinements[facet] &&
this.state.disjunctiveRefinements[facet].length > 0;
};
AlgoliaSearchHelper.prototype._change = function() {
this.emit('change', this.state, this.lastResults);
};
/**
* Clears the cache of the underlying Algolia client.
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.clearCache = function() {
this.client.clearCache();
return this;
};
/**
* Updates the internal client instance. If the reference of the clients
* are equal then no update is actually done.
* @param {AlgoliaSearch} newClient an AlgoliaSearch client
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.setClient = function(newClient) {
if (this.client === newClient) return this;
if (newClient.addAlgoliaAgent && !doesClientAgentContainsHelper(newClient)) newClient.addAlgoliaAgent('JS Helper ' + version$1);
this.client = newClient;
return this;
};
/**
* Gets the instance of the currently used client.
* @return {AlgoliaSearch}
*/
AlgoliaSearchHelper.prototype.getClient = function() {
return this.client;
};
/**
* Creates an derived instance of the Helper. A derived helper
* is a way to request other indices synchronised with the lifecycle
* of the main Helper. This mechanism uses the multiqueries feature
* of Algolia to aggregate all the requests in a single network call.
*
* This method takes a function that is used to create a new SearchParameter
* that will be used to create requests to Algolia. Those new requests
* are created just before the `search` event. The signature of the function
* is `SearchParameters -> SearchParameters`.
*
* This method returns a new DerivedHelper which is an EventEmitter
* that fires the same `search`, `result` and `error` events. Those
* events, however, will receive data specific to this DerivedHelper
* and the SearchParameters that is returned by the call of the
* parameter function.
* @param {function} fn SearchParameters -> SearchParameters
* @return {DerivedHelper}
*/
AlgoliaSearchHelper.prototype.derive = function(fn) {
var derivedHelper = new DerivedHelper_1(this, fn);
this.derivedHelpers.push(derivedHelper);
return derivedHelper;
};
/**
* This method detaches a derived Helper from the main one. Prefer using the one from the
* derived helper itself, to remove the event listeners too.
* @private
* @return {undefined}
* @throws Error
*/
AlgoliaSearchHelper.prototype.detachDerivedHelper = function(derivedHelper) {
var pos = this.derivedHelpers.indexOf(derivedHelper);
if (pos === -1) throw new Error('Derived helper already detached');
this.derivedHelpers.splice(pos, 1);
};
/**
* This method returns true if there is currently at least one on-going search.
* @return {boolean} true if there is a search pending
*/
AlgoliaSearchHelper.prototype.hasPendingRequests = function() {
return this._currentNbQueries > 0;
};
/**
* @typedef AlgoliaSearchHelper.NumericRefinement
* @type {object}
* @property {number[]} value the numbers that are used for filtering this attribute with
* the operator specified.
* @property {string} operator the faceting data: value, number of entries
* @property {string} type will be 'numeric'
*/
/**
* @typedef AlgoliaSearchHelper.FacetRefinement
* @type {object}
* @property {string} value the string use to filter the attribute
* @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude'
*/
/*
* This function tests if the _ua parameter of the client
* already contains the JS Helper UA
*/
function doesClientAgentContainsHelper(client) {
// this relies on JS Client internal variable, this might break if implementation changes
var currentAgent = client._ua;
return !currentAgent ? false :
currentAgent.indexOf('JS Helper') !== -1;
}
var algoliasearch_helper = AlgoliaSearchHelper;
/**
* The algoliasearchHelper module is the function that will let its
* contains everything needed to use the Algoliasearch
* Helper. It is a also a function that instanciate the helper.
* To use the helper, you also need the Algolia JS client v3.
* @example
* //using the UMD build
* var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
* var helper = algoliasearchHelper(client, 'bestbuy', {
* facets: ['shipping'],
* disjunctiveFacets: ['category']
* });
* helper.on('result', function(result) {
* console.log(result);
* });
* helper.toggleRefine('Movies & TV Shows')
* .toggleRefine('Free shipping')
* .search();
* @example
* // The helper is an event emitter using the node API
* helper.on('result', updateTheResults);
* helper.once('result', updateTheResults);
* helper.removeListener('result', updateTheResults);
* helper.removeAllListeners('result');
* @module algoliasearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the name of the index to query
* @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
* @return {AlgoliaSearchHelper}
*/
function algoliasearchHelper(client, index, opts) {
return new algoliasearch_helper(client, index, opts);
}
/**
* The version currently used
* @member module:algoliasearchHelper.version
* @type {number}
*/
algoliasearchHelper.version = version$1;
/**
* Constructor for the Helper.
* @member module:algoliasearchHelper.AlgoliaSearchHelper
* @type {AlgoliaSearchHelper}
*/
algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper;
/**
* Constructor for the object containing all the parameters of the search.
* @member module:algoliasearchHelper.SearchParameters
* @type {SearchParameters}
*/
algoliasearchHelper.SearchParameters = SearchParameters_1;
/**
* Constructor for the object containing the results of the search.
* @member module:algoliasearchHelper.SearchResults
* @type {SearchResults}
*/
algoliasearchHelper.SearchResults = SearchResults_1;
/**
* URL tools to generate query string and parse them from/into
* SearchParameters
* @member module:algoliasearchHelper.url
* @type {object} {@link url}
*
*/
algoliasearchHelper.url = url;
var algoliasearchHelper_1 = algoliasearchHelper;
var algoliasearchHelper_4 = algoliasearchHelper_1.SearchParameters;
// 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 getDisplayName(Component) {
return Component.displayName || Component.name || 'UnknownComponent';
}
var resolved = Promise.resolve();
var defer = function defer(f) {
resolved.then(f);
};
function removeEmptyKey(obj) {
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (isEmpty_1(value) && isPlainObject_1(value)) {
delete obj[key];
} else if (isPlainObject_1(value)) {
removeEmptyKey(value);
}
});
return obj;
}
function createWidgetsManager(onWidgetsUpdate) {
var widgets = [];
// Is an update scheduled?
var scheduled = false;
// The state manager's updates need to be batched since more than one
// component can register or unregister widgets during the same tick.
function scheduleUpdate() {
if (scheduled) {
return;
}
scheduled = true;
defer(function () {
scheduled = false;
onWidgetsUpdate();
});
}
return {
registerWidget: function registerWidget(widget) {
widgets.push(widget);
scheduleUpdate();
return function unregisterWidget() {
widgets.splice(widgets.indexOf(widget), 1);
scheduleUpdate();
};
},
update: scheduleUpdate,
getWidgets: function getWidgets() {
return widgets;
}
};
}
function createStore(initialState) {
var state = initialState;
var listeners = [];
function dispatch() {
listeners.forEach(function (listener) {
return listener();
});
}
return {
getState: function getState() {
return state;
},
setState: function setState(nextState) {
state = nextState;
dispatch();
},
subscribe: function subscribe(listener) {
listeners.push(listener);
return function unsubcribe() {
listeners.splice(listeners.indexOf(listener), 1);
};
}
};
}
var highlightTags = {
highlightPreTag: "<ais-highlight-0000000000>",
highlightPostTag: "</ais-highlight-0000000000>"
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty$1 = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
/**
* Creates a new instance of the InstantSearchManager which controls the widgets and
* trigger the search when the widgets are updated.
* @param {string} indexName - the main index name
* @param {object} initialState - initial widget state
* @param {object} SearchParameters - optional additional parameters to send to the algolia API
* @param {number} stalledSearchDelay - time (in ms) after the search is stalled
* @return {InstantSearchManager} a new instance of InstantSearchManager
*/
function createInstantSearchManager(_ref) {
var indexName = _ref.indexName,
_ref$initialState = _ref.initialState,
initialState = _ref$initialState === undefined ? {} : _ref$initialState,
algoliaClient = _ref.algoliaClient,
resultsState = _ref.resultsState,
stalledSearchDelay = _ref.stalledSearchDelay;
var baseSP = new algoliasearchHelper_4(_extends({
index: indexName
}, highlightTags));
var stalledSearchTimer = null;
var helper = algoliasearchHelper_1(algoliaClient, indexName, baseSP);
helper.on('result', handleSearchSuccess);
helper.on('error', handleSearchError);
helper.on('search', handleNewSearch);
var derivedHelpers = {};
var indexMapping = {}; // keep track of the original index where the parameters applied when sortBy is used.
var initialSearchParameters = helper.state;
var widgetsManager = createWidgetsManager(onWidgetsUpdate);
var store = createStore({
widgets: initialState,
metadata: [],
results: resultsState || null,
error: null,
searching: false,
isSearchStalled: true,
searchingForFacetValues: false
});
var skip = false;
function skipSearch() {
skip = true;
}
function updateClient(client) {
helper.setClient(client);
search();
}
function clearCache() {
helper.clearCache();
search();
}
function getMetadata(state) {
return widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getMetadata);
}).map(function (widget) {
return widget.getMetadata(state);
});
}
function getSearchParameters() {
indexMapping = {};
var sharedParameters = widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).filter(function (widget) {
return !widget.context.multiIndexContext && (widget.props.indexName === indexName || !widget.props.indexName);
}).reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, initialSearchParameters);
indexMapping[sharedParameters.index] = indexName;
var derivatedWidgets = widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).filter(function (widget) {
return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex !== indexName || widget.props.indexName && widget.props.indexName !== indexName;
}).reduce(function (indices, widget) {
var targetedIndex = widget.context.multiIndexContext ? widget.context.multiIndexContext.targetedIndex : widget.props.indexName;
var index = indices.find(function (i) {
return i.targetedIndex === targetedIndex;
});
if (index) {
index.widgets.push(widget);
} else {
indices.push({ targetedIndex: targetedIndex, widgets: [widget] });
}
return indices;
}, []);
var mainIndexParameters = widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.getSearchParameters);
}).filter(function (widget) {
return widget.context.multiIndexContext && widget.context.multiIndexContext.targetedIndex === indexName || widget.props.indexName && widget.props.indexName === indexName;
}).reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, sharedParameters);
indexMapping[mainIndexParameters.index] = indexName;
return { sharedParameters: sharedParameters, mainIndexParameters: mainIndexParameters, derivatedWidgets: derivatedWidgets };
}
function search() {
if (!skip) {
var _getSearchParameters = getSearchParameters(helper.state),
sharedParameters = _getSearchParameters.sharedParameters,
mainIndexParameters = _getSearchParameters.mainIndexParameters,
derivatedWidgets = _getSearchParameters.derivatedWidgets;
Object.keys(derivedHelpers).forEach(function (key) {
return derivedHelpers[key].detach();
});
derivedHelpers = {};
helper.setState(sharedParameters);
derivatedWidgets.forEach(function (derivatedSearchParameters) {
var index = derivatedSearchParameters.targetedIndex;
var derivedHelper = helper.derive(function () {
var parameters = derivatedSearchParameters.widgets.reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, sharedParameters);
indexMapping[parameters.index] = index;
return parameters;
});
derivedHelper.on('result', handleSearchSuccess);
derivedHelper.on('error', handleSearchError);
derivedHelpers[index] = derivedHelper;
});
helper.setState(mainIndexParameters);
helper.search();
}
}
function handleSearchSuccess(content) {
var state = store.getState();
var results = state.results ? state.results : {};
/* if switching from mono index to multi index and vice versa,
results needs to reset to {}*/
results = !isEmpty_1(derivedHelpers) && results.getFacetByName ? {} : results;
if (!isEmpty_1(derivedHelpers)) {
results[indexMapping[content.index]] = content;
} else {
results = content;
}
var currentState = store.getState();
var nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
stalledSearchTimer = null;
nextIsSearchStalled = false;
}
var nextState = omit_1(_extends({}, currentState, {
results: results,
isSearchStalled: nextIsSearchStalled,
searching: false,
error: null
}), 'resultsFacetValues');
store.setState(nextState);
}
function handleSearchError(error) {
var currentState = store.getState();
var nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
nextIsSearchStalled = false;
}
var nextState = omit_1(_extends({}, currentState, {
isSearchStalled: nextIsSearchStalled,
error: error,
searching: false
}), 'resultsFacetValues');
store.setState(nextState);
}
function handleNewSearch() {
if (!stalledSearchTimer) {
stalledSearchTimer = setTimeout(function () {
var nextState = omit_1(_extends({}, store.getState(), {
isSearchStalled: true
}), 'resultsFacetValues');
store.setState(nextState);
}, stalledSearchDelay);
}
}
// Called whenever a widget has been rendered with new props.
function onWidgetsUpdate() {
var metadata = getMetadata(store.getState().widgets);
store.setState(_extends({}, store.getState(), {
metadata: metadata,
searching: true
}));
// Since the `getSearchParameters` method of widgets also depends on props,
// the result search parameters might have changed.
search();
}
function transitionState(nextSearchState) {
var searchState = store.getState().widgets;
return widgetsManager.getWidgets().filter(function (widget) {
return Boolean(widget.transitionState);
}).reduce(function (res, widget) {
return widget.transitionState(searchState, res);
}, nextSearchState);
}
function onExternalStateUpdate(nextSearchState) {
var metadata = getMetadata(nextSearchState);
store.setState(_extends({}, store.getState(), {
widgets: nextSearchState,
metadata: metadata,
searching: true
}));
search();
}
function onSearchForFacetValues(_ref2) {
var facetName = _ref2.facetName,
query = _ref2.query,
maxFacetHits = _ref2.maxFacetHits;
store.setState(_extends({}, store.getState(), {
searchingForFacetValues: true
}));
helper.searchForFacetValues(facetName, query, maxFacetHits).then(function (content) {
var _babelHelpers$extends;
store.setState(_extends({}, store.getState(), {
resultsFacetValues: _extends({}, store.getState().resultsFacetValues, (_babelHelpers$extends = {}, defineProperty$1(_babelHelpers$extends, facetName, content.facetHits), defineProperty$1(_babelHelpers$extends, 'query', query), _babelHelpers$extends)),
searchingForFacetValues: false
}));
}, function (error) {
store.setState(_extends({}, store.getState(), {
error: error,
searchingForFacetValues: false
}));
}).catch(function (error) {
// Since setState is synchronous, any error that occurs in the render of a
// component will be swallowed by this promise.
// This is a trick to make the error show up correctly in the console.
// See http://stackoverflow.com/a/30741722/969302
setTimeout(function () {
throw error;
});
});
}
function updateIndex(newIndex) {
initialSearchParameters = initialSearchParameters.setIndex(newIndex);
search();
}
function getWidgetsIds() {
return store.getState().metadata.reduce(function (res, meta) {
return typeof meta.id !== 'undefined' ? res.concat(meta.id) : res;
}, []);
}
return {
store: store,
widgetsManager: widgetsManager,
getWidgetsIds: getWidgetsIds,
onExternalStateUpdate: onExternalStateUpdate,
transitionState: transitionState,
onSearchForFacetValues: onSearchForFacetValues,
updateClient: updateClient,
updateIndex: updateIndex,
clearCache: clearCache,
skipSearch: skipSearch
};
}
function validateNextProps(props, nextProps) {
if (!props.searchState && nextProps.searchState) {
throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled");
} else if (props.searchState && !nextProps.searchState) {
throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled");
}
}
/* eslint valid-jsdoc: 0 */
/**
* @description
* `<InstantSearch>` is the root component of all React InstantSearch implementations.
* It provides all the connected components (aka widgets) a means to interact
* with the searchState.
* @kind widget
* @name <InstantSearch>
* @requirements You will need to have an Algolia account to be able to use this widget.
* [Create one now](https://www.algolia.com/users/sign_up).
* @propType {string} appId - Your Algolia application id.
* @propType {string} apiKey - Your Algolia search-only API key.
* @propType {string} indexName - Main index in which to search.
* @propType {boolean} [refresh=false] - Flag to activate when the cache needs to be cleared so that the front-end is updated when a change occurs in the index.
* @propType {object} [algoliaClient] - Provide a custom Algolia client instead of the internal one.
* @propType {func} [onSearchStateChange] - Function to be called everytime a new search is done. Useful for [URL Routing](guide/Routing.html).
* @propType {object} [searchState] - Object to inject some search state. Switches the InstantSearch component in controlled mode. Useful for [URL Routing](guide/Routing.html).
* @propType {func} [createURL] - Function to call when creating links, useful for [URL Routing](guide/Routing.html).
* @propType {SearchResults|SearchResults[]} [resultsState] - Use this to inject the results that will be used at first rendering. Those results are found by using the `findResultsState` function. Useful for [Server Side Rendering](guide/Server-side_rendering.html).
* @propType {number} [stalledSearchDelay=200] - The amount of time before considering that the search takes too much time. The time is expressed in milliseconds.
* @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }`
* @example
* import React from 'react';
* import { InstantSearch, SearchBox, Hits } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SearchBox />
* <Hits />
* </InstantSearch>
* );
*/
var InstantSearch = function (_Component) {
inherits(InstantSearch, _Component);
function InstantSearch(props) {
classCallCheck(this, InstantSearch);
var _this = possibleConstructorReturn(this, (InstantSearch.__proto__ || Object.getPrototypeOf(InstantSearch)).call(this, props));
_this.isControlled = Boolean(props.searchState);
var initialState = _this.isControlled ? props.searchState : {};
_this.isUnmounting = false;
_this.aisManager = createInstantSearchManager({
indexName: props.indexName,
algoliaClient: props.algoliaClient,
initialState: initialState,
resultsState: props.resultsState,
stalledSearchDelay: props.stalledSearchDelay
});
return _this;
}
createClass(InstantSearch, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
validateNextProps(this.props, nextProps);
if (this.props.indexName !== nextProps.indexName) {
this.aisManager.updateIndex(nextProps.indexName);
}
if (this.props.refresh !== nextProps.refresh) {
if (nextProps.refresh) {
this.aisManager.clearCache();
}
}
if (this.props.algoliaClient !== nextProps.algoliaClient) {
this.aisManager.updateClient(nextProps.algoliaClient);
}
if (this.isControlled) {
this.aisManager.onExternalStateUpdate(nextProps.searchState);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.isUnmounting = true;
this.aisManager.skipSearch();
}
}, {
key: 'getChildContext',
value: function getChildContext() {
// If not already cached, cache the bound methods so that we can forward them as part
// of the context.
if (!this._aisContextCache) {
this._aisContextCache = {
ais: {
onInternalStateUpdate: this.onWidgetsInternalStateUpdate.bind(this),
createHrefForState: this.createHrefForState.bind(this),
onSearchForFacetValues: this.onSearchForFacetValues.bind(this),
onSearchStateChange: this.onSearchStateChange.bind(this),
onSearchParameters: this.onSearchParameters.bind(this)
}
};
}
return {
ais: _extends({}, this._aisContextCache.ais, {
store: this.aisManager.store,
widgetsManager: this.aisManager.widgetsManager,
mainTargetedIndex: this.props.indexName
})
};
}
}, {
key: 'createHrefForState',
value: function createHrefForState(searchState) {
searchState = this.aisManager.transitionState(searchState);
return this.isControlled && this.props.createURL ? this.props.createURL(searchState, this.getKnownKeys()) : '#';
}
}, {
key: 'onWidgetsInternalStateUpdate',
value: function onWidgetsInternalStateUpdate(searchState) {
searchState = this.aisManager.transitionState(searchState);
this.onSearchStateChange(searchState);
if (!this.isControlled) {
this.aisManager.onExternalStateUpdate(searchState);
}
}
}, {
key: 'onSearchStateChange',
value: function onSearchStateChange(searchState) {
if (this.props.onSearchStateChange && !this.isUnmounting) {
this.props.onSearchStateChange(searchState);
}
}
}, {
key: 'onSearchParameters',
value: function onSearchParameters(getSearchParameters, context, props) {
if (this.props.onSearchParameters) {
var searchState = this.props.searchState ? this.props.searchState : {};
this.props.onSearchParameters(getSearchParameters, context, props, searchState);
}
}
}, {
key: 'onSearchForFacetValues',
value: function onSearchForFacetValues(searchState) {
this.aisManager.onSearchForFacetValues(searchState);
}
}, {
key: 'getKnownKeys',
value: function getKnownKeys() {
return this.aisManager.getWidgetsIds();
}
}, {
key: 'render',
value: function render() {
var childrenCount = React.Children.count(this.props.children);
var _props$root = this.props.root,
Root = _props$root.Root,
props = _props$root.props;
if (childrenCount === 0) return null;else return React__default.createElement(
Root,
props,
this.props.children
);
}
}]);
return InstantSearch;
}(React.Component);
InstantSearch.defaultProps = {
stalledSearchDelay: 200
};
InstantSearch.propTypes = {
// @TODO: These props are currently constant.
indexName: propTypes.string.isRequired,
algoliaClient: propTypes.object.isRequired,
createURL: propTypes.func,
refresh: propTypes.bool.isRequired,
searchState: propTypes.object,
onSearchStateChange: propTypes.func,
onSearchParameters: propTypes.func,
resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]),
children: propTypes.node,
root: propTypes.shape({
Root: propTypes.oneOfType([propTypes.string, propTypes.func]),
props: propTypes.object
}).isRequired,
stalledSearchDelay: propTypes.number
};
InstantSearch.childContextTypes = {
// @TODO: more precise widgets manager propType
ais: propTypes.object.isRequired
};
var _name$version$descrip = {
name: 'react-instantsearch',
version: '5.0.1',
description: '\u26A1 Lightning-fast search for React and React Native apps, by Algolia',
keywords: ['algolia', 'components', 'fast', 'instantsearch', 'react', 'react-native', 'search'],
homepage: 'https://community.algolia.com/react-instantsearch',
license: 'MIT',
author: {
name: 'Algolia, Inc.',
url: 'https://www.algolia.com'
},
main: 'index.js',
module: 'es/index.js',
repository: {
type: 'git',
url: 'https://github.com/algolia/react-instantsearch'
},
scripts: {
build: './scripts/build.sh',
'build-and-publish': './scripts/build-and-publish.sh'
},
dependencies: {
algoliasearch: '^3.24.0',
'algoliasearch-helper': '^2.21.0',
classnames: '^2.2.5',
lodash: '^4.17.4',
'prop-types': '^15.5.10'
},
devDependencies: {
enzyme: '3.3.0',
'enzyme-adapter-react-16': '1.1.1',
react: '16.2.0',
'react-dom': '16.2.0',
'react-native': '0.54.1',
'react-test-renderer': '16.2.0'
}
},
version$2 = _name$version$descrip.version;
/**
* Creates a specialized root InstantSearch component. It accepts
* an algolia client and a specification of the root Element.
* @param {function} defaultAlgoliaClient - a function that builds an Algolia client
* @param {object} root - the defininition of the root of an InstantSearch sub tree.
* @returns {object} an InstantSearch root
*/
function createInstantSearch(defaultAlgoliaClient, root) {
var _class, _temp;
return _temp = _class = function (_Component) {
inherits(CreateInstantSearch, _Component);
function CreateInstantSearch() {
var _ref;
classCallCheck(this, CreateInstantSearch);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var _this = possibleConstructorReturn(this, (_ref = CreateInstantSearch.__proto__ || Object.getPrototypeOf(CreateInstantSearch)).call.apply(_ref, [this].concat(args)));
_this.client = _this.props.algoliaClient || defaultAlgoliaClient(_this.props.appId, _this.props.apiKey);
_this.client.addAlgoliaAgent('react-instantsearch ' + version$2);
return _this;
}
createClass(CreateInstantSearch, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var props = this.props;
if (nextProps.algoliaClient) {
this.client = nextProps.algoliaClient;
} else if (props.appId !== nextProps.appId || props.apiKey !== nextProps.apiKey) {
this.client = defaultAlgoliaClient(nextProps.appId, nextProps.apiKey);
}
this.client.addAlgoliaAgent('react-instantsearch ' + version$2);
}
}, {
key: 'render',
value: function render() {
return React__default.createElement(
InstantSearch,
{
createURL: this.props.createURL,
indexName: this.props.indexName,
searchState: this.props.searchState,
onSearchStateChange: this.props.onSearchStateChange,
onSearchParameters: this.props.onSearchParameters,
root: this.props.root,
algoliaClient: this.client,
refresh: this.props.refresh,
resultsState: this.props.resultsState
},
this.props.children
);
}
}]);
return CreateInstantSearch;
}(React.Component), _class.propTypes = {
algoliaClient: propTypes.object,
appId: propTypes.string,
apiKey: propTypes.string,
children: propTypes.oneOfType([propTypes.arrayOf(propTypes.node), propTypes.node]),
indexName: propTypes.string.isRequired,
createURL: propTypes.func,
searchState: propTypes.object,
refresh: propTypes.bool.isRequired,
onSearchStateChange: propTypes.func,
onSearchParameters: propTypes.func,
resultsState: propTypes.oneOfType([propTypes.object, propTypes.array]),
root: propTypes.shape({
Root: propTypes.oneOfType([propTypes.string, propTypes.func]).isRequired,
props: propTypes.object
})
}, _class.defaultProps = {
refresh: false,
root: root
}, _temp;
}
/* eslint valid-jsdoc: 0 */
/**
* @description
* `<Index>` is the component that allows you to apply widgets to a dedicated index. It's
* useful if you want to build an interface that targets multiple indices.
* @kind widget
* @name <Index>
* @propType {string} indexName - index in which to search.
* @propType {{ Root: string|function, props: object }} [root] - Use this to customize the root element. Default value: `{ Root: 'div' }`
* @example
* import React from 'react';
* import { InstantSearch, Index, SearchBox, Hits, Configure } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Configure hitsPerPage={5} />
* <SearchBox />
* <Index indexName="ikea">
* <Hits />
* </Index>
* <Index indexName="bestbuy">
* <Hits />
* </Index>
* </InstantSearch>
* );
*/
var Index = function (_Component) {
inherits(Index, _Component);
function Index(props, context) {
classCallCheck(this, Index);
var _this = possibleConstructorReturn(this, (Index.__proto__ || Object.getPrototypeOf(Index)).call(this, props));
var widgetsManager = context.ais.widgetsManager;
/*
we want <Index> to be seen as a regular widget.
It means that with only <Index> present a new query will be sent to Algolia.
That way you don't need a virtual hits widget to use the connectAutoComplete.
*/
_this.unregisterWidget = widgetsManager.registerWidget(_this);
return _this;
}
createClass(Index, [{
key: 'componentWillMount',
value: function componentWillMount() {
this.context.ais.onSearchParameters(this.getSearchParameters, this.getChildContext(), this.props);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.props.indexName !== nextProps.indexName) {
this.context.ais.widgetsManager.update();
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.unregisterWidget();
}
}, {
key: 'getChildContext',
value: function getChildContext() {
return {
multiIndexContext: {
targetedIndex: this.props.indexName
}
};
}
}, {
key: 'getSearchParameters',
value: function getSearchParameters(searchParameters, props) {
return searchParameters.setIndex(this.props ? this.props.indexName : props.indexName);
}
}, {
key: 'render',
value: function render() {
var childrenCount = React.Children.count(this.props.children);
var _props$root = this.props.root,
Root = _props$root.Root,
props = _props$root.props;
if (childrenCount === 0) return null;else return React__default.createElement(
Root,
props,
this.props.children
);
}
}]);
return Index;
}(React.Component);
Index.propTypes = {
// @TODO: These props are currently constant.
indexName: propTypes.string.isRequired,
children: propTypes.node,
root: propTypes.shape({
Root: propTypes.oneOfType([propTypes.string, propTypes.func]),
props: propTypes.object
}).isRequired
};
Index.childContextTypes = {
multiIndexContext: propTypes.object.isRequired
};
Index.contextTypes = {
// @TODO: more precise widgets manager propType
ais: propTypes.object.isRequired
};
/**
* Creates a specialized root Index component. It accepts
* a specification of the root Element.
* @param {object} defaultRoot - the defininition of the root of an Index sub tree.
* @return {object} a Index root
*/
var createIndex = function createIndex(defaultRoot) {
var CreateIndex = function CreateIndex(_ref) {
var indexName = _ref.indexName,
root = _ref.root,
children = _ref.children;
return React__default.createElement(
Index,
{ indexName: indexName, root: root },
children
);
};
CreateIndex.propTypes = {
indexName: propTypes.string.isRequired,
root: propTypes.shape({
Root: propTypes.oneOfType([propTypes.string, propTypes.func]).isRequired,
props: propTypes.object
}),
children: propTypes.node
};
CreateIndex.defaultProps = {
root: defaultRoot
};
return CreateIndex;
};
var inherits_browser$1 = createCommonjsModule(function (module) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
};
}
});
var hasOwn = Object.prototype.hasOwnProperty;
var toString$1 = Object.prototype.toString;
var foreach = function forEach (obj, fn, ctx) {
if (toString$1.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
// This file hosts our error definitions
// We use custom error "types" so that we can act on them when we need it
// e.g.: if error instanceof errors.UnparsableJSON then..
function AlgoliaSearchError(message, extraProperties) {
var forEach = foreach;
var error = this;
// try to get a stacktrace
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
error.stack = (new Error()).stack || 'Cannot get a stacktrace, browser is too old';
}
this.name = 'AlgoliaSearchError';
this.message = message || 'Unknown error';
if (extraProperties) {
forEach(extraProperties, function addToErrorObject(value, key) {
error[key] = value;
});
}
}
inherits_browser$1(AlgoliaSearchError, Error);
function createCustomError(name, message) {
function AlgoliaSearchCustomError() {
var args = Array.prototype.slice.call(arguments, 0);
// custom message not set, use default
if (typeof args[0] !== 'string') {
args.unshift(message);
}
AlgoliaSearchError.apply(this, args);
this.name = 'AlgoliaSearch' + name + 'Error';
}
inherits_browser$1(AlgoliaSearchCustomError, AlgoliaSearchError);
return AlgoliaSearchCustomError;
}
// late exports to let various fn defs and inherits take place
var errors = {
AlgoliaSearchError: AlgoliaSearchError,
UnparsableJSON: createCustomError(
'UnparsableJSON',
'Could not parse the incoming response as JSON, see err.more for details'
),
RequestTimeout: createCustomError(
'RequestTimeout',
'Request timedout before getting a response'
),
Network: createCustomError(
'Network',
'Network issue, see err.more for details'
),
JSONPScriptFail: createCustomError(
'JSONPScriptFail',
'<script> was loaded but did not call our provided callback'
),
JSONPScriptError: createCustomError(
'JSONPScriptError',
'<script> unable to load due to an `error` event on it'
),
Unknown: createCustomError(
'Unknown',
'Unknown error occured'
)
};
// Parse cloud does not supports setTimeout
// We do not store a setTimeout reference in the client everytime
// We only fallback to a fake setTimeout when not available
// setTimeout cannot be override globally sadly
var exitPromise = function exitPromise(fn, _setTimeout) {
_setTimeout(fn, 0);
};
var buildSearchMethod_1 = buildSearchMethod;
/**
* Creates a search method to be used in clients
* @param {string} queryParam the name of the attribute used for the query
* @param {string} url the url
* @return {function} the search method
*/
function buildSearchMethod(queryParam, url) {
/**
* The search method. Prepares the data and send the query to Algolia.
* @param {string} query the string used for query search
* @param {object} args additional parameters to send with the search
* @param {function} [callback] the callback to be called with the client gets the answer
* @return {undefined|Promise} If the callback is not provided then this methods returns a Promise
*/
return function search(query, args, callback) {
// warn V2 users on how to search
if (typeof query === 'function' && typeof args === 'object' ||
typeof callback === 'object') {
// .search(query, params, cb)
// .search(cb, params)
throw new errors.AlgoliaSearchError('index.search usage is index.search(query, params, cb)');
}
// Normalizing the function signature
if (arguments.length === 0 || typeof query === 'function') {
// Usage : .search(), .search(cb)
callback = query;
query = '';
} else if (arguments.length === 1 || typeof args === 'function') {
// Usage : .search(query/args), .search(query, cb)
callback = args;
args = undefined;
}
// At this point we have 3 arguments with values
// Usage : .search(args) // careful: typeof null === 'object'
if (typeof query === 'object' && query !== null) {
args = query;
query = undefined;
} else if (query === undefined || query === null) { // .search(undefined/null)
query = '';
}
var params = '';
if (query !== undefined) {
params += queryParam + '=' + encodeURIComponent(query);
}
var additionalUA;
if (args !== undefined) {
if (args.additionalUA) {
additionalUA = args.additionalUA;
delete args.additionalUA;
}
// `_getSearchParams` will augment params, do not be fooled by the = versus += from previous if
params = this.as._getSearchParams(args, params);
}
return this._search(params, url, callback, additionalUA);
};
}
var deprecate = function deprecate(fn, message) {
var warned = false;
function deprecated() {
if (!warned) {
/* eslint no-console:0 */
console.warn(message);
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var deprecatedMessage = function deprecatedMessage(previousUsage, newUsage) {
var githubAnchorLink = previousUsage.toLowerCase()
.replace(/[\.\(\)]/g, '');
return 'algoliasearch: `' + previousUsage + '` was replaced by `' + newUsage +
'`. Please see https://github.com/algolia/algoliasearch-client-javascript/wiki/Deprecated#' + githubAnchorLink;
};
var merge$1 = function merge(destination/* , sources */) {
var sources = Array.prototype.slice.call(arguments);
foreach(sources, function(source) {
for (var keyName in source) {
if (source.hasOwnProperty(keyName)) {
if (typeof destination[keyName] === 'object' && typeof source[keyName] === 'object') {
destination[keyName] = merge({}, destination[keyName], source[keyName]);
} else if (source[keyName] !== undefined) {
destination[keyName] = source[keyName];
}
}
}
});
return destination;
};
var clone = function clone(obj) {
return JSON.parse(JSON.stringify(obj));
};
var toStr = Object.prototype.toString;
var isArguments$1 = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
// modified from https://github.com/es-shims/es5-shim
var has$1 = Object.prototype.hasOwnProperty;
var toStr$1 = Object.prototype.toString;
var slice = Array.prototype.slice;
var isEnumerable = Object.prototype.propertyIsEnumerable;
var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var excludedKeys = {
$console: true,
$external: true,
$frame: true,
$frameElement: true,
$frames: true,
$innerHeight: true,
$innerWidth: true,
$outerHeight: true,
$outerWidth: true,
$pageXOffset: true,
$pageYOffset: true,
$parent: true,
$scrollLeft: true,
$scrollTop: true,
$scrollX: true,
$scrollY: true,
$self: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true,
$window: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!excludedKeys['$' + k] && has$1.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr$1.call(object) === '[object Function]';
var isArguments = isArguments$1(object);
var isString = isObject && toStr$1.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has$1.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has$1.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has$1.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArguments$1(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
var objectKeys = keysShim;
var omit$1 = function omit(obj, test) {
var keys = objectKeys;
var foreach$$1 = foreach;
var filtered = {};
foreach$$1(keys(obj), function doFilter(keyName) {
if (test(keyName) !== true) {
filtered[keyName] = obj[keyName];
}
});
return filtered;
};
var toString$2 = {}.toString;
var isarray = Array.isArray || function (arr) {
return toString$2.call(arr) == '[object Array]';
};
var map$1 = function map(arr, fn) {
var newArr = [];
foreach(arr, function(item, itemIndex) {
newArr.push(fn(item, itemIndex, arr));
});
return newArr;
};
var IndexCore_1 = IndexCore;
/*
* Index class constructor.
* You should not use this method directly but use initIndex() function
*/
function IndexCore(algoliasearch, indexName) {
this.indexName = indexName;
this.as = algoliasearch;
this.typeAheadArgs = null;
this.typeAheadValueOption = null;
// make sure every index instance has it's own cache
this.cache = {};
}
/*
* Clear all queries in cache
*/
IndexCore.prototype.clearCache = function() {
this.cache = {};
};
/*
* Search inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the full text query
* @param {object} [args] (optional) if set, contains an object with query parameters:
* - page: (integer) Pagination parameter used to select the page to retrieve.
* Page is zero-based and defaults to 0. Thus,
* to retrieve the 10th page you need to set page=9
* - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20.
* - attributesToRetrieve: a string that contains the list of object attributes
* you want to retrieve (let you minimize the answer size).
* Attributes are separated with a comma (for example "name,address").
* You can also use an array (for example ["name","address"]).
* By default, all attributes are retrieved. You can also use '*' to retrieve all
* values when an attributesToRetrieve setting is specified for your index.
* - attributesToHighlight: a string that contains the list of attributes you
* want to highlight according to the query.
* Attributes are separated by a comma. You can also use an array (for example ["name","address"]).
* If an attribute has no match for the query, the raw value is returned.
* By default all indexed text attributes are highlighted.
* You can use `*` if you want to highlight all textual attributes.
* Numerical attributes are not highlighted.
* A matchLevel is returned for each highlighted attribute and can contain:
* - full: if all the query terms were found in the attribute,
* - partial: if only some of the query terms were found,
* - none: if none of the query terms were found.
* - attributesToSnippet: a string that contains the list of attributes to snippet alongside
* the number of words to return (syntax is `attributeName:nbWords`).
* Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10).
* You can also use an array (Example: attributesToSnippet: ['name:10','content:10']).
* By default no snippet is computed.
* - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word.
* Defaults to 3.
* - minWordSizefor2Typos: the minimum number of characters in a query word
* to accept two typos in this word. Defaults to 7.
* - getRankingInfo: if set to 1, the result hits will contain ranking
* information in _rankingInfo attribute.
* - aroundLatLng: search for entries around a given
* latitude/longitude (specified as two floats separated by a comma).
* For example aroundLatLng=47.316669,5.016670).
* You can specify the maximum distance in meters with the aroundRadius parameter (in meters)
* and the precision for ranking with aroundPrecision
* (for example if you set aroundPrecision=100, two objects that are distant of
* less than 100m will be considered as identical for "geo" ranking parameter).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - insideBoundingBox: search entries inside a given area defined by the two extreme points
* of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng).
* For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201).
* At indexing, you should specify geoloc of an object with the _geoloc attribute
* (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}})
* - numericFilters: a string that contains the list of numeric filters you want to
* apply separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value`.
* Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000.
* You can also use an array (for example numericFilters: ["price>100","price<1000"]).
* - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas.
* To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* You can also use an array, for example tagFilters: ["tag1",["tag2","tag3"]]
* means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags** attribute
* of objects (for example {"_tags":["tag1","tag2"]}).
* - facetFilters: filter the query by a list of facets.
* Facets are separated by commas and each facet is encoded as `attributeName:value`.
* For example: `facetFilters=category:Book,author:John%20Doe`.
* You can also use an array (for example `["category:Book","author:John%20Doe"]`).
* - facets: List of object attributes that you want to use for faceting.
* Comma separated list: `"category,author"` or array `['category','author']`
* Only attributes that have been added in **attributesForFaceting** index setting
* can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
* - queryType: select how the query words are interpreted, it can be one of the following value:
* - prefixAll: all query words are interpreted as prefixes,
* - prefixLast: only the last word is interpreted as a prefix (default behavior),
* - prefixNone: no query word is interpreted as a prefix. This option is not recommended.
* - optionalWords: a string that contains the list of words that should
* be considered as optional when found in the query.
* Comma separated and array are accepted.
* - distinct: If set to 1, enable the distinct feature (disabled by default)
* if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled
* in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have
* the same value for show_name, then only the best
* one is kept and others are removed.
* - restrictSearchableAttributes: List of attributes you want to use for
* textual search (must be a subset of the attributesToIndex index setting)
* either comma separated or as an array
* @param {function} [callback] the result callback called with two arguments:
* error: null or Error('message'). If false, the content contains the error.
* content: the server answer that contains the list of results.
*/
IndexCore.prototype.search = buildSearchMethod_1('query');
/*
* -- BETA --
* Search a record similar to the query inside the index using XMLHttpRequest request (Using a POST query to
* minimize number of OPTIONS queries: Cross-Origin Resource Sharing).
*
* @param {string} [query] the similar query
* @param {object} [args] (optional) if set, contains an object with query parameters.
* All search parameters are supported (see search function), restrictSearchableAttributes and facetFilters
* are the two most useful to restrict the similar results and get more relevant content
*/
IndexCore.prototype.similarSearch = buildSearchMethod_1('similarQuery');
/*
* Browse index content. The response content will have a `cursor` property that you can use
* to browse subsequent pages for this query. Use `index.browseFrom(cursor)` when you want.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browse('cool songs', {
* tagFilters: 'public,comments',
* hitsPerPage: 500
* }, callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browse = function(query, queryParameters, callback) {
var merge = merge$1;
var indexObj = this;
var page;
var hitsPerPage;
// we check variadic calls that are not the one defined
// .browse()/.browse(fn)
// => page = 0
if (arguments.length === 0 || arguments.length === 1 && typeof arguments[0] === 'function') {
page = 0;
callback = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'number') {
// .browse(2)/.browse(2, 10)/.browse(2, fn)/.browse(2, 10, fn)
page = arguments[0];
if (typeof arguments[1] === 'number') {
hitsPerPage = arguments[1];
} else if (typeof arguments[1] === 'function') {
callback = arguments[1];
hitsPerPage = undefined;
}
query = undefined;
queryParameters = undefined;
} else if (typeof arguments[0] === 'object') {
// .browse(queryParameters)/.browse(queryParameters, cb)
if (typeof arguments[1] === 'function') {
callback = arguments[1];
}
queryParameters = arguments[0];
query = undefined;
} else if (typeof arguments[0] === 'string' && typeof arguments[1] === 'function') {
// .browse(query, cb)
callback = arguments[1];
queryParameters = undefined;
}
// otherwise it's a .browse(query)/.browse(query, queryParameters)/.browse(query, queryParameters, cb)
// get search query parameters combining various possible calls
// to .browse();
queryParameters = merge({}, queryParameters || {}, {
page: page,
hitsPerPage: hitsPerPage,
query: query
});
var params = this.as._getSearchParams(queryParameters, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/browse',
body: {params: params},
hostType: 'read',
callback: callback
});
};
/*
* Continue browsing from a previous position (cursor), obtained via a call to `.browse()`.
*
* @param {string} query - The full text query
* @param {Object} [queryParameters] - Any search query parameter
* @param {Function} [callback] - The result callback called with two arguments
* error: null or Error('message')
* content: the server answer with the browse result
* @return {Promise|undefined} Returns a promise if no callback given
* @example
* index.browseFrom('14lkfsakl32', callback);
* @see {@link https://www.algolia.com/doc/rest_api#Browse|Algolia REST API Documentation}
*/
IndexCore.prototype.browseFrom = function(cursor, callback) {
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' + encodeURIComponent(this.indexName) + '/browse',
body: {cursor: cursor},
hostType: 'read',
callback: callback
});
};
/*
* Search for facet values
* https://www.algolia.com/doc/rest-api/search#search-for-facet-values
*
* @param {string} params.facetName Facet name, name of the attribute to search for values in.
* Must be declared as a facet
* @param {string} params.facetQuery Query for the facet search
* @param {string} [params.*] Any search parameter of Algolia,
* see https://www.algolia.com/doc/api-client/javascript/search#search-parameters
* Pagination is not supported. The page and hitsPerPage parameters will be ignored.
* @param callback (optional)
*/
IndexCore.prototype.searchForFacetValues = function(params, callback) {
var clone$$1 = clone;
var omit = omit$1;
var usage = 'Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])';
if (params.facetName === undefined || params.facetQuery === undefined) {
throw new Error(usage);
}
var facetName = params.facetName;
var filteredParams = omit(clone$$1(params), function(keyName) {
return keyName === 'facetName';
});
var searchParameters = this.as._getSearchParams(filteredParams, '');
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/' +
encodeURIComponent(this.indexName) + '/facets/' + encodeURIComponent(facetName) + '/query',
hostType: 'read',
body: {params: searchParameters},
callback: callback
});
};
IndexCore.prototype.searchFacet = deprecate(function(params, callback) {
return this.searchForFacetValues(params, callback);
}, deprecatedMessage(
'index.searchFacet(params[, callback])',
'index.searchForFacetValues(params[, callback])'
));
IndexCore.prototype._search = function(params, url, callback, additionalUA) {
return this.as._jsonRequest({
cache: this.cache,
method: 'POST',
url: url || '/1/indexes/' + encodeURIComponent(this.indexName) + '/query',
body: {params: params},
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(this.indexName),
body: {params: params}
},
callback: callback,
additionalUA: additionalUA
});
};
/*
* Get an object from this index
*
* @param objectID the unique identifier of the object to retrieve
* @param attrs (optional) if set, contains the array of attribute names to retrieve
* @param callback (optional) the result callback called with two arguments
* error: null or Error('message')
* content: the object to retrieve or the error message if a failure occured
*/
IndexCore.prototype.getObject = function(objectID, attrs, callback) {
var indexObj = this;
if (arguments.length === 1 || typeof attrs === 'function') {
callback = attrs;
attrs = undefined;
}
var params = '';
if (attrs !== undefined) {
params = '?attributes=';
for (var i = 0; i < attrs.length; ++i) {
if (i !== 0) {
params += ',';
}
params += attrs[i];
}
}
return this.as._jsonRequest({
method: 'GET',
url: '/1/indexes/' + encodeURIComponent(indexObj.indexName) + '/' + encodeURIComponent(objectID) + params,
hostType: 'read',
callback: callback
});
};
/*
* Get several objects from this index
*
* @param objectIDs the array of unique identifier of objects to retrieve
*/
IndexCore.prototype.getObjects = function(objectIDs, attributesToRetrieve, callback) {
var isArray = isarray;
var map = map$1;
var usage = 'Usage: index.getObjects(arrayOfObjectIDs[, callback])';
if (!isArray(objectIDs)) {
throw new Error(usage);
}
var indexObj = this;
if (arguments.length === 1 || typeof attributesToRetrieve === 'function') {
callback = attributesToRetrieve;
attributesToRetrieve = undefined;
}
var body = {
requests: map(objectIDs, function prepareRequest(objectID) {
var request = {
indexName: indexObj.indexName,
objectID: objectID
};
if (attributesToRetrieve) {
request.attributesToRetrieve = attributesToRetrieve.join(',');
}
return request;
})
};
return this.as._jsonRequest({
method: 'POST',
url: '/1/indexes/*/objects',
hostType: 'read',
body: body,
callback: callback
});
};
IndexCore.prototype.as = null;
IndexCore.prototype.indexName = null;
IndexCore.prototype.typeAheadArgs = null;
IndexCore.prototype.typeAheadValueOption = null;
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
var ms = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse$1(val);
} else if (type === 'number' && isNaN(val) === false) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse$1(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd';
}
if (ms >= h) {
return Math.round(ms / h) + 'h';
}
if (ms >= m) {
return Math.round(ms / m) + 'm';
}
if (ms >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, n, name) {
if (ms < n) {
return;
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name;
}
return Math.ceil(ms / n) + ' ' + name + 's';
}
var debug = createCommonjsModule(function (module, exports) {
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = ms;
/**
* The currently active debug mode names, and names to skip.
*/
exports.names = [];
exports.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
exports.formatters = {};
/**
* Previous log timestamp.
*/
var prevTime;
/**
* Select a color.
* @param {String} namespace
* @return {Number}
* @api private
*/
function selectColor(namespace) {
var hash = 0, i;
for (i in namespace) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return exports.colors[Math.abs(hash) % exports.colors.length];
}
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
function debug() {
// disabled?
if (!debug.enabled) return;
var self = debug;
// set `diff` timestamp
var curr = +new Date();
var ms$$1 = curr - (prevTime || curr);
self.diff = ms$$1;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
// turn the `arguments` into a proper Array
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
args[0] = exports.coerce(args[0]);
if ('string' !== typeof args[0]) {
// anything else let's inspect with %O
args.unshift('%O');
}
// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);
// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args);
var logFn = debug.log || exports.log || console.log.bind(console);
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = exports.enabled(namespace);
debug.useColors = exports.useColors();
debug.color = selectColor(namespace);
// env-specific initialization logic for debug instances
if ('function' === typeof exports.init) {
exports.init(debug);
}
return debug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
exports.save(namespaces);
exports.names = [];
exports.skips = [];
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (var i = 0; i < len; i++) {
if (!split[i]) continue; // ignore empty strings
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
exports.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
exports.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
var i, len;
for (i = 0, len = exports.skips.length; i < len; i++) {
if (exports.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = exports.names.length; i < len; i++) {
if (exports.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
});
var debug_1 = debug.coerce;
var debug_2 = debug.disable;
var debug_3 = debug.enable;
var debug_4 = debug.enabled;
var debug_5 = debug.humanize;
var debug_6 = debug.names;
var debug_7 = debug.skips;
var debug_8 = debug.formatters;
var browser$1 = createCommonjsModule(function (module, exports) {
/**
* This is the web browser implementation of `debug()`.
*
* Expose `debug()` as the module.
*/
exports = module.exports = debug;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
&& 'undefined' != typeof chrome.storage
? chrome.storage.local
: localstorage();
/**
* Colors.
*/
exports.colors = [
'lightseagreen',
'forestgreen',
'goldenrod',
'dodgerblue',
'darkorchid',
'crimson'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
return true;
}
// is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
exports.formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (err) {
return '[UnexpectedJSONParseError]: ' + err.message;
}
};
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
var useColors = this.useColors;
args[0] = (useColors ? '%c' : '')
+ this.namespace
+ (useColors ? ' %c' : ' ')
+ args[0]
+ (useColors ? '%c ' : ' ')
+ '+' + exports.humanize(this.diff);
if (!useColors) return;
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// the final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function(match) {
if ('%%' === match) return;
index++;
if ('%c' === match) {
// we only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
// this hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return 'object' === typeof console
&& console.log
&& Function.prototype.apply.call(console.log, console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (null == namespaces) {
exports.storage.removeItem('debug');
} else {
exports.storage.debug = namespaces;
}
} catch(e) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Enable namespaces listed in `localStorage.debug` initially.
*/
exports.enable(load());
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return window.localStorage;
} catch (e) {}
}
});
var browser_1 = browser$1.log;
var browser_2 = browser$1.formatArgs;
var browser_3 = browser$1.save;
var browser_4 = browser$1.load;
var browser_5 = browser$1.useColors;
var browser_6 = browser$1.storage;
var browser_7 = browser$1.colors;
var debug$1 = browser$1('algoliasearch:src/hostIndexState.js');
var localStorageNamespace = 'algoliasearch-client-js';
var store;
var moduleStore = {
state: {},
set: function(key, data) {
this.state[key] = data;
return this.state[key];
},
get: function(key) {
return this.state[key] || null;
}
};
var localStorageStore = {
set: function(key, data) {
moduleStore.set(key, data); // always replicate localStorageStore to moduleStore in case of failure
try {
var namespace = JSON.parse(commonjsGlobal.localStorage[localStorageNamespace]);
namespace[key] = data;
commonjsGlobal.localStorage[localStorageNamespace] = JSON.stringify(namespace);
return namespace[key];
} catch (e) {
return localStorageFailure(key, e);
}
},
get: function(key) {
try {
return JSON.parse(commonjsGlobal.localStorage[localStorageNamespace])[key] || null;
} catch (e) {
return localStorageFailure(key, e);
}
}
};
function localStorageFailure(key, e) {
debug$1('localStorage failed with', e);
cleanup();
store = moduleStore;
return store.get(key);
}
store = supportsLocalStorage() ? localStorageStore : moduleStore;
var store_1 = {
get: getOrSet,
set: getOrSet,
supportsLocalStorage: supportsLocalStorage
};
function getOrSet(key, data) {
if (arguments.length === 1) {
return store.get(key);
}
return store.set(key, data);
}
function supportsLocalStorage() {
try {
if ('localStorage' in commonjsGlobal &&
commonjsGlobal.localStorage !== null) {
if (!commonjsGlobal.localStorage[localStorageNamespace]) {
// actual creation of the namespace
commonjsGlobal.localStorage.setItem(localStorageNamespace, JSON.stringify({}));
}
return true;
}
return false;
} catch (_) {
return false;
}
}
// In case of any error on localStorage, we clean our own namespace, this should handle
// quota errors when a lot of keys + data are used
function cleanup() {
try {
commonjsGlobal.localStorage.removeItem(localStorageNamespace);
} catch (_) {
// nothing to do
}
}
var AlgoliaSearchCore_1 = AlgoliaSearchCore;
// We will always put the API KEY in the JSON body in case of too long API KEY,
// to avoid query string being too long and failing in various conditions (our server limit, browser limit,
// proxies limit)
var MAX_API_KEY_LENGTH = 500;
var RESET_APP_DATA_TIMER =
process.env.RESET_APP_DATA_TIMER && parseInt(process.env.RESET_APP_DATA_TIMER, 10) ||
60 * 2 * 1000; // after 2 minutes reset to first host
/*
* Algolia Search library initialization
* https://www.algolia.com/
*
* @param {string} applicationID - Your applicationID, found in your dashboard
* @param {string} apiKey - Your API key, found in your dashboard
* @param {Object} [opts]
* @param {number} [opts.timeout=2000] - The request timeout set in milliseconds,
* another request will be issued after this timeout
* @param {string} [opts.protocol='http:'] - The protocol used to query Algolia Search API.
* Set to 'https:' to force using https.
* Default to document.location.protocol in browsers
* @param {Object|Array} [opts.hosts={
* read: [this.applicationID + '-dsn.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]),
* write: [this.applicationID + '.algolia.net'].concat([
* this.applicationID + '-1.algolianet.com',
* this.applicationID + '-2.algolianet.com',
* this.applicationID + '-3.algolianet.com']
* ]) - The hosts to use for Algolia Search API.
* If you provide them, you will less benefit from our HA implementation
*/
function AlgoliaSearchCore(applicationID, apiKey, opts) {
var debug = browser$1('algoliasearch');
var clone$$1 = clone;
var isArray = isarray;
var map = map$1;
var usage = 'Usage: algoliasearch(applicationID, apiKey, opts)';
if (opts._allowEmptyCredentials !== true && !applicationID) {
throw new errors.AlgoliaSearchError('Please provide an application ID. ' + usage);
}
if (opts._allowEmptyCredentials !== true && !apiKey) {
throw new errors.AlgoliaSearchError('Please provide an API key. ' + usage);
}
this.applicationID = applicationID;
this.apiKey = apiKey;
this.hosts = {
read: [],
write: []
};
opts = opts || {};
var protocol = opts.protocol || 'https:';
this._timeouts = opts.timeouts || {
connect: 1 * 1000, // 500ms connect is GPRS latency
read: 2 * 1000,
write: 30 * 1000
};
// backward compat, if opts.timeout is passed, we use it to configure all timeouts like before
if (opts.timeout) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = opts.timeout;
}
// while we advocate for colon-at-the-end values: 'http:' for `opts.protocol`
// we also accept `http` and `https`. It's a common error.
if (!/:$/.test(protocol)) {
protocol = protocol + ':';
}
if (opts.protocol !== 'http:' && opts.protocol !== 'https:') {
throw new errors.AlgoliaSearchError('protocol must be `http:` or `https:` (was `' + opts.protocol + '`)');
}
this._checkAppIdData();
if (!opts.hosts) {
var defaultHosts = map(this._shuffleResult, function(hostNumber) {
return applicationID + '-' + hostNumber + '.algolianet.com';
});
// no hosts given, compute defaults
this.hosts.read = [this.applicationID + '-dsn.algolia.net'].concat(defaultHosts);
this.hosts.write = [this.applicationID + '.algolia.net'].concat(defaultHosts);
} else if (isArray(opts.hosts)) {
// when passing custom hosts, we need to have a different host index if the number
// of write/read hosts are different.
this.hosts.read = clone$$1(opts.hosts);
this.hosts.write = clone$$1(opts.hosts);
} else {
this.hosts.read = clone$$1(opts.hosts.read);
this.hosts.write = clone$$1(opts.hosts.write);
}
// add protocol and lowercase hosts
this.hosts.read = map(this.hosts.read, prepareHost(protocol));
this.hosts.write = map(this.hosts.write, prepareHost(protocol));
this.extraHeaders = {};
// In some situations you might want to warm the cache
this.cache = opts._cache || {};
this._ua = opts._ua;
this._useCache = opts._useCache === undefined || opts._cache ? true : opts._useCache;
this._useFallback = opts.useFallback === undefined ? true : opts.useFallback;
this._setTimeout = opts._setTimeout;
debug('init done, %j', this);
}
/*
* Get the index object initialized
*
* @param indexName the name of index
* @param callback the result callback with one argument (the Index instance)
*/
AlgoliaSearchCore.prototype.initIndex = function(indexName) {
return new IndexCore_1(this, indexName);
};
/**
* Add an extra field to the HTTP request
*
* @param name the header field name
* @param value the header field value
*/
AlgoliaSearchCore.prototype.setExtraHeader = function(name, value) {
this.extraHeaders[name.toLowerCase()] = value;
};
/**
* Get the value of an extra HTTP header
*
* @param name the header field name
*/
AlgoliaSearchCore.prototype.getExtraHeader = function(name) {
return this.extraHeaders[name.toLowerCase()];
};
/**
* Remove an extra field from the HTTP request
*
* @param name the header field name
*/
AlgoliaSearchCore.prototype.unsetExtraHeader = function(name) {
delete this.extraHeaders[name.toLowerCase()];
};
/**
* Augment sent x-algolia-agent with more data, each agent part
* is automatically separated from the others by a semicolon;
*
* @param algoliaAgent the agent to add
*/
AlgoliaSearchCore.prototype.addAlgoliaAgent = function(algoliaAgent) {
if (this._ua.indexOf(';' + algoliaAgent) === -1) {
this._ua += ';' + algoliaAgent;
}
};
/*
* Wrapper that try all hosts to maximize the quality of service
*/
AlgoliaSearchCore.prototype._jsonRequest = function(initialOpts) {
this._checkAppIdData();
var requestDebug = browser$1('algoliasearch:' + initialOpts.url);
var body;
var additionalUA = initialOpts.additionalUA || '';
var cache = initialOpts.cache;
var client = this;
var tries = 0;
var usingFallback = false;
var hasFallback = client._useFallback && client._request.fallback && initialOpts.fallback;
var headers;
if (
this.apiKey.length > MAX_API_KEY_LENGTH &&
initialOpts.body !== undefined &&
(initialOpts.body.params !== undefined || // index.search()
initialOpts.body.requests !== undefined) // client.search()
) {
initialOpts.body.apiKey = this.apiKey;
headers = this._computeRequestHeaders(additionalUA, false);
} else {
headers = this._computeRequestHeaders(additionalUA);
}
if (initialOpts.body !== undefined) {
body = safeJSONStringify(initialOpts.body);
}
requestDebug('request start');
var debugData = [];
function doRequest(requester, reqOpts) {
client._checkAppIdData();
var startTime = new Date();
var cacheID;
if (client._useCache) {
cacheID = initialOpts.url;
}
// as we sometime use POST requests to pass parameters (like query='aa'),
// the cacheID must also include the body to be different between calls
if (client._useCache && body) {
cacheID += '_body_' + reqOpts.body;
}
// handle cache existence
if (client._useCache && cache && cache[cacheID] !== undefined) {
requestDebug('serving response from cache');
return client._promise.resolve(JSON.parse(cache[cacheID]));
}
// if we reached max tries
if (tries >= client.hosts[initialOpts.hostType].length) {
if (!hasFallback || usingFallback) {
requestDebug('could not get any response');
// then stop
return client._promise.reject(new errors.AlgoliaSearchError(
'Cannot connect to the AlgoliaSearch API.' +
' Send an email to support@algolia.com to report and resolve the issue.' +
' Application id was: ' + client.applicationID, {debugData: debugData}
));
}
requestDebug('switching to fallback');
// let's try the fallback starting from here
tries = 0;
// method, url and body are fallback dependent
reqOpts.method = initialOpts.fallback.method;
reqOpts.url = initialOpts.fallback.url;
reqOpts.jsonBody = initialOpts.fallback.body;
if (reqOpts.jsonBody) {
reqOpts.body = safeJSONStringify(reqOpts.jsonBody);
}
// re-compute headers, they could be omitting the API KEY
headers = client._computeRequestHeaders(additionalUA);
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
client._setHostIndexByType(0, initialOpts.hostType);
usingFallback = true; // the current request is now using fallback
return doRequest(client._request.fallback, reqOpts);
}
var currentHost = client._getHostByType(initialOpts.hostType);
var url = currentHost + reqOpts.url;
var options = {
body: reqOpts.body,
jsonBody: reqOpts.jsonBody,
method: reqOpts.method,
headers: headers,
timeouts: reqOpts.timeouts,
debug: requestDebug
};
requestDebug('method: %s, url: %s, headers: %j, timeouts: %d',
options.method, url, options.headers, options.timeouts);
if (requester === client._request.fallback) {
requestDebug('using fallback');
}
// `requester` is any of this._request or this._request.fallback
// thus it needs to be called using the client as context
return requester.call(client, url, options).then(success, tryFallback);
function success(httpResponse) {
// compute the status of the response,
//
// When in browser mode, using XDR or JSONP, we have no statusCode available
// So we rely on our API response `status` property.
// But `waitTask` can set a `status` property which is not the statusCode (it's the task status)
// So we check if there's a `message` along `status` and it means it's an error
//
// That's the only case where we have a response.status that's not the http statusCode
var status = httpResponse && httpResponse.body && httpResponse.body.message && httpResponse.body.status ||
// this is important to check the request statusCode AFTER the body eventual
// statusCode because some implementations (jQuery XDomainRequest transport) may
// send statusCode 200 while we had an error
httpResponse.statusCode ||
// When in browser mode, using XDR or JSONP
// we default to success when no error (no response.status && response.message)
// If there was a JSON.parse() error then body is null and it fails
httpResponse && httpResponse.body && 200;
requestDebug('received response: statusCode: %s, computed statusCode: %d, headers: %j',
httpResponse.statusCode, status, httpResponse.headers);
var httpResponseOk = Math.floor(status / 100) === 2;
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime,
statusCode: status
});
if (httpResponseOk) {
if (client._useCache && cache) {
cache[cacheID] = httpResponse.responseText;
}
return httpResponse.body;
}
var shouldRetry = Math.floor(status / 100) !== 4;
if (shouldRetry) {
tries += 1;
return retryRequest();
}
requestDebug('unrecoverable error');
// no success and no retry => fail
var unrecoverableError = new errors.AlgoliaSearchError(
httpResponse.body && httpResponse.body.message, {debugData: debugData, statusCode: status}
);
return client._promise.reject(unrecoverableError);
}
function tryFallback(err) {
// error cases:
// While not in fallback mode:
// - CORS not supported
// - network error
// While in fallback mode:
// - timeout
// - network error
// - badly formatted JSONP (script loaded, did not call our callback)
// In both cases:
// - uncaught exception occurs (TypeError)
requestDebug('error: %s, stack: %s', err.message, err.stack);
var endTime = new Date();
debugData.push({
currentHost: currentHost,
headers: removeCredentials(headers),
content: body || null,
contentLength: body !== undefined ? body.length : null,
method: reqOpts.method,
timeouts: reqOpts.timeouts,
url: reqOpts.url,
startTime: startTime,
endTime: endTime,
duration: endTime - startTime
});
if (!(err instanceof errors.AlgoliaSearchError)) {
err = new errors.Unknown(err && err.message, err);
}
tries += 1;
// stop the request implementation when:
if (
// we did not generate this error,
// it comes from a throw in some other piece of code
err instanceof errors.Unknown ||
// server sent unparsable JSON
err instanceof errors.UnparsableJSON ||
// max tries and already using fallback or no fallback
tries >= client.hosts[initialOpts.hostType].length &&
(usingFallback || !hasFallback)) {
// stop request implementation for this command
err.debugData = debugData;
return client._promise.reject(err);
}
// When a timeout occured, retry by raising timeout
if (err instanceof errors.RequestTimeout) {
return retryRequestWithHigherTimeout();
}
return retryRequest();
}
function retryRequest() {
requestDebug('retrying request');
client._incrementHostIndex(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
function retryRequestWithHigherTimeout() {
requestDebug('retrying request with higher timeout');
client._incrementHostIndex(initialOpts.hostType);
client._incrementTimeoutMultipler();
reqOpts.timeouts = client._getTimeoutsForRequest(initialOpts.hostType);
return doRequest(requester, reqOpts);
}
}
var promise = doRequest(
client._request, {
url: initialOpts.url,
method: initialOpts.method,
body: body,
jsonBody: initialOpts.body,
timeouts: client._getTimeoutsForRequest(initialOpts.hostType)
}
);
// either we have a callback
// either we are using promises
if (typeof initialOpts.callback === 'function') {
promise.then(function okCb(content) {
exitPromise(function() {
initialOpts.callback(null, content);
}, client._setTimeout || setTimeout);
}, function nookCb(err) {
exitPromise(function() {
initialOpts.callback(err);
}, client._setTimeout || setTimeout);
});
} else {
return promise;
}
};
/*
* Transform search param object in query string
* @param {object} args arguments to add to the current query string
* @param {string} params current query string
* @return {string} the final query string
*/
AlgoliaSearchCore.prototype._getSearchParams = function(args, params) {
if (args === undefined || args === null) {
return params;
}
for (var key in args) {
if (key !== null && args[key] !== undefined && args.hasOwnProperty(key)) {
params += params === '' ? '' : '&';
params += key + '=' + encodeURIComponent(Object.prototype.toString.call(args[key]) === '[object Array]' ? safeJSONStringify(args[key]) : args[key]);
}
}
return params;
};
AlgoliaSearchCore.prototype._computeRequestHeaders = function(additionalUA, withAPIKey) {
var forEach = foreach;
var ua = additionalUA ?
this._ua + ';' + additionalUA :
this._ua;
var requestHeaders = {
'x-algolia-agent': ua,
'x-algolia-application-id': this.applicationID
};
// browser will inline headers in the url, node.js will use http headers
// but in some situations, the API KEY will be too long (big secured API keys)
// so if the request is a POST and the KEY is very long, we will be asked to not put
// it into headers but in the JSON body
if (withAPIKey !== false) {
requestHeaders['x-algolia-api-key'] = this.apiKey;
}
if (this.userToken) {
requestHeaders['x-algolia-usertoken'] = this.userToken;
}
if (this.securityTags) {
requestHeaders['x-algolia-tagfilters'] = this.securityTags;
}
forEach(this.extraHeaders, function addToRequestHeaders(value, key) {
requestHeaders[key] = value;
});
return requestHeaders;
};
/**
* Search through multiple indices at the same time
* @param {Object[]} queries An array of queries you want to run.
* @param {string} queries[].indexName The index name you want to target
* @param {string} [queries[].query] The query to issue on this index. Can also be passed into `params`
* @param {Object} queries[].params Any search param like hitsPerPage, ..
* @param {Function} callback Callback to be called
* @return {Promise|undefined} Returns a promise if no callback given
*/
AlgoliaSearchCore.prototype.search = function(queries, opts, callback) {
var isArray = isarray;
var map = map$1;
var usage = 'Usage: client.search(arrayOfQueries[, callback])';
if (!isArray(queries)) {
throw new Error(usage);
}
if (typeof opts === 'function') {
callback = opts;
opts = {};
} else if (opts === undefined) {
opts = {};
}
var client = this;
var postObj = {
requests: map(queries, function prepareRequest(query) {
var params = '';
// allow query.query
// so we are mimicing the index.search(query, params) method
// {indexName:, query:, params:}
if (query.query !== undefined) {
params += 'query=' + encodeURIComponent(query.query);
}
return {
indexName: query.indexName,
params: client._getSearchParams(query.params, params)
};
})
};
var JSONPParams = map(postObj.requests, function prepareJSONPParams(request, requestId) {
return requestId + '=' +
encodeURIComponent(
'/1/indexes/' + encodeURIComponent(request.indexName) + '?' +
request.params
);
}).join('&');
var url = '/1/indexes/*/queries';
if (opts.strategy !== undefined) {
url += '?strategy=' + opts.strategy;
}
return this._jsonRequest({
cache: this.cache,
method: 'POST',
url: url,
body: postObj,
hostType: 'read',
fallback: {
method: 'GET',
url: '/1/indexes/*',
body: {
params: JSONPParams
}
},
callback: callback
});
};
/**
* Set the extra security tagFilters header
* @param {string|array} tags The list of tags defining the current security filters
*/
AlgoliaSearchCore.prototype.setSecurityTags = function(tags) {
if (Object.prototype.toString.call(tags) === '[object Array]') {
var strTags = [];
for (var i = 0; i < tags.length; ++i) {
if (Object.prototype.toString.call(tags[i]) === '[object Array]') {
var oredTags = [];
for (var j = 0; j < tags[i].length; ++j) {
oredTags.push(tags[i][j]);
}
strTags.push('(' + oredTags.join(',') + ')');
} else {
strTags.push(tags[i]);
}
}
tags = strTags.join(',');
}
this.securityTags = tags;
};
/**
* Set the extra user token header
* @param {string} userToken The token identifying a uniq user (used to apply rate limits)
*/
AlgoliaSearchCore.prototype.setUserToken = function(userToken) {
this.userToken = userToken;
};
/**
* Clear all queries in client's cache
* @return undefined
*/
AlgoliaSearchCore.prototype.clearCache = function() {
this.cache = {};
};
/**
* Set the number of milliseconds a request can take before automatically being terminated.
* @deprecated
* @param {Number} milliseconds
*/
AlgoliaSearchCore.prototype.setRequestTimeout = function(milliseconds) {
if (milliseconds) {
this._timeouts.connect = this._timeouts.read = this._timeouts.write = milliseconds;
}
};
/**
* Set the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.setTimeouts = function(timeouts) {
this._timeouts = timeouts;
};
/**
* Get the three different (connect, read, write) timeouts to be used when requesting
* @param {Object} timeouts
*/
AlgoliaSearchCore.prototype.getTimeouts = function() {
return this._timeouts;
};
AlgoliaSearchCore.prototype._getAppIdData = function() {
var data = store_1.get(this.applicationID);
if (data !== null) this._cacheAppIdData(data);
return data;
};
AlgoliaSearchCore.prototype._setAppIdData = function(data) {
data.lastChange = (new Date()).getTime();
this._cacheAppIdData(data);
return store_1.set(this.applicationID, data);
};
AlgoliaSearchCore.prototype._checkAppIdData = function() {
var data = this._getAppIdData();
var now = (new Date()).getTime();
if (data === null || now - data.lastChange > RESET_APP_DATA_TIMER) {
return this._resetInitialAppIdData(data);
}
return data;
};
AlgoliaSearchCore.prototype._resetInitialAppIdData = function(data) {
var newData = data || {};
newData.hostIndexes = {read: 0, write: 0};
newData.timeoutMultiplier = 1;
newData.shuffleResult = newData.shuffleResult || shuffle([1, 2, 3]);
return this._setAppIdData(newData);
};
AlgoliaSearchCore.prototype._cacheAppIdData = function(data) {
this._hostIndexes = data.hostIndexes;
this._timeoutMultiplier = data.timeoutMultiplier;
this._shuffleResult = data.shuffleResult;
};
AlgoliaSearchCore.prototype._partialAppIdDataUpdate = function(newData) {
var foreach$$1 = foreach;
var currentData = this._getAppIdData();
foreach$$1(newData, function(value, key) {
currentData[key] = value;
});
return this._setAppIdData(currentData);
};
AlgoliaSearchCore.prototype._getHostByType = function(hostType) {
return this.hosts[hostType][this._getHostIndexByType(hostType)];
};
AlgoliaSearchCore.prototype._getTimeoutMultiplier = function() {
return this._timeoutMultiplier;
};
AlgoliaSearchCore.prototype._getHostIndexByType = function(hostType) {
return this._hostIndexes[hostType];
};
AlgoliaSearchCore.prototype._setHostIndexByType = function(hostIndex, hostType) {
var clone$$1 = clone;
var newHostIndexes = clone$$1(this._hostIndexes);
newHostIndexes[hostType] = hostIndex;
this._partialAppIdDataUpdate({hostIndexes: newHostIndexes});
return hostIndex;
};
AlgoliaSearchCore.prototype._incrementHostIndex = function(hostType) {
return this._setHostIndexByType(
(this._getHostIndexByType(hostType) + 1) % this.hosts[hostType].length, hostType
);
};
AlgoliaSearchCore.prototype._incrementTimeoutMultipler = function() {
var timeoutMultiplier = Math.max(this._timeoutMultiplier + 1, 4);
return this._partialAppIdDataUpdate({timeoutMultiplier: timeoutMultiplier});
};
AlgoliaSearchCore.prototype._getTimeoutsForRequest = function(hostType) {
return {
connect: this._timeouts.connect * this._timeoutMultiplier,
complete: this._timeouts[hostType] * this._timeoutMultiplier
};
};
function prepareHost(protocol) {
return function prepare(host) {
return protocol + '//' + host.toLowerCase();
};
}
// Prototype.js < 1.7, a widely used library, defines a weird
// Array.prototype.toJSON function that will fail to stringify our content
// appropriately
// refs:
// - https://groups.google.com/forum/#!topic/prototype-core/E-SAVvV_V9Q
// - https://github.com/sstephenson/prototype/commit/038a2985a70593c1a86c230fadbdfe2e4898a48c
// - http://stackoverflow.com/a/3148441/147079
function safeJSONStringify(obj) {
/* eslint no-extend-native:0 */
if (Array.prototype.toJSON === undefined) {
return JSON.stringify(obj);
}
var toJSON = Array.prototype.toJSON;
delete Array.prototype.toJSON;
var out = JSON.stringify(obj);
Array.prototype.toJSON = toJSON;
return out;
}
function shuffle(array) {
var currentIndex = array.length;
var temporaryValue;
var randomIndex;
// While there remain elements to shuffle...
while (currentIndex !== 0) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function removeCredentials(headers) {
var newHeaders = {};
for (var headerName in headers) {
if (Object.prototype.hasOwnProperty.call(headers, headerName)) {
var value;
if (headerName === 'x-algolia-api-key' || headerName === 'x-algolia-application-id') {
value = '**hidden for security purposes**';
} else {
value = headers[headerName];
}
newHeaders[headerName] = value;
}
}
return newHeaders;
}
var win;
if (typeof window !== "undefined") {
win = window;
} else if (typeof commonjsGlobal !== "undefined") {
win = commonjsGlobal;
} else if (typeof self !== "undefined"){
win = self;
} else {
win = {};
}
var window_1 = win;
var es6Promise = createCommonjsModule(function (module, exports) {
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version 4.1.1
*/
(function (global, factory) {
module.exports = factory();
}(commonjsGlobal, (function () {
function objectOrFunction(x) {
var type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = undefined;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
}
var isArray = _isArray;
var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var r = commonjsRequire;
var vertx = r('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof commonjsRequire === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var _arguments = arguments;
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
(function () {
var callback = _arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
})();
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve$1(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(16);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var GET_THEN_ERROR = new ErrorObject();
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch (error) {
GET_THEN_ERROR.error = error;
return GET_THEN_ERROR;
}
}
function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
try {
then$$1.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then$$1) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then$$1, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return resolve(promise, value);
}, function (reason) {
return reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$1) {
if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$1 === GET_THEN_ERROR) {
reject(promise, GET_THEN_ERROR.error);
GET_THEN_ERROR.error = null;
} else if (then$$1 === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$1)) {
handleForeignThenable(promise, maybeThenable, then$$1);
} else {
fulfill(promise, maybeThenable);
}
}
}
function resolve(promise, value) {
if (promise === value) {
reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = undefined,
callback = undefined,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function ErrorObject() {
this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = undefined,
error = undefined,
succeeded = undefined,
failed = undefined;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value.error = null;
} else {
succeeded = true;
}
if (promise === value) {
reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
resolve(promise, value);
}, function rejectPromise(reason) {
reject(promise, reason);
});
} catch (e) {
reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function Enumerator$1(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate(input);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
function validationError() {
return new Error('Array Methods must be provided an Array');
}
Enumerator$1.prototype._enumerate = function (input) {
for (var i = 0; this._state === PENDING && i < input.length; i++) {
this._eachEntry(input[i], i);
}
};
Enumerator$1.prototype._eachEntry = function (entry, i) {
var c = this._instanceConstructor;
var resolve$$1 = c.resolve;
if (resolve$$1 === resolve$1) {
var _then = getThen(entry);
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise$2) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, _then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$1) {
return resolve$$1(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$1(entry), i);
}
};
Enumerator$1.prototype._settledAt = function (state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator$1.prototype._willSettleAt = function (promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all$1(entries) {
return new Enumerator$1(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race$1(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject$1(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function Promise$2(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
}
}
Promise$2.all = all$1;
Promise$2.race = race$1;
Promise$2.resolve = resolve$1;
Promise$2.reject = reject$1;
Promise$2._setScheduler = setScheduler;
Promise$2._setAsap = setAsap;
Promise$2._asap = asap;
Promise$2.prototype = {
constructor: Promise$2,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: then,
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function _catch(onRejection) {
return this.then(null, onRejection);
}
};
/*global self*/
function polyfill$1() {
var local = undefined;
if (typeof commonjsGlobal !== 'undefined') {
local = commonjsGlobal;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise$2;
}
// Strange compat..
Promise$2.polyfill = polyfill$1;
Promise$2.Promise = Promise$2;
return Promise$2;
})));
});
// Copyright Joyent, Inc. and other Node contributors.
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
var encode$1 = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map$2(objectKeys$1(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray$1(obj[k])) {
return map$2(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray$1 = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map$2 (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys$1 = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
var inlineHeaders_1 = inlineHeaders;
function inlineHeaders(url, headers) {
if (/\?/.test(url)) {
url += '&';
} else {
url += '?';
}
return url + encode$1(headers);
}
var jsonpRequest_1 = jsonpRequest;
var JSONPCounter = 0;
function jsonpRequest(url, opts, cb) {
if (opts.method !== 'GET') {
cb(new Error('Method ' + opts.method + ' ' + url + ' is not supported by JSONP.'));
return;
}
opts.debug('JSONP: start');
var cbCalled = false;
var timedOut = false;
JSONPCounter += 1;
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var cbName = 'algoliaJSONP_' + JSONPCounter;
var done = false;
window[cbName] = function(data) {
removeGlobals();
if (timedOut) {
opts.debug('JSONP: Late answer, ignoring');
return;
}
cbCalled = true;
clean();
cb(null, {
body: data/* ,
// We do not send the statusCode, there's no statusCode in JSONP, it will be
// computed using data.status && data.message like with XDR
statusCode*/
});
};
// add callback by hand
url += '&callback=' + cbName;
// add body params manually
if (opts.jsonBody && opts.jsonBody.params) {
url += '&' + opts.jsonBody.params;
}
var ontimeout = setTimeout(timeout, opts.timeouts.complete);
// script onreadystatechange needed only for
// <= IE8
// https://github.com/angular/angular.js/issues/4523
script.onreadystatechange = readystatechange;
script.onload = success;
script.onerror = error;
script.async = true;
script.defer = true;
script.src = url;
head.appendChild(script);
function success() {
opts.debug('JSONP: success');
if (done || timedOut) {
return;
}
done = true;
// script loaded but did not call the fn => script loading error
if (!cbCalled) {
opts.debug('JSONP: Fail. Script loaded but did not call the callback');
clean();
cb(new errors.JSONPScriptFail());
}
}
function readystatechange() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
success();
}
}
function clean() {
clearTimeout(ontimeout);
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
head.removeChild(script);
}
function removeGlobals() {
try {
delete window[cbName];
delete window[cbName + '_loaded'];
} catch (e) {
window[cbName] = window[cbName + '_loaded'] = undefined;
}
}
function timeout() {
opts.debug('JSONP: Script timeout');
timedOut = true;
clean();
cb(new errors.RequestTimeout());
}
function error() {
opts.debug('JSONP: Script error');
if (done || timedOut) {
return;
}
clean();
cb(new errors.JSONPScriptError());
}
}
var places = createPlacesClient;
function createPlacesClient(algoliasearch) {
return function places(appID, apiKey, opts) {
var cloneDeep = clone;
opts = opts && cloneDeep(opts) || {};
opts.hosts = opts.hosts || [
'places-dsn.algolia.net',
'places-1.algolianet.com',
'places-2.algolianet.com',
'places-3.algolianet.com'
];
// allow initPlaces() no arguments => community rate limited
if (arguments.length === 0 || typeof appID === 'object' || appID === undefined) {
appID = '';
apiKey = '';
opts._allowEmptyCredentials = true;
}
var client = algoliasearch(appID, apiKey, opts);
var index = client.initIndex('places');
index.search = buildSearchMethod_1('query', '/1/places/query');
index.getObject = function(objectID, callback) {
return this.as._jsonRequest({
method: 'GET',
url: '/1/places/' + encodeURIComponent(objectID),
hostType: 'read',
callback: callback
});
};
return index;
};
}
var getDocumentProtocol_1 = getDocumentProtocol;
function getDocumentProtocol() {
var protocol = window.document.location.protocol;
// when in `file:` mode (local html file), default to `http:`
if (protocol !== 'http:' && protocol !== 'https:') {
protocol = 'http:';
}
return protocol;
}
var version$3 = '3.24.5';
var Promise$2 = window_1.Promise || es6Promise.Promise;
// This is the standalone browser build entry point
// Browser implementation of the Algolia Search JavaScript client,
// using XMLHttpRequest, XDomainRequest and JSONP as fallback
var createAlgoliasearch = function createAlgoliasearch(AlgoliaSearch, uaSuffix) {
var inherits = inherits_browser$1;
var errors$$1 = errors;
var inlineHeaders = inlineHeaders_1;
var jsonpRequest = jsonpRequest_1;
var places$$1 = places;
uaSuffix = uaSuffix || '';
function algoliasearch(applicationID, apiKey, opts) {
var cloneDeep = clone;
var getDocumentProtocol = getDocumentProtocol_1;
opts = cloneDeep(opts || {});
if (opts.protocol === undefined) {
opts.protocol = getDocumentProtocol();
}
opts._ua = opts._ua || algoliasearch.ua;
return new AlgoliaSearchBrowser(applicationID, apiKey, opts);
}
algoliasearch.version = version$3;
algoliasearch.ua = 'Algolia for vanilla JavaScript ' + uaSuffix + algoliasearch.version;
algoliasearch.initPlaces = places$$1(algoliasearch);
// we expose into window no matter how we are used, this will allow
// us to easily debug any website running algolia
window_1.__algolia = {
debug: browser$1,
algoliasearch: algoliasearch
};
var support = {
hasXMLHttpRequest: 'XMLHttpRequest' in window_1,
hasXDomainRequest: 'XDomainRequest' in window_1
};
if (support.hasXMLHttpRequest) {
support.cors = 'withCredentials' in new XMLHttpRequest();
}
function AlgoliaSearchBrowser() {
// call AlgoliaSearch constructor
AlgoliaSearch.apply(this, arguments);
}
inherits(AlgoliaSearchBrowser, AlgoliaSearch);
AlgoliaSearchBrowser.prototype._request = function request(url, opts) {
return new Promise$2(function wrapRequest(resolve, reject) {
// no cors or XDomainRequest, no request
if (!support.cors && !support.hasXDomainRequest) {
// very old browser, not supported
reject(new errors$$1.Network('CORS not supported'));
return;
}
url = inlineHeaders(url, opts.headers);
var body = opts.body;
var req = support.cors ? new XMLHttpRequest() : new XDomainRequest();
var reqTimeout;
var timedOut;
var connected = false;
reqTimeout = setTimeout(onTimeout, opts.timeouts.connect);
// we set an empty onprogress listener
// so that XDomainRequest on IE9 is not aborted
// refs:
// - https://github.com/algolia/algoliasearch-client-js/issues/76
// - https://social.msdn.microsoft.com/Forums/ie/en-US/30ef3add-767c-4436-b8a9-f1ca19b4812e/ie9-rtm-xdomainrequest-issued-requests-may-abort-if-all-event-handlers-not-specified?forum=iewebdevelopment
req.onprogress = onProgress;
if ('onreadystatechange' in req) req.onreadystatechange = onReadyStateChange;
req.onload = onLoad;
req.onerror = onError;
// do not rely on default XHR async flag, as some analytics code like hotjar
// breaks it and set it to false by default
if (req instanceof XMLHttpRequest) {
req.open(opts.method, url, true);
} else {
req.open(opts.method, url);
}
// headers are meant to be sent after open
if (support.cors) {
if (body) {
if (opts.method === 'POST') {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
} else {
req.setRequestHeader('content-type', 'application/json');
}
}
req.setRequestHeader('accept', 'application/json');
}
req.send(body);
// event object not received in IE8, at least
// but we do not use it, still important to note
function onLoad(/* event */) {
// When browser does not supports req.timeout, we can
// have both a load and timeout event, since handled by a dumb setTimeout
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
var out;
try {
out = {
body: JSON.parse(req.responseText),
responseText: req.responseText,
statusCode: req.status,
// XDomainRequest does not have any response headers
headers: req.getAllResponseHeaders && req.getAllResponseHeaders() || {}
};
} catch (e) {
out = new errors$$1.UnparsableJSON({
more: req.responseText
});
}
if (out instanceof errors$$1.UnparsableJSON) {
reject(out);
} else {
resolve(out);
}
}
function onError(event) {
if (timedOut) {
return;
}
clearTimeout(reqTimeout);
// error event is trigerred both with XDR/XHR on:
// - DNS error
// - unallowed cross domain request
reject(
new errors$$1.Network({
more: event
})
);
}
function onTimeout() {
timedOut = true;
req.abort();
reject(new errors$$1.RequestTimeout());
}
function onConnect() {
connected = true;
clearTimeout(reqTimeout);
reqTimeout = setTimeout(onTimeout, opts.timeouts.complete);
}
function onProgress() {
if (!connected) onConnect();
}
function onReadyStateChange() {
if (!connected && req.readyState > 1) onConnect();
}
});
};
AlgoliaSearchBrowser.prototype._request.fallback = function requestFallback(url, opts) {
url = inlineHeaders(url, opts.headers);
return new Promise$2(function wrapJsonpRequest(resolve, reject) {
jsonpRequest(url, opts, function jsonpRequestDone(err, content) {
if (err) {
reject(err);
return;
}
resolve(content);
});
});
};
AlgoliaSearchBrowser.prototype._promise = {
reject: function rejectPromise(val) {
return Promise$2.reject(val);
},
resolve: function resolvePromise(val) {
return Promise$2.resolve(val);
},
delay: function delayPromise(ms) {
return new Promise$2(function resolveOnTimeout(resolve/* , reject*/) {
setTimeout(resolve, ms);
});
}
};
return algoliasearch;
};
var algoliasearchLite = createAlgoliasearch(AlgoliaSearchCore_1, '(lite) ');
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE$1 = 200;
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = _arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = _arrayMap(values, _baseUnary(iteratee));
}
if (comparator) {
includes = _arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE$1) {
includes = _cacheHas;
isCommon = false;
values = new _SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
var _baseDifference = baseDifference;
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = _baseRest(function(array, values) {
return isArrayLikeObject_1(array)
? _baseDifference(array, _baseFlatten(values, 1, isArrayLikeObject_1, true))
: [];
});
var difference_1 = difference;
/** Used for built-in method references. */
var objectProto$20 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$18 = objectProto$20.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$18.call(object, key);
}
var _baseHas = baseHas;
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has$2(object, path) {
return object != null && _hasPath(object, path, _baseHas);
}
var has_1 = has$2;
/**
* @typedef {object} ConnectorDescription
* @property {string} displayName - the displayName used by the wrapper
* @property {function} refine - a function to filter the local state
* @property {function} getSearchParameters - function transforming the local state to a SearchParameters
* @property {function} getMetadata - metadata of the widget
* @property {function} transitionState - hook after the state has changed
* @property {function} getProvidedProps - transform the state into props passed to the wrapped component.
* Receives (props, widgetStates, searchState, metadata) and returns the local state.
* @property {function} getId - Receives props and return the id that will be used to identify the widget
* @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state.
* @property {object} propTypes - PropTypes forwarded to the wrapped component.
* @property {object} defaultProps - default values for the props
*/
/**
* Connectors are the HOC used to transform React components
* into InstantSearch widgets.
* In order to simplify the construction of such connectors
* `createConnector` takes a description and transform it into
* a connector.
* @param {ConnectorDescription} connectorDesc the description of the connector
* @return {Connector} a function that wraps a component into
* an instantsearch connected one.
*/
function createConnector(connectorDesc) {
if (!connectorDesc.displayName) {
throw new Error('`createConnector` requires you to provide a `displayName` property.');
}
var hasRefine = has_1(connectorDesc, 'refine');
var hasSearchForFacetValues = has_1(connectorDesc, 'searchForFacetValues');
var hasSearchParameters = has_1(connectorDesc, 'getSearchParameters');
var hasMetadata = has_1(connectorDesc, 'getMetadata');
var hasTransitionState = has_1(connectorDesc, 'transitionState');
var hasCleanUp = has_1(connectorDesc, 'cleanUp');
var isWidget = hasSearchParameters || hasMetadata || hasTransitionState;
return function (Composed) {
var _class, _temp, _initialiseProps;
return _temp = _class = function (_Component) {
inherits(Connector, _Component);
function Connector(props, context) {
classCallCheck(this, Connector);
var _this = possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context));
_initialiseProps.call(_this);
var _context$ais = context.ais,
store = _context$ais.store,
widgetsManager = _context$ais.widgetsManager;
var canRender = false;
_this.state = {
props: _this.getProvidedProps(_extends({}, props, { canRender: canRender })),
canRender: canRender // use to know if a component is rendered (browser), or not (server).
};
_this.unsubscribe = store.subscribe(function () {
if (_this.state.canRender) {
_this.setState({
props: _this.getProvidedProps(_extends({}, _this.props, {
canRender: _this.state.canRender
}))
});
}
});
if (isWidget) {
_this.unregisterWidget = widgetsManager.registerWidget(_this);
}
return _this;
}
createClass(Connector, [{
key: 'getMetadata',
value: function getMetadata(nextWidgetsState) {
if (hasMetadata) {
return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState);
}
return {};
}
}, {
key: 'getSearchParameters',
value: function getSearchParameters(searchParameters) {
if (hasSearchParameters) {
return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.context.ais.store.getState().widgets);
}
return null;
}
}, {
key: 'transitionState',
value: function transitionState(prevWidgetsState, nextWidgetsState) {
if (hasTransitionState) {
return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState);
}
return nextWidgetsState;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.setState({
canRender: true
});
}
}, {
key: 'componentWillMount',
value: function componentWillMount() {
if (connectorDesc.getSearchParameters) {
this.context.ais.onSearchParameters(connectorDesc.getSearchParameters, this.context, this.props);
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (!isEqual_1(this.props, nextProps)) {
this.setState({
props: this.getProvidedProps(nextProps)
});
if (isWidget) {
// Since props might have changed, we need to re-run getSearchParameters
// and getMetadata with the new props.
this.context.ais.widgetsManager.update();
if (connectorDesc.transitionState) {
this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets));
}
}
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.unsubscribe();
if (isWidget) {
this.unregisterWidget(); // will schedule an update
if (hasCleanUp) {
var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets);
this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), {
widgets: newState
}));
this.context.ais.onSearchStateChange(removeEmptyKey(newState));
}
}
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
var propsEqual = shallowEqual(this.props, nextProps);
if (this.state.props === null || nextState.props === null) {
if (this.state.props === nextState.props) {
return !propsEqual;
}
return true;
}
return !propsEqual || !shallowEqual(this.state.props, nextState.props);
}
}, {
key: 'render',
value: function render() {
if (this.state.props === null) {
return null;
}
var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {};
var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues } : {};
return React__default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps));
}
}]);
return Connector;
}(React.Component), _class.displayName = connectorDesc.displayName + '(' + getDisplayName(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = {
// @TODO: more precise state manager propType
ais: propTypes.object.isRequired,
multiIndexContext: propTypes.object
}, _initialiseProps = function _initialiseProps() {
var _this2 = this;
this.getProvidedProps = function (props) {
var store = _this2.context.ais.store;
var _store$getState = store.getState(),
results = _store$getState.results,
searching = _store$getState.searching,
error = _store$getState.error,
widgets = _store$getState.widgets,
metadata = _store$getState.metadata,
resultsFacetValues = _store$getState.resultsFacetValues,
searchingForFacetValues = _store$getState.searchingForFacetValues,
isSearchStalled = _store$getState.isSearchStalled;
var searchResults = {
results: results,
searching: searching,
error: error,
searchingForFacetValues: searchingForFacetValues,
isSearchStalled: isSearchStalled
};
return connectorDesc.getProvidedProps.call(_this2, props, widgets, searchResults, metadata, resultsFacetValues);
};
this.refine = function () {
var _connectorDesc$refine;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this2.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this2, _this2.props, _this2.context.ais.store.getState().widgets].concat(args)));
};
this.searchForFacetValues = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
_this2.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this2.props, _this2.context.ais.store.getState().widgets].concat(args)));
};
this.createURL = function () {
var _connectorDesc$refine2;
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return _this2.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this2, _this2.props, _this2.context.ais.store.getState().widgets].concat(args)));
};
this.cleanUp = function () {
var _connectorDesc$cleanU;
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this2].concat(args));
};
}, _temp;
};
}
function getIndex(context) {
return context && context.multiIndexContext ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex;
}
function getResults(searchResults, context) {
if (searchResults.results && !searchResults.results.hits) {
return searchResults.results[getIndex(context)] ? searchResults.results[getIndex(context)] : null;
} else {
return searchResults.results ? searchResults.results : null;
}
}
function hasMultipleIndex(context) {
return context && context.multiIndexContext;
}
// eslint-disable-next-line max-params
function refineValue(searchState, nextRefinement, context, resetPage, namespace) {
if (hasMultipleIndex(context)) {
return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, context, resetPage);
} else {
// When we have a multi index page with shared widgets we should also
// reset their page to 1 if the resetPage is provided. Otherwise the
// indices will always be reset
// see: https://github.com/algolia/react-instantsearch/issues/310
// see: https://github.com/algolia/react-instantsearch/issues/637
if (searchState.indices && resetPage) {
Object.keys(searchState.indices).forEach(function (targetedIndex) {
searchState = refineValue(searchState, { page: 1 }, { multiIndexContext: { targetedIndex: targetedIndex } }, true, namespace);
});
}
return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage);
}
}
function refineMultiIndex(searchState, nextRefinement, context, resetPage) {
var page = resetPage ? { page: 1 } : undefined;
var index = getIndex(context);
var state = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$1({}, index, _extends({}, searchState.indices[index], nextRefinement, page))) : _extends({}, searchState.indices, defineProperty$1({}, index, _extends({}, nextRefinement, page)));
return _extends({}, searchState, { indices: state });
}
function refineSingleIndex(searchState, nextRefinement, resetPage) {
var page = resetPage ? { page: 1 } : undefined;
return _extends({}, searchState, nextRefinement, page);
}
// eslint-disable-next-line max-params
function refineMultiIndexWithNamespace(searchState, nextRefinement, context, resetPage, namespace) {
var _babelHelpers$extends3;
var index = getIndex(context);
var page = resetPage ? { page: 1 } : undefined;
var state = has_1(searchState, 'indices.' + index) ? _extends({}, searchState.indices, defineProperty$1({}, index, _extends({}, searchState.indices[index], (_babelHelpers$extends3 = {}, defineProperty$1(_babelHelpers$extends3, namespace, _extends({}, searchState.indices[index][namespace], nextRefinement)), defineProperty$1(_babelHelpers$extends3, 'page', 1), _babelHelpers$extends3)))) : _extends({}, searchState.indices, defineProperty$1({}, index, _extends(defineProperty$1({}, namespace, nextRefinement), page)));
return _extends({}, searchState, { indices: state });
}
function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) {
var page = resetPage ? { page: 1 } : undefined;
return _extends({}, searchState, defineProperty$1({}, namespace, _extends({}, searchState[namespace], nextRefinement)), page);
}
function getNamespaceAndAttributeName(id) {
var parts = id.match(/^([^.]*)\.(.*)/);
var namespace = parts && parts[1];
var attributeName = parts && parts[2];
return { namespace: namespace, attributeName: attributeName };
}
// eslint-disable-next-line max-params
function getCurrentRefinementValue(props, searchState, context, id, defaultValue, refinementsCallback) {
var index = getIndex(context);
var _getNamespaceAndAttri = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri.namespace,
attributeName = _getNamespaceAndAttri.attributeName;
var refinements = hasMultipleIndex(context) && searchState.indices && namespace && searchState.indices['' + index] && has_1(searchState.indices['' + index][namespace], '' + attributeName) || hasMultipleIndex(context) && searchState.indices && has_1(searchState, 'indices.' + index + '.' + id) || !hasMultipleIndex(context) && namespace && has_1(searchState[namespace], attributeName) || !hasMultipleIndex(context) && has_1(searchState, id);
if (refinements) {
var currentRefinement = void 0;
if (hasMultipleIndex(context)) {
currentRefinement = namespace ? get_1(searchState.indices['' + index][namespace], attributeName) : get_1(searchState.indices[index], id);
} else {
currentRefinement = namespace ? get_1(searchState[namespace], attributeName) : get_1(searchState, id);
}
return refinementsCallback(currentRefinement);
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return defaultValue;
}
function cleanUpValue(searchState, context, id) {
var index = getIndex(context);
var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri2.namespace,
attributeName = _getNamespaceAndAttri2.attributeName;
if (hasMultipleIndex(context) && Boolean(searchState.indices)) {
return namespace ? _extends({}, searchState, {
indices: _extends({}, searchState.indices, defineProperty$1({}, index, _extends({}, searchState.indices[index], defineProperty$1({}, namespace, omit_1(searchState.indices[index][namespace], '' + attributeName)))))
}) : omit_1(searchState, 'indices.' + index + '.' + id);
} else {
return namespace ? _extends({}, searchState, defineProperty$1({}, namespace, omit_1(searchState[namespace], '' + attributeName))) : omit_1(searchState, '' + id);
}
}
function getId() {
return 'configure';
}
var connectConfigure = createConnector({
displayName: 'AlgoliaConfigure',
getProvidedProps: function getProvidedProps() {
return {};
},
getSearchParameters: function getSearchParameters(searchParameters, props) {
var items = omit_1(props, 'children');
return searchParameters.setQueryParameters(items);
},
transitionState: function transitionState(props, prevSearchState, nextSearchState) {
var id = getId();
var items = omit_1(props, 'children');
var nonPresentKeys = this._props ? difference_1(keys_1(this._props), keys_1(props)) : [];
this._props = props;
var nextValue = defineProperty$1({}, id, _extends({}, omit_1(nextSearchState[id], nonPresentKeys), items));
return refineValue(nextSearchState, nextValue, this.context);
},
cleanUp: function cleanUp(props, searchState) {
var id = getId();
var index = getIndex(this.context);
var subState = hasMultipleIndex(this.context) && searchState.indices ? searchState.indices[index] : searchState;
var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : [];
var configureState = configureKeys.reduce(function (acc, item) {
if (!props[item]) {
acc[item] = subState[id][item];
}
return acc;
}, {});
var nextValue = defineProperty$1({}, id, configureState);
return refineValue(searchState, nextValue, this.context);
}
});
var Configure = (function () {
return null;
});
/**
* Configure is a widget that lets you provide raw search parameters
* to the Algolia API.
*
* Any of the props added to this widget will be forwarded to Algolia. For more information
* on the different parameters that can be set, have a look at the
* [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters).
*
* This widget can be used either with react-dom and react-native. It will not render anything
* on screen, only configure some parameters.
*
* Read more in the [Search parameters](guide/Search_parameters.html) guide.
* @name Configure
* @kind widget
* @example
* import React from 'react';
* import { InstantSearch, Configure, Hits } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Configure hitsPerPage={5} />
* <Hits />
* </InstantSearch>
* );
*/
var Configure$1 = connectConfigure(Configure);
/**
* connectCurrentRefinements connector provides the logic to build a widget that will
* give the user the ability to remove all or some of the filters that were
* set.
* @name connectCurrentRefinements
* @kind connector
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {function} [clearsQuery=false] - Pass true to also clear the search query
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {array.<{label: string, attribute: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attribute` and `currentRefinement` are metadata containing row values.
* @providedPropType {string} query - the search query
*/
var connectCurrentRefinements = createConnector({
displayName: 'AlgoliaCurrentRefinements',
propTypes: {
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) {
var items = metadata.reduce(function (res, meta) {
if (typeof meta.items !== 'undefined') {
if (!props.clearsQuery && meta.id === 'query') {
return res;
} else {
if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') {
return res;
}
return res.concat(meta.items.map(function (item) {
return _extends({}, item, {
id: meta.id,
index: meta.index
});
}));
}
}
return res;
}, []);
return {
items: props.transformItems ? props.transformItems(items) : items,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, items) {
// `value` corresponds to our internal clear function computed in each connector metadata.
var refinementsToClear = items instanceof Array ? items.map(function (item) {
return item.value;
}) : [items];
return refinementsToClear.reduce(function (res, clear) {
return clear(res);
}, searchState);
}
});
var PanelCallbackHandler = function (_Component) {
inherits(PanelCallbackHandler, _Component);
function PanelCallbackHandler() {
classCallCheck(this, PanelCallbackHandler);
return possibleConstructorReturn(this, (PanelCallbackHandler.__proto__ || Object.getPrototypeOf(PanelCallbackHandler)).apply(this, arguments));
}
createClass(PanelCallbackHandler, [{
key: 'componentWillMount',
value: function componentWillMount() {
if (this.context.setCanRefine) {
this.context.setCanRefine(this.props.canRefine);
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.context.setCanRefine && this.props.canRefine !== nextProps.canRefine) {
this.context.setCanRefine(nextProps.canRefine);
}
}
}, {
key: 'render',
value: function render() {
return this.props.children;
}
}]);
return PanelCallbackHandler;
}(React.Component);
PanelCallbackHandler.propTypes = {
children: propTypes.node.isRequired,
canRefine: propTypes.bool.isRequired
};
PanelCallbackHandler.contextTypes = {
setCanRefine: propTypes.func
};
var classnames = createCommonjsModule(function (module) {
/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if ('object' !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (typeof undefined === 'function' && typeof undefined.amd === 'object' && undefined.amd) {
// register as 'classnames', consistent with npm package name
undefined('classnames', [], function () {
return classNames;
});
} else {
window.classNames = classNames;
}
}());
});
var configManagerPropType = propTypes.shape({
register: propTypes.func.isRequired,
swap: propTypes.func.isRequired,
unregister: propTypes.func.isRequired
});
var stateManagerPropType = propTypes.shape({
createURL: propTypes.func.isRequired,
setState: propTypes.func.isRequired,
getState: propTypes.func.isRequired,
unlisten: propTypes.func.isRequired
});
var withKeysPropType = function withKeysPropType(keys) {
return function (props, propName, componentName) {
var prop = props[propName];
if (prop) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(prop)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
if (keys.indexOf(key) === -1) {
return new Error('Unknown `' + propName + '` key `' + key + '`. Check the render method ' + ('of `' + componentName + '`.'));
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
return undefined;
};
};
function translatable(defaultTranslations) {
return function (Composed) {
function Translatable(props) {
var translations = props.translations,
otherProps = objectWithoutProperties(props, ['translations']);
var translate = function translate(key) {
for (var _len = arguments.length, params = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
var translation = translations && has_1(translations, key) ? translations[key] : defaultTranslations[key];
if (typeof translation === 'function') {
return translation.apply(undefined, params);
}
return translation;
};
return React__default.createElement(Composed, _extends({ translate: translate }, otherProps));
}
Translatable.displayName = 'Translatable(' + getDisplayName(Composed) + ')';
Translatable.propTypes = {
translations: withKeysPropType(Object.keys(defaultTranslations))
};
return Translatable;
};
}
var createClassNames = function createClassNames(block) {
var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'ais';
return function () {
for (var _len = arguments.length, elements = Array(_len), _key = 0; _key < _len; _key++) {
elements[_key] = arguments[_key];
}
var suitElements = elements.filter(function (element) {
return element || element === '';
}).map(function (element) {
var baseClassName = prefix + '-' + block;
return element ? baseClassName + '-' + element : baseClassName;
});
return classnames(suitElements);
};
};
var cx = createClassNames('CurrentRefinements');
var CurrentRefinements = function CurrentRefinements(_ref) {
var items = _ref.items,
canRefine = _ref.canRefine,
refine = _ref.refine,
translate = _ref.translate,
className = _ref.className;
return React__default.createElement(
'div',
{ className: classnames(cx('', !canRefine && '-noRefinement'), className) },
React__default.createElement(
'ul',
{ className: cx('list', !canRefine && 'list--noRefinement') },
items.map(function (item) {
return React__default.createElement(
'li',
{ key: item.label, className: cx('item') },
React__default.createElement(
'span',
{ className: cx('label') },
item.label
),
item.items ? item.items.map(function (nest) {
return React__default.createElement(
'span',
{ key: nest.label, className: cx('category') },
React__default.createElement(
'span',
{ className: cx('categoryLabel') },
nest.label
),
React__default.createElement(
'button',
{
className: cx('delete'),
onClick: function onClick() {
return refine(nest.value);
}
},
translate('clearFilter', nest)
)
);
}) : React__default.createElement(
'span',
{ className: cx('category') },
React__default.createElement(
'button',
{
className: cx('delete'),
onClick: function onClick() {
return refine(item.value);
}
},
translate('clearFilter', item)
)
)
);
})
)
);
};
var itemPropTypes = propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.func.isRequired,
items: function items() {
return itemPropTypes.apply(undefined, arguments);
}
}));
CurrentRefinements.propTypes = {
items: itemPropTypes.isRequired,
canRefine: propTypes.bool.isRequired,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
className: propTypes.string
};
CurrentRefinements.defaultProps = {
className: ''
};
var CurrentRefinements$1 = translatable({
clearFilter: '✕'
})(CurrentRefinements);
/**
* The CurrentRefinements widget displays the list of currently applied filters.
*
* It allows the user to selectively remove them.
* @name CurrentRefinements
* @kind widget
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-CurrentRefinements - the root div of the widget
* @themeKey ais-CurrentRefinements--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-CurrentRefinements-list - the list of all refined items
* @themeKey ais-CurrentRefinements-list--noRefinement - the list of all refined items when there is no refinement
* @themeKey ais-CurrentRefinements-item - the refined list item
* @themeKey ais-CurrentRefinements-button - the button of each refined list item
* @themeKey ais-CurrentRefinements-label - the refined list label
* @themeKey ais-CurrentRefinements-category - the category of each item
* @themeKey ais-CurrentRefinements-categoryLabel - the label of each catgory
* @themeKey ais-CurrentRefinements-delete - the delete button of each label
* @translationKey clearFilter - the remove filter button label
* @example
* import React from 'react';
* import { InstantSearch, CurrentRefinements, RefinementList } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <CurrentRefinements />
* <RefinementList
* attribute="colors"
* defaultRefinement={['Black']}
* />
* </InstantSearch>
* );
*/
var CurrentRefinementsWidget = function CurrentRefinementsWidget(props) {
return React__default.createElement(
PanelCallbackHandler,
props,
React__default.createElement(CurrentRefinements$1, props)
);
};
var CurrentRefinements$2 = connectCurrentRefinements(CurrentRefinementsWidget);
var getId$1 = function getId(props) {
return props.attributes[0];
};
var namespace = 'hierarchicalMenu';
function getCurrentRefinement(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, namespace + '.' + getId$1(props), null, function (currentRefinement) {
if (currentRefinement === '') {
return null;
}
return currentRefinement;
});
}
function getValue$1(path, props, searchState, context) {
var id = props.id,
attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel;
var currentRefinement = getCurrentRefinement(props, searchState, context);
var nextRefinement = void 0;
if (currentRefinement === null) {
nextRefinement = path;
} else {
var tmpSearchParameters = new algoliasearchHelper_4({
hierarchicalFacets: [{
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}]
});
nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0];
}
return nextRefinement;
}
function transformValue(value, props, searchState, context) {
return value.map(function (v) {
return {
label: v.name,
value: getValue$1(v.path, props, searchState, context),
count: v.count,
isRefined: v.isRefined,
items: v.data && transformValue(v.data, props, searchState, context)
};
});
}
var truncate = function truncate() {
var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
return items.slice(0, limit).map(function () {
var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Array.isArray(item.items) ? _extends({}, item, {
items: truncate(item.items, limit)
}) : item;
});
};
function _refine(props, searchState, nextRefinement, context) {
var id = getId$1(props);
var nextValue = defineProperty$1({}, id, nextRefinement || '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace);
}
function _cleanUp(props, searchState, context) {
return cleanUpValue(searchState, context, namespace + '.' + getId$1(props));
}
var sortBy = ['name:asc'];
/**
* connectHierarchicalMenu connector provides the logic to build a widget that will
* give the user the ability to explore a tree-like structure.
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
* @name connectHierarchicalMenu
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limit and showMoreLimit.
* @propType {number} [limit=10] - The maximum number of items displayed.
* @propType {number} [showMoreLimit=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string[]} [rootPath=null] - The already selected and hidden path.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items.
*/
var connectHierarchicalMenu = createConnector({
displayName: 'AlgoliaHierarchicalMenu',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings');
}
return undefined;
},
separator: propTypes.string,
rootPath: propTypes.string,
showParentLevel: propTypes.bool,
defaultRefinement: propTypes.string,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
transformItems: propTypes.func
},
defaultProps: {
showMore: false,
limit: 10,
showMoreLimit: 20,
separator: ' > ',
rootPath: null,
showParentLevel: true
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var showMore = props.showMore,
limit = props.limit,
showMoreLimit = props.showMoreLimit;
var id = getId$1(props);
var results = getResults(searchResults, this.context);
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
currentRefinement: getCurrentRefinement(props, searchState, this.context),
canRefine: false
};
}
var itemsLimit = showMore ? showMoreLimit : limit;
var value = results.getFacetValues(id, { sortBy: sortBy });
var items = value.data ? transformValue(value.data, props, searchState, this.context) : [];
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: truncate(transformedItems, itemsLimit),
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,
limit = props.limit,
showMoreLimit = props.showMoreLimit;
var id = getId$1(props);
var itemsLimit = showMore ? showMoreLimit : limit;
searchParameters = searchParameters.addHierarchicalFacet({
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}).setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, itemsLimit)
});
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
if (currentRefinement !== null) {
searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var rootAttribute = props.attributes[0];
var id = getId$1(props);
var currentRefinement = getCurrentRefinement(props, searchState, this.context);
return {
id: id,
index: getIndex(this.context),
items: !currentRefinement ? [] : [{
label: rootAttribute + ': ' + currentRefinement,
attribute: rootAttribute,
value: function value(nextState) {
return _refine(props, nextState, '', _this.context);
},
currentRefinement: currentRefinement
}]
};
}
});
var cx$1 = createClassNames('SearchBox');
var defaultLoadingIndicator = React__default.createElement(
'svg',
{
width: '18',
height: '18',
viewBox: '0 0 38 38',
xmlns: 'http://www.w3.org/2000/svg',
stroke: '#444',
className: cx$1('loadingIcon')
},
React__default.createElement(
'g',
{ fill: 'none', fillRule: 'evenodd' },
React__default.createElement(
'g',
{ transform: 'translate(1 1)', strokeWidth: '2' },
React__default.createElement('circle', { strokeOpacity: '.5', cx: '18', cy: '18', r: '18' }),
React__default.createElement(
'path',
{ d: 'M36 18c0-9.94-8.06-18-18-18' },
React__default.createElement('animateTransform', {
attributeName: 'transform',
type: 'rotate',
from: '0 18 18',
to: '360 18 18',
dur: '1s',
repeatCount: 'indefinite'
})
)
)
)
);
var defaultReset = React__default.createElement(
'svg',
{
className: cx$1('resetIcon'),
xmlns: 'http://www.w3.org/2000/svg',
viewBox: '0 0 20 20',
width: '10',
height: '10'
},
React__default.createElement('path', { d: 'M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z' })
);
var defaultSubmit = React__default.createElement(
'svg',
{
className: cx$1('submitIcon'),
xmlns: 'http://www.w3.org/2000/svg',
width: '10',
height: '10',
viewBox: '0 0 40 40'
},
React__default.createElement('path', { d: 'M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z' })
);
var SearchBox = function (_Component) {
inherits(SearchBox, _Component);
function SearchBox(props) {
classCallCheck(this, SearchBox);
var _this = possibleConstructorReturn(this, (SearchBox.__proto__ || Object.getPrototypeOf(SearchBox)).call(this));
_this.getQuery = function () {
return _this.props.searchAsYouType ? _this.props.currentRefinement : _this.state.query;
};
_this.onInputMount = function (input) {
_this.input = input;
if (_this.props.__inputRef) {
_this.props.__inputRef(input);
}
};
_this.onKeyDown = function (e) {
if (!_this.props.focusShortcuts) {
return;
}
var shortcuts = _this.props.focusShortcuts.map(function (key) {
return typeof key === 'string' ? key.toUpperCase().charCodeAt(0) : key;
});
var elt = e.target || e.srcElement;
var tagName = elt.tagName;
if (elt.isContentEditable || tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA') {
// already in an input
return;
}
var which = e.which || e.keyCode;
if (shortcuts.indexOf(which) === -1) {
// not the right shortcut
return;
}
_this.input.focus();
e.stopPropagation();
e.preventDefault();
};
_this.onSubmit = function (e) {
e.preventDefault();
e.stopPropagation();
_this.input.blur();
var _this$props = _this.props,
refine = _this$props.refine,
searchAsYouType = _this$props.searchAsYouType;
if (!searchAsYouType) {
refine(_this.getQuery());
}
return false;
};
_this.onChange = function (event) {
var _this$props2 = _this.props,
searchAsYouType = _this$props2.searchAsYouType,
refine = _this$props2.refine,
onChange = _this$props2.onChange;
var value = event.target.value;
if (searchAsYouType) {
refine(value);
} else {
_this.setState({ query: value });
}
if (onChange) {
onChange(event);
}
};
_this.onReset = function (event) {
var _this$props3 = _this.props,
searchAsYouType = _this$props3.searchAsYouType,
refine = _this$props3.refine,
onReset = _this$props3.onReset;
refine('');
_this.input.focus();
if (!searchAsYouType) {
_this.setState({ query: '' });
}
if (onReset) {
onReset(event);
}
};
_this.state = {
query: props.searchAsYouType ? null : props.currentRefinement
};
return _this;
}
createClass(SearchBox, [{
key: 'componentDidMount',
value: function componentDidMount() {
document.addEventListener('keydown', this.onKeyDown);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
document.removeEventListener('keydown', this.onKeyDown);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
// Reset query when the searchParameters query has changed.
// This is kind of an anti-pattern (props in state), but it works here
// since we know for sure that searchParameters having changed means a
// new search has been triggered.
if (!nextProps.searchAsYouType && nextProps.currentRefinement !== this.props.currentRefinement) {
this.setState({
query: nextProps.currentRefinement
});
}
}
// From https://github.com/algolia/autocomplete.js/pull/86
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props,
className = _props.className,
translate = _props.translate,
autoFocus = _props.autoFocus,
loadingIndicator = _props.loadingIndicator,
submit = _props.submit,
reset = _props.reset;
var query = this.getQuery();
var searchInputEvents = Object.keys(this.props).reduce(function (props, prop) {
if (['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) === -1 && prop.indexOf('on') === 0) {
return _extends({}, props, defineProperty$1({}, prop, _this2.props[prop]));
}
return props;
}, {});
var isSearchStalled = this.props.showLoadingIndicator && this.props.isSearchStalled;
/* eslint-disable max-len */
return React__default.createElement(
'div',
{ className: classnames(cx$1(''), className) },
React__default.createElement(
'form',
{
noValidate: true,
onSubmit: this.props.onSubmit ? this.props.onSubmit : this.onSubmit,
onReset: this.onReset,
className: cx$1('form', isSearchStalled && 'form--stalledSearch'),
action: '',
role: 'search'
},
React__default.createElement('input', _extends({
ref: this.onInputMount,
type: 'search',
placeholder: translate('placeholder'),
autoFocus: autoFocus,
autoComplete: 'off',
autoCorrect: 'off',
autoCapitalize: 'off',
spellCheck: 'false',
required: true,
maxLength: '512',
value: query,
onChange: this.onChange
}, searchInputEvents, {
className: cx$1('input')
})),
React__default.createElement(
'button',
{
type: 'submit',
title: translate('submitTitle'),
className: cx$1('submit')
},
submit
),
React__default.createElement(
'button',
{
type: 'reset',
title: translate('resetTitle'),
className: cx$1('reset'),
hidden: !query || isSearchStalled
},
reset
),
this.props.showLoadingIndicator && React__default.createElement(
'span',
{ hidden: !isSearchStalled, className: cx$1('loadingIndicator') },
loadingIndicator
)
)
);
/* eslint-enable */
}
}]);
return SearchBox;
}(React.Component);
SearchBox.propTypes = {
currentRefinement: propTypes.string,
className: propTypes.string,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
loadingIndicator: propTypes.node,
reset: propTypes.node,
submit: propTypes.node,
focusShortcuts: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])),
autoFocus: propTypes.bool,
searchAsYouType: propTypes.bool,
onSubmit: propTypes.func,
onReset: propTypes.func,
onChange: propTypes.func,
isSearchStalled: propTypes.bool,
showLoadingIndicator: propTypes.bool,
// For testing purposes
__inputRef: propTypes.func
};
SearchBox.defaultProps = {
currentRefinement: '',
className: '',
focusShortcuts: ['s', '/'],
autoFocus: false,
searchAsYouType: true,
showLoadingIndicator: false,
isSearchStalled: false,
loadingIndicator: defaultLoadingIndicator,
reset: defaultReset,
submit: defaultSubmit
};
var SearchBox$1 = translatable({
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(SearchBox);
var itemsPropType = propTypes.arrayOf(propTypes.shape({
value: propTypes.any,
label: propTypes.node.isRequired,
items: function items() {
return itemsPropType.apply(undefined, arguments);
}
}));
var List = function (_Component) {
inherits(List, _Component);
function List() {
classCallCheck(this, List);
var _this = possibleConstructorReturn(this, (List.__proto__ || Object.getPrototypeOf(List)).call(this));
_this.onShowMoreClick = function () {
_this.setState(function (state) {
return {
extended: !state.extended
};
});
};
_this.getLimit = function () {
var _this$props = _this.props,
limit = _this$props.limit,
showMoreLimit = _this$props.showMoreLimit;
var extended = _this.state.extended;
return extended ? showMoreLimit : limit;
};
_this.resetQuery = function () {
_this.setState({ query: '' });
};
_this.renderItem = function (item, resetQuery) {
var items = item.items && React__default.createElement(
'ul',
{ className: _this.props.cx('list', 'list--child') },
item.items.slice(0, _this.getLimit()).map(function (child) {
return _this.renderItem(child, item);
})
);
return React__default.createElement(
'li',
{
key: item.key || item.label,
className: _this.props.cx('item', item.isRefined && 'item--selected', item.noRefinement && 'item--noRefinement', items && 'item--parent')
},
_this.props.renderItem(item, resetQuery),
items
);
};
_this.state = {
extended: false,
query: ''
};
return _this;
}
createClass(List, [{
key: 'renderShowMore',
value: function renderShowMore() {
var _props = this.props,
showMore = _props.showMore,
translate = _props.translate,
cx = _props.cx;
var extended = this.state.extended;
var disabled = this.props.limit >= this.props.items.length;
if (!showMore) {
return null;
}
return React__default.createElement(
'button',
{
disabled: disabled,
className: cx('showMore', disabled && 'showMore--disabled'),
onClick: this.onShowMoreClick
},
translate('showMore', extended)
);
}
}, {
key: 'renderSearchBox',
value: function renderSearchBox() {
var _this2 = this;
var _props2 = this.props,
cx = _props2.cx,
searchForItems = _props2.searchForItems,
isFromSearch = _props2.isFromSearch,
translate = _props2.translate,
items = _props2.items,
selectItem = _props2.selectItem;
var noResults = items.length === 0 && this.state.query !== '' ? React__default.createElement(
'div',
{ className: cx('noResults') },
translate('noResults')
) : null;
return React__default.createElement(
'div',
{ className: cx('searchBox') },
React__default.createElement(SearchBox$1, {
currentRefinement: this.state.query,
refine: function refine(value) {
_this2.setState({ query: value });
searchForItems(value);
},
focusShortcuts: [],
translate: translate,
onSubmit: function onSubmit(e) {
e.preventDefault();
e.stopPropagation();
if (isFromSearch) {
selectItem(items[0], _this2.resetQuery);
}
}
}),
noResults
);
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var _props3 = this.props,
cx = _props3.cx,
items = _props3.items,
className = _props3.className,
searchable = _props3.searchable,
canRefine = _props3.canRefine;
var searchBox = searchable ? this.renderSearchBox() : null;
var rootClassName = classnames(cx('', !canRefine && '-noRefinement'), className);
if (items.length === 0) {
return React__default.createElement(
'div',
{ className: rootClassName },
searchBox
);
}
// Always limit the number of items we show on screen, since the actual
// number of retrieved items might vary with the `maxValuesPerFacet` config
// option.
return React__default.createElement(
'div',
{ className: rootClassName },
searchBox,
React__default.createElement(
'ul',
{ className: cx('list', !canRefine && 'list--noRefinement') },
items.slice(0, this.getLimit()).map(function (item) {
return _this3.renderItem(item, _this3.resetQuery);
})
),
this.renderShowMore()
);
}
}]);
return List;
}(React.Component);
List.propTypes = {
cx: propTypes.func.isRequired,
// Only required with showMore.
translate: propTypes.func,
items: itemsPropType,
renderItem: propTypes.func.isRequired,
selectItem: propTypes.func,
className: propTypes.string,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
show: propTypes.func,
searchForItems: propTypes.func,
searchable: propTypes.bool,
isFromSearch: propTypes.bool,
canRefine: propTypes.bool
};
List.defaultProps = {
className: '',
isFromSearch: false
};
var Link = function (_Component) {
inherits(Link, _Component);
function Link() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, Link);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Link.__proto__ || Object.getPrototypeOf(Link)).call.apply(_ref, [this].concat(args))), _this), _this.onClick = function (e) {
if (isSpecialClick(e)) {
return;
}
_this.props.onClick();
e.preventDefault();
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(Link, [{
key: 'render',
value: function render() {
return React__default.createElement('a', _extends({}, omit_1(this.props, 'onClick'), { onClick: this.onClick }));
}
}]);
return Link;
}(React.Component);
Link.propTypes = {
onClick: propTypes.func.isRequired
};
var cx$2 = createClassNames('HierarchicalMenu');
var itemsPropType$1 = propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string,
count: propTypes.number.isRequired,
items: function items() {
return itemsPropType$1.apply(undefined, arguments);
}
}));
var HierarchicalMenu = function (_Component) {
inherits(HierarchicalMenu, _Component);
function HierarchicalMenu() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, HierarchicalMenu);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = HierarchicalMenu.__proto__ || Object.getPrototypeOf(HierarchicalMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) {
var _this$props = _this.props,
createURL = _this$props.createURL,
refine = _this$props.refine;
return React__default.createElement(
Link,
{
className: cx$2('link'),
onClick: function onClick() {
return refine(item.value);
},
href: createURL(item.value)
},
React__default.createElement(
'span',
{ className: cx$2('label') },
item.label
),
' ',
React__default.createElement(
'span',
{ className: cx$2('count') },
item.count
)
);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(HierarchicalMenu, [{
key: 'render',
value: function render() {
return React__default.createElement(List, _extends({
renderItem: this.renderItem,
cx: cx$2
}, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isEmpty', 'canRefine', 'className'])));
}
}]);
return HierarchicalMenu;
}(React.Component);
HierarchicalMenu.propTypes = {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
canRefine: propTypes.bool.isRequired,
items: itemsPropType$1,
showMore: propTypes.bool,
className: propTypes.string,
limit: propTypes.number,
showMoreLimit: propTypes.number,
transformItems: propTypes.func
};
HierarchicalMenu.defaultProps = {
className: ''
};
var HierarchicalMenu$1 = translatable({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
}
})(HierarchicalMenu);
/**
* The hierarchical menu lets the user browse attributes using a tree-like structure.
*
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
*
* @name HierarchicalMenu
* @kind widget
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* [{
* "objectID": "321432",
* "name": "lemon",
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* },
* {
* "objectID": "8976987",
* "name": "orange",
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* }]
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "objectID": "321432",
* "name": "lemon",
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limit and showMoreLimit.
* @propType {number} [limit=10] - The maximum number of items displayed.
* @propType {number} [showMoreLimit=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string[]} [rootPath=null] - The already selected and hidden path.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-HierarchicalMenu - the root div of the widget
* @themeKey ais-HierarchicalMenu-noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-HierarchicalMenu-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @themeKey ais-HierarchicalMenu-list - the list of menu items
* @themeKey ais-HierarchicalMenu-list--child - the child list of menu items
* @themeKey ais-HierarchicalMenu-item - the menu list item
* @themeKey ais-HierarchicalMenu-item--selected - the selected menu list item
* @themeKey ais-HierarchicalMenu-item--parent - the menu list item containing children
* @themeKey ais-HierarchicalMenu-link - the clickable menu element
* @themeKey ais-HierarchicalMenu-label - the label of each item
* @themeKey ais-HierarchicalMenu-count - the count of values for each item
* @themeKey ais-HierarchicalMenu-showMore - the button used to display more categories
* @themeKey ais-HierarchicalMenu-showMore--disabled - the disabled button used to display more categories
* @translationKey showMore - The label of the show more button. Accepts one parameter, a boolean that is true if the values are expanded
* @example
* import React from 'react';
* import { InstantSearch, HierarchicalMenu } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <HierarchicalMenu
* attributes={[
* 'category',
* 'sub_category',
* 'sub_sub_category',
* ]}
* />
* </InstantSearch>
* );
*/
var HierarchicalMenuWidget = function HierarchicalMenuWidget(props) {
return React__default.createElement(
PanelCallbackHandler,
props,
React__default.createElement(HierarchicalMenu$1, props)
);
};
var HierarchicalMenu$2 = connectHierarchicalMenu(HierarchicalMenuWidget);
/**
* Find an highlighted attribute given an `attribute` and an `highlightProperty`, parses it,
* and provided an array of objects with the string value and a boolean if this
* value is highlighted.
*
* In order to use this feature, highlight must be activated in the configuration of
* the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and
* highligtPostTag in Algolia configuration.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightProperty - the property that contains the highlight structure in the results
* @param {string} attribute - the highlighted attribute to look for
* @param {object} hit - the actual hit returned by Algolia.
* @return {object[]} - An array of {value: string, isHighlighted: boolean}.
*/
function parseAlgoliaHit(_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,
attribute = _ref.attribute,
hit = _ref.hit;
if (!hit) throw new Error('`hit`, the matching record, must be provided');
var highlightObject = get_1(hit[highlightProperty], attribute, {});
if (Array.isArray(highlightObject)) {
return highlightObject.map(function (item) {
return parseHighlightedAttribute({
preTag: preTag,
postTag: postTag,
highlightedValue: item.value
});
});
}
return parseHighlightedAttribute({
preTag: preTag,
postTag: postTag,
highlightedValue: highlightObject.value
});
}
/**
* 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,
_ref2$highlightedValu = _ref2.highlightedValue,
highlightedValue = _ref2$highlightedValu === undefined ? '' : _ref2$highlightedValu;
var splitByPreTag = highlightedValue.split(preTag);
var firstValue = splitByPreTag.shift();
var elements = firstValue === '' ? [] : [{ value: firstValue, isHighlighted: false }];
if (postTag === preTag) {
var isHighlighted = true;
splitByPreTag.forEach(function (split) {
elements.push({ value: split, isHighlighted: isHighlighted });
isHighlighted = !isHighlighted;
});
} else {
splitByPreTag.forEach(function (split) {
var splitByPostTag = split.split(postTag);
elements.push({
value: splitByPostTag[0],
isHighlighted: true
});
if (splitByPostTag[1] !== '') {
elements.push({
value: splitByPostTag[1],
isHighlighted: false
});
}
});
}
return elements;
}
var highlight = function highlight(_ref) {
var attribute = _ref.attribute,
hit = _ref.hit,
highlightProperty = _ref.highlightProperty;
return parseAlgoliaHit({
attribute: attribute,
hit: hit,
preTag: highlightTags.highlightPreTag,
postTag: highlightTags.highlightPostTag,
highlightProperty: highlightProperty
});
};
/**
* connectHighlight connector provides the logic to create an highlighter
* component that will retrieve, parse and render an highlighted attribute
* from an Algolia hit.
* @name connectHighlight
* @kind connector
* @category connector
* @providedPropType {function} highlight - function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attributes: `highlightProperty` which is the property that contains the highlight structure from the records, `attribute` which is the name of the attribute (it can be either a string or an array of strings) to look for and `hit` which is the hit from Algolia. It returns an array of objects `{value: string, isHighlighted: boolean}`. If the element that corresponds to the attribute is an array of strings, it will return a nested array of objects.
* @example
* import React from 'react';
* import { InstantSearch, SearchBox, Hits } from 'react-instantsearch/dom';
* import { connectHighlight } from 'react-instantsearch/connectors';
*
* const CustomHighlight = connectHighlight(
* ({ highlight, attribute, hit, highlightProperty }) => {
* const highlights = highlight({
* highlightProperty: '_highlightResult',
* attribute,
* hit
* });
*
* return highlights.map(part => part.isHighlighted ? (
* <mark>{part.value}</mark>
* ) : (
* <span>{part.value}</span>
* ));
* }
* );
*
* const Hit = ({ hit }) => (
* <p>
* <CustomHighlight attribute="name" hit={hit} />
* </p>
* );
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SearchBox defaultRefinement="legi" />
* <Hits hitComponent={Hit} />
* </InstantSearch>
* );
*/
var connectHighlight = createConnector({
displayName: 'AlgoliaHighlighter',
propTypes: {},
getProvidedProps: function getProvidedProps() {
return { highlight: highlight };
}
});
function generateKey(i, value) {
return 'split-' + i + '-' + value;
}
var Highlight = function Highlight(_ref) {
var cx = _ref.cx,
value = _ref.value,
highlightedTagName = _ref.highlightedTagName,
isHighlighted = _ref.isHighlighted,
nonHighlightedTagName = _ref.nonHighlightedTagName;
var TagName = isHighlighted ? highlightedTagName : nonHighlightedTagName;
var className = isHighlighted ? 'highlighted' : 'nonHighlighted';
return React__default.createElement(
TagName,
{ className: cx(className) },
value
);
};
Highlight.propTypes = {
cx: propTypes.func.isRequired,
value: propTypes.string.isRequired,
isHighlighted: propTypes.bool.isRequired,
highlightedTagName: propTypes.string.isRequired,
nonHighlightedTagName: propTypes.string.isRequired
};
var Highlighter = function Highlighter(_ref2) {
var cx = _ref2.cx,
hit = _ref2.hit,
attribute = _ref2.attribute,
highlight = _ref2.highlight,
highlightProperty = _ref2.highlightProperty,
tagName = _ref2.tagName,
nonHighlightedTagName = _ref2.nonHighlightedTagName,
separator = _ref2.separator,
className = _ref2.className;
var parsedHighlightedValue = highlight({
hit: hit,
attribute: attribute,
highlightProperty: highlightProperty
});
return React__default.createElement(
'span',
{ className: classnames(cx(''), className) },
parsedHighlightedValue.map(function (item, i) {
if (Array.isArray(item)) {
var isLast = i === parsedHighlightedValue.length - 1;
return React__default.createElement(
'span',
{ key: generateKey(i, hit[attribute][i]) },
item.map(function (element, index) {
return React__default.createElement(Highlight, {
cx: cx,
key: generateKey(index, element.value),
value: element.value,
highlightedTagName: tagName,
nonHighlightedTagName: nonHighlightedTagName,
isHighlighted: element.isHighlighted
});
}),
!isLast && React__default.createElement(
'span',
{ className: cx('separator') },
separator
)
);
}
return React__default.createElement(Highlight, {
cx: cx,
key: generateKey(i, item.value),
value: item.value,
highlightedTagName: tagName,
nonHighlightedTagName: nonHighlightedTagName,
isHighlighted: item.isHighlighted
});
})
);
};
Highlighter.propTypes = {
cx: propTypes.func.isRequired,
hit: propTypes.object.isRequired,
attribute: propTypes.string.isRequired,
highlight: propTypes.func.isRequired,
highlightProperty: propTypes.string.isRequired,
tagName: propTypes.string,
nonHighlightedTagName: propTypes.string,
className: propTypes.string,
separator: propTypes.node
};
Highlighter.defaultProps = {
tagName: 'em',
nonHighlightedTagName: 'span',
className: '',
separator: ', '
};
var cx$3 = createClassNames('Highlight');
var Highlight$1 = function Highlight$$1(props) {
return React__default.createElement(Highlighter, _extends({}, props, { highlightProperty: '_highlightResult', cx: cx$3 }));
};
/**
* Renders any attribute from a hit into its highlighted form when relevant.
*
* Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide.
* @name Highlight
* @kind widget
* @propType {string} attribute - location of the highlighted attribute in the hit (the corresponding element can be either a string or an array of strings)
* @propType {object} hit - hit object containing the highlighted attribute
* @propType {string} [tagName='em'] - tag to be used for highlighted parts of the hit
* @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted
* @propType {node} [separator=',<space>'] - symbol used to separate the elements of the array in case the attribute points to an array of strings.
* @themeKey ais-Highlight - root of the component
* @themeKey ais-Highlight-highlighted - part of the text which is highlighted
* @themeKey ais-Highlight-nonHighlighted - part of the text that is not highlighted
* @example
* import React from 'react';
* import { InstantSearch, SearchBox, Hits, Highlight } from 'react-instantsearch/dom';
*
* const Hit = ({ hit }) => (
* <div>
* <Highlight attribute="name" hit={hit} />
* </div>
* );
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SearchBox defaultRefinement="Legi" />
* <Hits hitComponent={Hit} />
* </InstantSearch>
* );
*/
var Highlight$2 = connectHighlight(Highlight$1);
var cx$4 = createClassNames('Snippet');
var Snippet = function Snippet(props) {
return React__default.createElement(Highlighter, _extends({}, props, { highlightProperty: '_snippetResult', cx: cx$4 }));
};
/**
* Renders any attribute from an hit into its highlighted snippet form when relevant.
*
* Read more about it in the [Highlighting results](guide/Highlighting_results.html) guide.
* @name Snippet
* @kind widget
* @requirements To use this widget, the attribute name passed to the `attribute` prop must be
* present in "Attributes to snippet" on the Algolia dashboard or configured as `attributesToSnippet`
* via a set settings call to the Algolia API.
* @propType {string} attribute - location of the highlighted snippet attribute in the hit (the corresponding element can be either a string or an array of strings)
* @propType {object} hit - hit object containing the highlighted snippet attribute
* @propType {string} [tagName='em'] - tag to be used for highlighted parts of the attribute
* @propType {string} [nonHighlightedTagName='span'] - tag to be used for the parts of the hit that are not highlighted
* @propType {node} [separator=',<space>'] - symbol used to separate the elements of the array in case the attribute points to an array of strings.
* @themeKey ais-Snippet - the root span of the widget
* @themeKey ais-Snippet-highlighted - the highlighted text
* @themeKey ais-Snippet-nonHighlighted - the normal text
* @example
* import React from 'react';
* import { InstantSearch, SearchBox, Hits, Snippet } from 'react-instantsearch/dom';
*
* const Hit = ({ hit }) => (
* <div>
* <Snippet attribute="description" hit={hit} />
* </div>
* );
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SearchBox defaultRefinement="adjustable" />
* <Hits hitComponent={Hit} />
* </InstantSearch>
* );
*/
var Snippet$1 = connectHighlight(Snippet);
/**
* connectHits connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* prop to a [Configure](guide/Search_parameters.html) widget.
*
* **Warning:** you will need to use the **objectID** property available on every hit as a key
* when iterating over them. This will ensure you have the best possible UI experience
* especially on slow networks.
* @name connectHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @example
* import React from 'react';
* import { InstantSearch, Highlight } from 'react-instantsearch/dom';
* import { connectHits } from 'react-instantsearch/connectors';
*
* const CustomHits = connectHits(({ hits }) => (
* <div>
* {hits.map(hit =>
* <p key={hit.objectID}>
* <Highlight attribute="name" hit={hit} />
* </p>
* )}
* </div>
* );
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <CustomHits />
* </InstantSearch>
* );
*/
var connectHits = createConnector({
displayName: 'AlgoliaHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, this.context);
var hits = results ? results.hits : [];
return { hits: hits };
},
/* Hits needs to be considered as a widget to trigger a search if no others widgets are used.
* To be considered as a widget you need either getSearchParameters, getMetadata or getTransitionState
* See createConnector.js
* */
getSearchParameters: function getSearchParameters(searchParameters) {
return searchParameters;
}
});
var cx$5 = createClassNames('Hits');
var Hits = function Hits(_ref) {
var hits = _ref.hits,
className = _ref.className,
HitComponent = _ref.hitComponent;
return (
// Spread the hit on HitComponent instead of passing the full object. BC.
// ex: <HitComponent {...hit} key={hit.objectID} />
React__default.createElement(
'div',
{ className: classnames(cx$5(''), className) },
React__default.createElement(
'ul',
{ className: cx$5('list') },
hits.map(function (hit) {
return React__default.createElement(
'li',
{ className: cx$5('item'), key: hit.objectID },
React__default.createElement(HitComponent, { hit: hit })
);
})
)
)
);
};
Hits.propTypes = {
hits: propTypes.arrayOf(propTypes.object).isRequired,
className: propTypes.string,
hitComponent: propTypes.func
};
Hits.defaultProps = {
className: '',
hitComponent: function hitComponent(props) {
return React__default.createElement(
'div',
{
style: {
borderBottom: '1px solid #bbb',
paddingBottom: '5px',
marginBottom: '5px',
wordBreak: 'break-all'
}
},
JSON.stringify(props).slice(0, 100),
'...'
);
}
};
/**
* Displays a list of hits.
*
* To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html).
*
* @name Hits
* @kind widget
* @propType {Component} [hitComponent] - Component used for rendering each hit from
* the results. If it is not provided the rendering defaults to displaying the
* hit in its JSON form. The component will be called with a `hit` prop.
* @themeKey ais-Hits - the root div of the widget
* @themeKey ais-Hits-list - the list of results
* @themeKey ais-Hits-item - the hit list item
* @example
* import React from 'react';
* import { InstantSearch, Hits } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Hits />
* </InstantSearch>
* );
*/
var Hits$1 = connectHits(Hits);
function getId$2() {
return 'hitsPerPage';
}
function getCurrentRefinement$1(props, searchState, context) {
var id = getId$2();
return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
/**
* connectHitsPerPage connector provides the logic to create connected
* components that will allow a user to choose to display more or less results from Algolia.
* @name connectHitsPerPage
* @kind connector
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {{value: number, label: string}[]} items - List of hits per page options.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
var connectHitsPerPage = createConnector({
displayName: 'AlgoliaHitsPerPage',
propTypes: {
defaultRefinement: propTypes.number.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string,
value: propTypes.number.isRequired
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement$1(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$2();
var nextValue = defineProperty$1({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, this.context, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, this.context, getId$2());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setHitsPerPage(getCurrentRefinement$1(props, searchState, this.context));
},
getMetadata: function getMetadata() {
return { id: getId$2() };
}
});
var Select = function (_Component) {
inherits(Select, _Component);
function Select() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, Select);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Select.__proto__ || Object.getPrototypeOf(Select)).call.apply(_ref, [this].concat(args))), _this), _this.onChange = function (e) {
_this.props.onSelect(e.target.value);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(Select, [{
key: 'render',
value: function render() {
var _props = this.props,
cx = _props.cx,
items = _props.items,
selectedItem = _props.selectedItem;
return React__default.createElement(
'select',
{
className: cx('select'),
value: selectedItem,
onChange: this.onChange
},
items.map(function (item) {
return React__default.createElement(
'option',
{
className: cx('option'),
key: has_1(item, 'key') ? item.key : item.value,
disabled: item.disabled,
value: item.value
},
has_1(item, 'label') ? item.label : item.value
);
})
);
}
}]);
return Select;
}(React.Component);
Select.propTypes = {
cx: propTypes.func.isRequired,
onSelect: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
value: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired,
key: propTypes.oneOfType([propTypes.string, propTypes.number]),
label: propTypes.string,
disabled: propTypes.bool
})).isRequired,
selectedItem: propTypes.oneOfType([propTypes.string, propTypes.number]).isRequired
};
var cx$6 = createClassNames('HitsPerPage');
var HitsPerPage = function (_Component) {
inherits(HitsPerPage, _Component);
function HitsPerPage() {
classCallCheck(this, HitsPerPage);
return possibleConstructorReturn(this, (HitsPerPage.__proto__ || Object.getPrototypeOf(HitsPerPage)).apply(this, arguments));
}
createClass(HitsPerPage, [{
key: 'render',
value: function render() {
var _props = this.props,
items = _props.items,
currentRefinement = _props.currentRefinement,
refine = _props.refine,
className = _props.className;
return React__default.createElement(
'div',
{ className: classnames(cx$6(''), className) },
React__default.createElement(Select, {
onSelect: refine,
selectedItem: currentRefinement,
items: items,
cx: cx$6
})
);
}
}]);
return HitsPerPage;
}(React.Component);
HitsPerPage.propTypes = {
items: propTypes.arrayOf(propTypes.shape({
value: propTypes.number.isRequired,
label: propTypes.string
})).isRequired,
currentRefinement: propTypes.number.isRequired,
refine: propTypes.func.isRequired,
className: propTypes.string
};
HitsPerPage.defaultProps = {
className: ''
};
/**
* The HitsPerPage widget displays a dropdown menu to let the user change the number
* of displayed hits.
*
* If you only want to configure the number of hits per page without
* displaying a widget, you should use the `<Configure hitsPerPage={20} />` widget. See [`<Configure />` documentation](widgets/Configure.html)
*
* @name HitsPerPage
* @kind widget
* @propType {{value: number, label: string}[]} items - List of available options.
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-HitsPerPage - the root div of the widget
* @themeKey ais-HitsPerPage-select - the select
* @themeKey ais-HitsPerPage-option - the select option
* @example
* import React from 'react';
* import { InstantSearch, HitsPerPage, Hits } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <HitsPerPage
* defaultRefinement={5}
* items={[
* { value: 5, label: 'Show 5 hits' },
* { value: 10, label: 'Show 10 hits' },
* ]}
* />
* <Hits />
* </InstantSearch>
* );
*/
var HitsPerPage$1 = connectHitsPerPage(HitsPerPage);
function getId$3() {
return 'page';
}
function getCurrentRefinement$2(props, searchState, context) {
var id = getId$3();
var page = 1;
return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
currentRefinement = parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
/**
* InfiniteHits connector provides the logic to create connected
* components that will render an continuous list of results retrieved from
* Algolia. This connector provides a function to load more results.
* @name connectInfiniteHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @providedPropType {boolean} hasMore - indicates if there are more pages to load
* @providedPropType {function} refine - call to load more results
*/
var connectInfiniteHits = createConnector({
displayName: 'AlgoliaInfiniteHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, this.context);
this._allResults = this._allResults || [];
if (!results) {
return {
hits: [],
hasMore: false
};
}
var hits = results.hits,
page = results.page,
nbPages = results.nbPages;
if (page === 0) {
this._allResults = hits;
} else if (page > this.previousPage) {
this._allResults = [].concat(toConsumableArray(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$2(props, searchState, this.context) - 1
});
},
refine: function refine(props, searchState) {
var id = getId$3();
var nextPage = getCurrentRefinement$2(props, searchState, this.context) + 1;
var nextValue = defineProperty$1({}, id, nextPage);
var resetPage = false;
return refineValue(searchState, nextValue, this.context, resetPage);
}
});
var cx$7 = createClassNames('InfiniteHits');
var InfiniteHits = function (_Component) {
inherits(InfiniteHits, _Component);
function InfiniteHits() {
classCallCheck(this, InfiniteHits);
return possibleConstructorReturn(this, (InfiniteHits.__proto__ || Object.getPrototypeOf(InfiniteHits)).apply(this, arguments));
}
createClass(InfiniteHits, [{
key: 'render',
value: function render() {
var _props = this.props,
HitComponent = _props.hitComponent,
hits = _props.hits,
hasMore = _props.hasMore,
refine = _props.refine,
translate = _props.translate,
className = _props.className;
return React__default.createElement(
'div',
{ className: classnames(cx$7(''), className) },
React__default.createElement(
'ul',
{ className: cx$7('list') },
hits.map(function (hit) {
return React__default.createElement(
'li',
{ key: hit.objectID, className: cx$7('item') },
React__default.createElement(HitComponent, { hit: hit })
);
})
),
React__default.createElement(
'button',
{
className: cx$7('loadMore', !hasMore && 'loadMore--disabled'),
onClick: function onClick() {
return refine();
},
disabled: !hasMore
},
translate('loadMore')
)
);
}
}]);
return InfiniteHits;
}(React.Component);
InfiniteHits.propTypes = {
hits: propTypes.arrayOf(propTypes.object).isRequired,
hasMore: propTypes.bool.isRequired,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
className: propTypes.string,
hitComponent: propTypes.oneOfType([propTypes.string, propTypes.func])
};
InfiniteHits.defaultProps = {
className: '',
hitComponent: function hitComponent(hit) {
return React__default.createElement(
'div',
{
style: {
borderBottom: '1px solid #bbb',
paddingBottom: '5px',
marginBottom: '5px',
wordBreak: 'break-all'
}
},
JSON.stringify(hit).slice(0, 100),
'...'
);
}
};
var InfiniteHits$1 = translatable({
loadMore: 'Load more'
})(InfiniteHits);
/**
* Displays an infinite list of hits along with a **load more** button.
*
* To configure the number of hits being shown, use the [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or the [Configure widget](widgets/Configure.html).
*
* @name InfiniteHits
* @kind widget
* @propType {Component} [hitComponent] - Component used for rendering each hit from
* the results. If it is not provided the rendering defaults to displaying the
* hit in its JSON form. The component will be called with a `hit` prop.
* @themeKey ais-InfiniteHits - the root div of the widget
* @themeKey ais-InfiniteHits-list - the list of hits
* @themeKey ais-InfiniteHits-item - the hit list item
* @themeKey ais-InfiniteHits-loadMore - the button used to display more results
* @themeKey ais-InfiniteHits-loadMore--disabled - the disabled button used to display more results
* @translationKey loadMore - the label of load more button
* @example
* import React from 'react';
* import { InstantSearch, InfiniteHits } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <InfiniteHits />
* </InstantSearch>
* );
*/
var InfiniteHits$2 = connectInfiniteHits(InfiniteHits$1);
var namespace$1 = 'menu';
function getId$4(props) {
return props.attribute;
}
function getCurrentRefinement$3(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, namespace$1 + '.' + getId$4(props), null, function (currentRefinement) {
if (currentRefinement === '') {
return null;
}
return currentRefinement;
});
}
function getValue$2(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement$3(props, searchState, context);
return name === currentRefinement ? '' : name;
}
function getLimit(_ref) {
var showMore = _ref.showMore,
limit = _ref.limit,
showMoreLimit = _ref.showMoreLimit;
return showMore ? showMoreLimit : limit;
}
function _refine$1(props, searchState, nextRefinement, context) {
var id = getId$4(props);
var nextValue = defineProperty$1({}, id, nextRefinement ? nextRefinement : '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$1);
}
function _cleanUp$1(props, searchState, context) {
return cleanUpValue(searchState, context, namespace$1 + '.' + getId$4(props));
}
var sortBy$1 = ['count:desc', 'name:asc'];
/**
* connectMenu connector provides the logic to build a widget that will
* give the user the ability to choose a single value for a specific facet.
* @name connectMenu
* @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @kind connector
* @propType {string} attribute - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limit=10] - the minimum number of diplayed items
* @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {boolean} [searchable=false] - allow search inside values
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
var connectMenu = createConnector({
displayName: 'AlgoliaMenu',
propTypes: {
attribute: propTypes.string.isRequired,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
defaultRefinement: propTypes.string,
transformItems: propTypes.func,
searchable: propTypes.bool
},
defaultProps: {
showMore: false,
limit: 10,
showMoreLimit: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) {
var _this = this;
var attribute = props.attribute,
searchable = props.searchable;
var results = getResults(searchResults, this.context);
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== '');
// Search For Facet Values is not available with derived helper (used for multi index search)
if (searchable && this.context.multiIndexContext) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement$3(props, searchState, this.context),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: canRefine
};
}
var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) {
return {
label: v.value,
value: getValue$2(v.value, props, searchState, _this.context),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attribute, { sortBy: sortBy$1 }).map(function (v) {
return {
label: v.name,
value: getValue$2(v.name, props, searchState, _this.context),
count: v.count,
isRefined: v.isRefined
};
});
var sortedItems = searchable && !isFromSearch ? orderBy_1(items, ['isRefined', 'count', 'label'], ['desc', 'desc', 'asc']) : items;
var transformedItems = props.transformItems ? props.transformItems(sortedItems) : sortedItems;
return {
items: transformedItems.slice(0, getLimit(props)),
currentRefinement: getCurrentRefinement$3(props, searchState, this.context),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$1(props, searchState, nextRefinement, this.context);
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return {
facetName: props.attribute,
query: nextRefinement,
maxFacetHits: getLimit(props)
};
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$1(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute;
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit(props))
});
searchParameters = searchParameters.addDisjunctiveFacet(attribute);
var currentRefinement = getCurrentRefinement$3(props, searchState, this.context);
if (currentRefinement !== null) {
searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this2 = this;
var id = getId$4(props);
var currentRefinement = getCurrentRefinement$3(props, searchState, this.context);
return {
id: id,
index: getIndex(this.context),
items: currentRefinement === null ? [] : [{
label: props.attribute + ': ' + currentRefinement,
attribute: props.attribute,
value: function value(nextState) {
return _refine$1(props, nextState, '', _this2.context);
},
currentRefinement: currentRefinement
}]
};
}
});
var cx$8 = createClassNames('Menu');
var Menu = function (_Component) {
inherits(Menu, _Component);
function Menu() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, Menu);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Menu.__proto__ || Object.getPrototypeOf(Menu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item, resetQuery) {
var createURL = _this.props.createURL;
var label = _this.props.isFromSearch ? React__default.createElement(Highlight$2, { attribute: 'label', hit: item }) : item.label;
return React__default.createElement(
Link,
{
className: cx$8('link'),
onClick: function onClick() {
return _this.selectItem(item, resetQuery);
},
href: createURL(item.value)
},
React__default.createElement(
'span',
{ className: cx$8('label') },
label
),
' ',
React__default.createElement(
'span',
{ className: cx$8('count') },
item.count
)
);
}, _this.selectItem = function (item, resetQuery) {
resetQuery();
_this.props.refine(item.value);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(Menu, [{
key: 'render',
value: function render() {
return React__default.createElement(List, _extends({
renderItem: this.renderItem,
selectItem: this.selectItem,
cx: cx$8
}, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isFromSearch', 'searchForItems', 'searchable', 'canRefine', 'className'])));
}
}]);
return Menu;
}(React.Component);
Menu.propTypes = {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
searchForItems: propTypes.func.isRequired,
searchable: propTypes.bool,
createURL: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string.isRequired,
count: propTypes.number.isRequired,
isRefined: propTypes.bool.isRequired
})),
isFromSearch: propTypes.bool.isRequired,
canRefine: propTypes.bool.isRequired,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
transformItems: propTypes.func,
className: propTypes.string
};
Menu.defaultProps = {
className: ''
};
var Menu$1 = translatable({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
},
noResults: 'No results',
submit: null,
reset: null,
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(Menu);
/**
* The Menu component displays a menu that lets the user choose a single value for a specific attribute.
* @name Menu
* @kind widget
* @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* If you are using the `searchable` prop, you'll also need to make the attribute searchable using
* the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values).
* @propType {string} attribute - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limit=10] - the minimum number of diplayed items
* @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {boolean} [searchable=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/).
* @themeKey ais-Menu - the root div of the widget
* @themeKey ais-Menu-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @themeKey ais-Menu-list - the list of all menu items
* @themeKey ais-Menu-item - the menu list item
* @themeKey ais-Menu-item--selected - the selected menu list item
* @themeKey ais-Menu-link - the clickable menu element
* @themeKey ais-Menu-label - the label of each item
* @themeKey ais-Menu-count - the count of values for each item
* @themeKey ais-Menu-noResults - the div displayed when there are no results
* @themeKey ais-Menu-showMore - the button used to display more categories
* @themeKey ais-Menu-showMore--disabled - the disabled button used to display more categories
* @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded
* @translationkey noResults - The label of the no results text when no search for facet values results are found.
* @example
* import React from 'react';
* import { InstantSearch, Menu } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Menu attribute="category" />
* </InstantSearch>
* );
*/
var MenuWidget = function MenuWidget(props) {
return React__default.createElement(
PanelCallbackHandler,
props,
React__default.createElement(Menu$1, props)
);
};
var Menu$2 = connectMenu(MenuWidget);
var cx$9 = createClassNames('MenuSelect');
var MenuSelect = function (_Component) {
inherits(MenuSelect, _Component);
function MenuSelect() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, MenuSelect);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = MenuSelect.__proto__ || Object.getPrototypeOf(MenuSelect)).call.apply(_ref, [this].concat(args))), _this), _this.handleSelectChange = function (_ref2) {
var value = _ref2.target.value;
_this.props.refine(value === 'ais__see__all__option' ? '' : value);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(MenuSelect, [{
key: 'render',
value: function render() {
var _props = this.props,
items = _props.items,
canRefine = _props.canRefine,
translate = _props.translate,
className = _props.className;
return React__default.createElement(
'div',
{
className: classnames(cx$9('', !canRefine && '-noRefinement'), className)
},
React__default.createElement(
'select',
{
value: this.selectedValue,
onChange: this.handleSelectChange,
className: cx$9('select')
},
React__default.createElement(
'option',
{ value: 'ais__see__all__option', className: cx$9('option') },
translate('seeAllOption')
),
items.map(function (item) {
return React__default.createElement(
'option',
{
key: item.value,
value: item.value,
className: cx$9('option')
},
item.label,
' (',
item.count,
')'
);
})
)
);
}
}, {
key: 'selectedValue',
get: function get() {
var _ref3 = find_1(this.props.items, { isRefined: true }) || {
value: 'ais__see__all__option'
},
value = _ref3.value;
return value;
}
}]);
return MenuSelect;
}(React.Component);
MenuSelect.propTypes = {
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string.isRequired,
count: propTypes.oneOfType([propTypes.number.isRequired, propTypes.string.isRequired]),
isRefined: propTypes.bool.isRequired
})).isRequired,
canRefine: propTypes.bool.isRequired,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
className: propTypes.string
};
MenuSelect.defaultProps = {
className: ''
};
var MenuSelect$1 = translatable({
seeAllOption: 'See all'
})(MenuSelect);
/**
* The MenuSelect component displays a select that lets the user choose a single value for a specific attribute.
* @name MenuSelect
* @kind widget
* @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @propType {string} attribute - the name of the attribute in the record
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-MenuSelect - the root div of the widget
* @themeKey ais-MenuSelect-noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-MenuSelect-select - the `<select>`
* @themeKey ais-MenuSelect-option - the select `<option>`
* @translationkey seeAllOption - The label of the option to select to remove the refinement
* @example
* import React from 'react';
* import { InstantSearch, MenuSelect } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <MenuSelect attribute="category" />
* </InstantSearch>
* );
*/
var MenuSelectWidget = function MenuSelectWidget(props) {
return React__default.createElement(
PanelCallbackHandler,
props,
React__default.createElement(MenuSelect$1, props)
);
};
var MenuSelect$2 = connectMenu(MenuSelectWidget);
function stringifyItem(item) {
if (typeof item.start === 'undefined' && typeof item.end === 'undefined') {
return '';
}
return (item.start ? item.start : '') + ':' + (item.end ? item.end : '');
}
function parseItem(value) {
if (value.length === 0) {
return { start: null, end: null };
}
var _value$split = value.split(':'),
_value$split2 = slicedToArray(_value$split, 2),
startStr = _value$split2[0],
endStr = _value$split2[1];
return {
start: startStr.length > 0 ? parseInt(startStr, 10) : null,
end: endStr.length > 0 ? parseInt(endStr, 10) : null
};
}
var namespace$2 = 'multiRange';
function getId$5(props) {
return props.attribute;
}
function getCurrentRefinement$4(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, namespace$2 + '.' + getId$5(props), '', function (currentRefinement) {
if (currentRefinement === '') {
return '';
}
return currentRefinement;
});
}
function isRefinementsRangeIncludesInsideItemRange(stats, start, end) {
return stats.min > start && stats.min < end || stats.max > start && stats.max < end;
}
function isItemRangeIncludedInsideRefinementsRange(stats, start, end) {
return start > stats.min && start < stats.max || end > stats.min && end < stats.max;
}
function itemHasRefinement(attribute, results, value) {
var stats = results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null;
var range = value.split(':');
var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]);
var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]);
return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end)));
}
function _refine$2(props, searchState, nextRefinement, context) {
var nextValue = defineProperty$1({}, getId$5(props, searchState), nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$2);
}
function _cleanUp$2(props, searchState, context) {
return cleanUpValue(searchState, context, namespace$2 + '.' + getId$5(props));
}
/**
* connectNumericMenu connector provides the logic to build a widget that will
* give the user the ability to select a range value for a numeric attribute.
* Ranges are defined statically.
* @name connectNumericMenu
* @requirements The attribute passed to the `attribute` prop must be holding numerical values.
* @kind connector
* @propType {string} attribute - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string.
* @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the NumericMenu can display.
*/
var connectNumericMenu = createConnector({
displayName: 'AlgoliaNumericMenu',
propTypes: {
id: propTypes.string,
attribute: propTypes.string.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.node,
start: propTypes.number,
end: propTypes.number
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attribute = props.attribute;
var currentRefinement = getCurrentRefinement$4(props, searchState, this.context);
var results = getResults(searchResults, this.context);
var items = props.items.map(function (item) {
var value = stringifyItem(item);
return {
label: item.label,
value: value,
isRefined: value === currentRefinement,
noRefinement: results ? itemHasRefinement(getId$5(props), results, value) : false
};
});
var stats = results && results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null;
var refinedItem = find_1(items, function (item) {
return item.isRefined === true;
});
if (!items.some(function (item) {
return item.value === '';
})) {
items.push({
value: '',
isRefined: isEmpty_1(refinedItem),
noRefinement: !stats,
label: 'All'
});
}
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement,
canRefine: items.length > 0 && items.some(function (item) {
return item.noRefinement === false;
})
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$2(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$2(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute;
var _parseItem = parseItem(getCurrentRefinement$4(props, searchState, this.context)),
start = _parseItem.start,
end = _parseItem.end;
searchParameters = searchParameters.addDisjunctiveFacet(attribute);
if (start) {
searchParameters = searchParameters.addNumericRefinement(attribute, '>=', start);
}
if (end) {
searchParameters = searchParameters.addNumericRefinement(attribute, '<=', end);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId$5(props);
var value = getCurrentRefinement$4(props, searchState, this.context);
var items = [];
var index = getIndex(this.context);
if (value !== '') {
var _find2 = find_1(props.items, function (item) {
return stringifyItem(item) === value;
}),
label = _find2.label;
items.push({
label: props.attribute + ': ' + label,
attribute: props.attribute,
currentRefinement: label,
value: function value(nextState) {
return _refine$2(props, nextState, '', _this.context);
}
});
}
return { id: id, index: index, items: items };
}
});
var cx$10 = createClassNames('NumericMenu');
var NumericMenu = function (_Component) {
inherits(NumericMenu, _Component);
function NumericMenu() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, NumericMenu);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = NumericMenu.__proto__ || Object.getPrototypeOf(NumericMenu)).call.apply(_ref, [this].concat(args))), _this), _this.renderItem = function (item) {
var _this$props = _this.props,
refine = _this$props.refine,
translate = _this$props.translate;
return React__default.createElement(
'label',
{ className: cx$10('label') },
React__default.createElement('input', {
className: cx$10('radio'),
type: 'radio',
checked: item.isRefined,
disabled: item.noRefinement,
onChange: function onChange() {
return refine(item.value);
}
}),
React__default.createElement(
'span',
{ className: cx$10('labelText') },
item.value === '' ? translate('all') : item.label
)
);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(NumericMenu, [{
key: 'render',
value: function render() {
var _props = this.props,
items = _props.items,
canRefine = _props.canRefine,
className = _props.className;
return React__default.createElement(List, {
renderItem: this.renderItem,
showMore: false,
canRefine: canRefine,
cx: cx$10,
items: items.map(function (item) {
return _extends({}, item, { key: item.value });
}),
className: className
});
}
}]);
return NumericMenu;
}(React.Component);
NumericMenu.propTypes = {
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.node.isRequired,
value: propTypes.string.isRequired,
isRefined: propTypes.bool.isRequired,
noRefinement: propTypes.bool.isRequired
})).isRequired,
canRefine: propTypes.bool.isRequired,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
className: propTypes.string
};
NumericMenu.defaultProps = {
className: ''
};
var NumericMenu$1 = translatable({
all: 'All'
})(NumericMenu);
/**
* NumericMenu is a widget used for selecting the range value of a numeric attribute.
* @name NumericMenu
* @kind widget
* @requirements The attribute passed to the `attribute` prop must be holding numerical values.
* @propType {string} attribute - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the format "min:max".
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-NumericMenu - the root div of the widget
* @themeKey ais-NumericMenu--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-NumericMenu-list - the list of all refinement items
* @themeKey ais-NumericMenu-item - the refinement list item
* @themeKey ais-NumericMenu-item--selected - the selected refinement list item
* @themeKey ais-NumericMenu-label - the label of each refinement item
* @themeKey ais-NumericMenu-radio - the radio input of each refinement item
* @themeKey ais-NumericMenu-labelText - the label text of each refinement item
* @translationkey all - The label of the largest range added automatically by react instantsearch
* @example
* import React from 'react';
* import { InstantSearch, NumericMenu } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <NumericMenu
* attribute="price"
* items={[
* { end: 10, label: '< $10' },
* { start: 10, end: 100, label: '$10 - $100' },
* { start: 100, end: 500, label: '$100 - $500' },
* { start: 500, label: '> $500' },
* ]}
* />
* </InstantSearch>
* );
*/
var NumericMenuWidget = function NumericMenuWidget(props) {
return React__default.createElement(
PanelCallbackHandler,
props,
React__default.createElement(NumericMenu$1, props)
);
};
var NumericMenu$2 = connectNumericMenu(NumericMenuWidget);
function getId$6() {
return 'page';
}
function getCurrentRefinement$5(props, searchState, context) {
var id = getId$6();
var page = 1;
return getCurrentRefinementValue(props, searchState, context, id, page, function (currentRefinement) {
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
});
}
function _refine$3(props, searchState, nextPage, context) {
var id = getId$6();
var nextValue = defineProperty$1({}, id, nextPage);
var resetPage = false;
return refineValue(searchState, nextValue, context, resetPage);
}
/**
* connectPagination connector provides the logic to build a widget that will
* let the user displays hits corresponding to a certain page.
* @name connectPagination
* @kind connector
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [padding=3] - How many page links to display around the current page.
* @propType {number} [totalPages=Infinity] - Maximum number of pages to display.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {number} nbPages - the total of existing pages
* @providedPropType {number} currentRefinement - the page refinement currently applied
*/
var connectPagination = createConnector({
displayName: 'AlgoliaPagination',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, this.context);
if (!results) {
return null;
}
var nbPages = results.nbPages;
return {
nbPages: nbPages,
currentRefinement: getCurrentRefinement$5(props, searchState, this.context),
canRefine: nbPages > 1
};
},
refine: function refine(props, searchState, nextPage) {
return _refine$3(props, searchState, nextPage, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, this.context, getId$6());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setPage(getCurrentRefinement$5(props, searchState, this.context) - 1);
},
getMetadata: function getMetadata() {
return { id: getId$6() };
}
});
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeMax$7 = Math.max;
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax$7(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
var _baseRange = baseRange;
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && _isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite_1(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite_1(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite_1(step);
return _baseRange(start, end, step, fromRight);
};
}
var _createRange = createRange;
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
var range = _createRange();
var range_1 = range;
var LinkList = function (_Component) {
inherits(LinkList, _Component);
function LinkList() {
classCallCheck(this, LinkList);
return possibleConstructorReturn(this, (LinkList.__proto__ || Object.getPrototypeOf(LinkList)).apply(this, arguments));
}
createClass(LinkList, [{
key: 'render',
value: function render() {
var _props = this.props,
cx = _props.cx,
createURL = _props.createURL,
items = _props.items,
onSelect = _props.onSelect,
canRefine = _props.canRefine;
return React__default.createElement(
'ul',
{ className: cx('list', !canRefine && 'list--noRefinement') },
items.map(function (item) {
return React__default.createElement(
'li',
{
key: has_1(item, 'key') ? item.key : item.value,
className: cx('item', item.selected && !item.disabled && 'item--selected', item.disabled && 'item--disabled', item.modifier)
},
item.disabled ? React__default.createElement(
'span',
{ className: cx('link') },
has_1(item, 'label') ? item.label : item.value
) : React__default.createElement(
Link,
{
className: cx('link', item.selected && 'link--selected'),
'aria-label': item.ariaLabel,
href: createURL(item.value),
onClick: function onClick() {
return onSelect(item.value);
}
},
has_1(item, 'label') ? item.label : item.value
)
);
})
);
}
}]);
return LinkList;
}(React.Component);
LinkList.propTypes = {
cx: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
value: propTypes.oneOfType([propTypes.string, propTypes.number, propTypes.object]).isRequired,
key: propTypes.oneOfType([propTypes.string, propTypes.number]),
label: propTypes.node,
modifier: propTypes.string,
ariaLabel: propTypes.string,
disabled: propTypes.bool
})),
onSelect: propTypes.func.isRequired,
canRefine: propTypes.bool.isRequired
};
var cx$11 = createClassNames('Pagination');
// Determines the size of the widget (the number of pages displayed - that the user can directly click on)
function calculateSize(padding, maxPages) {
return Math.min(2 * padding + 1, maxPages);
}
function calculatePaddingLeft(currentPage, padding, maxPages, size) {
if (currentPage <= padding) {
return currentPage;
}
if (currentPage >= maxPages - padding) {
return size - (maxPages - currentPage);
}
return padding + 1;
}
// Retrieve the correct page range to populate the widget
function getPages(currentPage, maxPages, padding) {
var size = calculateSize(padding, maxPages);
// If the widget size is equal to the max number of pages, return the entire page range
if (size === maxPages) return range_1(1, maxPages + 1);
var paddingLeft = calculatePaddingLeft(currentPage, padding, maxPages, size);
var paddingRight = size - paddingLeft;
var first = currentPage - paddingLeft;
var last = currentPage + paddingRight;
return range_1(first + 1, last + 1);
}
var Pagination = function (_Component) {
inherits(Pagination, _Component);
function Pagination() {
classCallCheck(this, Pagination);
return possibleConstructorReturn(this, (Pagination.__proto__ || Object.getPrototypeOf(Pagination)).apply(this, arguments));
}
createClass(Pagination, [{
key: 'getItem',
value: function getItem(modifier, translationKey, value) {
var _props = this.props,
nbPages = _props.nbPages,
totalPages = _props.totalPages,
translate = _props.translate;
return {
key: modifier + '.' + value,
modifier: modifier,
disabled: value < 1 || value >= Math.min(totalPages, nbPages),
label: translate(translationKey, value),
value: value,
ariaLabel: translate('aria' + capitalize(translationKey), value)
};
}
}, {
key: 'render',
value: function render() {
var _props2 = this.props,
ListComponent = _props2.listComponent,
nbPages = _props2.nbPages,
totalPages = _props2.totalPages,
currentRefinement = _props2.currentRefinement,
padding = _props2.padding,
showFirst = _props2.showFirst,
showPrevious = _props2.showPrevious,
showNext = _props2.showNext,
showLast = _props2.showLast,
refine = _props2.refine,
createURL = _props2.createURL,
canRefine = _props2.canRefine,
translate = _props2.translate,
className = _props2.className,
otherProps = objectWithoutProperties(_props2, ['listComponent', 'nbPages', 'totalPages', 'currentRefinement', 'padding', 'showFirst', 'showPrevious', 'showNext', 'showLast', 'refine', 'createURL', 'canRefine', 'translate', 'className']);
var maxPages = Math.min(nbPages, totalPages);
var lastPage = maxPages;
var items = [];
if (showFirst) {
items.push({
key: 'first',
modifier: 'item--firstPage',
disabled: currentRefinement === 1,
label: translate('first'),
value: 1,
ariaLabel: translate('ariaFirst')
});
}
if (showPrevious) {
items.push({
key: 'previous',
modifier: 'item--previousPage',
disabled: currentRefinement === 1,
label: translate('previous'),
value: currentRefinement - 1,
ariaLabel: translate('ariaPrevious')
});
}
items = items.concat(getPages(currentRefinement, maxPages, padding).map(function (value) {
return {
key: value,
modifier: 'item--page',
label: translate('page', value),
value: value,
selected: value === currentRefinement,
ariaLabel: translate('ariaPage', value)
};
}));
if (showNext) {
items.push({
key: 'next',
modifier: 'item--nextPage',
disabled: currentRefinement === lastPage || lastPage <= 1,
label: translate('next'),
value: currentRefinement + 1,
ariaLabel: translate('ariaNext')
});
}
if (showLast) {
items.push({
key: 'last',
modifier: 'item--lastPage',
disabled: currentRefinement === lastPage || lastPage <= 1,
label: translate('last'),
value: lastPage,
ariaLabel: translate('ariaLast')
});
}
return React__default.createElement(
'div',
{
className: classnames(cx$11('', !canRefine && '-noRefinement'), className)
},
React__default.createElement(ListComponent, _extends({}, otherProps, {
cx: cx$11,
items: items,
onSelect: refine,
createURL: createURL,
canRefine: canRefine
}))
);
}
}]);
return Pagination;
}(React.Component);
Pagination.propTypes = {
nbPages: propTypes.number.isRequired,
currentRefinement: propTypes.number.isRequired,
refine: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
canRefine: propTypes.bool.isRequired,
translate: propTypes.func.isRequired,
listComponent: propTypes.func,
showFirst: propTypes.bool,
showPrevious: propTypes.bool,
showNext: propTypes.bool,
showLast: propTypes.bool,
padding: propTypes.number,
totalPages: propTypes.number,
className: propTypes.string
};
Pagination.defaultProps = {
listComponent: LinkList,
showFirst: true,
showPrevious: true,
showNext: true,
showLast: false,
padding: 3,
totalPages: Infinity,
className: ''
};
var Pagination$1 = translatable({
previous: '‹',
next: '›',
first: '«',
last: '»',
page: function page(currentRefinement) {
return currentRefinement.toString();
},
ariaPrevious: 'Previous page',
ariaNext: 'Next page',
ariaFirst: 'First page',
ariaLast: 'Last page',
ariaPage: function ariaPage(currentRefinement) {
return 'Page ' + currentRefinement.toString();
}
})(Pagination);
/**
* The Pagination widget displays a simple pagination system allowing the user to
* change the current page.
* @name Pagination
* @kind widget
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [padding=3] - How many page links to display around the current page.
* @propType {number} [totalPages=Infinity] - Maximum number of pages to display.
* @themeKey ais-Pagination - the root div of the widget
* @themeKey ais-Pagination--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-Pagination-list - the list of all pagination items
* @themeKey ais-Pagination-list--noRefinement - the list of all pagination items when there is no refinement
* @themeKey ais-Pagination-item - the pagination list item
* @themeKey ais-Pagination-item--firstPage - the "first" pagination list item
* @themeKey ais-Pagination-item--lastPage - the "last" pagination list item
* @themeKey ais-Pagination-item--previousPage - the "previous" pagination list item
* @themeKey ais-Pagination-item--nextPage - the "next" pagination list item
* @themeKey ais-Pagination-item--page - the "page" pagination list item
* @themeKey ais-Pagination-item--selected - the selected pagination list item
* @themeKey ais-Pagination-item--disabled - the disabled pagination list item
* @themeKey ais-Pagination-link - the pagination clickable element
* @translationKey previous - Label value for the previous page link
* @translationKey next - Label value for the next page link
* @translationKey first - Label value for the first page link
* @translationKey last - Label value for the last page link
* @translationkey page - Label value for a page item. You get function(currentRefinement) and you need to return a string
* @translationKey ariaPrevious - Accessibility label value for the previous page link
* @translationKey ariaNext - Accessibility label value for the next page link
* @translationKey ariaFirst - Accessibility label value for the first page link
* @translationKey ariaLast - Accessibility label value for the last page link
* @translationkey ariaPage - Accessibility label value for a page item. You get function(currentRefinement) and you need to return a string
* @example
* import React from 'react';
* import { InstantSearch, Pagination } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Pagination />
* </InstantSearch>
* );
*/
var PaginationWidget = function PaginationWidget(props) {
return React__default.createElement(
PanelCallbackHandler,
props,
React__default.createElement(Pagination$1, props)
);
};
var Pagination$2 = connectPagination(PaginationWidget);
/**
* connectPoweredBy connector provides the logic to build a widget that
* will display a link to algolia.
* @name connectPoweredBy
* @kind connector
* @providedPropType {string} url - the url to redirect to algolia
*/
var connectPoweredBy = createConnector({
displayName: 'AlgoliaPoweredBy',
propTypes: {},
getProvidedProps: function getProvidedProps(props) {
var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + ('utm_content=' + (props.canRender ? location.hostname : '') + '&') + 'utm_campaign=poweredby';
return { url: url };
}
});
var cx$12 = createClassNames('PoweredBy');
/* eslint-disable max-len */
var AlgoliaLogo = function AlgoliaLogo() {
return React__default.createElement(
'svg',
{
xmlns: 'http://www.w3.org/2000/svg',
baseProfile: 'basic',
viewBox: '0 0 1366 362',
width: '100',
height: '27',
className: cx$12('logo')
},
React__default.createElement(
'linearGradient',
{
id: 'g',
x1: '428.258',
x2: '434.145',
y1: '404.15',
y2: '409.85',
gradientUnits: 'userSpaceOnUse',
gradientTransform: 'matrix(94.045 0 0 -94.072 -40381.527 38479.52)'
},
React__default.createElement('stop', { offset: '0', stopColor: '#00AEFF' }),
React__default.createElement('stop', { offset: '1', stopColor: '#3369E7' })
),
React__default.createElement('path', {
d: 'M61.8 15.4h242.8c23.9 0 43.4 19.4 43.4 43.4v242.9c0 23.9-19.4 43.4-43.4 43.4H61.8c-23.9 0-43.4-19.4-43.4-43.4v-243c0-23.9 19.4-43.3 43.4-43.3z',
fill: 'url(#g)'
}),
React__default.createElement('path', {
d: 'M187 98.7c-51.4 0-93.1 41.7-93.1 93.2S135.6 285 187 285s93.1-41.7 93.1-93.2-41.6-93.1-93.1-93.1zm0 158.8c-36.2 0-65.6-29.4-65.6-65.6s29.4-65.6 65.6-65.6 65.6 29.4 65.6 65.6-29.3 65.6-65.6 65.6zm0-117.8v48.9c0 1.4 1.5 2.4 2.8 1.7l43.4-22.5c1-.5 1.3-1.7.8-2.7-9-15.8-25.7-26.6-45-27.3-1 0-2 .8-2 1.9zm-60.8-35.9l-5.7-5.7c-5.6-5.6-14.6-5.6-20.2 0l-6.8 6.8c-5.6 5.6-5.6 14.6 0 20.2l5.6 5.6c.9.9 2.2.7 3-.2 3.3-4.5 6.9-8.8 10.9-12.8 4.1-4.1 8.3-7.7 12.9-11 1-.6 1.1-2 .3-2.9zM217.5 89V77.7c0-7.9-6.4-14.3-14.3-14.3h-33.3c-7.9 0-14.3 6.4-14.3 14.3v11.6c0 1.3 1.2 2.2 2.5 1.9 9.3-2.7 19.1-4.1 29-4.1 9.5 0 18.9 1.3 28 3.8 1.2.3 2.4-.6 2.4-1.9z',
fill: '#FFFFFF'
}),
React__default.createElement('path', {
d: 'M842.5 267.6c0 26.7-6.8 46.2-20.5 58.6-13.7 12.4-34.6 18.6-62.8 18.6-10.3 0-31.7-2-48.8-5.8l6.3-31c14.3 3 33.2 3.8 43.1 3.8 15.7 0 26.9-3.2 33.6-9.6s10-15.9 10-28.5v-6.4c-3.9 1.9-9 3.8-15.3 5.8-6.3 1.9-13.6 2.9-21.8 2.9-10.8 0-20.6-1.7-29.5-5.1-8.9-3.4-16.6-8.4-22.9-15-6.3-6.6-11.3-14.9-14.8-24.8s-5.3-27.6-5.3-40.6c0-12.2 1.9-27.5 5.6-37.7 3.8-10.2 9.2-19 16.5-26.3 7.2-7.3 16-12.9 26.3-17s22.4-6.7 35.5-6.7c12.7 0 24.4 1.6 35.8 3.5 11.4 1.9 21.1 3.9 29 6.1v155.2zm-108.7-77.2c0 16.4 3.6 34.6 10.8 42.2 7.2 7.6 16.5 11.4 27.9 11.4 6.2 0 12.1-.9 17.6-2.6 5.5-1.7 9.9-3.7 13.4-6.1v-97.1c-2.8-.6-14.5-3-25.8-3.3-14.2-.4-25 5.4-32.6 14.7-7.5 9.3-11.3 25.6-11.3 40.8zm294.3 0c0 13.2-1.9 23.2-5.8 34.1s-9.4 20.2-16.5 27.9c-7.1 7.7-15.6 13.7-25.6 17.9s-25.4 6.6-33.1 6.6c-7.7-.1-23-2.3-32.9-6.6-9.9-4.3-18.4-10.2-25.5-17.9-7.1-7.7-12.6-17-16.6-27.9s-6-20.9-6-34.1c0-13.2 1.8-25.9 5.8-36.7 4-10.8 9.6-20 16.8-27.7s15.8-13.6 25.6-17.8c9.9-4.2 20.8-6.2 32.6-6.2s22.7 2.1 32.7 6.2c10 4.2 18.6 10.1 25.6 17.8 7.1 7.7 12.6 16.9 16.6 27.7 4.2 10.8 6.3 23.5 6.3 36.7zm-40 .1c0-16.9-3.7-31-10.9-40.8-7.2-9.9-17.3-14.8-30.2-14.8-12.9 0-23 4.9-30.2 14.8-7.2 9.9-10.7 23.9-10.7 40.8 0 17.1 3.6 28.6 10.8 38.5 7.2 10 17.3 14.9 30.2 14.9 12.9 0 23-5 30.2-14.9 7.2-10 10.8-21.4 10.8-38.5zm127.1 86.4c-64.1.3-64.1-51.8-64.1-60.1L1051 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9zm68.9 0h-39.3V108.1l39.3-6.2v175zm-19.7-193.5c13.1 0 23.8-10.6 23.8-23.7S1177.6 36 1164.4 36s-23.8 10.6-23.8 23.7 10.7 23.7 23.8 23.7zm117.4 18.6c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4s8.9 13.5 11.1 21.7c2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6s-25.9 2.7-41.1 2.7c-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8s9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2s-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 9 18s13.7 5.3 23.6 5.3zm158.5 31.9c-64.1.3-64.1-51.8-64.1-60.1L610.6 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9z',
fill: '#182359'
})
);
};
/* eslint-enable max-len */
var PoweredBy = function (_Component) {
inherits(PoweredBy, _Component);
function PoweredBy() {
classCallCheck(this, PoweredBy);
return possibleConstructorReturn(this, (PoweredBy.__proto__ || Object.getPrototypeOf(PoweredBy)).apply(this, arguments));
}
createClass(PoweredBy, [{
key: 'render',
value: function render() {
var _props = this.props,
url = _props.url,
translate = _props.translate,
className = _props.className;
return React__default.createElement(
'div',
{ className: classnames(cx$12(''), className) },
React__default.createElement(
'span',
{ className: cx$12('text') },
translate('searchBy')
),
' ',
React__default.createElement(
'a',
{
href: url,
target: '_blank',
className: cx$12('link'),
'aria-label': 'Algolia'
},
React__default.createElement(AlgoliaLogo, null)
)
);
}
}]);
return PoweredBy;
}(React.Component);
PoweredBy.propTypes = {
url: propTypes.string.isRequired,
translate: propTypes.func.isRequired,
className: propTypes.string
};
var PoweredByComponent = translatable({
searchBy: 'Search by'
})(PoweredBy);
/**
* PoweredBy displays an Algolia logo.
*
* Algolia requires that you use this widget if you are on a [community or free plan](https://www.algolia.com/pricing).
* @name PoweredBy
* @kind widget
* @themeKey ais-PoweredBy - the root div of the widget
* @themeKey ais-PoweredBy-text - the text of the widget
* @themeKey ais-PoweredBy-link - the link of the logo
* @themeKey ais-PoweredBy-logo - the logo of the widget
* @translationKey searchBy - Label value for the powered by
* @example
* import React from 'react';
* import { InstantSearch, PoweredBy } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <PoweredBy />
* </InstantSearch>
* );
*/
var PoweredBy$1 = connectPoweredBy(PoweredByComponent);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsFinite = _root.isFinite;
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
*/
function isFinite$1(value) {
return typeof value == 'number' && nativeIsFinite(value);
}
var _isFinite = isFinite$1;
/**
* connectRange connector provides the logic to create connected
* components that will give the ability for a user to refine results using
* a numeric range.
* @name connectRange
* @kind connector
* @requirements The attribute passed to the `attribute` prop must be holding numerical values.
* @propType {string} attribute - Name of the attribute for faceting
* @propType {{min?: number, max?: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [precision=0] - Number of digits after decimal point to use.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {number} min - the minimum value available.
* @providedPropType {number} max - the maximum value available.
* @providedPropType {number} precision - Number of digits after decimal point to use.
*/
function getId$7(props) {
return props.attribute;
}
var namespace$3 = 'range';
function getCurrentRange(boundaries, stats, precision) {
var pow = Math.pow(10, precision);
var min = void 0;
if (_isFinite(boundaries.min)) {
min = boundaries.min;
} else if (_isFinite(stats.min)) {
min = stats.min;
} else {
min = undefined;
}
var max = void 0;
if (_isFinite(boundaries.max)) {
max = boundaries.max;
} else if (_isFinite(stats.max)) {
max = stats.max;
} else {
max = undefined;
}
return {
min: min !== undefined ? Math.floor(min * pow) / pow : min,
max: max !== undefined ? Math.ceil(max * pow) / pow : max
};
}
function getCurrentRefinement$6(props, searchState, currentRange, context) {
var refinement = getCurrentRefinementValue(props, searchState, context, namespace$3 + '.' + getId$7(props), {}, function (currentRefinement) {
var min = currentRefinement.min,
max = currentRefinement.max;
if (typeof min === 'string') {
min = parseInt(min, 10);
}
if (typeof max === 'string') {
max = parseInt(max, 10);
}
return { min: min, max: max };
});
var hasMinBound = props.min !== undefined;
var hasMaxBound = props.max !== undefined;
var hasMinRefinment = refinement.min !== undefined;
var hasMaxRefinment = refinement.max !== undefined;
if (hasMinBound && hasMinRefinment && refinement.min < currentRange.min) {
throw Error("You can't provide min value lower than range.");
}
if (hasMaxBound && hasMaxRefinment && refinement.max > currentRange.max) {
throw Error("You can't provide max value greater than range.");
}
if (hasMinBound && !hasMinRefinment) {
refinement.min = currentRange.min;
}
if (hasMaxBound && !hasMaxRefinment) {
refinement.max = currentRange.max;
}
return refinement;
}
function getCurrentRefinementWithRange(refinement, range) {
return {
min: refinement.min !== undefined ? refinement.min : range.min,
max: refinement.max !== undefined ? refinement.max : range.max
};
}
function nextValueForRefinement(hasBound, isReset, range, value) {
var next = void 0;
if (!hasBound && range === value) {
next = undefined;
} else if (hasBound && isReset) {
next = range;
} else {
next = value;
}
return next;
}
function _refine$4(props, searchState, nextRefinement, currentRange, context) {
var nextMin = nextRefinement.min,
nextMax = nextRefinement.max;
var currentMinRange = currentRange.min,
currentMaxRange = currentRange.max;
var isMinReset = nextMin === undefined || nextMin === '';
var isMaxReset = nextMax === undefined || nextMax === '';
var nextMinAsNumber = !isMinReset ? parseFloat(nextMin) : undefined;
var nextMaxAsNumber = !isMaxReset ? parseFloat(nextMax) : undefined;
var isNextMinValid = isMinReset || _isFinite(nextMinAsNumber);
var isNextMaxValid = isMaxReset || _isFinite(nextMaxAsNumber);
if (!isNextMinValid || !isNextMaxValid) {
throw Error("You can't provide non finite values to the range connector.");
}
if (nextMinAsNumber < currentMinRange) {
throw Error("You can't provide min value lower than range.");
}
if (nextMaxAsNumber > currentMaxRange) {
throw Error("You can't provide max value greater than range.");
}
var id = getId$7(props);
var resetPage = true;
var nextValue = defineProperty$1({}, id, {
min: nextValueForRefinement(props.min !== undefined, isMinReset, currentMinRange, nextMinAsNumber),
max: nextValueForRefinement(props.max !== undefined, isMaxReset, currentMaxRange, nextMaxAsNumber)
});
return refineValue(searchState, nextValue, context, resetPage, namespace$3);
}
function _cleanUp$3(props, searchState, context) {
return cleanUpValue(searchState, context, namespace$3 + '.' + getId$7(props));
}
var connectRange = createConnector({
displayName: 'AlgoliaRange',
propTypes: {
id: propTypes.string,
attribute: propTypes.string.isRequired,
defaultRefinement: propTypes.shape({
min: propTypes.number,
max: propTypes.number
}),
min: propTypes.number,
max: propTypes.number,
precision: propTypes.number,
header: propTypes.node,
footer: propTypes.node
},
defaultProps: {
precision: 0
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attribute = props.attribute,
precision = props.precision,
minBound = props.min,
maxBound = props.max;
var results = getResults(searchResults, this.context);
var hasFacet = results && results.getFacetByName(attribute);
var stats = hasFacet ? results.getFacetStats(attribute) || {} : {};
var facetValues = hasFacet ? results.getFacetValues(attribute) : [];
var count = facetValues.map(function (v) {
return {
value: v.name,
count: v.count
};
});
var _getCurrentRange = getCurrentRange({ min: minBound, max: maxBound }, stats, precision),
rangeMin = _getCurrentRange.min,
rangeMax = _getCurrentRange.max;
// The searchState is not always in sync with the helper state. For example
// when we set boundaries on the first render the searchState don't have
// the correct refinement. If this behaviour change in the upcoming version
// we could store the range inside the searchState instead of rely on `this`.
this._currentRange = {
min: rangeMin,
max: rangeMax
};
var currentRefinement = getCurrentRefinement$6(props, searchState, this._currentRange, this.context);
return {
min: rangeMin,
max: rangeMax,
canRefine: count.length > 0,
currentRefinement: getCurrentRefinementWithRange(currentRefinement, this._currentRange),
count: count,
precision: precision
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$4(props, searchState, nextRefinement, this._currentRange, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$3(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(params, props, searchState) {
var attribute = props.attribute;
var _getCurrentRefinement = getCurrentRefinement$6(props, searchState, this._currentRange, this.context),
min = _getCurrentRefinement.min,
max = _getCurrentRefinement.max;
params = params.addDisjunctiveFacet(attribute);
if (min !== undefined) {
params = params.addNumericRefinement(attribute, '>=', min);
}
if (max !== undefined) {
params = params.addNumericRefinement(attribute, '<=', max);
}
return params;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var _currentRange = this._currentRange,
minRange = _currentRange.min,
maxRange = _currentRange.max;
var _getCurrentRefinement2 = getCurrentRefinement$6(props, searchState, this._currentRange, this.context),
minValue = _getCurrentRefinement2.min,
maxValue = _getCurrentRefinement2.max;
var items = [];
var hasMin = minValue !== undefined;
var hasMax = maxValue !== undefined;
var shouldDisplayMinLabel = hasMin && minValue !== minRange;
var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange;
if (shouldDisplayMinLabel || shouldDisplayMaxLabel) {
var fragments = [hasMin ? minValue + ' <= ' : '', props.attribute, hasMax ? ' <= ' + maxValue : ''];
items.push({
label: fragments.join(''),
attribute: props.attribute,
value: function value(nextState) {
return _refine$4(props, nextState, {}, _this._currentRange, _this.context);
},
currentRefinement: getCurrentRefinementWithRange({ min: minValue, max: maxValue }, { min: minRange, max: maxRange })
});
}
return {
id: getId$7(props),
index: getIndex(this.context),
items: items
};
}
});
var cx$13 = createClassNames('RangeInput');
var RawRangeInput = function (_Component) {
inherits(RawRangeInput, _Component);
function RawRangeInput(props) {
classCallCheck(this, RawRangeInput);
var _this = possibleConstructorReturn(this, (RawRangeInput.__proto__ || Object.getPrototypeOf(RawRangeInput)).call(this, props));
_this.onSubmit = function (e) {
e.preventDefault();
_this.props.refine({
min: _this.state.from,
max: _this.state.to
});
};
_this.state = _this.normalizeStateForRendering(props);
return _this;
}
createClass(RawRangeInput, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
// In react@16.0.0 the call to setState on the inputs trigger this lifecycle hook
// because the context has changed (for react). I don't think that the bug is related
// to react because I failed to reproduce it with a simple hierarchy of components.
// The workaround here is to check the differences between previous & next props in order
// to avoid to override current state when values are not yet refined. In the react documentation,
// they DON'T categorically say that setState never run componentWillReceiveProps.
// see: https://reactjs.org/docs/react-component.html#componentwillreceiveprops
if (nextProps.canRefine && (this.props.canRefine !== nextProps.canRefine || this.props.currentRefinement.min !== nextProps.currentRefinement.min || this.props.currentRefinement.max !== nextProps.currentRefinement.max)) {
this.setState(this.normalizeStateForRendering(nextProps));
}
}
}, {
key: 'normalizeStateForRendering',
value: function normalizeStateForRendering(props) {
var canRefine = props.canRefine,
rangeMin = props.min,
rangeMax = props.max;
var _props$currentRefinem = props.currentRefinement,
valueMin = _props$currentRefinem.min,
valueMax = _props$currentRefinem.max;
return {
from: canRefine && valueMin !== undefined && valueMin !== rangeMin ? valueMin : '',
to: canRefine && valueMax !== undefined && valueMax !== rangeMax ? valueMax : ''
};
}
}, {
key: 'normalizeRangeForRendering',
value: function normalizeRangeForRendering(_ref) {
var canRefine = _ref.canRefine,
min = _ref.min,
max = _ref.max;
var hasMin = min !== undefined;
var hasMax = max !== undefined;
return {
min: canRefine && hasMin && hasMax ? min : '',
max: canRefine && hasMin && hasMax ? max : ''
};
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _state = this.state,
from = _state.from,
to = _state.to;
var _props = this.props,
precision = _props.precision,
translate = _props.translate,
canRefine = _props.canRefine,
className = _props.className;
var _normalizeRangeForRen = this.normalizeRangeForRendering(this.props),
min = _normalizeRangeForRen.min,
max = _normalizeRangeForRen.max;
var step = 1 / Math.pow(10, precision);
return React__default.createElement(
'div',
{
className: classnames(cx$13('', !canRefine && '-noRefinement'), className)
},
React__default.createElement(
'form',
{ className: cx$13('form'), onSubmit: this.onSubmit },
React__default.createElement('input', {
className: cx$13('input', 'input--min'),
type: 'number',
min: min,
max: max,
value: from,
step: step,
placeholder: min,
disabled: !canRefine,
onChange: function onChange(e) {
return _this2.setState({ from: e.currentTarget.value });
}
}),
React__default.createElement(
'span',
{ className: cx$13('separator') },
translate('separator')
),
React__default.createElement('input', {
className: cx$13('input', 'input--max'),
type: 'number',
min: min,
max: max,
value: to,
step: step,
placeholder: max,
disabled: !canRefine,
onChange: function onChange(e) {
return _this2.setState({ to: e.currentTarget.value });
}
}),
React__default.createElement(
'button',
{ className: cx$13('submit'), type: 'submit' },
translate('submit')
)
)
);
}
}]);
return RawRangeInput;
}(React.Component);
RawRangeInput.propTypes = {
canRefine: propTypes.bool.isRequired,
precision: propTypes.number.isRequired,
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
min: propTypes.number,
max: propTypes.number,
currentRefinement: propTypes.shape({
min: propTypes.number,
max: propTypes.number
}),
className: propTypes.string
};
RawRangeInput.defaultProps = {
currentRefinement: {},
className: ''
};
var RangeInput = translatable({
submit: 'ok',
separator: 'to'
})(RawRangeInput);
/**
* RangeInput allows a user to select a numeric range using a minimum and maximum input.
* @name RangeInput
* @kind widget
* @requirements The attribute passed to the `attribute` prop must be holding numerical values.
* @propType {string} attribute - the name of the attribute in the record
* @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [precision=0] - Number of digits after decimal point to use.
* @themeKey ais-RangeInput - the root div of the widget
* @themeKey ais-RangeInput-form - the wrapping form
* @themeKey ais-RangeInput-label - the label wrapping inputs
* @themeKey ais-RangeInput-input - the input (number)
* @themeKey ais-RangeInput-input--min - the minimum input
* @themeKey ais-RangeInput-input--max - the maximum input
* @themeKey ais-RangeInput-separator - the separator word used between the two inputs
* @themeKey ais-RangeInput-button - the submit button
* @translationKey submit - Label value for the submit button
* @translationKey separator - Label value for the input separator
* @example
* import React from 'react';
* import { InstantSearch, RangeInput } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <RangeInput attribute="price" />
* </InstantSearch>
* );
*/
var RangeInputWidget = function RangeInputWidget(props) {
return React__default.createElement(
PanelCallbackHandler,
props,
React__default.createElement(RangeInput, props)
);
};
var RangeInput$1 = connectRange(RangeInputWidget);
/**
* Since a lot of sliders already exist, we did not include one by default.
* However you can easily connect React InstantSearch to an existing one
* using the [connectRange connector](connectors/connectRange.html).
*
* @name RangeSlider
* @requirements To connect any slider to Algolia, the underlying attribute used must be holding numerical values.
* @kind widget
* @example
*
* // Here's an example showing how to connect the airbnb rheostat slider to React InstantSearch using the
* // range connector
import PropTypes from 'prop-types';
import React, {Component} from 'react';
import {connectRange} from 'react-instantsearch/connectors';
import Rheostat from 'rheostat';
class Range extends React.Component {
static propTypes = {
min: PropTypes.number,
max: PropTypes.number,
currentRefinement: PropTypes.object,
refine: PropTypes.func.isRequired,
canRefine: PropTypes.bool.isRequired
};
state = { currentValues: { min: this.props.min, max: this.props.max } };
componentWillReceiveProps(sliderState) {
if (sliderState.canRefine) {
this.setState({
currentValues: {
min: sliderState.currentRefinement.min,
max: sliderState.currentRefinement.max
}
});
}
}
onValuesUpdated = sliderState => {
this.setState({
currentValues: { min: sliderState.values[0], max: sliderState.values[1] }
});
};
onChange = sliderState => {
if (
this.props.currentRefinement.min !== sliderState.values[0] ||
this.props.currentRefinement.max !== sliderState.values[1]
) {
this.props.refine({
min: sliderState.values[0],
max: sliderState.values[1]
});
}
};
render() {
const { min, max, currentRefinement } = this.props;
const { currentValues } = this.state;
return min !== max ? (
<div>
<Rheostat
className="ais-RangeSlider"
min={min}
max={max}
values={[currentRefinement.min, currentRefinement.max]}
onChange={this.onChange}
onValuesUpdated={this.onValuesUpdated}
/>
<div style={{ display: "flex", justifyContent: "space-between" }}>
<div>{currentValues.min}</div>
<div>{currentValues.max}</div>
</div>
</div>
) : null;
}
}
const ConnectedRange = connectRange(Range);
*/
var RangeSlider = (function () {
return React__default.createElement(
"div",
null,
"We do not provide any Slider, see the documentation to learn how to connect one easily:",
React__default.createElement(
"a",
{
target: "_blank",
rel: "noopener noreferrer",
href: "https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html"
},
"https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html"
)
);
});
var cx$14 = createClassNames('RatingMenu');
var RatingMenu = function (_Component) {
inherits(RatingMenu, _Component);
function RatingMenu() {
classCallCheck(this, RatingMenu);
return possibleConstructorReturn(this, (RatingMenu.__proto__ || Object.getPrototypeOf(RatingMenu)).apply(this, arguments));
}
createClass(RatingMenu, [{
key: 'onClick',
value: function onClick(min, max, e) {
e.preventDefault();
e.stopPropagation();
if (min === this.props.currentRefinement.min && max === this.props.currentRefinement.max) {
this.props.refine({ min: this.props.min, max: this.props.max });
} else {
this.props.refine({ min: min, max: max });
}
}
}, {
key: 'buildItem',
value: function buildItem(_ref) {
var max = _ref.max,
lowerBound = _ref.lowerBound,
count = _ref.count,
translate = _ref.translate,
createURL = _ref.createURL,
isLastSelectableItem = _ref.isLastSelectableItem;
var disabled = !count;
var isCurrentMinLower = this.props.currentRefinement.min < lowerBound;
var selected = isLastSelectableItem && isCurrentMinLower || !disabled && lowerBound === this.props.currentRefinement.min && max === this.props.currentRefinement.max;
var icons = [];
var rating = 0;
for (var icon = 0; icon < max; icon++) {
if (icon < lowerBound) {
rating++;
}
icons.push([React__default.createElement(
'svg',
{
key: icon,
className: cx$14('starIcon', icon >= lowerBound ? 'starIcon--empty' : 'starIcon--full'),
'aria-hidden': 'true',
width: '24',
height: '24'
},
React__default.createElement('use', {
xlinkHref: '#' + cx$14(icon >= lowerBound ? 'starEmptySymbol' : 'starSymbol')
})
), ' ']);
}
// The last item of the list (the default item), should not
// be clickable if it is selected.
var isLastAndSelect = isLastSelectableItem && selected;
var onClickHandler = disabled || isLastAndSelect ? {} : {
href: createURL({ min: lowerBound, max: max }),
onClick: this.onClick.bind(this, lowerBound, max)
};
return React__default.createElement(
'li',
{
key: lowerBound,
className: cx$14('item', selected && 'item--selected', disabled && 'item--disabled')
},
React__default.createElement(
'a',
_extends({
className: cx$14('link'),
'aria-label': '' + rating + translate('ratingLabel')
}, onClickHandler),
icons,
React__default.createElement(
'span',
{ className: cx$14('label'), 'aria-hidden': 'true' },
translate('ratingLabel')
),
' ',
React__default.createElement(
'span',
{ className: cx$14('count') },
count
)
)
);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props,
min = _props.min,
max = _props.max,
translate = _props.translate,
count = _props.count,
createURL = _props.createURL,
canRefine = _props.canRefine,
className = _props.className;
// min & max are always set when there is a results, otherwise it means
// that we don't want to render anything since we don't have any values.
var limitMin = min !== undefined && min >= 0 ? min : 1;
var limitMax = max !== undefined && max >= 0 ? max : 0;
var inclusiveLength = limitMax - limitMin + 1;
var safeInclusiveLength = Math.max(inclusiveLength, 0);
var values = count.map(function (item) {
return _extends({}, item, { value: parseFloat(item.value) });
}).filter(function (item) {
return item.value >= limitMin && item.value <= limitMax;
});
var range = new Array(safeInclusiveLength).fill(null).map(function (_, index) {
var element = values.find(function (item) {
return item.value === limitMax - index;
});
var placeholder = { value: limitMax - index, count: 0, total: 0 };
return element || placeholder;
}).reduce(function (acc, item, index) {
return acc.concat(_extends({}, item, {
total: index === 0 ? item.count : acc[index - 1].total + item.count
}));
}, []);
var items = range.map(function (item, index) {
return _this2.buildItem({
lowerBound: item.value,
count: item.total,
isLastSelectableItem: range.length - 1 === index,
max: limitMax,
translate: translate,
createURL: createURL
});
});
return React__default.createElement(
'div',
{
className: classnames(cx$14('', !canRefine && '-noRefinement'), className)
},
React__default.createElement(
'svg',
{ xmlns: 'http://www.w3.org/2000/svg', style: { display: 'none' } },
React__default.createElement(
'symbol',
{ id: cx$14('starSymbol'), viewBox: '0 0 24 24' },
React__default.createElement('path', { d: 'M12 .288l2.833 8.718h9.167l-7.417 5.389 2.833 8.718-7.416-5.388-7.417 5.388 2.833-8.718-7.416-5.389h9.167z' })
),
React__default.createElement(
'symbol',
{ id: cx$14('starEmptySymbol'), viewBox: '0 0 24 24' },
React__default.createElement('path', { d: 'M12 6.76l1.379 4.246h4.465l-3.612 2.625 1.379 4.246-3.611-2.625-3.612 2.625 1.379-4.246-3.612-2.625h4.465l1.38-4.246zm0-6.472l-2.833 8.718h-9.167l7.416 5.389-2.833 8.718 7.417-5.388 7.416 5.388-2.833-8.718 7.417-5.389h-9.167l-2.833-8.718z' })
)
),
React__default.createElement(
'ul',
{ className: cx$14('list', !canRefine && 'list--noRefinement') },
items
)
);
}
}]);
return RatingMenu;
}(React.Component);
RatingMenu.propTypes = {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
createURL: propTypes.func.isRequired,
min: propTypes.number,
max: propTypes.number,
currentRefinement: propTypes.shape({
min: propTypes.number,
max: propTypes.number
}),
count: propTypes.arrayOf(propTypes.shape({
value: propTypes.string,
count: propTypes.number
})),
canRefine: propTypes.bool.isRequired,
className: propTypes.string
};
RatingMenu.defaultProps = {
className: ''
};
var RatingMenu$1 = translatable({
ratingLabel: ' & Up'
})(RatingMenu);
/**
* RatingMenu lets the user refine search results by clicking on stars.
*
* The stars are based on the selected `attribute`.
* @requirements The attribute passed to the `attribute` prop must be holding numerical values.
* @name RatingMenu
* @kind widget
* @propType {string} attribute - the name of the attribute in the record
* @propType {number} [min] - Minimum value for the rating. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value for the rating. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @propType {{min: number, max: number}} [defaultRefinement] - Default state of the widget containing the lower bound (end) and the max for the rating.
* @themeKey ais-RatingMenu - the root div of the widget
* @themeKey ais-RatingMenu--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-RatingMenu-list - the list of ratings
* @themeKey ais-RatingMenu-list--noRefinement - the list of ratings when there is no refinement
* @themeKey ais-RatingMenu-item - the rating list item
* @themeKey ais-RatingMenu-item--selected - the selected rating list item
* @themeKey ais-RatingMenu-item--disabled - the disabled rating list item
* @themeKey ais-RatingMenu-link - the rating clickable item
* @themeKey ais-RatingMenu-starIcon - the star icon
* @themeKey ais-RatingMenu-starIcon--full - the filled star icon
* @themeKey ais-RatingMenu-starIcon--empty - the empty star icon
* @themeKey ais-RatingMenu-label - the label used after the stars
* @themeKey ais-RatingMenu-count - the count of ratings for a specific item
* @translationKey ratingLabel - Label value for the rating link
* @example
* import React from 'react';
* import { InstantSearch, RefinementList } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <RefinementList attribute="colors" />
* </InstantSearch>
* );
*/
var RatingMenuWidget = function RatingMenuWidget(props) {
return React__default.createElement(
PanelCallbackHandler,
props,
React__default.createElement(RatingMenu$1, props)
);
};
var RatingMenu$2 = connectRange(RatingMenuWidget);
var namespace$4 = 'refinementList';
function getId$8(props) {
return props.attribute;
}
function getCurrentRefinement$7(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, namespace$4 + '.' + getId$8(props), [], function (currentRefinement) {
if (typeof currentRefinement === 'string') {
// All items were unselected
if (currentRefinement === '') {
return [];
}
// Only one item was in the searchState but we know it should be an array
return [currentRefinement];
}
return currentRefinement;
});
}
function getValue$3(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement$7(props, searchState, context);
var isAnewValue = currentRefinement.indexOf(name) === -1;
var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates
: currentRefinement.filter(function (selectedValue) {
return selectedValue !== name;
}); // cannot use .splice(), it mutates
return nextRefinement;
}
function getLimit$1(_ref) {
var showMore = _ref.showMore,
limit = _ref.limit,
showMoreLimit = _ref.showMoreLimit;
return showMore ? showMoreLimit : limit;
}
function _refine$5(props, searchState, nextRefinement, context) {
var id = getId$8(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$1({}, id, nextRefinement.length > 0 ? nextRefinement : '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$4);
}
function _cleanUp$4(props, searchState, context) {
return cleanUpValue(searchState, context, namespace$4 + '.' + getId$8(props));
}
/**
* connectRefinementList connector provides the logic to build a widget that will
* give the user the ability to choose multiple values for a specific facet.
* @name connectRefinementList
* @kind connector
* @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @propType {string} attribute - the name of the attribute in the record
* @propType {boolean} [searchable=false] - allow search inside values
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limit=10] - the minimum number of displayed items
* @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
var sortBy$2 = ['isRefined', 'count:desc', 'name:asc'];
var connectRefinementList = createConnector({
displayName: 'AlgoliaRefinementList',
propTypes: {
id: propTypes.string,
attribute: propTypes.string.isRequired,
operator: propTypes.oneOf(['and', 'or']),
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])),
searchable: propTypes.bool,
transformItems: propTypes.func
},
defaultProps: {
operator: 'or',
showMore: false,
limit: 10,
showMoreLimit: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) {
var _this = this;
var attribute = props.attribute,
searchable = props.searchable;
var results = getResults(searchResults, this.context);
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== '');
// Search For Facet Values is not available with derived helper (used for multi index search)
if (searchable && this.context.multiIndexContext) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement$7(props, searchState, this.context),
canRefine: canRefine,
isFromSearch: isFromSearch,
searchable: searchable
};
}
var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) {
return {
label: v.value,
value: getValue$3(v.value, props, searchState, _this.context),
_highlightResult: { label: { value: v.highlighted } },
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attribute, { sortBy: sortBy$2 }).map(function (v) {
return {
label: v.name,
value: getValue$3(v.name, props, searchState, _this.context),
count: v.count,
isRefined: v.isRefined
};
});
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, getLimit$1(props)),
currentRefinement: getCurrentRefinement$7(props, searchState, this.context),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: items.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$5(props, searchState, nextRefinement, this.context);
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return {
facetName: props.attribute,
query: nextRefinement,
maxFacetHits: getLimit$1(props)
};
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$4(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute,
operator = props.operator;
var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet';
var addRefinementKey = addKey + 'Refinement';
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props))
});
searchParameters = searchParameters[addKey](attribute);
return getCurrentRefinement$7(props, searchState, this.context).reduce(function (res, val) {
return res[addRefinementKey](attribute, val);
}, searchParameters);
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$8(props);
var context = this.context;
return {
id: id,
index: getIndex(this.context),
items: getCurrentRefinement$7(props, searchState, context).length > 0 ? [{
attribute: props.attribute,
label: props.attribute + ': ',
currentRefinement: getCurrentRefinement$7(props, searchState, context),
value: function value(nextState) {
return _refine$5(props, nextState, [], context);
},
items: getCurrentRefinement$7(props, searchState, context).map(function (item) {
return {
label: '' + item,
value: function value(nextState) {
var nextSelectedItems = getCurrentRefinement$7(props, nextState, context).filter(function (other) {
return other !== item;
});
return _refine$5(props, searchState, nextSelectedItems, context);
}
};
})
}] : []
};
}
});
var cx$15 = createClassNames('RefinementList');
var RefinementList$1 = function (_Component) {
inherits(RefinementList, _Component);
function RefinementList() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, RefinementList);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = RefinementList.__proto__ || Object.getPrototypeOf(RefinementList)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
query: ''
}, _this.selectItem = function (item, resetQuery) {
resetQuery();
_this.props.refine(item.value);
}, _this.renderItem = function (item, resetQuery) {
var label = _this.props.isFromSearch ? React__default.createElement(Highlight$2, { attribute: 'label', hit: item }) : item.label;
return React__default.createElement(
'label',
{ className: cx$15('label') },
React__default.createElement('input', {
className: cx$15('checkbox'),
type: 'checkbox',
checked: item.isRefined,
onChange: function onChange() {
return _this.selectItem(item, resetQuery);
}
}),
React__default.createElement(
'span',
{ className: cx$15('labelText') },
label
),
' ',
React__default.createElement(
'span',
{ className: cx$15('count') },
item.count.toLocaleString()
)
);
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(RefinementList, [{
key: 'render',
value: function render() {
return React__default.createElement(List, _extends({
renderItem: this.renderItem,
selectItem: this.selectItem,
cx: cx$15
}, pick_1(this.props, ['translate', 'items', 'showMore', 'limit', 'showMoreLimit', 'isFromSearch', 'searchForItems', 'searchable', 'canRefine', 'className']), {
query: this.state.query
}));
}
}]);
return RefinementList;
}(React.Component);
RefinementList$1.propTypes = {
translate: propTypes.func.isRequired,
refine: propTypes.func.isRequired,
searchForItems: propTypes.func.isRequired,
searchable: propTypes.bool,
createURL: propTypes.func.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.arrayOf(propTypes.string).isRequired,
count: propTypes.number.isRequired,
isRefined: propTypes.bool.isRequired
})),
isFromSearch: propTypes.bool.isRequired,
canRefine: propTypes.bool.isRequired,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
transformItems: propTypes.func,
className: propTypes.string
};
RefinementList$1.defaultProps = {
className: ''
};
var RefinementList$2 = translatable({
showMore: function showMore(extended) {
return extended ? 'Show less' : 'Show more';
},
noResults: 'No results',
submit: null,
reset: null,
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…'
})(RefinementList$1);
/**
* The RefinementList component displays a list that let the end user choose multiple values for a specific facet.
* @name RefinementList
* @kind widget
* @propType {string} attribute - the name of the attribute in the record
* @propType {boolean} [searchable=false] - true if the component should display an input to search for facet values. <br> In order to make this feature work, you need to make the attribute searchable [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) or [the dashboard](https://www.algolia.com/explorer/display/).
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limit=10] - the minimum number of displayed items
* @propType {number} [showMoreLimit=20] - the maximum number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} [defaultRefinement] - the values of the items selected by default
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-RefinementList - the root div of the widget
* @themeKey ais-RefinementList--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-RefinementList-searchBox - the search box of the widget. See [the SearchBox documentation](widgets/SearchBox.html#classnames) for the classnames and translation keys of the SearchBox.
* @themeKey ais-RefinementList-list - the list of refinement items
* @themeKey ais-RefinementList-item - the refinement list item
* @themeKey ais-RefinementList-item--selected - the refinement selected list item
* @themeKey ais-RefinementList-label - the label of each refinement item
* @themeKey ais-RefinementList-checkbox - the checkbox input of each refinement item
* @themeKey ais-RefinementList-labelText - the label text of each refinement item
* @themeKey ais-RefinementList-count - the count of values for each item
* @themeKey ais-RefinementList-noResults - the div displayed when there are no results
* @themeKey ais-RefinementList-showMore - the button used to display more categories
* @themeKey ais-RefinementList-showMore--disabled - the disabled button used to display more categories
* @translationkey showMore - The label of the show more button. Accepts one parameters, a boolean that is true if the values are expanded
* @translationkey noResults - The label of the no results text when no search for facet values results are found.
* @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* If you are using the `searchable` prop, you'll also need to make the attribute searchable using
* the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values).
* @example
* import React from 'react';
*
* import { RefinementList, InstantSearch } from '../packages/react-instantsearch/dom';
*
* export default function App() {
* return (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <RefinementList attribute="colors" />
* </InstantSearch>
* );
* }
*/
var RefinementListWidget = function RefinementListWidget(props) {
return React__default.createElement(
PanelCallbackHandler,
props,
React__default.createElement(RefinementList$2, props)
);
};
var RefinementList$3 = connectRefinementList(RefinementListWidget);
var cx$16 = createClassNames('ClearRefinements');
var ClearRefinements = function (_Component) {
inherits(ClearRefinements, _Component);
function ClearRefinements() {
classCallCheck(this, ClearRefinements);
return possibleConstructorReturn(this, (ClearRefinements.__proto__ || Object.getPrototypeOf(ClearRefinements)).apply(this, arguments));
}
createClass(ClearRefinements, [{
key: 'render',
value: function render() {
var _props = this.props,
items = _props.items,
canRefine = _props.canRefine,
refine = _props.refine,
translate = _props.translate,
className = _props.className;
return React__default.createElement(
'div',
{ className: classnames(cx$16(''), className) },
React__default.createElement(
'button',
{
className: cx$16('button', !canRefine && 'button--disabled'),
onClick: function onClick() {
return refine(items);
},
disabled: !canRefine
},
translate('reset')
)
);
}
}]);
return ClearRefinements;
}(React.Component);
ClearRefinements.propTypes = {
items: propTypes.arrayOf(propTypes.object).isRequired,
canRefine: propTypes.bool.isRequired,
refine: propTypes.func.isRequired,
translate: propTypes.func.isRequired,
className: propTypes.string
};
ClearRefinements.defaultProps = {
className: ''
};
var ClearRefinements$1 = translatable({
reset: 'Clear all filters'
})(ClearRefinements);
/**
* The ClearRefinements widget displays a button that lets the user clean every refinement applied
* to the search.
* @name ClearRefinements
* @kind widget
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {boolean} [clearsQuery=false] - Pass true to also clear the search query
* @themeKey ais-ClearRefinements - the root div of the widget
* @themeKey ais-ClearRefinements-button - the clickable button
* @themeKey ais-ClearRefinements-button--disabled - the disabled clickable button
* @translationKey reset - the clear all button value
* @example
* import React from 'react';
* import { InstantSearch, ClearRefinements, RefinementList } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <ClearRefinements />
* <RefinementList
* attribute="colors"
* defaultRefinement={['Black']}
* />
* </InstantSearch>
* );
*/
var ClearRefinementsWidget = function ClearRefinementsWidget(props) {
return React__default.createElement(
PanelCallbackHandler,
props,
React__default.createElement(ClearRefinements$1, props)
);
};
var ClearRefinements$2 = connectCurrentRefinements(ClearRefinementsWidget);
/**
* connectScrollTo connector provides the logic to build a widget that will
* let the page scroll to a certain point.
* @name connectScrollTo
* @kind connector
* @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget.
* @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo
* @providedPropType {boolean} hasNotChanged - indicates whether the refinement came from the scrollOn argument (for instance page by default)
*/
var connectScrollTo = createConnector({
displayName: 'AlgoliaScrollTo',
propTypes: {
scrollOn: propTypes.string
},
defaultProps: {
scrollOn: 'page'
},
getProvidedProps: function getProvidedProps(props, searchState) {
var id = props.scrollOn;
var value = getCurrentRefinementValue(props, searchState, this.context, id, null, function (currentRefinement) {
return currentRefinement;
});
if (!this._prevSearchState) {
this._prevSearchState = {};
}
/* Get the subpart of the state that interest us*/
if (hasMultipleIndex(this.context)) {
var index = getIndex(this.context);
searchState = searchState.indices ? searchState.indices[index] : {};
}
/*
if there is a change in the app that has been triggered by another element than
"props.scrollOn (id) or the Configure widget, we need to keep track of the search state to
know if there's a change in the app that was not triggered by the props.scrollOn (id)
or the Configure widget. This is useful when using ScrollTo in combination of Pagination.
As pagination can be change by every widget, we want to scroll only if it cames from the pagination
widget itself. We also remove the configure key from the search state to do this comparaison because for
now configure values are not present in the search state before a first refinement has been made
and will false the results.
See: https://github.com/algolia/react-instantsearch/issues/164
*/
var cleanedSearchState = omit_1(omit_1(searchState, 'configure'), id);
var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState);
this._prevSearchState = cleanedSearchState;
return { value: value, hasNotChanged: hasNotChanged };
}
});
var cx$17 = createClassNames('ScrollTo');
var ScrollTo = function (_Component) {
inherits(ScrollTo, _Component);
function ScrollTo() {
classCallCheck(this, ScrollTo);
return possibleConstructorReturn(this, (ScrollTo.__proto__ || Object.getPrototypeOf(ScrollTo)).apply(this, arguments));
}
createClass(ScrollTo, [{
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
var _props = this.props,
value = _props.value,
hasNotChanged = _props.hasNotChanged;
if (value !== prevProps.value && hasNotChanged) {
this.el.scrollIntoView();
}
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
return React__default.createElement(
'div',
{ ref: function ref(_ref) {
return _this2.el = _ref;
}, className: cx$17('') },
this.props.children
);
}
}]);
return ScrollTo;
}(React.Component);
ScrollTo.propTypes = {
value: propTypes.any,
children: propTypes.node,
hasNotChanged: propTypes.bool
};
/**
* The ScrollTo component will make the page scroll to the component wrapped by it when one of the
* [search state](guide/Search_state.html) prop is updated. By default when the page number changes,
* the scroll goes to the wrapped component.
*
* @name ScrollTo
* @kind widget
* @propType {string} [scrollOn="page"] - Widget state key on which to listen for changes.
* @themeKey ais-ScrollTo - the root div of the widget
* @example
* import React from 'react';
* import { InstantSearch, ScrollTo, Hits } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <ScrollTo>
* <Hits />
* </ScrollTo>
* </InstantSearch>
* );
*/
var ScrollTo$1 = connectScrollTo(ScrollTo);
function getId$9() {
return 'query';
}
function getCurrentRefinement$8(props, searchState, context) {
var id = getId$9(props);
return getCurrentRefinementValue(props, searchState, context, id, '', function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return '';
});
}
function _refine$6(props, searchState, nextRefinement, context) {
var id = getId$9();
var nextValue = defineProperty$1({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage);
}
function _cleanUp$5(props, searchState, context) {
return cleanUpValue(searchState, context, getId$9());
}
/**
* 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.
* @providedPropType {boolean} isSearchStalled - a flag that indicates if react-is has detected that searches are stalled.
*/
var connectSearchBox = createConnector({
displayName: 'AlgoliaSearchBox',
propTypes: {
defaultRefinement: propTypes.string
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
return {
currentRefinement: getCurrentRefinement$8(props, searchState, this.context),
isSearchStalled: searchResults.isSearchStalled
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$6(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$5(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement$8(props, searchState, this.context));
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId$9(props);
var currentRefinement = getCurrentRefinement$8(props, searchState, this.context);
return {
id: id,
index: getIndex(this.context),
items: currentRefinement === null ? [] : [{
label: id + ': ' + currentRefinement,
value: function value(nextState) {
return _refine$6(props, nextState, '', _this.context);
},
currentRefinement: currentRefinement
}]
};
}
});
/**
* The SearchBox component displays a search box that lets the user search for a specific query.
* @name SearchBox
* @kind widget
* @propType {string[]} [focusShortcuts=['s','/']] - List of keyboard shortcuts that focus the search box. Accepts key names and key codes.
* @propType {boolean} [autoFocus=false] - Should the search box be focused on render?
* @propType {boolean} [searchAsYouType=true] - Should we search on every change to the query? If you disable this option, new searches will only be triggered by clicking the search button or by pressing the enter key while the search box is focused.
* @propType {function} [onSubmit] - Intercept submit event sent from the SearchBox form container.
* @propType {function} [onReset] - Listen to `reset` event sent from the SearchBox form container.
* @propType {function} [on*] - Listen to any events sent form the search input itself.
* @propType {node} [submit] - Change the apparence of the default submit button (magnifying glass).
* @propType {node} [reset] - Change the apparence of the default reset button (cross).
* @propType {node} [loadingIndicator] - Change the apparence of the default loading indicator (spinning circle).
* @propType {string} [defaultRefinement] - Provide default refinement value when component is mounted.
* @propType {boolean} [showLoadingIndicator=false] - Display that the search is loading. This only happens after a certain amount of time to avoid a blinking effect. This timer can be configured with `stalledSearchDelay` props on <InstantSearch>. By default, the value is 200ms.
* @themeKey ais-SearchBox - the root div of the widget
* @themeKey ais-SearchBox-form - the wrapping form
* @themeKey ais-SearchBox-input - the search input
* @themeKey ais-SearchBox-submit - the submit button
* @themeKey ais-SearchBox-submitIcon - the default magnifier icon used with the search input
* @themeKey ais-SearchBox-reset - the reset button used to clear the content of the input
* @themeKey ais-SearchBox-resetIcon - the default reset icon used inside the reset button
* @themeKey ais-SearchBox-loadingIndicator - the loading indicator container
* @themeKey ais-SearchBox-loadingIcon - the default loading icon
* @translationkey submitTitle - The submit button title
* @translationkey resetTitle - The reset button title
* @translationkey placeholder - The label of the input placeholder
* @example
* import React from 'react';
* import { InstantSearch, SearchBox } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SearchBox />
* </InstantSearch>
* );
*/
var SearchBox$2 = connectSearchBox(SearchBox$1);
function getId$10() {
return 'sortBy';
}
function getCurrentRefinement$9(props, searchState, context) {
var id = getId$10(props);
return getCurrentRefinementValue(props, searchState, context, id, null, function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return null;
});
}
/**
* The connectSortBy connector provides the logic to build a widget that will
* display a list of indices. This allows a user to change how the hits are being sorted.
* @name connectSortBy
* @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on
* the Algolia website.
* @kind connector
* @propType {string} defaultRefinement - The default selected index.
* @propType {{value: string, label: string}[]} items - The list of indexes to search in.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
var connectSortBy = createConnector({
displayName: 'AlgoliaSortBy',
propTypes: {
defaultRefinement: propTypes.string,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string,
value: propTypes.string.isRequired
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement$9(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$10();
var nextValue = defineProperty$1({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, this.context, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, this.context, getId$10());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var selectedIndex = getCurrentRefinement$9(props, searchState, this.context);
return searchParameters.setIndex(selectedIndex);
},
getMetadata: function getMetadata() {
return { id: getId$10() };
}
});
var cx$18 = createClassNames('SortBy');
var SortBy = function (_Component) {
inherits(SortBy, _Component);
function SortBy() {
classCallCheck(this, SortBy);
return possibleConstructorReturn(this, (SortBy.__proto__ || Object.getPrototypeOf(SortBy)).apply(this, arguments));
}
createClass(SortBy, [{
key: 'render',
value: function render() {
var _props = this.props,
items = _props.items,
currentRefinement = _props.currentRefinement,
refine = _props.refine,
className = _props.className;
return React__default.createElement(
'div',
{ className: classnames(cx$18(''), className) },
React__default.createElement(Select, {
cx: cx$18,
items: items,
selectedItem: currentRefinement,
onSelect: refine
})
);
}
}]);
return SortBy;
}(React.Component);
SortBy.propTypes = {
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string,
value: propTypes.string.isRequired
})).isRequired,
currentRefinement: propTypes.string.isRequired,
refine: propTypes.func.isRequired,
className: propTypes.string
};
SortBy.defaultProps = {
className: ''
};
/**
* The SortBy component displays a list of indexes allowing a user to change the hits are sorting.
* @name SortBy
* @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on
* the Algolia website.
* @kind widget
* @propType {{value: string, label: string}[]} items - The list of indexes to search in.
* @propType {string} defaultRefinement - The default selected index.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @themeKey ais-SortBy - the root div of the widget
* @themeKey ais-SortBy-select - the select
* @themeKey ais-SortBy-option - the select option
* @example
* import React from 'react';
* import { InstantSearch, SortBy } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <SortBy
* defaultRefinement="ikea"
* items={[
* { value: 'ikea', label: 'Featured' },
* { value: 'ikea_price_asc', label: 'Price asc.' },
* { value: 'ikea_price_desc', label: 'Price desc.' },
* ]}
* />
* </InstantSearch>
* );
*/
var SortBy$1 = connectSortBy(SortBy);
/**
* connectStats connector provides the logic to build a widget that will
* displays algolia search statistics (hits number and processing time).
* @name connectStats
* @kind connector
* @providedPropType {number} nbHits - number of hits returned by Algolia.
* @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results.
*/
var connectStats = createConnector({
displayName: 'AlgoliaStats',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, this.context);
if (!results) {
return null;
}
return {
nbHits: results.nbHits,
processingTimeMS: results.processingTimeMS
};
}
});
var cx$19 = createClassNames('Stats');
var Stats = function (_Component) {
inherits(Stats, _Component);
function Stats() {
classCallCheck(this, Stats);
return possibleConstructorReturn(this, (Stats.__proto__ || Object.getPrototypeOf(Stats)).apply(this, arguments));
}
createClass(Stats, [{
key: 'render',
value: function render() {
var _props = this.props,
translate = _props.translate,
nbHits = _props.nbHits,
processingTimeMS = _props.processingTimeMS,
className = _props.className;
return React__default.createElement(
'div',
{ className: classnames(cx$19(''), className) },
React__default.createElement(
'span',
{ className: cx$19('text') },
translate('stats', nbHits, processingTimeMS)
)
);
}
}]);
return Stats;
}(React.Component);
Stats.propTypes = {
translate: propTypes.func.isRequired,
nbHits: propTypes.number.isRequired,
processingTimeMS: propTypes.number.isRequired,
className: propTypes.string
};
Stats.defaultProps = {
className: ''
};
var Stats$1 = translatable({
stats: function stats(n, ms) {
return n.toLocaleString() + ' results found in ' + ms.toLocaleString() + 'ms';
}
})(Stats);
/**
* The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server).
* @name Stats
* @kind widget
* @themeKey ais-Stats - the root div of the widget
* @themeKey ais-Stats-text - the text of the widget - the count of items for each item
* @translationkey stats - The string displayed by the stats widget. You get function(n, ms) and you need to return a string. n is a number of hits retrieved, ms is a processed time.
* @example
* import React from 'react';
* import { InstantSearch, Stats, Hits } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Stats />
* <Hits />
* </InstantSearch>
* );
*/
var Stats$2 = connectStats(Stats$1);
function getId$11(props) {
return props.attribute;
}
var namespace$5 = 'toggle';
function getCurrentRefinement$10(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, namespace$5 + '.' + getId$11(props), false, function (currentRefinement) {
if (currentRefinement) {
return currentRefinement;
}
return false;
});
}
function _refine$7(props, searchState, nextRefinement, context) {
var id = getId$11(props);
var nextValue = defineProperty$1({}, id, nextRefinement ? nextRefinement : false);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$5);
}
function _cleanUp$6(props, searchState, context) {
return cleanUpValue(searchState, context, namespace$5 + '.' + getId$11(props));
}
/**
* connectToggleRefinement connector provides the logic to build a widget that will
* provides an on/off filtering feature based on an attribute value.
* @name connectToggleRefinement
* @kind connector
* @requirements To use this widget, you'll need an attribute to toggle on.
*
* You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an
* extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details.
*
* @propType {string} attribute - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {string} value - Value of the refinement to apply on `attribute`.
* @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default?
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {boolean} currentRefinement - `true` when the refinement is applied, `false` otherwise
*/
var connectToggleRefinement = createConnector({
displayName: 'AlgoliaToggle',
propTypes: {
label: propTypes.string,
filter: propTypes.func,
attribute: propTypes.string,
value: propTypes.any,
defaultRefinement: propTypes.bool
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement$10(props, searchState, this.context);
return { currentRefinement: currentRefinement };
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$7(props, searchState, nextRefinement, this.context);
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$6(props, searchState, this.context);
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute,
value = props.value,
filter = props.filter;
var checked = getCurrentRefinement$10(props, searchState, this.context);
if (checked) {
if (attribute) {
searchParameters = searchParameters.addFacet(attribute).addFacetRefinement(attribute, value);
}
if (filter) {
searchParameters = filter(searchParameters);
}
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var id = getId$11(props);
var checked = getCurrentRefinement$10(props, searchState, this.context);
var items = [];
var index = getIndex(this.context);
if (checked) {
items.push({
label: props.label,
currentRefinement: checked,
attribute: props.attribute,
value: function value(nextState) {
return _refine$7(props, nextState, false, _this.context);
}
});
}
return { id: id, index: index, items: items };
}
});
var cx$20 = createClassNames('ToggleRefinement');
var ToggleRefinement = function ToggleRefinement(_ref) {
var currentRefinement = _ref.currentRefinement,
label = _ref.label,
refine = _ref.refine,
className = _ref.className;
return React__default.createElement(
'div',
{ className: classnames(cx$20(''), className) },
React__default.createElement(
'label',
{ className: cx$20('label') },
React__default.createElement('input', {
className: cx$20('checkbox'),
type: 'checkbox',
checked: currentRefinement,
onChange: function onChange(event) {
return refine(event.target.checked);
}
}),
React__default.createElement(
'span',
{ className: cx$20('labelText') },
label
)
)
);
};
ToggleRefinement.propTypes = {
currentRefinement: propTypes.bool.isRequired,
label: propTypes.string.isRequired,
refine: propTypes.func.isRequired,
className: propTypes.string
};
ToggleRefinement.defaultProps = {
className: ''
};
/**
* The ToggleRefinement provides an on/off filtering feature based on an attribute value.
* @name ToggleRefinement
* @kind widget
* @requirements To use this widget, you'll need an attribute to toggle on.
*
* You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an
* extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details.
*
* @propType {string} attribute - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {any} value - Value of the refinement to apply on `attribute` when checked.
* @propType {boolean} [defaultRefinement=false] - Default state of the widget. Should the toggle be checked by default?
* @themeKey ais-ToggleRefinement - the root div of the widget
* @themeKey ais-ToggleRefinement-list - the list of toggles
* @themeKey ais-ToggleRefinement-item - the toggle list item
* @themeKey ais-ToggleRefinement-label - the label of each toggle item
* @themeKey ais-ToggleRefinement-checkbox - the checkbox input of each toggle item
* @themeKey ais-ToggleRefinement-labelText - the label text of each toggle item
* @themeKey ais-ToggleRefinement-count - the count of items for each item
* @example
* import React from 'react';
* import { InstantSearch, ToggleRefinement } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <ToggleRefinement
* attribute="materials"
* label="Made with solid pine"
* value="Solid pine"
* />
* </InstantSearch>
* );
*/
var ToggleRefinement$1 = connectToggleRefinement(ToggleRefinement);
var cx$21 = createClassNames('Panel');
var Panel = function (_Component) {
inherits(Panel, _Component);
function Panel() {
var _ref;
var _temp, _this, _ret;
classCallCheck(this, Panel);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = Panel.__proto__ || Object.getPrototypeOf(Panel)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
canRefine: true
}, _this.setCanRefine = function (nextCanRefine) {
_this.setState({ canRefine: nextCanRefine });
}, _temp), possibleConstructorReturn(_this, _ret);
}
createClass(Panel, [{
key: 'getChildContext',
value: function getChildContext() {
return {
setCanRefine: this.setCanRefine
};
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
children = _props.children,
className = _props.className,
header = _props.header,
footer = _props.footer;
var canRefine = this.state.canRefine;
return React__default.createElement(
'div',
{
className: classnames(cx$21('', !canRefine && '-noRefinement'), className)
},
header && React__default.createElement(
'div',
{ className: cx$21('header') },
header
),
React__default.createElement(
'div',
{ className: cx$21('body') },
children
),
footer && React__default.createElement(
'div',
{ className: cx$21('footer') },
footer
)
);
}
}]);
return Panel;
}(React.Component);
Panel.propTypes = {
children: propTypes.node.isRequired,
className: propTypes.string,
header: propTypes.node,
footer: propTypes.node
};
Panel.childContextTypes = {
setCanRefine: propTypes.func.isRequired
};
Panel.defaultProps = {
className: '',
header: null,
footer: null
};
var getId$12 = function getId(props) {
return props.attributes[0];
};
var namespace$6 = 'hierarchicalMenu';
function _refine$8(props, searchState, nextRefinement, context) {
var id = getId$12(props);
var nextValue = defineProperty$1({}, id, nextRefinement || '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$6);
}
function transformValue$1(values) {
return values.reduce(function (acc, item) {
if (item.isRefined) {
acc.push({
label: item.name,
// If dealing with a nested "items", "value" is equal to the previous value concatenated with the current label
// If dealing with the first level, "value" is equal to the current label
value: item.path
});
// Create a variable in order to keep the same acc for the recursion, otherwise "reduce" returns a new one
if (item.data) {
acc = acc.concat(transformValue$1(item.data, acc));
}
}
return acc;
}, []);
}
/**
* The breadcrumb component is s a type of secondary navigation scheme that
* reveals the user’s location in a website or web application.
*
* @name connectBreadcrumb
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a Breadcrumb of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display.
*/
var connectBreadcrumb = createConnector({
displayName: 'AlgoliaBreadcrumb',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error('Invalid prop ' + propName + ' supplied to ' + componentName + '. Expected an Array of Strings');
}
return undefined;
},
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var id = getId$12(props);
var results = getResults(searchResults, this.context);
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
canRefine: false
};
}
var values = results.getFacetValues(id);
var items = values.data ? transformValue$1(values.data) : [];
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
canRefine: transformedItems.length > 0,
items: transformedItems
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$8(props, searchState, nextRefinement, this.context);
}
});
var cx$22 = createClassNames('Breadcrumb');
var itemsPropType$2 = propTypes.arrayOf(propTypes.shape({
label: propTypes.string.isRequired,
value: propTypes.string.isRequired
}));
var Breadcrumb = function (_Component) {
inherits(Breadcrumb, _Component);
function Breadcrumb() {
classCallCheck(this, Breadcrumb);
return possibleConstructorReturn(this, (Breadcrumb.__proto__ || Object.getPrototypeOf(Breadcrumb)).apply(this, arguments));
}
createClass(Breadcrumb, [{
key: 'render',
value: function render() {
var _props = this.props,
canRefine = _props.canRefine,
createURL = _props.createURL,
items = _props.items,
refine = _props.refine,
rootURL = _props.rootURL,
separator = _props.separator,
translate = _props.translate,
className = _props.className;
var rootPath = canRefine ? React__default.createElement(
'li',
{ className: cx$22('item') },
React__default.createElement(
Link,
{
className: cx$22('link'),
onClick: function onClick() {
return !rootURL ? refine() : null;
},
href: rootURL ? rootURL : createURL()
},
translate('rootLabel')
)
) : null;
var breadcrumb = items.map(function (item, idx) {
var isLast = idx === items.length - 1;
return React__default.createElement(
'li',
{ className: cx$22('item', isLast && 'item--selected'), key: idx },
React__default.createElement(
'span',
{ className: cx$22('separator') },
separator
),
!isLast ? React__default.createElement(
Link,
{
className: cx$22('link'),
onClick: function onClick() {
return refine(item.value);
},
href: createURL(item.value)
},
item.label
) : item.label
);
});
return React__default.createElement(
'div',
{
className: classnames(cx$22('', !canRefine && '-noRefinement'), className)
},
React__default.createElement(
'ul',
{ className: cx$22('list') },
rootPath,
breadcrumb
)
);
}
}]);
return Breadcrumb;
}(React.Component);
Breadcrumb.propTypes = {
canRefine: propTypes.bool.isRequired,
createURL: propTypes.func.isRequired,
items: itemsPropType$2,
refine: propTypes.func.isRequired,
rootURL: propTypes.string,
separator: propTypes.node,
translate: propTypes.func.isRequired,
className: propTypes.string
};
Breadcrumb.defaultProps = {
rootURL: null,
separator: ' > ',
className: ''
};
var Breadcrumb$1 = translatable({
rootLabel: 'Home'
})(Breadcrumb);
/**
* A breadcrumb is a secondary navigation scheme that allows the user to see where the current page
* is in relation to the website or web application’s hierarchy.
* In terms of usability, using a breadcrumb reduces the number of actions a visitor needs to take in
* order to get to a higher-level page.
*
* If you want to select a specific refinement for your Breadcrumb component, you will need to
* use a [Virtual Hierarchical Menu](https://community.algolia.com/react-instantsearch/guide/Virtual_widgets.html)
* and set its defaultRefinement that will be then used by the Breadcrumb.
*
* @name Breadcrumb
* @kind widget
* @requirements Breadcrumbs are used for websites with a large amount of content organised in a hierarchical manner.
* The typical example is an e-commerce website which has a large variety of products grouped into logical categories
* (with categories, subcategories which also have subcategories).To use this widget, your attributes must be formatted in a specific way.
*
* Keep in mind that breadcrumbs shouldn’t replace effective primary navigation menus:
* it is only an alternative way to navigate around the website.
*
* If, for instance, you would like to have a breadcrumb of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow
* @propType {node} [separator='>'] - Symbol used for separating hyperlinks
* @propType {string} [rootURL=null] - The originating page (homepage)
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return
* @themeKey ais-Breadcrumb - the root div of the widget
* @themeKey ais-Breadcrumb--noRefinement - the root div of the widget when there is no refinement
* @themeKey ais-Breadcrumb-list - the list of all breadcrumb items
* @themeKey ais-Breadcrumb-item - the breadcrumb navigation item
* @themeKey ais-Breadcrumb-item--selected - the selected breadcrumb item
* @themeKey ais-Breadcrumb-separator - the separator of each breadcrumb item
* @themeKey ais-Breadcrumb-link - the clickable breadcrumb element
* @translationKey rootLabel - The root's label. Accepts a string
* @example
* import React from 'react';
* import { Breadcrumb, InstantSearch, HierarchicalMenu } from 'react-instantsearch/dom';
*
* const App = () => (
* <InstantSearch
* appId="latency"
* apiKey="6be0576ff61c053d5f9a3225e2a90f76"
* indexName="ikea"
* >
* <Breadcrumb
* attributes={[
* 'category',
* 'sub_category',
* 'sub_sub_category',
* ]}
* />
* <HierarchicalMenu
* defaultRefinement="Kitchen & appliances > Pantry"
* attributes={[
* 'category',
* 'sub_category',
* 'sub_sub_category',
* ]}
* />
* </InstantSearch>
* );
*/
var BreadcrumbWidget = function BreadcrumbWidget(props) {
return React__default.createElement(
PanelCallbackHandler,
props,
React__default.createElement(Breadcrumb$1, props)
);
};
var Breadcrumb$2 = connectBreadcrumb(BreadcrumbWidget);
var InstantSearch$1 = createInstantSearch(algoliasearchLite, {
Root: 'div',
props: { className: 'ais-InstantSearch__root' }
});
var Index$1 = createIndex({
Root: 'div',
props: { className: 'ais-MultiIndex__root' }
});
exports.InstantSearch = InstantSearch$1;
exports.Index = Index$1;
exports.Configure = Configure$1;
exports.CurrentRefinements = CurrentRefinements$2;
exports.HierarchicalMenu = HierarchicalMenu$2;
exports.Highlight = Highlight$2;
exports.Snippet = Snippet$1;
exports.Hits = Hits$1;
exports.HitsPerPage = HitsPerPage$1;
exports.InfiniteHits = InfiniteHits$2;
exports.Menu = Menu$2;
exports.MenuSelect = MenuSelect$2;
exports.NumericMenu = NumericMenu$2;
exports.Pagination = Pagination$2;
exports.PoweredBy = PoweredBy$1;
exports.RangeInput = RangeInput$1;
exports.RangeSlider = RangeSlider;
exports.RatingMenu = RatingMenu$2;
exports.RefinementList = RefinementList$3;
exports.ClearRefinements = ClearRefinements$2;
exports.ScrollTo = ScrollTo$1;
exports.SearchBox = SearchBox$2;
exports.SortBy = SortBy$1;
exports.Stats = Stats$2;
exports.ToggleRefinement = ToggleRefinement$1;
exports.Panel = Panel;
exports.Breadcrumb = Breadcrumb$2;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=Dom.js.map
|
ajax/libs/boardgame-io/0.49.6/boardgameio.es.js | cdnjs/cdnjs | import { nanoid } from 'nanoid/non-secure';
import { applyMiddleware, compose, createStore } from 'redux';
import produce from 'immer';
import isPlainObject from 'lodash.isplainobject';
import { applyPatch, createPatch } from 'rfc6902';
import { stringify, parse } from 'flatted';
import 'setimmediate';
import React from 'react';
import PropTypes from 'prop-types';
import ioNamespace__default from 'socket.io-client';
function noop() { }
const identity = x => x;
function assign(tar, src) {
// @ts-ignore
for (const k in src)
tar[k] = src[k];
return tar;
}
function run(fn) {
return fn();
}
function blank_object() {
return Object.create(null);
}
function run_all(fns) {
fns.forEach(run);
}
function is_function(thing) {
return typeof thing === 'function';
}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}
function is_empty(obj) {
return Object.keys(obj).length === 0;
}
function subscribe(store, ...callbacks) {
if (store == null) {
return noop;
}
const unsub = store.subscribe(...callbacks);
return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
function component_subscribe(component, store, callback) {
component.$$.on_destroy.push(subscribe(store, callback));
}
function create_slot(definition, ctx, $$scope, fn) {
if (definition) {
const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
return definition[0](slot_ctx);
}
}
function get_slot_context(definition, ctx, $$scope, fn) {
return definition[1] && fn
? assign($$scope.ctx.slice(), definition[1](fn(ctx)))
: $$scope.ctx;
}
function get_slot_changes(definition, $$scope, dirty, fn) {
if (definition[2] && fn) {
const lets = definition[2](fn(dirty));
if ($$scope.dirty === undefined) {
return lets;
}
if (typeof lets === 'object') {
const merged = [];
const len = Math.max($$scope.dirty.length, lets.length);
for (let i = 0; i < len; i += 1) {
merged[i] = $$scope.dirty[i] | lets[i];
}
return merged;
}
return $$scope.dirty | lets;
}
return $$scope.dirty;
}
function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
if (slot_changes) {
const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
slot.p(slot_context, slot_changes);
}
}
function get_all_dirty_from_scope($$scope) {
if ($$scope.ctx.length > 32) {
const dirty = [];
const length = $$scope.ctx.length / 32;
for (let i = 0; i < length; i++) {
dirty[i] = -1;
}
return dirty;
}
return -1;
}
function exclude_internal_props(props) {
const result = {};
for (const k in props)
if (k[0] !== '$')
result[k] = props[k];
return result;
}
function null_to_empty(value) {
return value == null ? '' : value;
}
const is_client = typeof window !== 'undefined';
let now = is_client
? () => window.performance.now()
: () => Date.now();
let raf = is_client ? cb => requestAnimationFrame(cb) : noop;
const tasks = new Set();
function run_tasks(now) {
tasks.forEach(task => {
if (!task.c(now)) {
tasks.delete(task);
task.f();
}
});
if (tasks.size !== 0)
raf(run_tasks);
}
/**
* Creates a new task that runs on each raf frame
* until it returns a falsy value or is aborted
*/
function loop(callback) {
let task;
if (tasks.size === 0)
raf(run_tasks);
return {
promise: new Promise(fulfill => {
tasks.add(task = { c: callback, f: fulfill });
}),
abort() {
tasks.delete(task);
}
};
}
function append(target, node) {
target.appendChild(node);
}
function append_styles(target, style_sheet_id, styles) {
const append_styles_to = get_root_for_style(target);
if (!append_styles_to.getElementById(style_sheet_id)) {
const style = element('style');
style.id = style_sheet_id;
style.textContent = styles;
append_stylesheet(append_styles_to, style);
}
}
function get_root_for_style(node) {
if (!node)
return document;
const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
if (root.host) {
return root;
}
return document;
}
function append_empty_stylesheet(node) {
const style_element = element('style');
append_stylesheet(get_root_for_style(node), style_element);
return style_element;
}
function append_stylesheet(node, style) {
append(node.head || node, style);
}
function insert(target, node, anchor) {
target.insertBefore(node, anchor || null);
}
function detach(node) {
node.parentNode.removeChild(node);
}
function destroy_each(iterations, detaching) {
for (let i = 0; i < iterations.length; i += 1) {
if (iterations[i])
iterations[i].d(detaching);
}
}
function element(name) {
return document.createElement(name);
}
function svg_element(name) {
return document.createElementNS('http://www.w3.org/2000/svg', name);
}
function text(data) {
return document.createTextNode(data);
}
function space() {
return text(' ');
}
function empty() {
return text('');
}
function listen(node, event, handler, options) {
node.addEventListener(event, handler, options);
return () => node.removeEventListener(event, handler, options);
}
function stop_propagation(fn) {
return function (event) {
event.stopPropagation();
// @ts-ignore
return fn.call(this, event);
};
}
function attr(node, attribute, value) {
if (value == null)
node.removeAttribute(attribute);
else if (node.getAttribute(attribute) !== value)
node.setAttribute(attribute, value);
}
function to_number(value) {
return value === '' ? null : +value;
}
function children(element) {
return Array.from(element.childNodes);
}
function set_data(text, data) {
data = '' + data;
if (text.wholeText !== data)
text.data = data;
}
function set_input_value(input, value) {
input.value = value == null ? '' : value;
}
function select_option(select, value) {
for (let i = 0; i < select.options.length; i += 1) {
const option = select.options[i];
if (option.__value === value) {
option.selected = true;
return;
}
}
}
function select_value(select) {
const selected_option = select.querySelector(':checked') || select.options[0];
return selected_option && selected_option.__value;
}
function toggle_class(element, name, toggle) {
element.classList[toggle ? 'add' : 'remove'](name);
}
function custom_event(type, detail, bubbles = false) {
const e = document.createEvent('CustomEvent');
e.initCustomEvent(type, bubbles, false, detail);
return e;
}
const active_docs = new Set();
let active = 0;
// https://github.com/darkskyapp/string-hash/blob/master/index.js
function hash(str) {
let hash = 5381;
let i = str.length;
while (i--)
hash = ((hash << 5) - hash) ^ str.charCodeAt(i);
return hash >>> 0;
}
function create_rule(node, a, b, duration, delay, ease, fn, uid = 0) {
const step = 16.666 / duration;
let keyframes = '{\n';
for (let p = 0; p <= 1; p += step) {
const t = a + (b - a) * ease(p);
keyframes += p * 100 + `%{${fn(t, 1 - t)}}\n`;
}
const rule = keyframes + `100% {${fn(b, 1 - b)}}\n}`;
const name = `__svelte_${hash(rule)}_${uid}`;
const doc = get_root_for_style(node);
active_docs.add(doc);
const stylesheet = doc.__svelte_stylesheet || (doc.__svelte_stylesheet = append_empty_stylesheet(node).sheet);
const current_rules = doc.__svelte_rules || (doc.__svelte_rules = {});
if (!current_rules[name]) {
current_rules[name] = true;
stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length);
}
const animation = node.style.animation || '';
node.style.animation = `${animation ? `${animation}, ` : ''}${name} ${duration}ms linear ${delay}ms 1 both`;
active += 1;
return name;
}
function delete_rule(node, name) {
const previous = (node.style.animation || '').split(', ');
const next = previous.filter(name
? anim => anim.indexOf(name) < 0 // remove specific animation
: anim => anim.indexOf('__svelte') === -1 // remove all Svelte animations
);
const deleted = previous.length - next.length;
if (deleted) {
node.style.animation = next.join(', ');
active -= deleted;
if (!active)
clear_rules();
}
}
function clear_rules() {
raf(() => {
if (active)
return;
active_docs.forEach(doc => {
const stylesheet = doc.__svelte_stylesheet;
let i = stylesheet.cssRules.length;
while (i--)
stylesheet.deleteRule(i);
doc.__svelte_rules = {};
});
active_docs.clear();
});
}
let current_component;
function set_current_component(component) {
current_component = component;
}
function get_current_component() {
if (!current_component)
throw new Error('Function called outside component initialization');
return current_component;
}
function afterUpdate(fn) {
get_current_component().$$.after_update.push(fn);
}
function onDestroy(fn) {
get_current_component().$$.on_destroy.push(fn);
}
function createEventDispatcher() {
const component = get_current_component();
return (type, detail) => {
const callbacks = component.$$.callbacks[type];
if (callbacks) {
// TODO are there situations where events could be dispatched
// in a server (non-DOM) environment?
const event = custom_event(type, detail);
callbacks.slice().forEach(fn => {
fn.call(component, event);
});
}
};
}
function setContext(key, context) {
get_current_component().$$.context.set(key, context);
}
function getContext(key) {
return get_current_component().$$.context.get(key);
}
// TODO figure out if we still want to support
// shorthand events, or if we want to implement
// a real bubbling mechanism
function bubble(component, event) {
const callbacks = component.$$.callbacks[event.type];
if (callbacks) {
// @ts-ignore
callbacks.slice().forEach(fn => fn.call(this, event));
}
}
const dirty_components = [];
const binding_callbacks = [];
const render_callbacks = [];
const flush_callbacks = [];
const resolved_promise = Promise.resolve();
let update_scheduled = false;
function schedule_update() {
if (!update_scheduled) {
update_scheduled = true;
resolved_promise.then(flush);
}
}
function add_render_callback(fn) {
render_callbacks.push(fn);
}
let flushing = false;
const seen_callbacks = new Set();
function flush() {
if (flushing)
return;
flushing = true;
do {
// first, call beforeUpdate functions
// and update components
for (let i = 0; i < dirty_components.length; i += 1) {
const component = dirty_components[i];
set_current_component(component);
update(component.$$);
}
set_current_component(null);
dirty_components.length = 0;
while (binding_callbacks.length)
binding_callbacks.pop()();
// then, once components are updated, call
// afterUpdate functions. This may cause
// subsequent updates...
for (let i = 0; i < render_callbacks.length; i += 1) {
const callback = render_callbacks[i];
if (!seen_callbacks.has(callback)) {
// ...so guard against infinite loops
seen_callbacks.add(callback);
callback();
}
}
render_callbacks.length = 0;
} while (dirty_components.length);
while (flush_callbacks.length) {
flush_callbacks.pop()();
}
update_scheduled = false;
flushing = false;
seen_callbacks.clear();
}
function update($$) {
if ($$.fragment !== null) {
$$.update();
run_all($$.before_update);
const dirty = $$.dirty;
$$.dirty = [-1];
$$.fragment && $$.fragment.p($$.ctx, dirty);
$$.after_update.forEach(add_render_callback);
}
}
let promise;
function wait() {
if (!promise) {
promise = Promise.resolve();
promise.then(() => {
promise = null;
});
}
return promise;
}
function dispatch(node, direction, kind) {
node.dispatchEvent(custom_event(`${direction ? 'intro' : 'outro'}${kind}`));
}
const outroing = new Set();
let outros;
function group_outros() {
outros = {
r: 0,
c: [],
p: outros // parent group
};
}
function check_outros() {
if (!outros.r) {
run_all(outros.c);
}
outros = outros.p;
}
function transition_in(block, local) {
if (block && block.i) {
outroing.delete(block);
block.i(local);
}
}
function transition_out(block, local, detach, callback) {
if (block && block.o) {
if (outroing.has(block))
return;
outroing.add(block);
outros.c.push(() => {
outroing.delete(block);
if (callback) {
if (detach)
block.d(1);
callback();
}
});
block.o(local);
}
}
const null_transition = { duration: 0 };
function create_in_transition(node, fn, params) {
let config = fn(node, params);
let running = false;
let animation_name;
let task;
let uid = 0;
function cleanup() {
if (animation_name)
delete_rule(node, animation_name);
}
function go() {
const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;
if (css)
animation_name = create_rule(node, 0, 1, duration, delay, easing, css, uid++);
tick(0, 1);
const start_time = now() + delay;
const end_time = start_time + duration;
if (task)
task.abort();
running = true;
add_render_callback(() => dispatch(node, true, 'start'));
task = loop(now => {
if (running) {
if (now >= end_time) {
tick(1, 0);
dispatch(node, true, 'end');
cleanup();
return running = false;
}
if (now >= start_time) {
const t = easing((now - start_time) / duration);
tick(t, 1 - t);
}
}
return running;
});
}
let started = false;
return {
start() {
if (started)
return;
started = true;
delete_rule(node);
if (is_function(config)) {
config = config();
wait().then(go);
}
else {
go();
}
},
invalidate() {
started = false;
},
end() {
if (running) {
cleanup();
running = false;
}
}
};
}
function create_out_transition(node, fn, params) {
let config = fn(node, params);
let running = true;
let animation_name;
const group = outros;
group.r += 1;
function go() {
const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;
if (css)
animation_name = create_rule(node, 1, 0, duration, delay, easing, css);
const start_time = now() + delay;
const end_time = start_time + duration;
add_render_callback(() => dispatch(node, false, 'start'));
loop(now => {
if (running) {
if (now >= end_time) {
tick(0, 1);
dispatch(node, false, 'end');
if (!--group.r) {
// this will result in `end()` being called,
// so we don't need to clean up here
run_all(group.c);
}
return false;
}
if (now >= start_time) {
const t = easing((now - start_time) / duration);
tick(1 - t, t);
}
}
return running;
});
}
if (is_function(config)) {
wait().then(() => {
// @ts-ignore
config = config();
go();
});
}
else {
go();
}
return {
end(reset) {
if (reset && config.tick) {
config.tick(1, 0);
}
if (running) {
if (animation_name)
delete_rule(node, animation_name);
running = false;
}
}
};
}
function create_bidirectional_transition(node, fn, params, intro) {
let config = fn(node, params);
let t = intro ? 0 : 1;
let running_program = null;
let pending_program = null;
let animation_name = null;
function clear_animation() {
if (animation_name)
delete_rule(node, animation_name);
}
function init(program, duration) {
const d = (program.b - t);
duration *= Math.abs(d);
return {
a: t,
b: program.b,
d,
duration,
start: program.start,
end: program.start + duration,
group: program.group
};
}
function go(b) {
const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;
const program = {
start: now() + delay,
b
};
if (!b) {
// @ts-ignore todo: improve typings
program.group = outros;
outros.r += 1;
}
if (running_program || pending_program) {
pending_program = program;
}
else {
// if this is an intro, and there's a delay, we need to do
// an initial tick and/or apply CSS animation immediately
if (css) {
clear_animation();
animation_name = create_rule(node, t, b, duration, delay, easing, css);
}
if (b)
tick(0, 1);
running_program = init(program, duration);
add_render_callback(() => dispatch(node, b, 'start'));
loop(now => {
if (pending_program && now > pending_program.start) {
running_program = init(pending_program, duration);
pending_program = null;
dispatch(node, running_program.b, 'start');
if (css) {
clear_animation();
animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css);
}
}
if (running_program) {
if (now >= running_program.end) {
tick(t = running_program.b, 1 - t);
dispatch(node, running_program.b, 'end');
if (!pending_program) {
// we're done
if (running_program.b) {
// intro — we can tidy up immediately
clear_animation();
}
else {
// outro — needs to be coordinated
if (!--running_program.group.r)
run_all(running_program.group.c);
}
}
running_program = null;
}
else if (now >= running_program.start) {
const p = now - running_program.start;
t = running_program.a + running_program.d * easing(p / running_program.duration);
tick(t, 1 - t);
}
}
return !!(running_program || pending_program);
});
}
}
return {
run(b) {
if (is_function(config)) {
wait().then(() => {
// @ts-ignore
config = config();
go(b);
});
}
else {
go(b);
}
},
end() {
clear_animation();
running_program = pending_program = null;
}
};
}
function get_spread_update(levels, updates) {
const update = {};
const to_null_out = {};
const accounted_for = { $$scope: 1 };
let i = levels.length;
while (i--) {
const o = levels[i];
const n = updates[i];
if (n) {
for (const key in o) {
if (!(key in n))
to_null_out[key] = 1;
}
for (const key in n) {
if (!accounted_for[key]) {
update[key] = n[key];
accounted_for[key] = 1;
}
}
levels[i] = n;
}
else {
for (const key in o) {
accounted_for[key] = 1;
}
}
}
for (const key in to_null_out) {
if (!(key in update))
update[key] = undefined;
}
return update;
}
function get_spread_object(spread_props) {
return typeof spread_props === 'object' && spread_props !== null ? spread_props : {};
}
function create_component(block) {
block && block.c();
}
function mount_component(component, target, anchor, customElement) {
const { fragment, on_mount, on_destroy, after_update } = component.$$;
fragment && fragment.m(target, anchor);
if (!customElement) {
// onMount happens before the initial afterUpdate
add_render_callback(() => {
const new_on_destroy = on_mount.map(run).filter(is_function);
if (on_destroy) {
on_destroy.push(...new_on_destroy);
}
else {
// Edge case - component was destroyed immediately,
// most likely as a result of a binding initialising
run_all(new_on_destroy);
}
component.$$.on_mount = [];
});
}
after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
const $$ = component.$$;
if ($$.fragment !== null) {
run_all($$.on_destroy);
$$.fragment && $$.fragment.d(detaching);
// TODO null out other refs, including component.$$ (but need to
// preserve final state?)
$$.on_destroy = $$.fragment = null;
$$.ctx = [];
}
}
function make_dirty(component, i) {
if (component.$$.dirty[0] === -1) {
dirty_components.push(component);
schedule_update();
component.$$.dirty.fill(0);
}
component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
}
function init(component, options, instance, create_fragment, not_equal, props, append_styles, dirty = [-1]) {
const parent_component = current_component;
set_current_component(component);
const $$ = component.$$ = {
fragment: null,
ctx: null,
// state
props,
update: noop,
not_equal,
bound: blank_object(),
// lifecycle
on_mount: [],
on_destroy: [],
on_disconnect: [],
before_update: [],
after_update: [],
context: new Map(parent_component ? parent_component.$$.context : options.context || []),
// everything else
callbacks: blank_object(),
dirty,
skip_bound: false,
root: options.target || parent_component.$$.root
};
append_styles && append_styles($$.root);
let ready = false;
$$.ctx = instance
? instance(component, options.props || {}, (i, ret, ...rest) => {
const value = rest.length ? rest[0] : ret;
if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
if (!$$.skip_bound && $$.bound[i])
$$.bound[i](value);
if (ready)
make_dirty(component, i);
}
return ret;
})
: [];
$$.update();
ready = true;
run_all($$.before_update);
// `false` as a special case of no DOM component
$$.fragment = create_fragment ? create_fragment($$.ctx) : false;
if (options.target) {
if (options.hydrate) {
const nodes = children(options.target);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.l(nodes);
nodes.forEach(detach);
}
else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.c();
}
if (options.intro)
transition_in(component.$$.fragment);
mount_component(component, options.target, options.anchor, options.customElement);
flush();
}
set_current_component(parent_component);
}
/**
* Base class for Svelte components. Used when dev=false.
*/
class SvelteComponent {
$destroy() {
destroy_component(this, 1);
this.$destroy = noop;
}
$on(type, callback) {
const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index !== -1)
callbacks.splice(index, 1);
};
}
$set($$props) {
if (this.$$set && !is_empty($$props)) {
this.$$.skip_bound = true;
this.$$set($$props);
this.$$.skip_bound = false;
}
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const MAKE_MOVE = 'MAKE_MOVE';
const GAME_EVENT = 'GAME_EVENT';
const REDO = 'REDO';
const RESET = 'RESET';
const SYNC = 'SYNC';
const UNDO = 'UNDO';
const UPDATE = 'UPDATE';
const PATCH = 'PATCH';
const PLUGIN = 'PLUGIN';
const STRIP_TRANSIENTS = 'STRIP_TRANSIENTS';
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Generate a move to be dispatched to the game move reducer.
*
* @param {string} type - The move type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const makeMove = (type, args, playerID, credentials) => ({
type: MAKE_MOVE,
payload: { type, args, playerID, credentials },
});
/**
* Generate a game event to be dispatched to the flow reducer.
*
* @param {string} type - The event type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const gameEvent = (type, args, playerID, credentials) => ({
type: GAME_EVENT,
payload: { type, args, playerID, credentials },
});
/**
* Generate an automatic game event that is a side-effect of a move.
* @param {string} type - The event type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const automaticGameEvent = (type, args, playerID, credentials) => ({
type: GAME_EVENT,
payload: { type, args, playerID, credentials },
automatic: true,
});
const sync = (info) => ({
type: SYNC,
state: info.state,
log: info.log,
initialState: info.initialState,
clientOnly: true,
});
/**
* Used to update the Redux store's state with patch in response to
* an action coming from another player.
* @param prevStateID previous stateID
* @param stateID stateID after this patch
* @param {Operation[]} patch - The patch to apply.
* @param {LogEntry[]} deltalog - A log delta.
*/
const patch = (prevStateID, stateID, patch, deltalog) => ({
type: PATCH,
prevStateID,
stateID,
patch,
deltalog,
clientOnly: true,
});
/**
* Used to update the Redux store's state in response to
* an action coming from another player.
* @param {object} state - The state to restore.
* @param {Array} deltalog - A log delta.
*/
const update$1 = (state, deltalog) => ({
type: UPDATE,
state,
deltalog,
clientOnly: true,
});
/**
* Used to reset the game state.
* @param {object} state - The initial state.
*/
const reset = (state) => ({
type: RESET,
state,
clientOnly: true,
});
/**
* Used to undo the last move.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const undo = (playerID, credentials) => ({
type: UNDO,
payload: { type: null, args: null, playerID, credentials },
});
/**
* Used to redo the last undone move.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const redo = (playerID, credentials) => ({
type: REDO,
payload: { type: null, args: null, playerID, credentials },
});
/**
* Allows plugins to define their own actions and intercept them.
*/
const plugin = (type, args, playerID, credentials) => ({
type: PLUGIN,
payload: { type, args, playerID, credentials },
});
/**
* Private action used to strip transient metadata (e.g. errors) from the game
* state.
*/
const stripTransients = () => ({
type: STRIP_TRANSIENTS,
});
var ActionCreators = /*#__PURE__*/Object.freeze({
__proto__: null,
makeMove: makeMove,
gameEvent: gameEvent,
automaticGameEvent: automaticGameEvent,
sync: sync,
patch: patch,
update: update$1,
reset: reset,
undo: undo,
redo: redo,
plugin: plugin,
stripTransients: stripTransients
});
/**
* Moves can return this when they want to indicate
* that the combination of arguments is illegal and
* the move ought to be discarded.
*/
const INVALID_MOVE = 'INVALID_MOVE';
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Plugin that allows using Immer to make immutable changes
* to G by just mutating it.
*/
const ImmerPlugin = {
name: 'plugin-immer',
fnWrap: (move) => (G, ctx, ...args) => {
let isInvalid = false;
const newG = produce(G, (G) => {
const result = move(G, ctx, ...args);
if (result === INVALID_MOVE) {
isInvalid = true;
return;
}
return result;
});
if (isInvalid)
return INVALID_MOVE;
return newG;
},
};
// Inlined version of Alea from https://github.com/davidbau/seedrandom.
// Converted to Typescript October 2020.
class Alea {
constructor(seed) {
const mash = Mash();
// Apply the seeding algorithm from Baagoe.
this.c = 1;
this.s0 = mash(' ');
this.s1 = mash(' ');
this.s2 = mash(' ');
this.s0 -= mash(seed);
if (this.s0 < 0) {
this.s0 += 1;
}
this.s1 -= mash(seed);
if (this.s1 < 0) {
this.s1 += 1;
}
this.s2 -= mash(seed);
if (this.s2 < 0) {
this.s2 += 1;
}
}
next() {
const t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
this.s0 = this.s1;
this.s1 = this.s2;
return (this.s2 = t - (this.c = Math.trunc(t)));
}
}
function Mash() {
let n = 0xefc8249d;
const mash = function (data) {
const str = data.toString();
for (let i = 0; i < str.length; i++) {
n += str.charCodeAt(i);
let h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
return mash;
}
function copy(f, t) {
t.c = f.c;
t.s0 = f.s0;
t.s1 = f.s1;
t.s2 = f.s2;
return t;
}
function alea(seed, state) {
const xg = new Alea(seed);
const prng = xg.next.bind(xg);
if (state)
copy(state, xg);
prng.state = () => copy(xg, {});
return prng;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Random
*
* Calls that require a pseudorandom number generator.
* Uses a seed from ctx, and also persists the PRNG
* state in ctx so that moves can stay pure.
*/
class Random {
/**
* constructor
* @param {object} ctx - The ctx object to initialize from.
*/
constructor(state) {
// If we are on the client, the seed is not present.
// Just use a temporary seed to execute the move without
// crashing it. The move state itself is discarded,
// so the actual value doesn't matter.
this.state = state || { seed: '0' };
this.used = false;
}
/**
* Generates a new seed from the current date / time.
*/
static seed() {
return Date.now().toString(36).slice(-10);
}
isUsed() {
return this.used;
}
getState() {
return this.state;
}
/**
* Generate a random number.
*/
_random() {
this.used = true;
const R = this.state;
const seed = R.prngstate ? '' : R.seed;
const rand = alea(seed, R.prngstate);
const number = rand();
this.state = {
...R,
prngstate: rand.state(),
};
return number;
}
api() {
const random = this._random.bind(this);
const SpotValue = {
D4: 4,
D6: 6,
D8: 8,
D10: 10,
D12: 12,
D20: 20,
};
// Generate functions for predefined dice values D4 - D20.
const predefined = {};
for (const key in SpotValue) {
const spotvalue = SpotValue[key];
predefined[key] = (diceCount) => {
return diceCount === undefined
? Math.floor(random() * spotvalue) + 1
: Array.from({ length: diceCount }).map(() => Math.floor(random() * spotvalue) + 1);
};
}
function Die(spotvalue = 6, diceCount) {
return diceCount === undefined
? Math.floor(random() * spotvalue) + 1
: Array.from({ length: diceCount }).map(() => Math.floor(random() * spotvalue) + 1);
}
return {
/**
* Similar to Die below, but with fixed spot values.
* Supports passing a diceCount
* if not defined, defaults to 1 and returns the value directly.
* if defined, returns an array containing the random dice values.
*
* D4: (diceCount) => value
* D6: (diceCount) => value
* D8: (diceCount) => value
* D10: (diceCount) => value
* D12: (diceCount) => value
* D20: (diceCount) => value
*/
...predefined,
/**
* Roll a die of specified spot value.
*
* @param {number} spotvalue - The die dimension (default: 6).
* @param {number} diceCount - number of dice to throw.
* if not defined, defaults to 1 and returns the value directly.
* if defined, returns an array containing the random dice values.
*/
Die,
/**
* Generate a random number between 0 and 1.
*/
Number: () => {
return random();
},
/**
* Shuffle an array.
*
* @param {Array} deck - The array to shuffle. Does not mutate
* the input, but returns the shuffled array.
*/
Shuffle: (deck) => {
const clone = [...deck];
let sourceIndex = deck.length;
let destinationIndex = 0;
const shuffled = Array.from({ length: sourceIndex });
while (sourceIndex) {
const randomIndex = Math.trunc(sourceIndex * random());
shuffled[destinationIndex++] = clone[randomIndex];
clone[randomIndex] = clone[--sourceIndex];
}
return shuffled;
},
_private: this,
};
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const RandomPlugin = {
name: 'random',
noClient: ({ api }) => {
return api._private.isUsed();
},
flush: ({ api }) => {
return api._private.getState();
},
api: ({ data }) => {
const random = new Random(data);
return random.api();
},
setup: ({ game }) => {
let { seed } = game;
if (seed === undefined) {
seed = Random.seed();
}
return { seed };
},
playerView: () => undefined,
};
var GameMethod;
(function (GameMethod) {
GameMethod["MOVE"] = "MOVE";
GameMethod["GAME_ON_END"] = "GAME_ON_END";
GameMethod["PHASE_ON_BEGIN"] = "PHASE_ON_BEGIN";
GameMethod["PHASE_ON_END"] = "PHASE_ON_END";
GameMethod["TURN_ON_BEGIN"] = "TURN_ON_BEGIN";
GameMethod["TURN_ON_MOVE"] = "TURN_ON_MOVE";
GameMethod["TURN_ON_END"] = "TURN_ON_END";
})(GameMethod || (GameMethod = {}));
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
var Errors;
(function (Errors) {
Errors["CalledOutsideHook"] = "Events must be called from moves or the `onBegin`, `onEnd`, and `onMove` hooks.\nThis error probably means you called an event from other game code, like an `endIf` trigger or one of the `turn.order` methods.";
Errors["EndTurnInOnEnd"] = "`endTurn` is disallowed in `onEnd` hooks \u2014 the turn is already ending.";
Errors["MaxTurnEndings"] = "Maximum number of turn endings exceeded for this update.\nThis likely means game code is triggering an infinite loop.";
Errors["PhaseEventInOnEnd"] = "`setPhase` & `endPhase` are disallowed in a phase\u2019s `onEnd` hook \u2014 the phase is already ending.\nIf you\u2019re trying to dynamically choose the next phase when a phase ends, use the phase\u2019s `next` trigger.";
Errors["StageEventInOnEnd"] = "`setStage`, `endStage` & `setActivePlayers` are disallowed in `onEnd` hooks.";
Errors["StageEventInPhaseBegin"] = "`setStage`, `endStage` & `setActivePlayers` are disallowed in a phase\u2019s `onBegin` hook.\nUse `setActivePlayers` in a `turn.onBegin` hook or declare stages with `turn.activePlayers` instead.";
Errors["StageEventInTurnBegin"] = "`setStage` & `endStage` are disallowed in `turn.onBegin`.\nUse `setActivePlayers` or declare stages with `turn.activePlayers` instead.";
})(Errors || (Errors = {}));
/**
* Events
*/
class Events {
constructor(flow, ctx, playerID) {
this.flow = flow;
this.playerID = playerID;
this.dispatch = [];
this.initialTurn = ctx.turn;
this.updateTurnContext(ctx, undefined);
// This is an arbitrarily large upper threshold, which could be made
// configurable via a game option if the need arises.
this.maxEndedTurnsPerAction = ctx.numPlayers * 100;
}
api() {
const events = {
_private: this,
};
for (const type of this.flow.eventNames) {
events[type] = (...args) => {
this.dispatch.push({
type,
args,
phase: this.currentPhase,
turn: this.currentTurn,
calledFrom: this.currentMethod,
// Used to capture a stack trace in case it is needed later.
error: new Error('Events Plugin Error'),
});
};
}
return events;
}
isUsed() {
return this.dispatch.length > 0;
}
updateTurnContext(ctx, methodType) {
this.currentPhase = ctx.phase;
this.currentTurn = ctx.turn;
this.currentMethod = methodType;
}
unsetCurrentMethod() {
this.currentMethod = undefined;
}
/**
* Updates ctx with the triggered events.
* @param {object} state - The state object { G, ctx }.
*/
update(state) {
const initialState = state;
const stateWithError = ({ stack }, message) => ({
...initialState,
plugins: {
...initialState.plugins,
events: {
...initialState.plugins.events,
data: { error: message + '\n' + stack },
},
},
});
EventQueue: for (let i = 0; i < this.dispatch.length; i++) {
const event = this.dispatch[i];
const turnHasEnded = event.turn !== state.ctx.turn;
// This protects against potential infinite loops if specific events are called on hooks.
// The moment we exceed the defined threshold, we just bail out of all phases.
const endedTurns = this.currentTurn - this.initialTurn;
if (endedTurns >= this.maxEndedTurnsPerAction) {
return stateWithError(event.error, Errors.MaxTurnEndings);
}
if (event.calledFrom === undefined) {
return stateWithError(event.error, Errors.CalledOutsideHook);
}
// Stop processing events once the game has finished.
if (state.ctx.gameover)
break EventQueue;
switch (event.type) {
case 'endStage':
case 'setStage':
case 'setActivePlayers': {
switch (event.calledFrom) {
// Disallow all stage events in onEnd and phase.onBegin hooks.
case GameMethod.TURN_ON_END:
case GameMethod.PHASE_ON_END:
return stateWithError(event.error, Errors.StageEventInOnEnd);
case GameMethod.PHASE_ON_BEGIN:
return stateWithError(event.error, Errors.StageEventInPhaseBegin);
// Disallow setStage & endStage in turn.onBegin hooks.
case GameMethod.TURN_ON_BEGIN:
if (event.type === 'setActivePlayers')
break;
return stateWithError(event.error, Errors.StageEventInTurnBegin);
}
// If the turn already ended, don't try to process stage events.
if (turnHasEnded)
continue EventQueue;
break;
}
case 'endTurn': {
if (event.calledFrom === GameMethod.TURN_ON_END ||
event.calledFrom === GameMethod.PHASE_ON_END) {
return stateWithError(event.error, Errors.EndTurnInOnEnd);
}
// If the turn already ended some other way,
// don't try to end the turn again.
if (turnHasEnded)
continue EventQueue;
break;
}
case 'endPhase':
case 'setPhase': {
if (event.calledFrom === GameMethod.PHASE_ON_END) {
return stateWithError(event.error, Errors.PhaseEventInOnEnd);
}
// If the phase already ended some other way,
// don't try to end the phase again.
if (event.phase !== state.ctx.phase)
continue EventQueue;
break;
}
}
const action = automaticGameEvent(event.type, event.args, this.playerID);
state = this.flow.processEvent(state, action);
}
return state;
}
}
/*
* Copyright 2020 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const EventsPlugin = {
name: 'events',
noClient: ({ api }) => api._private.isUsed(),
isInvalid: ({ data }) => data.error || false,
// Update the events plugin’s internal turn context each time a move
// or hook is called. This allows events called after turn or phase
// endings to dispatch the current turn and phase correctly.
fnWrap: (method, methodType) => (G, ctx, ...args) => {
const api = ctx.events;
if (api)
api._private.updateTurnContext(ctx, methodType);
G = method(G, ctx, ...args);
if (api)
api._private.unsetCurrentMethod();
return G;
},
dangerouslyFlushRawState: ({ state, api }) => api._private.update(state),
api: ({ game, ctx, playerID }) => new Events(game.flow, ctx, playerID).api(),
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Plugin that makes it possible to add metadata to log entries.
* During a move, you can set metadata using ctx.log.setMetadata and it will be
* available on the log entry for that move.
*/
const LogPlugin = {
name: 'log',
flush: () => ({}),
api: ({ data }) => {
return {
setMetadata: (metadata) => {
data.metadata = metadata;
},
};
},
setup: () => ({}),
};
/**
* Check if a value can be serialized (e.g. using `JSON.stringify`).
* Adapted from: https://stackoverflow.com/a/30712764/3829557
*/
function isSerializable(value) {
// Primitives are OK.
if (value === undefined ||
value === null ||
typeof value === 'boolean' ||
typeof value === 'number' ||
typeof value === 'string') {
return true;
}
// A non-primitive value that is neither a POJO or an array cannot be serialized.
if (!isPlainObject(value) && !Array.isArray(value)) {
return false;
}
// Recurse entries if the value is an object or array.
for (const key in value) {
if (!isSerializable(value[key]))
return false;
}
return true;
}
/**
* Plugin that checks whether state is serializable, in order to avoid
* network serialization bugs.
*/
const SerializablePlugin = {
name: 'plugin-serializable',
fnWrap: (move) => (G, ctx, ...args) => {
const result = move(G, ctx, ...args);
// Check state in non-production environments.
if (process.env.NODE_ENV !== 'production' && !isSerializable(result)) {
throw new Error('Move state is not JSON-serialiazable.\n' +
'See https://boardgame.io/documentation/#/?id=state for more information.');
}
return result;
},
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const production = process.env.NODE_ENV === 'production';
const logfn = production ? () => { } : (...msg) => console.log(...msg);
const errorfn = (...msg) => console.error(...msg);
function info(msg) {
logfn(`INFO: ${msg}`);
}
function error(error) {
errorfn('ERROR:', error);
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* List of plugins that are always added.
*/
const CORE_PLUGINS = [ImmerPlugin, RandomPlugin, LogPlugin, SerializablePlugin];
const DEFAULT_PLUGINS = [...CORE_PLUGINS, EventsPlugin];
/**
* Allow plugins to intercept actions and process them.
*/
const ProcessAction = (state, action, opts) => {
// TODO(#723): Extend error handling to plugins.
opts.game.plugins
.filter((plugin) => plugin.action !== undefined)
.filter((plugin) => plugin.name === action.payload.type)
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
const data = plugin.action(pluginState.data, action.payload);
state = {
...state,
plugins: {
...state.plugins,
[name]: { ...pluginState, data },
},
};
});
return state;
};
/**
* The API's created by various plugins are stored in the plugins
* section of the state object:
*
* {
* G: {},
* ctx: {},
* plugins: {
* plugin-a: {
* data: {}, // this is generated by the plugin at Setup / Flush.
* api: {}, // this is ephemeral and generated by Enhance.
* }
* }
* }
*
* This function takes these API's and stuffs them back into
* ctx for consumption inside a move function or hook.
*/
const EnhanceCtx = (state) => {
const ctx = { ...state.ctx };
const plugins = state.plugins || {};
Object.entries(plugins).forEach(([name, { api }]) => {
ctx[name] = api;
});
return ctx;
};
/**
* Applies the provided plugins to the given move / flow function.
*
* @param methodToWrap - The move function or hook to apply the plugins to.
* @param methodType - The type of the move or hook being wrapped.
* @param plugins - The list of plugins.
*/
const FnWrap = (methodToWrap, methodType, plugins) => {
return [...CORE_PLUGINS, ...plugins, EventsPlugin]
.filter((plugin) => plugin.fnWrap !== undefined)
.reduce((method, { fnWrap }) => fnWrap(method, methodType), methodToWrap);
};
/**
* Allows the plugin to generate its initial state.
*/
const Setup = (state, opts) => {
[...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.setup !== undefined)
.forEach((plugin) => {
const name = plugin.name;
const data = plugin.setup({
G: state.G,
ctx: state.ctx,
game: opts.game,
});
state = {
...state,
plugins: {
...state.plugins,
[name]: { data },
},
};
});
return state;
};
/**
* Invokes the plugin before a move or event.
* The API that the plugin generates is stored inside
* the `plugins` section of the state (which is subsequently
* merged into ctx).
*/
const Enhance = (state, opts) => {
[...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.api !== undefined)
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
const api = plugin.api({
G: state.G,
ctx: state.ctx,
data: pluginState.data,
game: opts.game,
playerID: opts.playerID,
});
state = {
...state,
plugins: {
...state.plugins,
[name]: { ...pluginState, api },
},
};
});
return state;
};
/**
* Allows plugins to update their state after a move / event.
*/
const Flush = (state, opts) => {
// We flush the events plugin first, then custom plugins and the core plugins.
// This means custom plugins cannot use the events API but will be available in event hooks.
// Note that plugins are flushed in reverse, to allow custom plugins calling each other.
[...CORE_PLUGINS, ...opts.game.plugins, EventsPlugin]
.reverse()
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
if (plugin.flush) {
const newData = plugin.flush({
G: state.G,
ctx: state.ctx,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
state = {
...state,
plugins: {
...state.plugins,
[plugin.name]: { data: newData },
},
};
}
else if (plugin.dangerouslyFlushRawState) {
state = plugin.dangerouslyFlushRawState({
state,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
// Remove everything other than data.
const data = state.plugins[name].data;
state = {
...state,
plugins: {
...state.plugins,
[plugin.name]: { data },
},
};
}
});
return state;
};
/**
* Allows plugins to indicate if they should not be materialized on the client.
* This will cause the client to discard the state update and wait for the
* master instead.
*/
const NoClient = (state, opts) => {
return [...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.noClient !== undefined)
.map((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name];
if (pluginState) {
return plugin.noClient({
G: state.G,
ctx: state.ctx,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
}
return false;
})
.includes(true);
};
/**
* Allows plugins to indicate if the entire action should be thrown out
* as invalid. This will cancel the entire state update.
*/
const IsInvalid = (state, opts) => {
const firstInvalidReturn = [...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.isInvalid !== undefined)
.map((plugin) => {
const { name } = plugin;
const pluginState = state.plugins[name];
const message = plugin.isInvalid({
G: state.G,
ctx: state.ctx,
game: opts.game,
data: pluginState && pluginState.data,
});
return message ? { plugin: name, message } : false;
})
.find((value) => value);
return firstInvalidReturn || false;
};
/**
* Update plugin state after move/event & check if plugins consider the update to be valid.
* @returns Tuple of `[updatedState]` or `[originalState, invalidError]`.
*/
const FlushAndValidate = (state, opts) => {
const updatedState = Flush(state, opts);
const isInvalid = IsInvalid(updatedState, opts);
if (!isInvalid)
return [updatedState];
const { plugin, message } = isInvalid;
error(`${plugin} plugin declared action invalid:\n${message}`);
return [state, isInvalid];
};
/**
* Allows plugins to customize their data for specific players.
* For example, a plugin may want to share no data with the client, or
* want to keep some player data secret from opponents.
*/
const PlayerView = ({ G, ctx, plugins = {} }, { game, playerID }) => {
[...DEFAULT_PLUGINS, ...game.plugins].forEach(({ name, playerView }) => {
if (!playerView)
return;
const { data } = plugins[name] || { data: {} };
const newData = playerView({ G, ctx, game, data, playerID });
plugins = {
...plugins,
[name]: { data: newData },
};
});
return plugins;
};
/**
* Adjust the given options to use the new minMoves/maxMoves if a legacy moveLimit was given
* @param options The options object to apply backwards compatibility to
* @param enforceMinMoves Use moveLimit to set both minMoves and maxMoves
*/
function supportDeprecatedMoveLimit(options, enforceMinMoves = false) {
if (options.moveLimit) {
if (enforceMinMoves) {
options.minMoves = options.moveLimit;
}
options.maxMoves = options.moveLimit;
delete options.moveLimit;
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function SetActivePlayers(ctx, arg) {
let activePlayers = {};
let _prevActivePlayers = [];
let _nextActivePlayers = null;
let _activePlayersMinMoves = {};
let _activePlayersMaxMoves = {};
if (Array.isArray(arg)) {
// support a simple array of player IDs as active players
const value = {};
arg.forEach((v) => (value[v] = Stage.NULL));
activePlayers = value;
}
else {
// process active players argument object
// stages previously did not enforce minMoves, this behaviour is kept intentionally
supportDeprecatedMoveLimit(arg);
if (arg.next) {
_nextActivePlayers = arg.next;
}
if (arg.revert) {
_prevActivePlayers = [
...ctx._prevActivePlayers,
{
activePlayers: ctx.activePlayers,
_activePlayersMinMoves: ctx._activePlayersMinMoves,
_activePlayersMaxMoves: ctx._activePlayersMaxMoves,
_activePlayersNumMoves: ctx._activePlayersNumMoves,
},
];
}
if (arg.currentPlayer !== undefined) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, ctx.currentPlayer, arg.currentPlayer);
}
if (arg.others !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
if (id !== ctx.currentPlayer) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, id, arg.others);
}
}
}
if (arg.all !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, id, arg.all);
}
}
if (arg.value) {
for (const id in arg.value) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, id, arg.value[id]);
}
}
if (arg.minMoves) {
for (const id in activePlayers) {
if (_activePlayersMinMoves[id] === undefined) {
_activePlayersMinMoves[id] = arg.minMoves;
}
}
}
if (arg.maxMoves) {
for (const id in activePlayers) {
if (_activePlayersMaxMoves[id] === undefined) {
_activePlayersMaxMoves[id] = arg.maxMoves;
}
}
}
}
if (Object.keys(activePlayers).length === 0) {
activePlayers = null;
}
if (Object.keys(_activePlayersMinMoves).length === 0) {
_activePlayersMinMoves = null;
}
if (Object.keys(_activePlayersMaxMoves).length === 0) {
_activePlayersMaxMoves = null;
}
const _activePlayersNumMoves = {};
for (const id in activePlayers) {
_activePlayersNumMoves[id] = 0;
}
return {
...ctx,
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
_activePlayersNumMoves,
_prevActivePlayers,
_nextActivePlayers,
};
}
/**
* Update activePlayers, setting it to previous, next or null values
* when it becomes empty.
* @param ctx
*/
function UpdateActivePlayersOnceEmpty(ctx) {
let { activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, _activePlayersNumMoves, _prevActivePlayers, _nextActivePlayers, } = ctx;
if (activePlayers && Object.keys(activePlayers).length === 0) {
if (_nextActivePlayers) {
ctx = SetActivePlayers(ctx, _nextActivePlayers);
({
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
_activePlayersNumMoves,
_prevActivePlayers,
} = ctx);
}
else if (_prevActivePlayers.length > 0) {
const lastIndex = _prevActivePlayers.length - 1;
({
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
_activePlayersNumMoves,
} = _prevActivePlayers[lastIndex]);
_prevActivePlayers = _prevActivePlayers.slice(0, lastIndex);
}
else {
activePlayers = null;
_activePlayersMinMoves = null;
_activePlayersMaxMoves = null;
}
}
return {
...ctx,
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
_activePlayersNumMoves,
_prevActivePlayers,
};
}
/**
* Apply an active player argument to the given player ID
* @param {Object} activePlayers
* @param {Object} _activePlayersMinMoves
* @param {Object} _activePlayersMaxMoves
* @param {String} playerID The player to apply the parameter to
* @param {(String|Object)} arg An active player argument
*/
function ApplyActivePlayerArgument(activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, playerID, arg) {
if (typeof arg !== 'object' || arg === Stage.NULL) {
arg = { stage: arg };
}
if (arg.stage !== undefined) {
// stages previously did not enforce minMoves, this behaviour is kept intentionally
supportDeprecatedMoveLimit(arg);
activePlayers[playerID] = arg.stage;
if (arg.minMoves)
_activePlayersMinMoves[playerID] = arg.minMoves;
if (arg.maxMoves)
_activePlayersMaxMoves[playerID] = arg.maxMoves;
}
}
/**
* Converts a playOrderPos index into its value in playOrder.
* @param {Array} playOrder - An array of player ID's.
* @param {number} playOrderPos - An index into the above.
*/
function getCurrentPlayer(playOrder, playOrderPos) {
// convert to string in case playOrder is set to number[]
return playOrder[playOrderPos] + '';
}
/**
* Called at the start of a turn to initialize turn order state.
*
* TODO: This is called inside StartTurn, which is called from
* both UpdateTurn and StartPhase (so it's called at the beginning
* of a new phase as well as between turns). We should probably
* split it into two.
*/
function InitTurnOrderState(state, turn) {
let { G, ctx } = state;
const { numPlayers } = ctx;
const ctxWithAPI = EnhanceCtx(state);
const order = turn.order;
let playOrder = [...Array.from({ length: numPlayers })].map((_, i) => i + '');
if (order.playOrder !== undefined) {
playOrder = order.playOrder(G, ctxWithAPI);
}
const playOrderPos = order.first(G, ctxWithAPI);
const posType = typeof playOrderPos;
if (posType !== 'number') {
error(`invalid value returned by turn.order.first — expected number got ${posType} “${playOrderPos}”.`);
}
const currentPlayer = getCurrentPlayer(playOrder, playOrderPos);
ctx = { ...ctx, currentPlayer, playOrderPos, playOrder };
ctx = SetActivePlayers(ctx, turn.activePlayers || {});
return ctx;
}
/**
* Called at the end of each turn to update the turn order state.
* @param {object} G - The game object G.
* @param {object} ctx - The game object ctx.
* @param {object} turn - A turn object for this phase.
* @param {string} endTurnArg - An optional argument to endTurn that
may specify the next player.
*/
function UpdateTurnOrderState(state, currentPlayer, turn, endTurnArg) {
const order = turn.order;
let { G, ctx } = state;
let playOrderPos = ctx.playOrderPos;
let endPhase = false;
if (endTurnArg && endTurnArg !== true) {
if (typeof endTurnArg !== 'object') {
error(`invalid argument to endTurn: ${endTurnArg}`);
}
Object.keys(endTurnArg).forEach((arg) => {
switch (arg) {
case 'remove':
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
break;
case 'next':
playOrderPos = ctx.playOrder.indexOf(endTurnArg.next);
currentPlayer = endTurnArg.next;
break;
default:
error(`invalid argument to endTurn: ${arg}`);
}
});
}
else {
const ctxWithAPI = EnhanceCtx(state);
const t = order.next(G, ctxWithAPI);
const type = typeof t;
if (t !== undefined && type !== 'number') {
error(`invalid value returned by turn.order.next — expected number or undefined got ${type} “${t}”.`);
}
if (t === undefined) {
endPhase = true;
}
else {
playOrderPos = t;
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
}
}
ctx = {
...ctx,
playOrderPos,
currentPlayer,
};
return { endPhase, ctx };
}
/**
* Set of different turn orders possible in a phase.
* These are meant to be passed to the `turn` setting
* in the flow objects.
*
* Each object defines the first player when the phase / game
* begins, and also a function `next` to determine who the
* next player is when the turn ends.
*
* The phase ends if next() returns undefined.
*/
const TurnOrder = {
/**
* DEFAULT
*
* The default round-robin turn order.
*/
DEFAULT: {
first: (G, ctx) => ctx.turn === 0
? ctx.playOrderPos
: (ctx.playOrderPos + 1) % ctx.playOrder.length,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* RESET
*
* Similar to DEFAULT, but starts from 0 each time.
*/
RESET: {
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* CONTINUE
*
* Similar to DEFAULT, but starts with the player who ended the last phase.
*/
CONTINUE: {
first: (G, ctx) => ctx.playOrderPos,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* ONCE
*
* Another round-robin turn order, but goes around just once.
* The phase ends after all players have played.
*/
ONCE: {
first: () => 0,
next: (G, ctx) => {
if (ctx.playOrderPos < ctx.playOrder.length - 1) {
return ctx.playOrderPos + 1;
}
},
},
/**
* CUSTOM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase.
*
* @param {Array} playOrder - The play order.
*/
CUSTOM: (playOrder) => ({
playOrder: () => playOrder,
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
/**
* CUSTOM_FROM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase to a value specified by a field
* in G.
*
* @param {string} playOrderField - Field in G.
*/
CUSTOM_FROM: (playOrderField) => ({
playOrder: (G) => G[playOrderField],
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
};
const Stage = {
NULL: null,
};
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Flow
*
* Creates a reducer that updates ctx (analogous to how moves update G).
*/
function Flow({ moves, phases, endIf, onEnd, turn, events, plugins, }) {
// Attach defaults.
if (moves === undefined) {
moves = {};
}
if (events === undefined) {
events = {};
}
if (plugins === undefined) {
plugins = [];
}
if (phases === undefined) {
phases = {};
}
if (!endIf)
endIf = () => undefined;
if (!onEnd)
onEnd = (G) => G;
if (!turn)
turn = {};
const phaseMap = { ...phases };
if ('' in phaseMap) {
error('cannot specify phase with empty name');
}
phaseMap[''] = {};
const moveMap = {};
const moveNames = new Set();
let startingPhase = null;
Object.keys(moves).forEach((name) => moveNames.add(name));
const HookWrapper = (hook, hookType) => {
const withPlugins = FnWrap(hook, hookType, plugins);
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return withPlugins(state.G, ctxWithAPI);
};
};
const TriggerWrapper = (trigger) => {
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return trigger(state.G, ctxWithAPI);
};
};
const wrapped = {
onEnd: HookWrapper(onEnd, GameMethod.GAME_ON_END),
endIf: TriggerWrapper(endIf),
};
for (const phase in phaseMap) {
const phaseConfig = phaseMap[phase];
if (phaseConfig.start === true) {
startingPhase = phase;
}
if (phaseConfig.moves !== undefined) {
for (const move of Object.keys(phaseConfig.moves)) {
moveMap[phase + '.' + move] = phaseConfig.moves[move];
moveNames.add(move);
}
}
if (phaseConfig.endIf === undefined) {
phaseConfig.endIf = () => undefined;
}
if (phaseConfig.onBegin === undefined) {
phaseConfig.onBegin = (G) => G;
}
if (phaseConfig.onEnd === undefined) {
phaseConfig.onEnd = (G) => G;
}
if (phaseConfig.turn === undefined) {
phaseConfig.turn = turn;
}
if (phaseConfig.turn.order === undefined) {
phaseConfig.turn.order = TurnOrder.DEFAULT;
}
if (phaseConfig.turn.onBegin === undefined) {
phaseConfig.turn.onBegin = (G) => G;
}
if (phaseConfig.turn.onEnd === undefined) {
phaseConfig.turn.onEnd = (G) => G;
}
if (phaseConfig.turn.endIf === undefined) {
phaseConfig.turn.endIf = () => false;
}
if (phaseConfig.turn.onMove === undefined) {
phaseConfig.turn.onMove = (G) => G;
}
if (phaseConfig.turn.stages === undefined) {
phaseConfig.turn.stages = {};
}
// turns previously treated moveLimit as both minMoves and maxMoves, this behaviour is kept intentionally
supportDeprecatedMoveLimit(phaseConfig.turn, true);
for (const stage in phaseConfig.turn.stages) {
const stageConfig = phaseConfig.turn.stages[stage];
const moves = stageConfig.moves || {};
for (const move of Object.keys(moves)) {
const key = phase + '.' + stage + '.' + move;
moveMap[key] = moves[move];
moveNames.add(move);
}
}
phaseConfig.wrapped = {
onBegin: HookWrapper(phaseConfig.onBegin, GameMethod.PHASE_ON_BEGIN),
onEnd: HookWrapper(phaseConfig.onEnd, GameMethod.PHASE_ON_END),
endIf: TriggerWrapper(phaseConfig.endIf),
};
phaseConfig.turn.wrapped = {
onMove: HookWrapper(phaseConfig.turn.onMove, GameMethod.TURN_ON_MOVE),
onBegin: HookWrapper(phaseConfig.turn.onBegin, GameMethod.TURN_ON_BEGIN),
onEnd: HookWrapper(phaseConfig.turn.onEnd, GameMethod.TURN_ON_END),
endIf: TriggerWrapper(phaseConfig.turn.endIf),
};
if (typeof phaseConfig.next !== 'function') {
const { next } = phaseConfig;
phaseConfig.next = () => next || null;
}
phaseConfig.wrapped.next = TriggerWrapper(phaseConfig.next);
}
function GetPhase(ctx) {
return ctx.phase ? phaseMap[ctx.phase] : phaseMap[''];
}
function OnMove(s) {
return s;
}
function Process(state, events) {
const phasesEnded = new Set();
const turnsEnded = new Set();
for (let i = 0; i < events.length; i++) {
const { fn, arg, ...rest } = events[i];
// Detect a loop of EndPhase calls.
// This could potentially even be an infinite loop
// if the endIf condition of each phase blindly
// returns true. The moment we detect a single
// loop, we just bail out of all phases.
if (fn === EndPhase) {
turnsEnded.clear();
const phase = state.ctx.phase;
if (phasesEnded.has(phase)) {
const ctx = { ...state.ctx, phase: null };
return { ...state, ctx };
}
phasesEnded.add(phase);
}
// Process event.
const next = [];
state = fn(state, {
...rest,
arg,
next,
});
if (fn === EndGame) {
break;
}
// Check if we should end the game.
const shouldEndGame = ShouldEndGame(state);
if (shouldEndGame) {
events.push({
fn: EndGame,
arg: shouldEndGame,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the phase.
const shouldEndPhase = ShouldEndPhase(state);
if (shouldEndPhase) {
events.push({
fn: EndPhase,
arg: shouldEndPhase,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the turn.
if ([OnMove, UpdateStage, UpdateActivePlayers].includes(fn)) {
const shouldEndTurn = ShouldEndTurn(state);
if (shouldEndTurn) {
events.push({
fn: EndTurn,
arg: shouldEndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
}
events.push(...next);
}
return state;
}
///////////
// Start //
///////////
function StartGame(state, { next }) {
next.push({ fn: StartPhase });
return state;
}
function StartPhase(state, { next }) {
let { G, ctx } = state;
const phaseConfig = GetPhase(ctx);
// Run any phase setup code provided by the user.
G = phaseConfig.wrapped.onBegin(state);
next.push({ fn: StartTurn });
return { ...state, G, ctx };
}
function StartTurn(state, { currentPlayer }) {
let { ctx } = state;
const phaseConfig = GetPhase(ctx);
// Initialize the turn order state.
if (currentPlayer) {
ctx = { ...ctx, currentPlayer };
if (phaseConfig.turn.activePlayers) {
ctx = SetActivePlayers(ctx, phaseConfig.turn.activePlayers);
}
}
else {
// This is only called at the beginning of the phase
// when there is no currentPlayer yet.
ctx = InitTurnOrderState(state, phaseConfig.turn);
}
const turn = ctx.turn + 1;
ctx = { ...ctx, turn, numMoves: 0, _prevActivePlayers: [] };
const G = phaseConfig.turn.wrapped.onBegin({ ...state, ctx });
return { ...state, G, ctx, _undo: [], _redo: [] };
}
////////////
// Update //
////////////
function UpdatePhase(state, { arg, next, phase }) {
const phaseConfig = GetPhase({ phase });
let { ctx } = state;
if (arg && arg.next) {
if (arg.next in phaseMap) {
ctx = { ...ctx, phase: arg.next };
}
else {
error('invalid phase: ' + arg.next);
return state;
}
}
else {
ctx = { ...ctx, phase: phaseConfig.wrapped.next(state) || null };
}
state = { ...state, ctx };
// Start the new phase.
next.push({ fn: StartPhase });
return state;
}
function UpdateTurn(state, { arg, currentPlayer, next }) {
let { G, ctx } = state;
const phaseConfig = GetPhase(ctx);
// Update turn order state.
const { endPhase, ctx: newCtx } = UpdateTurnOrderState(state, currentPlayer, phaseConfig.turn, arg);
ctx = newCtx;
state = { ...state, G, ctx };
if (endPhase) {
next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase });
}
else {
next.push({ fn: StartTurn, currentPlayer: ctx.currentPlayer });
}
return state;
}
function UpdateStage(state, { arg, playerID }) {
if (typeof arg === 'string' || arg === Stage.NULL) {
arg = { stage: arg };
}
if (typeof arg !== 'object')
return state;
// `arg` should be of type `StageArg`, loose typing as `any` here for historic reasons
// stages previously did not enforce minMoves, this behaviour is kept intentionally
supportDeprecatedMoveLimit(arg);
let { ctx } = state;
let { activePlayers, _activePlayersMinMoves, _activePlayersMaxMoves, _activePlayersNumMoves, } = ctx;
// Checking if stage is valid, even Stage.NULL
if (arg.stage !== undefined) {
if (activePlayers === null) {
activePlayers = {};
}
activePlayers[playerID] = arg.stage;
_activePlayersNumMoves[playerID] = 0;
if (arg.minMoves) {
if (_activePlayersMinMoves === null) {
_activePlayersMinMoves = {};
}
_activePlayersMinMoves[playerID] = arg.minMoves;
}
if (arg.maxMoves) {
if (_activePlayersMaxMoves === null) {
_activePlayersMaxMoves = {};
}
_activePlayersMaxMoves[playerID] = arg.maxMoves;
}
}
ctx = {
...ctx,
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
_activePlayersNumMoves,
};
return { ...state, ctx };
}
function UpdateActivePlayers(state, { arg }) {
return { ...state, ctx: SetActivePlayers(state.ctx, arg) };
}
///////////////
// ShouldEnd //
///////////////
function ShouldEndGame(state) {
return wrapped.endIf(state);
}
function ShouldEndPhase(state) {
const phaseConfig = GetPhase(state.ctx);
return phaseConfig.wrapped.endIf(state);
}
function ShouldEndTurn(state) {
const phaseConfig = GetPhase(state.ctx);
// End the turn if the required number of moves has been made.
const currentPlayerMoves = state.ctx.numMoves || 0;
if (phaseConfig.turn.maxMoves &&
currentPlayerMoves >= phaseConfig.turn.maxMoves) {
return true;
}
return phaseConfig.turn.wrapped.endIf(state);
}
/////////
// End //
/////////
function EndGame(state, { arg, phase }) {
state = EndPhase(state, { phase });
if (arg === undefined) {
arg = true;
}
state = { ...state, ctx: { ...state.ctx, gameover: arg } };
// Run game end hook.
const G = wrapped.onEnd(state);
return { ...state, G };
}
function EndPhase(state, { arg, next, turn: initialTurn, automatic }) {
// End the turn first.
state = EndTurn(state, { turn: initialTurn, force: true, automatic: true });
const { phase, turn } = state.ctx;
if (next) {
next.push({ fn: UpdatePhase, arg, phase });
}
// If we aren't in a phase, there is nothing else to do.
if (phase === null) {
return state;
}
// Run any cleanup code for the phase that is about to end.
const phaseConfig = GetPhase(state.ctx);
const G = phaseConfig.wrapped.onEnd(state);
// Reset the phase.
const ctx = { ...state.ctx, phase: null };
// Add log entry.
const action = gameEvent('endPhase', arg);
const { _stateID } = state;
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog };
}
function EndTurn(state, { arg, next, turn: initialTurn, force, automatic, playerID }) {
// This is not the turn that EndTurn was originally
// called for. The turn was probably ended some other way.
if (initialTurn !== state.ctx.turn) {
return state;
}
const { currentPlayer, numMoves, phase, turn } = state.ctx;
const phaseConfig = GetPhase(state.ctx);
// Prevent ending the turn if minMoves haven't been reached.
const currentPlayerMoves = numMoves || 0;
if (!force &&
phaseConfig.turn.minMoves &&
currentPlayerMoves < phaseConfig.turn.minMoves) {
info(`cannot end turn before making ${phaseConfig.turn.minMoves} moves`);
return state;
}
// Run turn-end triggers.
const G = phaseConfig.turn.wrapped.onEnd(state);
if (next) {
next.push({ fn: UpdateTurn, arg, currentPlayer });
}
// Reset activePlayers.
let ctx = { ...state.ctx, activePlayers: null };
// Remove player from playerOrder
if (arg && arg.remove) {
playerID = playerID || currentPlayer;
const playOrder = ctx.playOrder.filter((i) => i != playerID);
const playOrderPos = ctx.playOrderPos > playOrder.length - 1 ? 0 : ctx.playOrderPos;
ctx = { ...ctx, playOrder, playOrderPos };
if (playOrder.length === 0) {
next.push({ fn: EndPhase, turn, phase });
return state;
}
}
// Create log entry.
const action = gameEvent('endTurn', arg);
const { _stateID } = state;
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog, _undo: [], _redo: [] };
}
function EndStage(state, { arg, next, automatic, playerID }) {
playerID = playerID || state.ctx.currentPlayer;
let { ctx, _stateID } = state;
let { activePlayers, _activePlayersNumMoves, _activePlayersMinMoves, _activePlayersMaxMoves, phase, turn, } = ctx;
const playerInStage = activePlayers !== null && playerID in activePlayers;
const phaseConfig = GetPhase(ctx);
if (!arg && playerInStage) {
const stage = phaseConfig.turn.stages[activePlayers[playerID]];
if (stage && stage.next) {
arg = stage.next;
}
}
// Checking if arg is a valid stage, even Stage.NULL
if (next) {
next.push({ fn: UpdateStage, arg, playerID });
}
// If player isn’t in a stage, there is nothing else to do.
if (!playerInStage)
return state;
// Prevent ending the stage if minMoves haven't been reached.
const currentPlayerMoves = _activePlayersNumMoves[playerID] || 0;
if (_activePlayersMinMoves &&
_activePlayersMinMoves[playerID] &&
currentPlayerMoves < _activePlayersMinMoves[playerID]) {
info(`cannot end stage before making ${_activePlayersMinMoves[playerID]} moves`);
return state;
}
// Remove player from activePlayers.
activePlayers = { ...activePlayers };
delete activePlayers[playerID];
if (_activePlayersMinMoves) {
// Remove player from _activePlayersMinMoves.
_activePlayersMinMoves = { ..._activePlayersMinMoves };
delete _activePlayersMinMoves[playerID];
}
if (_activePlayersMaxMoves) {
// Remove player from _activePlayersMaxMoves.
_activePlayersMaxMoves = { ..._activePlayersMaxMoves };
delete _activePlayersMaxMoves[playerID];
}
ctx = UpdateActivePlayersOnceEmpty({
...ctx,
activePlayers,
_activePlayersMinMoves,
_activePlayersMaxMoves,
});
// Create log entry.
const action = gameEvent('endStage', arg);
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, ctx, deltalog };
}
/**
* Retrieves the relevant move that can be played by playerID.
*
* If ctx.activePlayers is set (i.e. one or more players are in some stage),
* then it attempts to find the move inside the stages config for
* that turn. If the stage for a player is '', then the player is
* allowed to make a move (as determined by the phase config), but
* isn't restricted to a particular set as defined in the stage config.
*
* If not, it then looks for the move inside the phase.
*
* If it doesn't find the move there, it looks at the global move definition.
*
* @param {object} ctx
* @param {string} name
* @param {string} playerID
*/
function GetMove(ctx, name, playerID) {
const phaseConfig = GetPhase(ctx);
const stages = phaseConfig.turn.stages;
const { activePlayers } = ctx;
if (activePlayers &&
activePlayers[playerID] !== undefined &&
activePlayers[playerID] !== Stage.NULL &&
stages[activePlayers[playerID]] !== undefined &&
stages[activePlayers[playerID]].moves !== undefined) {
// Check if moves are defined for the player's stage.
const stage = stages[activePlayers[playerID]];
const moves = stage.moves;
if (name in moves) {
return moves[name];
}
}
else if (phaseConfig.moves) {
// Check if moves are defined for the current phase.
if (name in phaseConfig.moves) {
return phaseConfig.moves[name];
}
}
else if (name in moves) {
// Check for the move globally.
return moves[name];
}
return null;
}
function ProcessMove(state, action) {
const { playerID, type } = action;
const { currentPlayer, activePlayers, _activePlayersMaxMoves } = state.ctx;
const move = GetMove(state.ctx, type, playerID);
const shouldCount = !move || typeof move === 'function' || move.noLimit !== true;
let { numMoves, _activePlayersNumMoves } = state.ctx;
if (shouldCount) {
if (playerID === currentPlayer)
numMoves++;
if (activePlayers)
_activePlayersNumMoves[playerID]++;
}
state = {
...state,
ctx: {
...state.ctx,
numMoves,
_activePlayersNumMoves,
},
};
if (_activePlayersMaxMoves &&
_activePlayersNumMoves[playerID] >= _activePlayersMaxMoves[playerID]) {
state = EndStage(state, { playerID, automatic: true });
}
const phaseConfig = GetPhase(state.ctx);
const G = phaseConfig.turn.wrapped.onMove({
...state,
ctx: { ...state.ctx, playerID },
});
state = { ...state, G };
const events = [{ fn: OnMove }];
return Process(state, events);
}
function SetStageEvent(state, playerID, arg) {
return Process(state, [{ fn: EndStage, arg, playerID }]);
}
function EndStageEvent(state, playerID) {
return Process(state, [{ fn: EndStage, playerID }]);
}
function SetActivePlayersEvent(state, _playerID, arg) {
return Process(state, [{ fn: UpdateActivePlayers, arg }]);
}
function SetPhaseEvent(state, _playerID, newPhase) {
return Process(state, [
{
fn: EndPhase,
phase: state.ctx.phase,
turn: state.ctx.turn,
arg: { next: newPhase },
},
]);
}
function EndPhaseEvent(state) {
return Process(state, [
{ fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn },
]);
}
function EndTurnEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
function PassEvent(state, _playerID, arg) {
return Process(state, [
{
fn: EndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
force: true,
arg,
},
]);
}
function EndGameEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndGame, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
const eventHandlers = {
endStage: EndStageEvent,
setStage: SetStageEvent,
endTurn: EndTurnEvent,
pass: PassEvent,
endPhase: EndPhaseEvent,
setPhase: SetPhaseEvent,
endGame: EndGameEvent,
setActivePlayers: SetActivePlayersEvent,
};
const enabledEventNames = [];
if (events.endTurn !== false) {
enabledEventNames.push('endTurn');
}
if (events.pass !== false) {
enabledEventNames.push('pass');
}
if (events.endPhase !== false) {
enabledEventNames.push('endPhase');
}
if (events.setPhase !== false) {
enabledEventNames.push('setPhase');
}
if (events.endGame !== false) {
enabledEventNames.push('endGame');
}
if (events.setActivePlayers !== false) {
enabledEventNames.push('setActivePlayers');
}
if (events.endStage !== false) {
enabledEventNames.push('endStage');
}
if (events.setStage !== false) {
enabledEventNames.push('setStage');
}
function ProcessEvent(state, action) {
const { type, playerID, args } = action.payload;
if (typeof eventHandlers[type] !== 'function')
return state;
return eventHandlers[type](state, playerID, ...(Array.isArray(args) ? args : [args]));
}
function IsPlayerActive(_G, ctx, playerID) {
if (ctx.activePlayers) {
return playerID in ctx.activePlayers;
}
return ctx.currentPlayer === playerID;
}
return {
ctx: (numPlayers) => ({
numPlayers,
turn: 0,
currentPlayer: '0',
playOrder: [...Array.from({ length: numPlayers })].map((_, i) => i + ''),
playOrderPos: 0,
phase: startingPhase,
activePlayers: null,
}),
init: (state) => {
return Process(state, [{ fn: StartGame }]);
},
isPlayerActive: IsPlayerActive,
eventHandlers,
eventNames: Object.keys(eventHandlers),
enabledEventNames,
moveMap,
moveNames: [...moveNames.values()],
processMove: ProcessMove,
processEvent: ProcessEvent,
getMove: GetMove,
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function IsProcessed(game) {
return game.processMove !== undefined;
}
/**
* Helper to generate the game move reducer. The returned
* reducer has the following signature:
*
* (G, action, ctx) => {}
*
* You can roll your own if you like, or use any Redux
* addon to generate such a reducer.
*
* The convention used in this framework is to
* have action.type contain the name of the move, and
* action.args contain any additional arguments as an
* Array.
*/
function ProcessGameConfig(game) {
// The Game() function has already been called on this
// config object, so just pass it through.
if (IsProcessed(game)) {
return game;
}
if (game.name === undefined)
game.name = 'default';
if (game.deltaState === undefined)
game.deltaState = false;
if (game.disableUndo === undefined)
game.disableUndo = false;
if (game.setup === undefined)
game.setup = () => ({});
if (game.moves === undefined)
game.moves = {};
if (game.playerView === undefined)
game.playerView = (G) => G;
if (game.plugins === undefined)
game.plugins = [];
game.plugins.forEach((plugin) => {
if (plugin.name === undefined) {
throw new Error('Plugin missing name attribute');
}
if (plugin.name.includes(' ')) {
throw new Error(plugin.name + ': Plugin name must not include spaces');
}
});
if (game.name.includes(' ')) {
throw new Error(game.name + ': Game name must not include spaces');
}
const flow = Flow(game);
return {
...game,
flow,
moveNames: flow.moveNames,
pluginNames: game.plugins.map((p) => p.name),
processMove: (state, action) => {
let moveFn = flow.getMove(state.ctx, action.type, action.playerID);
if (IsLongFormMove(moveFn)) {
moveFn = moveFn.move;
}
if (moveFn instanceof Function) {
const fn = FnWrap(moveFn, GameMethod.MOVE, game.plugins);
const ctxWithAPI = {
...EnhanceCtx(state),
playerID: action.playerID,
};
let args = [];
if (action.args !== undefined) {
args = Array.isArray(action.args) ? action.args : [action.args];
}
return fn(state.G, ctxWithAPI, ...args);
}
error(`invalid move object: ${action.type}`);
return state.G;
},
};
}
function IsLongFormMove(move) {
return move instanceof Object && move.move !== undefined;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
var UpdateErrorType;
(function (UpdateErrorType) {
// The action’s credentials were missing or invalid
UpdateErrorType["UnauthorizedAction"] = "update/unauthorized_action";
// The action’s matchID was not found
UpdateErrorType["MatchNotFound"] = "update/match_not_found";
// Could not apply Patch operation (rfc6902).
UpdateErrorType["PatchFailed"] = "update/patch_failed";
})(UpdateErrorType || (UpdateErrorType = {}));
var ActionErrorType;
(function (ActionErrorType) {
// The action contained a stale state ID
ActionErrorType["StaleStateId"] = "action/stale_state_id";
// The requested move is unknown or not currently available
ActionErrorType["UnavailableMove"] = "action/unavailable_move";
// The move declared it was invalid (INVALID_MOVE constant)
ActionErrorType["InvalidMove"] = "action/invalid_move";
// The player making the action is not currently active
ActionErrorType["InactivePlayer"] = "action/inactive_player";
// The game has finished
ActionErrorType["GameOver"] = "action/gameover";
// The requested action is disabled (e.g. undo/redo, events)
ActionErrorType["ActionDisabled"] = "action/action_disabled";
// The requested action is not currently possible
ActionErrorType["ActionInvalid"] = "action/action_invalid";
// The requested action was declared invalid by a plugin
ActionErrorType["PluginActionInvalid"] = "action/plugin_invalid";
})(ActionErrorType || (ActionErrorType = {}));
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Check if the payload for the passed action contains a playerID.
*/
const actionHasPlayerID = (action) => action.payload.playerID !== null && action.payload.playerID !== undefined;
/**
* Returns true if a move can be undone.
*/
const CanUndoMove = (G, ctx, move) => {
function HasUndoable(move) {
return move.undoable !== undefined;
}
function IsFunction(undoable) {
return undoable instanceof Function;
}
if (!HasUndoable(move)) {
return true;
}
if (IsFunction(move.undoable)) {
return move.undoable(G, ctx);
}
return move.undoable;
};
/**
* Update the undo and redo stacks for a move or event.
*/
function updateUndoRedoState(state, opts) {
if (opts.game.disableUndo)
return state;
const undoEntry = {
G: state.G,
ctx: state.ctx,
plugins: state.plugins,
playerID: opts.action.payload.playerID || state.ctx.currentPlayer,
};
if (opts.action.type === 'MAKE_MOVE') {
undoEntry.moveType = opts.action.payload.type;
}
return {
...state,
_undo: [...state._undo, undoEntry],
// Always reset redo stack when making a move or event
_redo: [],
};
}
/**
* Process state, adding the initial deltalog for this action.
*/
function initializeDeltalog(state, action, move) {
// Create a log entry for this action.
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
const pluginLogMetadata = state.plugins.log.data.metadata;
if (pluginLogMetadata !== undefined) {
logEntry.metadata = pluginLogMetadata;
}
if (typeof move === 'object' && move.redact === true) {
logEntry.redact = true;
}
return {
...state,
deltalog: [logEntry],
};
}
/**
* Update plugin state after move/event & check if plugins consider the action to be valid.
* @param state Current version of state in the reducer.
* @param oldState State to revert to in case of error.
* @param pluginOpts Plugin configuration options.
* @returns Tuple of the new state updated after flushing plugins and the old
* state augmented with an error if a plugin declared the action invalid.
*/
function flushAndValidatePlugins(state, oldState, pluginOpts) {
const [newState, isInvalid] = FlushAndValidate(state, pluginOpts);
if (!isInvalid)
return [newState];
return [
newState,
WithError(oldState, ActionErrorType.PluginActionInvalid, isInvalid),
];
}
/**
* ExtractTransientsFromState
*
* Split out transients from the a TransientState
*/
function ExtractTransients(transientState) {
if (!transientState) {
// We preserve null for the state for legacy callers, but the transient
// field should be undefined if not present to be consistent with the
// code path below.
return [null, undefined];
}
const { transients, ...state } = transientState;
return [state, transients];
}
/**
* WithError
*
* Augment a State instance with transient error information.
*/
function WithError(state, errorType, payload) {
const error = {
type: errorType,
payload,
};
return {
...state,
transients: {
error,
},
};
}
/**
* Middleware for processing TransientState associated with the reducer
* returned by CreateGameReducer.
* This should pretty much be used everywhere you want realistic state
* transitions and error handling.
*/
const TransientHandlingMiddleware = (store) => (next) => (action) => {
const result = next(action);
switch (action.type) {
case STRIP_TRANSIENTS: {
return result;
}
default: {
const [, transients] = ExtractTransients(store.getState());
if (typeof transients !== 'undefined') {
store.dispatch(stripTransients());
// Dev Note: If parent middleware needs to correlate the spawned
// StripTransients action to the triggering action, instrument here.
//
// This is a bit tricky; for more details, see:
// https://github.com/boardgameio/boardgame.io/pull/940#discussion_r636200648
return {
...result,
transients,
};
}
return result;
}
}
};
/**
* CreateGameReducer
*
* Creates the main game state reducer.
*/
function CreateGameReducer({ game, isClient, }) {
game = ProcessGameConfig(game);
/**
* GameReducer
*
* Redux reducer that maintains the overall game state.
* @param {object} state - The state before the action.
* @param {object} action - A Redux action.
*/
return (stateWithTransients = null, action) => {
let [state /*, transients */] = ExtractTransients(stateWithTransients);
switch (action.type) {
case STRIP_TRANSIENTS: {
// This action indicates that transient metadata in the state has been
// consumed and should now be stripped from the state..
return state;
}
case GAME_EVENT: {
state = { ...state, deltalog: [] };
// Process game events only on the server.
// These events like `endTurn` typically
// contain code that may rely on secret state
// and cannot be computed on the client.
if (isClient) {
return state;
}
// Disallow events once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot call event after game end`);
return WithError(state, ActionErrorType.GameOver);
}
// Ignore the event if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed event: ${action.payload.type}`);
return WithError(state, ActionErrorType.InactivePlayer);
}
// Execute plugins.
state = Enhance(state, {
game,
isClient: false,
playerID: action.payload.playerID,
});
// Process event.
let newState = game.flow.processEvent(state, action);
// Execute plugins.
let stateWithError;
[newState, stateWithError] = flushAndValidatePlugins(newState, state, {
game,
isClient: false,
});
if (stateWithError)
return stateWithError;
// Update undo / redo state.
newState = updateUndoRedoState(newState, { game, action });
return { ...newState, _stateID: state._stateID + 1 };
}
case MAKE_MOVE: {
const oldState = (state = { ...state, deltalog: [] });
// Check whether the move is allowed at this time.
const move = game.flow.getMove(state.ctx, action.payload.type, action.payload.playerID || state.ctx.currentPlayer);
if (move === null) {
error(`disallowed move: ${action.payload.type}`);
return WithError(state, ActionErrorType.UnavailableMove);
}
// Don't run move on client if move says so.
if (isClient && move.client === false) {
return state;
}
// Disallow moves once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot make move after game end`);
return WithError(state, ActionErrorType.GameOver);
}
// Ignore the move if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed move: ${action.payload.type}`);
return WithError(state, ActionErrorType.InactivePlayer);
}
// Execute plugins.
state = Enhance(state, {
game,
isClient,
playerID: action.payload.playerID,
});
// Process the move.
const G = game.processMove(state, action.payload);
// The game declared the move as invalid.
if (G === INVALID_MOVE) {
error(`invalid move: ${action.payload.type} args: ${action.payload.args}`);
// TODO(#723): Marshal a nice error payload with the processed move.
return WithError(state, ActionErrorType.InvalidMove);
}
const newState = { ...state, G };
// Some plugin indicated that it is not suitable to be
// materialized on the client (and must wait for the server
// response instead).
if (isClient && NoClient(newState, { game })) {
return state;
}
state = newState;
// If we're on the client, just process the move
// and no triggers in multiplayer mode.
// These will be processed on the server, which
// will send back a state update.
if (isClient) {
let stateWithError;
[state, stateWithError] = flushAndValidatePlugins(state, oldState, {
game,
isClient: true,
});
if (stateWithError)
return stateWithError;
return {
...state,
_stateID: state._stateID + 1,
};
}
// On the server, construct the deltalog.
state = initializeDeltalog(state, action, move);
// Allow the flow reducer to process any triggers that happen after moves.
state = game.flow.processMove(state, action.payload);
let stateWithError;
[state, stateWithError] = flushAndValidatePlugins(state, oldState, {
game,
});
if (stateWithError)
return stateWithError;
// Update undo / redo state.
state = updateUndoRedoState(state, { game, action });
return {
...state,
_stateID: state._stateID + 1,
};
}
case RESET:
case UPDATE:
case SYNC: {
return action.state;
}
case UNDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Undo is not enabled');
return WithError(state, ActionErrorType.ActionDisabled);
}
const { G, ctx, _undo, _redo, _stateID } = state;
if (_undo.length < 2) {
error(`No moves to undo`);
return WithError(state, ActionErrorType.ActionInvalid);
}
const last = _undo[_undo.length - 1];
const restore = _undo[_undo.length - 2];
// Only allow players to undo their own moves.
if (actionHasPlayerID(action) &&
action.payload.playerID !== last.playerID) {
error(`Cannot undo other players' moves`);
return WithError(state, ActionErrorType.ActionInvalid);
}
// If undoing a move, check it is undoable.
if (last.moveType) {
const lastMove = game.flow.getMove(restore.ctx, last.moveType, last.playerID);
if (!CanUndoMove(G, ctx, lastMove)) {
error(`Move cannot be undone`);
return WithError(state, ActionErrorType.ActionInvalid);
}
}
state = initializeDeltalog(state, action);
return {
...state,
G: restore.G,
ctx: restore.ctx,
plugins: restore.plugins,
_stateID: _stateID + 1,
_undo: _undo.slice(0, -1),
_redo: [last, ..._redo],
};
}
case REDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Redo is not enabled');
return WithError(state, ActionErrorType.ActionDisabled);
}
const { _undo, _redo, _stateID } = state;
if (_redo.length === 0) {
error(`No moves to redo`);
return WithError(state, ActionErrorType.ActionInvalid);
}
const first = _redo[0];
// Only allow players to redo their own undos.
if (actionHasPlayerID(action) &&
action.payload.playerID !== first.playerID) {
error(`Cannot redo other players' moves`);
return WithError(state, ActionErrorType.ActionInvalid);
}
state = initializeDeltalog(state, action);
return {
...state,
G: first.G,
ctx: first.ctx,
plugins: first.plugins,
_stateID: _stateID + 1,
_undo: [..._undo, first],
_redo: _redo.slice(1),
};
}
case PLUGIN: {
// TODO(#723): Expose error semantics to plugin processing.
return ProcessAction(state, action, { game });
}
case PATCH: {
const oldState = state;
const newState = JSON.parse(JSON.stringify(oldState));
const patchError = applyPatch(newState, action.patch);
const hasError = patchError.some((entry) => entry !== null);
if (hasError) {
error(`Patch ${JSON.stringify(action.patch)} apply failed`);
return WithError(oldState, UpdateErrorType.PatchFailed, patchError);
}
else {
return newState;
}
}
default: {
return state;
}
}
};
}
/*
* Copyright 2020 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Creates the initial game state.
*/
function InitializeGame({ game, numPlayers, setupData, }) {
game = ProcessGameConfig(game);
if (!numPlayers) {
numPlayers = 2;
}
const ctx = game.flow.ctx(numPlayers);
let state = {
// User managed state.
G: {},
// Framework managed state.
ctx,
// Plugin related state.
plugins: {},
};
// Run plugins over initial state.
state = Setup(state, { game });
state = Enhance(state, { game, playerID: undefined });
const enhancedCtx = EnhanceCtx(state);
state.G = game.setup(enhancedCtx, setupData);
let initial = {
...state,
// List of {G, ctx} pairs that can be undone.
_undo: [],
// List of {G, ctx} pairs that can be redone.
_redo: [],
// A monotonically non-decreasing ID to ensure that
// state updates are only allowed from clients that
// are at the same version that the server.
_stateID: 0,
};
initial = game.flow.init(initial);
[initial] = FlushAndValidate(initial, { game });
// Initialize undo stack.
if (!game.disableUndo) {
initial._undo = [
{
G: initial.G,
ctx: initial.ctx,
plugins: initial.plugins,
},
];
}
return initial;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
class Transport {
constructor({ transportDataCallback, gameName, playerID, matchID, credentials, numPlayers, }) {
/** Callback to let the client know when the connection status has changed. */
this.connectionStatusCallback = () => { };
this.isConnected = false;
this.transportDataCallback = transportDataCallback;
this.gameName = gameName || 'default';
this.playerID = playerID || null;
this.matchID = matchID || 'default';
this.credentials = credentials;
this.numPlayers = numPlayers || 2;
}
/** Subscribe to connection state changes. */
subscribeToConnectionStatus(fn) {
this.connectionStatusCallback = fn;
}
/** Transport implementations should call this when they connect/disconnect. */
setConnectionStatus(isConnected) {
this.isConnected = isConnected;
this.connectionStatusCallback();
}
/** Transport implementations should call this when they receive data from a master. */
notifyClient(data) {
this.transportDataCallback(data);
}
}
/**
* This class doesn’t do anything, but simplifies the client class by providing
* dummy functions to call, so we don’t need to mock them in the client.
*/
class DummyImpl extends Transport {
connect() { }
disconnect() { }
sendAction() { }
sendChatMessage() { }
requestSync() { }
updateCredentials() { }
updateMatchID() { }
updatePlayerID() { }
}
const DummyTransport = (opts) => new DummyImpl(opts);
const subscriber_queue = [];
/**
* Create a `Writable` store that allows both updating and reading by subscription.
* @param {*=}value initial value
* @param {StartStopNotifier=}start start and stop notifications for subscriptions
*/
function writable(value, start = noop) {
let stop;
const subscribers = new Set();
function set(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
if (stop) { // store is ready
const run_queue = !subscriber_queue.length;
for (const subscriber of subscribers) {
subscriber[1]();
subscriber_queue.push(subscriber, value);
}
if (run_queue) {
for (let i = 0; i < subscriber_queue.length; i += 2) {
subscriber_queue[i][0](subscriber_queue[i + 1]);
}
subscriber_queue.length = 0;
}
}
}
}
function update(fn) {
set(fn(value));
}
function subscribe(run, invalidate = noop) {
const subscriber = [run, invalidate];
subscribers.add(subscriber);
if (subscribers.size === 1) {
stop = start(set) || noop;
}
run(value);
return () => {
subscribers.delete(subscriber);
if (subscribers.size === 0) {
stop();
stop = null;
}
};
}
return { set, update, subscribe };
}
function cubicOut(t) {
const f = t - 1.0;
return f * f * f + 1.0;
}
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function fly(node, { delay = 0, duration = 400, easing = cubicOut, x = 0, y = 0, opacity = 0 } = {}) {
const style = getComputedStyle(node);
const target_opacity = +style.opacity;
const transform = style.transform === 'none' ? '' : style.transform;
const od = target_opacity * (1 - opacity);
return {
delay,
duration,
easing,
css: (t, u) => `
transform: ${transform} translate(${(1 - t) * x}px, ${(1 - t) * y}px);
opacity: ${target_opacity - (od * u)}`
};
}
function crossfade(_a) {
var { fallback } = _a, defaults = __rest(_a, ["fallback"]);
const to_receive = new Map();
const to_send = new Map();
function crossfade(from, node, params) {
const { delay = 0, duration = d => Math.sqrt(d) * 30, easing = cubicOut } = assign(assign({}, defaults), params);
const to = node.getBoundingClientRect();
const dx = from.left - to.left;
const dy = from.top - to.top;
const dw = from.width / to.width;
const dh = from.height / to.height;
const d = Math.sqrt(dx * dx + dy * dy);
const style = getComputedStyle(node);
const transform = style.transform === 'none' ? '' : style.transform;
const opacity = +style.opacity;
return {
delay,
duration: is_function(duration) ? duration(d) : duration,
easing,
css: (t, u) => `
opacity: ${t * opacity};
transform-origin: top left;
transform: ${transform} translate(${u * dx}px,${u * dy}px) scale(${t + (1 - t) * dw}, ${t + (1 - t) * dh});
`
};
}
function transition(items, counterparts, intro) {
return (node, params) => {
items.set(params.key, {
rect: node.getBoundingClientRect()
});
return () => {
if (counterparts.has(params.key)) {
const { rect } = counterparts.get(params.key);
counterparts.delete(params.key);
return crossfade(rect, node, params);
}
// if the node is disappearing altogether
// (i.e. wasn't claimed by the other list)
// then we need to supply an outro
items.delete(params.key);
return fallback && fallback(node, params, intro);
};
};
}
return [
transition(to_send, to_receive, false),
transition(to_receive, to_send, true)
];
}
/* node_modules/svelte-icons/components/IconBase.svelte generated by Svelte v3.41.0 */
function add_css(target) {
append_styles(target, "svelte-c8tyih", "svg.svelte-c8tyih{stroke:currentColor;fill:currentColor;stroke-width:0;width:100%;height:auto;max-height:100%}");
}
// (18:2) {#if title}
function create_if_block(ctx) {
let title_1;
let t;
return {
c() {
title_1 = svg_element("title");
t = text(/*title*/ ctx[0]);
},
m(target, anchor) {
insert(target, title_1, anchor);
append(title_1, t);
},
p(ctx, dirty) {
if (dirty & /*title*/ 1) set_data(t, /*title*/ ctx[0]);
},
d(detaching) {
if (detaching) detach(title_1);
}
};
}
function create_fragment(ctx) {
let svg;
let if_block_anchor;
let current;
let if_block = /*title*/ ctx[0] && create_if_block(ctx);
const default_slot_template = /*#slots*/ ctx[3].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[2], null);
return {
c() {
svg = svg_element("svg");
if (if_block) if_block.c();
if_block_anchor = empty();
if (default_slot) default_slot.c();
attr(svg, "xmlns", "http://www.w3.org/2000/svg");
attr(svg, "viewBox", /*viewBox*/ ctx[1]);
attr(svg, "class", "svelte-c8tyih");
},
m(target, anchor) {
insert(target, svg, anchor);
if (if_block) if_block.m(svg, null);
append(svg, if_block_anchor);
if (default_slot) {
default_slot.m(svg, null);
}
current = true;
},
p(ctx, [dirty]) {
if (/*title*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block(ctx);
if_block.c();
if_block.m(svg, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (default_slot) {
if (default_slot.p && (!current || dirty & /*$$scope*/ 4)) {
update_slot_base(
default_slot,
default_slot_template,
ctx,
/*$$scope*/ ctx[2],
!current
? get_all_dirty_from_scope(/*$$scope*/ ctx[2])
: get_slot_changes(default_slot_template, /*$$scope*/ ctx[2], dirty, null),
null
);
}
}
if (!current || dirty & /*viewBox*/ 2) {
attr(svg, "viewBox", /*viewBox*/ ctx[1]);
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (detaching) detach(svg);
if (if_block) if_block.d();
if (default_slot) default_slot.d(detaching);
}
};
}
function instance($$self, $$props, $$invalidate) {
let { $$slots: slots = {}, $$scope } = $$props;
let { title = null } = $$props;
let { viewBox } = $$props;
$$self.$$set = $$props => {
if ('title' in $$props) $$invalidate(0, title = $$props.title);
if ('viewBox' in $$props) $$invalidate(1, viewBox = $$props.viewBox);
if ('$$scope' in $$props) $$invalidate(2, $$scope = $$props.$$scope);
};
return [title, viewBox, $$scope, slots];
}
class IconBase extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, create_fragment, safe_not_equal, { title: 0, viewBox: 1 }, add_css);
}
}
/* node_modules/svelte-icons/fa/FaChevronRight.svelte generated by Svelte v3.41.0 */
function create_default_slot(ctx) {
let path;
return {
c() {
path = svg_element("path");
attr(path, "d", "M285.476 272.971L91.132 467.314c-9.373 9.373-24.569 9.373-33.941 0l-22.667-22.667c-9.357-9.357-9.375-24.522-.04-33.901L188.505 256 34.484 101.255c-9.335-9.379-9.317-24.544.04-33.901l22.667-22.667c9.373-9.373 24.569-9.373 33.941 0L285.475 239.03c9.373 9.372 9.373 24.568.001 33.941z");
},
m(target, anchor) {
insert(target, path, anchor);
},
d(detaching) {
if (detaching) detach(path);
}
};
}
function create_fragment$1(ctx) {
let iconbase;
let current;
const iconbase_spread_levels = [{ viewBox: "0 0 320 512" }, /*$$props*/ ctx[0]];
let iconbase_props = {
$$slots: { default: [create_default_slot] },
$$scope: { ctx }
};
for (let i = 0; i < iconbase_spread_levels.length; i += 1) {
iconbase_props = assign(iconbase_props, iconbase_spread_levels[i]);
}
iconbase = new IconBase({ props: iconbase_props });
return {
c() {
create_component(iconbase.$$.fragment);
},
m(target, anchor) {
mount_component(iconbase, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const iconbase_changes = (dirty & /*$$props*/ 1)
? get_spread_update(iconbase_spread_levels, [iconbase_spread_levels[0], get_spread_object(/*$$props*/ ctx[0])])
: {};
if (dirty & /*$$scope*/ 2) {
iconbase_changes.$$scope = { dirty, ctx };
}
iconbase.$set(iconbase_changes);
},
i(local) {
if (current) return;
transition_in(iconbase.$$.fragment, local);
current = true;
},
o(local) {
transition_out(iconbase.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(iconbase, detaching);
}
};
}
function instance$1($$self, $$props, $$invalidate) {
$$self.$$set = $$new_props => {
$$invalidate(0, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
};
$$props = exclude_internal_props($$props);
return [$$props];
}
class FaChevronRight extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$1, create_fragment$1, safe_not_equal, {});
}
}
/* src/client/debug/Menu.svelte generated by Svelte v3.41.0 */
function add_css$1(target) {
append_styles(target, "svelte-1xg9v5h", ".menu.svelte-1xg9v5h{display:flex;margin-top:43px;flex-direction:row-reverse;border:1px solid #ccc;border-radius:5px 5px 0 0;height:25px;line-height:25px;margin-right:-500px;transform-origin:bottom right;transform:rotate(-90deg) translate(0, -500px)}.menu-item.svelte-1xg9v5h{line-height:25px;cursor:pointer;border:0;background:#fefefe;color:#555;padding-left:15px;padding-right:15px;text-align:center}.menu-item.svelte-1xg9v5h:first-child{border-radius:0 5px 0 0}.menu-item.svelte-1xg9v5h:last-child{border-radius:5px 0 0 0}.menu-item.active.svelte-1xg9v5h{cursor:default;font-weight:bold;background:#ddd;color:#555}.menu-item.svelte-1xg9v5h:hover,.menu-item.svelte-1xg9v5h:focus{background:#eee;color:#555}");
}
function get_each_context(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[4] = list[i][0];
child_ctx[5] = list[i][1].label;
return child_ctx;
}
// (57:2) {#each Object.entries(panes) as [key, {label}
function create_each_block(ctx) {
let button;
let t0_value = /*label*/ ctx[5] + "";
let t0;
let t1;
let mounted;
let dispose;
function click_handler() {
return /*click_handler*/ ctx[3](/*key*/ ctx[4]);
}
return {
c() {
button = element("button");
t0 = text(t0_value);
t1 = space();
attr(button, "class", "menu-item svelte-1xg9v5h");
toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, t0);
append(button, t1);
if (!mounted) {
dispose = listen(button, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*panes*/ 2 && t0_value !== (t0_value = /*label*/ ctx[5] + "")) set_data(t0, t0_value);
if (dirty & /*pane, Object, panes*/ 3) {
toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]);
}
},
d(detaching) {
if (detaching) detach(button);
mounted = false;
dispose();
}
};
}
function create_fragment$2(ctx) {
let nav;
let each_value = Object.entries(/*panes*/ ctx[1]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
}
return {
c() {
nav = element("nav");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(nav, "class", "menu svelte-1xg9v5h");
},
m(target, anchor) {
insert(target, nav, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(nav, null);
}
},
p(ctx, [dirty]) {
if (dirty & /*pane, Object, panes, dispatch*/ 7) {
each_value = Object.entries(/*panes*/ ctx[1]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block(child_ctx);
each_blocks[i].c();
each_blocks[i].m(nav, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(nav);
destroy_each(each_blocks, detaching);
}
};
}
function instance$2($$self, $$props, $$invalidate) {
let { pane } = $$props;
let { panes } = $$props;
const dispatch = createEventDispatcher();
const click_handler = key => dispatch('change', key);
$$self.$$set = $$props => {
if ('pane' in $$props) $$invalidate(0, pane = $$props.pane);
if ('panes' in $$props) $$invalidate(1, panes = $$props.panes);
};
return [pane, panes, dispatch, click_handler];
}
class Menu extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$2, create_fragment$2, safe_not_equal, { pane: 0, panes: 1 }, add_css$1);
}
}
var contextKey = {};
/* node_modules/svelte-json-tree-auto/src/JSONArrow.svelte generated by Svelte v3.41.0 */
function add_css$2(target) {
append_styles(target, "svelte-1vyml86", ".container.svelte-1vyml86{display:inline-block;cursor:pointer;transform:translate(calc(0px - var(--li-identation)), -50%);position:absolute;top:50%;padding-right:100%}.arrow.svelte-1vyml86{transform-origin:25% 50%;position:relative;line-height:1.1em;font-size:0.75em;margin-left:0;transition:150ms;color:var(--arrow-sign);user-select:none;font-family:'Courier New', Courier, monospace}.expanded.svelte-1vyml86{transform:rotateZ(90deg) translateX(-3px)}");
}
function create_fragment$3(ctx) {
let div1;
let div0;
let mounted;
let dispose;
return {
c() {
div1 = element("div");
div0 = element("div");
div0.textContent = `${'\u25B6'}`;
attr(div0, "class", "arrow svelte-1vyml86");
toggle_class(div0, "expanded", /*expanded*/ ctx[0]);
attr(div1, "class", "container svelte-1vyml86");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, div0);
if (!mounted) {
dispose = listen(div1, "click", /*click_handler*/ ctx[1]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*expanded*/ 1) {
toggle_class(div0, "expanded", /*expanded*/ ctx[0]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div1);
mounted = false;
dispose();
}
};
}
function instance$3($$self, $$props, $$invalidate) {
let { expanded } = $$props;
function click_handler(event) {
bubble.call(this, $$self, event);
}
$$self.$$set = $$props => {
if ('expanded' in $$props) $$invalidate(0, expanded = $$props.expanded);
};
return [expanded, click_handler];
}
class JSONArrow extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$3, create_fragment$3, safe_not_equal, { expanded: 0 }, add_css$2);
}
}
/* node_modules/svelte-json-tree-auto/src/JSONKey.svelte generated by Svelte v3.41.0 */
function add_css$3(target) {
append_styles(target, "svelte-1vlbacg", "label.svelte-1vlbacg{display:inline-block;color:var(--label-color);padding:0}.spaced.svelte-1vlbacg{padding-right:var(--li-colon-space)}");
}
// (16:0) {#if showKey && key}
function create_if_block$1(ctx) {
let label;
let span;
let t0;
let t1;
let mounted;
let dispose;
return {
c() {
label = element("label");
span = element("span");
t0 = text(/*key*/ ctx[0]);
t1 = text(/*colon*/ ctx[2]);
attr(label, "class", "svelte-1vlbacg");
toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]);
},
m(target, anchor) {
insert(target, label, anchor);
append(label, span);
append(span, t0);
append(span, t1);
if (!mounted) {
dispose = listen(label, "click", /*click_handler*/ ctx[5]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*key*/ 1) set_data(t0, /*key*/ ctx[0]);
if (dirty & /*colon*/ 4) set_data(t1, /*colon*/ ctx[2]);
if (dirty & /*isParentExpanded*/ 2) {
toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]);
}
},
d(detaching) {
if (detaching) detach(label);
mounted = false;
dispose();
}
};
}
function create_fragment$4(ctx) {
let if_block_anchor;
let if_block = /*showKey*/ ctx[3] && /*key*/ ctx[0] && create_if_block$1(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*showKey*/ ctx[3] && /*key*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$1(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop,
o: noop,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function instance$4($$self, $$props, $$invalidate) {
let showKey;
let { key, isParentExpanded, isParentArray = false, colon = ':' } = $$props;
function click_handler(event) {
bubble.call(this, $$self, event);
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ('colon' in $$props) $$invalidate(2, colon = $$props.colon);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*isParentExpanded, isParentArray, key*/ 19) {
$$invalidate(3, showKey = isParentExpanded || !isParentArray || key != +key);
}
};
return [key, isParentExpanded, colon, showKey, isParentArray, click_handler];
}
class JSONKey extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$4,
create_fragment$4,
safe_not_equal,
{
key: 0,
isParentExpanded: 1,
isParentArray: 4,
colon: 2
},
add_css$3
);
}
}
/* node_modules/svelte-json-tree-auto/src/JSONNested.svelte generated by Svelte v3.41.0 */
function add_css$4(target) {
append_styles(target, "svelte-rwxv37", "label.svelte-rwxv37{display:inline-block}.indent.svelte-rwxv37{padding-left:var(--li-identation)}.collapse.svelte-rwxv37{--li-display:inline;display:inline;font-style:italic}.comma.svelte-rwxv37{margin-left:-0.5em;margin-right:0.5em}label.svelte-rwxv37{position:relative}");
}
function get_each_context$1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[12] = list[i];
child_ctx[20] = i;
return child_ctx;
}
// (57:4) {#if expandable && isParentExpanded}
function create_if_block_3(ctx) {
let jsonarrow;
let current;
jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } });
jsonarrow.$on("click", /*toggleExpand*/ ctx[15]);
return {
c() {
create_component(jsonarrow.$$.fragment);
},
m(target, anchor) {
mount_component(jsonarrow, target, anchor);
current = true;
},
p(ctx, dirty) {
const jsonarrow_changes = {};
if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0];
jsonarrow.$set(jsonarrow_changes);
},
i(local) {
if (current) return;
transition_in(jsonarrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonarrow.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonarrow, detaching);
}
};
}
// (75:4) {:else}
function create_else_block(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = "…";
},
m(target, anchor) {
insert(target, span, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(span);
}
};
}
// (63:4) {#if isParentExpanded}
function create_if_block$2(ctx) {
let ul;
let t;
let current;
let mounted;
let dispose;
let each_value = /*slicedKeys*/ ctx[13];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$1(get_each_context$1(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block = /*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length && create_if_block_1();
return {
c() {
ul = element("ul");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t = space();
if (if_block) if_block.c();
attr(ul, "class", "svelte-rwxv37");
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
},
m(target, anchor) {
insert(target, ul, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(ul, null);
}
append(ul, t);
if (if_block) if_block.m(ul, null);
current = true;
if (!mounted) {
dispose = listen(ul, "click", /*expand*/ ctx[16]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*expanded, previewKeys, getKey, slicedKeys, isArray, getValue, getPreviewValue*/ 10129) {
each_value = /*slicedKeys*/ ctx[13];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$1(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$1(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(ul, t);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length) {
if (if_block) ; else {
if_block = create_if_block_1();
if_block.c();
if_block.m(ul, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*expanded*/ 1) {
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_each(each_blocks, detaching);
if (if_block) if_block.d();
mounted = false;
dispose();
}
};
}
// (67:10) {#if !expanded && index < previewKeys.length - 1}
function create_if_block_2(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = ",";
attr(span, "class", "comma svelte-rwxv37");
},
m(target, anchor) {
insert(target, span, anchor);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
// (65:8) {#each slicedKeys as key, index}
function create_each_block$1(ctx) {
let jsonnode;
let t;
let if_block_anchor;
let current;
jsonnode = new JSONNode({
props: {
key: /*getKey*/ ctx[8](/*key*/ ctx[12]),
isParentExpanded: /*expanded*/ ctx[0],
isParentArray: /*isArray*/ ctx[4],
value: /*expanded*/ ctx[0]
? /*getValue*/ ctx[9](/*key*/ ctx[12])
: /*getPreviewValue*/ ctx[10](/*key*/ ctx[12])
}
});
let if_block = !/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1 && create_if_block_2();
return {
c() {
create_component(jsonnode.$$.fragment);
t = space();
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
mount_component(jsonnode, target, anchor);
insert(target, t, anchor);
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const jsonnode_changes = {};
if (dirty & /*getKey, slicedKeys*/ 8448) jsonnode_changes.key = /*getKey*/ ctx[8](/*key*/ ctx[12]);
if (dirty & /*expanded*/ 1) jsonnode_changes.isParentExpanded = /*expanded*/ ctx[0];
if (dirty & /*isArray*/ 16) jsonnode_changes.isParentArray = /*isArray*/ ctx[4];
if (dirty & /*expanded, getValue, slicedKeys, getPreviewValue*/ 9729) jsonnode_changes.value = /*expanded*/ ctx[0]
? /*getValue*/ ctx[9](/*key*/ ctx[12])
: /*getPreviewValue*/ ctx[10](/*key*/ ctx[12]);
jsonnode.$set(jsonnode_changes);
if (!/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1) {
if (if_block) ; else {
if_block = create_if_block_2();
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnode, detaching);
if (detaching) detach(t);
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (71:8) {#if slicedKeys.length < previewKeys.length }
function create_if_block_1(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = "…";
},
m(target, anchor) {
insert(target, span, anchor);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
function create_fragment$5(ctx) {
let li;
let label_1;
let t0;
let jsonkey;
let t1;
let span1;
let span0;
let t2;
let t3;
let t4;
let current_block_type_index;
let if_block1;
let t5;
let span2;
let t6;
let current;
let mounted;
let dispose;
let if_block0 = /*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2] && create_if_block_3(ctx);
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[12],
colon: /*context*/ ctx[14].colon,
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3]
}
});
jsonkey.$on("click", /*toggleExpand*/ ctx[15]);
const if_block_creators = [create_if_block$2, create_else_block];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*isParentExpanded*/ ctx[2]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
li = element("li");
label_1 = element("label");
if (if_block0) if_block0.c();
t0 = space();
create_component(jsonkey.$$.fragment);
t1 = space();
span1 = element("span");
span0 = element("span");
t2 = text(/*label*/ ctx[1]);
t3 = text(/*bracketOpen*/ ctx[5]);
t4 = space();
if_block1.c();
t5 = space();
span2 = element("span");
t6 = text(/*bracketClose*/ ctx[6]);
attr(label_1, "class", "svelte-rwxv37");
attr(li, "class", "svelte-rwxv37");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]);
},
m(target, anchor) {
insert(target, li, anchor);
append(li, label_1);
if (if_block0) if_block0.m(label_1, null);
append(label_1, t0);
mount_component(jsonkey, label_1, null);
append(label_1, t1);
append(label_1, span1);
append(span1, span0);
append(span0, t2);
append(span1, t3);
append(li, t4);
if_blocks[current_block_type_index].m(li, null);
append(li, t5);
append(li, span2);
append(span2, t6);
current = true;
if (!mounted) {
dispose = listen(span1, "click", /*toggleExpand*/ ctx[15]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2]) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*expandable, isParentExpanded*/ 2052) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_3(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(label_1, t0);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
const jsonkey_changes = {};
if (dirty & /*key*/ 4096) jsonkey_changes.key = /*key*/ ctx[12];
if (dirty & /*isParentExpanded*/ 4) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[3];
jsonkey.$set(jsonkey_changes);
if (!current || dirty & /*label*/ 2) set_data(t2, /*label*/ ctx[1]);
if (!current || dirty & /*bracketOpen*/ 32) set_data(t3, /*bracketOpen*/ ctx[5]);
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block1 = if_blocks[current_block_type_index];
if (!if_block1) {
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block1.c();
} else {
if_block1.p(ctx, dirty);
}
transition_in(if_block1, 1);
if_block1.m(li, t5);
}
if (!current || dirty & /*bracketClose*/ 64) set_data(t6, /*bracketClose*/ ctx[6]);
if (dirty & /*isParentExpanded*/ 4) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(jsonkey.$$.fragment, local);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(jsonkey.$$.fragment, local);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (detaching) detach(li);
if (if_block0) if_block0.d();
destroy_component(jsonkey);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$5($$self, $$props, $$invalidate) {
let slicedKeys;
let { key, keys, colon = ':', label = '', isParentExpanded, isParentArray, isArray = false, bracketOpen, bracketClose } = $$props;
let { previewKeys = keys } = $$props;
let { getKey = key => key } = $$props;
let { getValue = key => key } = $$props;
let { getPreviewValue = getValue } = $$props;
let { expanded = false, expandable = true } = $$props;
const context = getContext(contextKey);
setContext(contextKey, { ...context, colon });
function toggleExpand() {
$$invalidate(0, expanded = !expanded);
}
function expand() {
$$invalidate(0, expanded = true);
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(12, key = $$props.key);
if ('keys' in $$props) $$invalidate(17, keys = $$props.keys);
if ('colon' in $$props) $$invalidate(18, colon = $$props.colon);
if ('label' in $$props) $$invalidate(1, label = $$props.label);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ('isArray' in $$props) $$invalidate(4, isArray = $$props.isArray);
if ('bracketOpen' in $$props) $$invalidate(5, bracketOpen = $$props.bracketOpen);
if ('bracketClose' in $$props) $$invalidate(6, bracketClose = $$props.bracketClose);
if ('previewKeys' in $$props) $$invalidate(7, previewKeys = $$props.previewKeys);
if ('getKey' in $$props) $$invalidate(8, getKey = $$props.getKey);
if ('getValue' in $$props) $$invalidate(9, getValue = $$props.getValue);
if ('getPreviewValue' in $$props) $$invalidate(10, getPreviewValue = $$props.getPreviewValue);
if ('expanded' in $$props) $$invalidate(0, expanded = $$props.expanded);
if ('expandable' in $$props) $$invalidate(11, expandable = $$props.expandable);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*isParentExpanded*/ 4) {
if (!isParentExpanded) {
$$invalidate(0, expanded = false);
}
}
if ($$self.$$.dirty & /*expanded, keys, previewKeys*/ 131201) {
$$invalidate(13, slicedKeys = expanded ? keys : previewKeys.slice(0, 5));
}
};
return [
expanded,
label,
isParentExpanded,
isParentArray,
isArray,
bracketOpen,
bracketClose,
previewKeys,
getKey,
getValue,
getPreviewValue,
expandable,
key,
slicedKeys,
context,
toggleExpand,
expand,
keys,
colon
];
}
class JSONNested extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$5,
create_fragment$5,
safe_not_equal,
{
key: 12,
keys: 17,
colon: 18,
label: 1,
isParentExpanded: 2,
isParentArray: 3,
isArray: 4,
bracketOpen: 5,
bracketClose: 6,
previewKeys: 7,
getKey: 8,
getValue: 9,
getPreviewValue: 10,
expanded: 0,
expandable: 11
},
add_css$4
);
}
}
/* node_modules/svelte-json-tree-auto/src/JSONObjectNode.svelte generated by Svelte v3.41.0 */
function create_fragment$6(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[5],
previewKeys: /*keys*/ ctx[5],
getValue: /*getValue*/ ctx[6],
label: "" + (/*nodeType*/ ctx[3] + " "),
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5];
if (dirty & /*keys*/ 32) jsonnested_changes.previewKeys = /*keys*/ ctx[5];
if (dirty & /*nodeType*/ 8) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + " ");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$6($$self, $$props, $$invalidate) {
let keys;
let { key, value, isParentExpanded, isParentArray, nodeType } = $$props;
let { expanded = true } = $$props;
function getValue(key) {
return value[key];
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(7, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(3, nodeType = $$props.nodeType);
if ('expanded' in $$props) $$invalidate(4, expanded = $$props.expanded);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 128) {
$$invalidate(5, keys = Object.getOwnPropertyNames(value));
}
};
return [
key,
isParentExpanded,
isParentArray,
nodeType,
expanded,
keys,
getValue,
value
];
}
class JSONObjectNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$6, create_fragment$6, safe_not_equal, {
key: 0,
value: 7,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONArrayNode.svelte generated by Svelte v3.41.0 */
function create_fragment$7(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
isArray: true,
keys: /*keys*/ ctx[5],
previewKeys: /*previewKeys*/ ctx[6],
getValue: /*getValue*/ ctx[7],
label: "Array(" + /*value*/ ctx[1].length + ")",
bracketOpen: "[",
bracketClose: "]"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5];
if (dirty & /*previewKeys*/ 64) jsonnested_changes.previewKeys = /*previewKeys*/ ctx[6];
if (dirty & /*value*/ 2) jsonnested_changes.label = "Array(" + /*value*/ ctx[1].length + ")";
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$7($$self, $$props, $$invalidate) {
let keys;
let previewKeys;
let { key, value, isParentExpanded, isParentArray } = $$props;
let { expanded = JSON.stringify(value).length < 1024 } = $$props;
const filteredKey = new Set(['length']);
function getValue(key) {
return value[key];
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ('expanded' in $$props) $$invalidate(4, expanded = $$props.expanded);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 2) {
$$invalidate(5, keys = Object.getOwnPropertyNames(value));
}
if ($$self.$$.dirty & /*keys*/ 32) {
$$invalidate(6, previewKeys = keys.filter(key => !filteredKey.has(key)));
}
};
return [
key,
value,
isParentExpanded,
isParentArray,
expanded,
keys,
previewKeys,
getValue
];
}
class JSONArrayNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$7, create_fragment$7, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONIterableArrayNode.svelte generated by Svelte v3.41.0 */
function create_fragment$8(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[4],
getKey,
getValue,
isArray: true,
label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"),
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4];
if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function getKey(key) {
return String(key[0]);
}
function getValue(key) {
return key[1];
}
function instance$8($$self, $$props, $$invalidate) {
let { key, value, isParentExpanded, isParentArray, nodeType } = $$props;
let keys = [];
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(5, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(3, nodeType = $$props.nodeType);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 32) {
{
let result = [];
let i = 0;
for (const entry of value) {
result.push([i++, entry]);
}
$$invalidate(4, keys = result);
}
}
};
return [key, isParentExpanded, isParentArray, nodeType, keys, value];
}
class JSONIterableArrayNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$8, create_fragment$8, safe_not_equal, {
key: 0,
value: 5,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3
});
}
}
class MapEntry {
constructor(key, value) {
this.key = key;
this.value = value;
}
}
/* node_modules/svelte-json-tree-auto/src/JSONIterableMapNode.svelte generated by Svelte v3.41.0 */
function create_fragment$9(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[4],
getKey: getKey$1,
getValue: getValue$1,
label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"),
colon: "",
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4];
if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function getKey$1(entry) {
return entry[0];
}
function getValue$1(entry) {
return entry[1];
}
function instance$9($$self, $$props, $$invalidate) {
let { key, value, isParentExpanded, isParentArray, nodeType } = $$props;
let keys = [];
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(5, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(3, nodeType = $$props.nodeType);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 32) {
{
let result = [];
let i = 0;
for (const entry of value) {
result.push([i++, new MapEntry(entry[0], entry[1])]);
}
$$invalidate(4, keys = result);
}
}
};
return [key, isParentExpanded, isParentArray, nodeType, keys, value];
}
class JSONIterableMapNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$9, create_fragment$9, safe_not_equal, {
key: 0,
value: 5,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONMapEntryNode.svelte generated by Svelte v3.41.0 */
function create_fragment$a(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
key: /*isParentExpanded*/ ctx[2]
? String(/*key*/ ctx[0])
: /*value*/ ctx[1].key,
keys: /*keys*/ ctx[5],
getValue: /*getValue*/ ctx[6],
label: /*isParentExpanded*/ ctx[2] ? 'Entry ' : '=> ',
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*isParentExpanded, key, value*/ 7) jsonnested_changes.key = /*isParentExpanded*/ ctx[2]
? String(/*key*/ ctx[0])
: /*value*/ ctx[1].key;
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.label = /*isParentExpanded*/ ctx[2] ? 'Entry ' : '=> ';
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$a($$self, $$props, $$invalidate) {
let { key, value, isParentExpanded, isParentArray } = $$props;
let { expanded = false } = $$props;
const keys = ['key', 'value'];
function getValue(key) {
return value[key];
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ('expanded' in $$props) $$invalidate(4, expanded = $$props.expanded);
};
return [key, value, isParentExpanded, isParentArray, expanded, keys, getValue];
}
class JSONMapEntryNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$a, create_fragment$a, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONValueNode.svelte generated by Svelte v3.41.0 */
function add_css$5(target) {
append_styles(target, "svelte-3bjyvl", "li.svelte-3bjyvl{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-3bjyvl{padding-left:var(--li-identation)}.String.svelte-3bjyvl{color:var(--string-color)}.Date.svelte-3bjyvl{color:var(--date-color)}.Number.svelte-3bjyvl{color:var(--number-color)}.Boolean.svelte-3bjyvl{color:var(--boolean-color)}.Null.svelte-3bjyvl{color:var(--null-color)}.Undefined.svelte-3bjyvl{color:var(--undefined-color)}.Function.svelte-3bjyvl{color:var(--function-color);font-style:italic}.Symbol.svelte-3bjyvl{color:var(--symbol-color)}");
}
function create_fragment$b(ctx) {
let li;
let jsonkey;
let t0;
let span;
let t1_value = (/*valueGetter*/ ctx[2]
? /*valueGetter*/ ctx[2](/*value*/ ctx[1])
: /*value*/ ctx[1]) + "";
let t1;
let span_class_value;
let current;
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[0],
colon: /*colon*/ ctx[6],
isParentExpanded: /*isParentExpanded*/ ctx[3],
isParentArray: /*isParentArray*/ ctx[4]
}
});
return {
c() {
li = element("li");
create_component(jsonkey.$$.fragment);
t0 = space();
span = element("span");
t1 = text(t1_value);
attr(span, "class", span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl"));
attr(li, "class", "svelte-3bjyvl");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(jsonkey, li, null);
append(li, t0);
append(li, span);
append(span, t1);
current = true;
},
p(ctx, [dirty]) {
const jsonkey_changes = {};
if (dirty & /*key*/ 1) jsonkey_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4];
jsonkey.$set(jsonkey_changes);
if ((!current || dirty & /*valueGetter, value*/ 6) && t1_value !== (t1_value = (/*valueGetter*/ ctx[2]
? /*valueGetter*/ ctx[2](/*value*/ ctx[1])
: /*value*/ ctx[1]) + "")) set_data(t1, t1_value);
if (!current || dirty & /*nodeType*/ 32 && span_class_value !== (span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl"))) {
attr(span, "class", span_class_value);
}
if (dirty & /*isParentExpanded*/ 8) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
}
},
i(local) {
if (current) return;
transition_in(jsonkey.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonkey.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(jsonkey);
}
};
}
function instance$b($$self, $$props, $$invalidate) {
let { key, value, valueGetter = null, isParentExpanded, isParentArray, nodeType } = $$props;
const { colon } = getContext(contextKey);
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('valueGetter' in $$props) $$invalidate(2, valueGetter = $$props.valueGetter);
if ('isParentExpanded' in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(5, nodeType = $$props.nodeType);
};
return [key, value, valueGetter, isParentExpanded, isParentArray, nodeType, colon];
}
class JSONValueNode extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$b,
create_fragment$b,
safe_not_equal,
{
key: 0,
value: 1,
valueGetter: 2,
isParentExpanded: 3,
isParentArray: 4,
nodeType: 5
},
add_css$5
);
}
}
/* node_modules/svelte-json-tree-auto/src/ErrorNode.svelte generated by Svelte v3.41.0 */
function add_css$6(target) {
append_styles(target, "svelte-1ca3gb2", "li.svelte-1ca3gb2{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-1ca3gb2{padding-left:var(--li-identation)}.collapse.svelte-1ca3gb2{--li-display:inline;display:inline;font-style:italic}");
}
function get_each_context$2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[8] = list[i];
child_ctx[10] = i;
return child_ctx;
}
// (40:2) {#if isParentExpanded}
function create_if_block_2$1(ctx) {
let jsonarrow;
let current;
jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } });
jsonarrow.$on("click", /*toggleExpand*/ ctx[7]);
return {
c() {
create_component(jsonarrow.$$.fragment);
},
m(target, anchor) {
mount_component(jsonarrow, target, anchor);
current = true;
},
p(ctx, dirty) {
const jsonarrow_changes = {};
if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0];
jsonarrow.$set(jsonarrow_changes);
},
i(local) {
if (current) return;
transition_in(jsonarrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonarrow.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonarrow, detaching);
}
};
}
// (45:2) {#if isParentExpanded}
function create_if_block$3(ctx) {
let ul;
let current;
let if_block = /*expanded*/ ctx[0] && create_if_block_1$1(ctx);
return {
c() {
ul = element("ul");
if (if_block) if_block.c();
attr(ul, "class", "svelte-1ca3gb2");
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
},
m(target, anchor) {
insert(target, ul, anchor);
if (if_block) if_block.m(ul, null);
current = true;
},
p(ctx, dirty) {
if (/*expanded*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*expanded*/ 1) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$1(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(ul, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
if (dirty & /*expanded*/ 1) {
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
if (if_block) if_block.d();
}
};
}
// (47:6) {#if expanded}
function create_if_block_1$1(ctx) {
let jsonnode;
let t0;
let li;
let jsonkey;
let t1;
let span;
let current;
jsonnode = new JSONNode({
props: {
key: "message",
value: /*value*/ ctx[2].message
}
});
jsonkey = new JSONKey({
props: {
key: "stack",
colon: ":",
isParentExpanded: /*isParentExpanded*/ ctx[3]
}
});
let each_value = /*stack*/ ctx[5];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$2(get_each_context$2(ctx, each_value, i));
}
return {
c() {
create_component(jsonnode.$$.fragment);
t0 = space();
li = element("li");
create_component(jsonkey.$$.fragment);
t1 = space();
span = element("span");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(li, "class", "svelte-1ca3gb2");
},
m(target, anchor) {
mount_component(jsonnode, target, anchor);
insert(target, t0, anchor);
insert(target, li, anchor);
mount_component(jsonkey, li, null);
append(li, t1);
append(li, span);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(span, null);
}
current = true;
},
p(ctx, dirty) {
const jsonnode_changes = {};
if (dirty & /*value*/ 4) jsonnode_changes.value = /*value*/ ctx[2].message;
jsonnode.$set(jsonnode_changes);
const jsonkey_changes = {};
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
jsonkey.$set(jsonkey_changes);
if (dirty & /*stack*/ 32) {
each_value = /*stack*/ ctx[5];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$2(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$2(child_ctx);
each_blocks[i].c();
each_blocks[i].m(span, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
transition_in(jsonkey.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
transition_out(jsonkey.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnode, detaching);
if (detaching) detach(t0);
if (detaching) detach(li);
destroy_component(jsonkey);
destroy_each(each_blocks, detaching);
}
};
}
// (52:12) {#each stack as line, index}
function create_each_block$2(ctx) {
let span;
let t_value = /*line*/ ctx[8] + "";
let t;
let br;
return {
c() {
span = element("span");
t = text(t_value);
br = element("br");
attr(span, "class", "svelte-1ca3gb2");
toggle_class(span, "indent", /*index*/ ctx[10] > 0);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
insert(target, br, anchor);
},
p(ctx, dirty) {
if (dirty & /*stack*/ 32 && t_value !== (t_value = /*line*/ ctx[8] + "")) set_data(t, t_value);
},
d(detaching) {
if (detaching) detach(span);
if (detaching) detach(br);
}
};
}
function create_fragment$c(ctx) {
let li;
let t0;
let jsonkey;
let t1;
let span;
let t2;
let t3_value = (/*expanded*/ ctx[0] ? '' : /*value*/ ctx[2].message) + "";
let t3;
let t4;
let current;
let mounted;
let dispose;
let if_block0 = /*isParentExpanded*/ ctx[3] && create_if_block_2$1(ctx);
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[1],
colon: /*context*/ ctx[6].colon,
isParentExpanded: /*isParentExpanded*/ ctx[3],
isParentArray: /*isParentArray*/ ctx[4]
}
});
let if_block1 = /*isParentExpanded*/ ctx[3] && create_if_block$3(ctx);
return {
c() {
li = element("li");
if (if_block0) if_block0.c();
t0 = space();
create_component(jsonkey.$$.fragment);
t1 = space();
span = element("span");
t2 = text("Error: ");
t3 = text(t3_value);
t4 = space();
if (if_block1) if_block1.c();
attr(li, "class", "svelte-1ca3gb2");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
},
m(target, anchor) {
insert(target, li, anchor);
if (if_block0) if_block0.m(li, null);
append(li, t0);
mount_component(jsonkey, li, null);
append(li, t1);
append(li, span);
append(span, t2);
append(span, t3);
append(li, t4);
if (if_block1) if_block1.m(li, null);
current = true;
if (!mounted) {
dispose = listen(span, "click", /*toggleExpand*/ ctx[7]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*isParentExpanded*/ ctx[3]) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*isParentExpanded*/ 8) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_2$1(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(li, t0);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
const jsonkey_changes = {};
if (dirty & /*key*/ 2) jsonkey_changes.key = /*key*/ ctx[1];
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4];
jsonkey.$set(jsonkey_changes);
if ((!current || dirty & /*expanded, value*/ 5) && t3_value !== (t3_value = (/*expanded*/ ctx[0] ? '' : /*value*/ ctx[2].message) + "")) set_data(t3, t3_value);
if (/*isParentExpanded*/ ctx[3]) {
if (if_block1) {
if_block1.p(ctx, dirty);
if (dirty & /*isParentExpanded*/ 8) {
transition_in(if_block1, 1);
}
} else {
if_block1 = create_if_block$3(ctx);
if_block1.c();
transition_in(if_block1, 1);
if_block1.m(li, null);
}
} else if (if_block1) {
group_outros();
transition_out(if_block1, 1, 1, () => {
if_block1 = null;
});
check_outros();
}
if (dirty & /*isParentExpanded*/ 8) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(jsonkey.$$.fragment, local);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(jsonkey.$$.fragment, local);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (detaching) detach(li);
if (if_block0) if_block0.d();
destroy_component(jsonkey);
if (if_block1) if_block1.d();
mounted = false;
dispose();
}
};
}
function instance$c($$self, $$props, $$invalidate) {
let stack;
let { key, value, isParentExpanded, isParentArray } = $$props;
let { expanded = false } = $$props;
const context = getContext(contextKey);
setContext(contextKey, { ...context, colon: ':' });
function toggleExpand() {
$$invalidate(0, expanded = !expanded);
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(1, key = $$props.key);
if ('value' in $$props) $$invalidate(2, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ('expanded' in $$props) $$invalidate(0, expanded = $$props.expanded);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 4) {
$$invalidate(5, stack = value.stack.split('\n'));
}
if ($$self.$$.dirty & /*isParentExpanded*/ 8) {
if (!isParentExpanded) {
$$invalidate(0, expanded = false);
}
}
};
return [
expanded,
key,
value,
isParentExpanded,
isParentArray,
stack,
context,
toggleExpand
];
}
class ErrorNode extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$c,
create_fragment$c,
safe_not_equal,
{
key: 1,
value: 2,
isParentExpanded: 3,
isParentArray: 4,
expanded: 0
},
add_css$6
);
}
}
function objType(obj) {
const type = Object.prototype.toString.call(obj).slice(8, -1);
if (type === 'Object') {
if (typeof obj[Symbol.iterator] === 'function') {
return 'Iterable';
}
return obj.constructor.name;
}
return type;
}
/* node_modules/svelte-json-tree-auto/src/JSONNode.svelte generated by Svelte v3.41.0 */
function create_fragment$d(ctx) {
let switch_instance;
let switch_instance_anchor;
let current;
var switch_value = /*componentType*/ ctx[6];
function switch_props(ctx) {
return {
props: {
key: /*key*/ ctx[0],
value: /*value*/ ctx[1],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
nodeType: /*nodeType*/ ctx[4],
valueGetter: /*valueGetter*/ ctx[5]
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
if (switch_instance) create_component(switch_instance.$$.fragment);
switch_instance_anchor = empty();
},
m(target, anchor) {
if (switch_instance) {
mount_component(switch_instance, target, anchor);
}
insert(target, switch_instance_anchor, anchor);
current = true;
},
p(ctx, [dirty]) {
const switch_instance_changes = {};
if (dirty & /*key*/ 1) switch_instance_changes.key = /*key*/ ctx[0];
if (dirty & /*value*/ 2) switch_instance_changes.value = /*value*/ ctx[1];
if (dirty & /*isParentExpanded*/ 4) switch_instance_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) switch_instance_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*nodeType*/ 16) switch_instance_changes.nodeType = /*nodeType*/ ctx[4];
if (dirty & /*valueGetter*/ 32) switch_instance_changes.valueGetter = /*valueGetter*/ ctx[5];
if (switch_value !== (switch_value = /*componentType*/ ctx[6])) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(switch_instance_anchor);
if (switch_instance) destroy_component(switch_instance, detaching);
}
};
}
function instance$d($$self, $$props, $$invalidate) {
let nodeType;
let componentType;
let valueGetter;
let { key, value, isParentExpanded, isParentArray } = $$props;
function getComponent(nodeType) {
switch (nodeType) {
case 'Object':
return JSONObjectNode;
case 'Error':
return ErrorNode;
case 'Array':
return JSONArrayNode;
case 'Iterable':
case 'Map':
case 'Set':
return typeof value.set === 'function'
? JSONIterableMapNode
: JSONIterableArrayNode;
case 'MapEntry':
return JSONMapEntryNode;
default:
return JSONValueNode;
}
}
function getValueGetter(nodeType) {
switch (nodeType) {
case 'Object':
case 'Error':
case 'Array':
case 'Iterable':
case 'Map':
case 'Set':
case 'MapEntry':
case 'Number':
return undefined;
case 'String':
return raw => `"${raw}"`;
case 'Boolean':
return raw => raw ? 'true' : 'false';
case 'Date':
return raw => raw.toISOString();
case 'Null':
return () => 'null';
case 'Undefined':
return () => 'undefined';
case 'Function':
case 'Symbol':
return raw => raw.toString();
default:
return () => `<${nodeType}>`;
}
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 2) {
$$invalidate(4, nodeType = objType(value));
}
if ($$self.$$.dirty & /*nodeType*/ 16) {
$$invalidate(6, componentType = getComponent(nodeType));
}
if ($$self.$$.dirty & /*nodeType*/ 16) {
$$invalidate(5, valueGetter = getValueGetter(nodeType));
}
};
return [
key,
value,
isParentExpanded,
isParentArray,
nodeType,
valueGetter,
componentType
];
}
class JSONNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$d, create_fragment$d, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3
});
}
}
/* node_modules/svelte-json-tree-auto/src/Root.svelte generated by Svelte v3.41.0 */
function add_css$7(target) {
append_styles(target, "svelte-773n60", "ul.svelte-773n60{--string-color:var(--json-tree-string-color, #cb3f41);--symbol-color:var(--json-tree-symbol-color, #cb3f41);--boolean-color:var(--json-tree-boolean-color, #112aa7);--function-color:var(--json-tree-function-color, #112aa7);--number-color:var(--json-tree-number-color, #3029cf);--label-color:var(--json-tree-label-color, #871d8f);--arrow-color:var(--json-tree-arrow-color, #727272);--null-color:var(--json-tree-null-color, #8d8d8d);--undefined-color:var(--json-tree-undefined-color, #8d8d8d);--date-color:var(--json-tree-date-color, #8d8d8d);--li-identation:var(--json-tree-li-indentation, 1em);--li-line-height:var(--json-tree-li-line-height, 1.3);--li-colon-space:0.3em;font-size:var(--json-tree-font-size, 12px);font-family:var(--json-tree-font-family, 'Courier New', Courier, monospace)}ul.svelte-773n60 li{line-height:var(--li-line-height);display:var(--li-display, list-item);list-style:none}ul.svelte-773n60,ul.svelte-773n60 ul{padding:0;margin:0}");
}
function create_fragment$e(ctx) {
let ul;
let jsonnode;
let current;
jsonnode = new JSONNode({
props: {
key: /*key*/ ctx[0],
value: /*value*/ ctx[1],
isParentExpanded: true,
isParentArray: false
}
});
return {
c() {
ul = element("ul");
create_component(jsonnode.$$.fragment);
attr(ul, "class", "svelte-773n60");
},
m(target, anchor) {
insert(target, ul, anchor);
mount_component(jsonnode, ul, null);
current = true;
},
p(ctx, [dirty]) {
const jsonnode_changes = {};
if (dirty & /*key*/ 1) jsonnode_changes.key = /*key*/ ctx[0];
if (dirty & /*value*/ 2) jsonnode_changes.value = /*value*/ ctx[1];
jsonnode.$set(jsonnode_changes);
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_component(jsonnode);
}
};
}
function instance$e($$self, $$props, $$invalidate) {
setContext(contextKey, {});
let { key = '', value } = $$props;
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
};
return [key, value];
}
class Root extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$e, create_fragment$e, safe_not_equal, { key: 0, value: 1 }, add_css$7);
}
}
/* src/client/debug/main/ClientSwitcher.svelte generated by Svelte v3.41.0 */
function add_css$8(target) {
append_styles(target, "svelte-jvfq3i", ".svelte-jvfq3i{box-sizing:border-box}section.switcher.svelte-jvfq3i{position:sticky;bottom:0;transform:translateY(20px);margin:40px -20px 0;border-top:1px solid #999;padding:20px;background:#fff}label.svelte-jvfq3i{display:flex;align-items:baseline;gap:5px;font-weight:bold}select.svelte-jvfq3i{min-width:140px}");
}
function get_each_context$3(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
child_ctx[9] = i;
return child_ctx;
}
// (42:0) {#if debuggableClients.length > 1}
function create_if_block$4(ctx) {
let section;
let label;
let t;
let select;
let mounted;
let dispose;
let each_value = /*debuggableClients*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$3(get_each_context$3(ctx, each_value, i));
}
return {
c() {
section = element("section");
label = element("label");
t = text("Client\n \n ");
select = element("select");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(select, "id", selectId);
attr(select, "class", "svelte-jvfq3i");
if (/*selected*/ ctx[2] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[6].call(select));
attr(label, "class", "svelte-jvfq3i");
attr(section, "class", "switcher svelte-jvfq3i");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, label);
append(label, t);
append(label, select);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(select, null);
}
select_option(select, /*selected*/ ctx[2]);
if (!mounted) {
dispose = [
listen(select, "change", /*handleSelection*/ ctx[3]),
listen(select, "change", /*select_change_handler*/ ctx[6])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*debuggableClients, JSON*/ 2) {
each_value = /*debuggableClients*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$3(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$3(child_ctx);
each_blocks[i].c();
each_blocks[i].m(select, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (dirty & /*selected*/ 4) {
select_option(select, /*selected*/ ctx[2]);
}
},
d(detaching) {
if (detaching) detach(section);
destroy_each(each_blocks, detaching);
mounted = false;
run_all(dispose);
}
};
}
// (48:8) {#each debuggableClients as clientOption, index}
function create_each_block$3(ctx) {
let option;
let t0;
let t1;
let t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + "";
let t2;
let t3;
let t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + "";
let t4;
let t5;
let t6_value = /*clientOption*/ ctx[7].game.name + "";
let t6;
let t7;
let option_value_value;
return {
c() {
option = element("option");
t0 = text(/*index*/ ctx[9]);
t1 = text(" —\n playerID: ");
t2 = text(t2_value);
t3 = text(",\n matchID: ");
t4 = text(t4_value);
t5 = text("\n (");
t6 = text(t6_value);
t7 = text(")\n ");
option.__value = option_value_value = /*index*/ ctx[9];
option.value = option.__value;
attr(option, "class", "svelte-jvfq3i");
},
m(target, anchor) {
insert(target, option, anchor);
append(option, t0);
append(option, t1);
append(option, t2);
append(option, t3);
append(option, t4);
append(option, t5);
append(option, t6);
append(option, t7);
},
p(ctx, dirty) {
if (dirty & /*debuggableClients*/ 2 && t2_value !== (t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + "")) set_data(t2, t2_value);
if (dirty & /*debuggableClients*/ 2 && t4_value !== (t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + "")) set_data(t4, t4_value);
if (dirty & /*debuggableClients*/ 2 && t6_value !== (t6_value = /*clientOption*/ ctx[7].game.name + "")) set_data(t6, t6_value);
},
d(detaching) {
if (detaching) detach(option);
}
};
}
function create_fragment$f(ctx) {
let if_block_anchor;
let if_block = /*debuggableClients*/ ctx[1].length > 1 && create_if_block$4(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*debuggableClients*/ ctx[1].length > 1) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$4(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop,
o: noop,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
const selectId = 'bgio-debug-select-client';
function instance$f($$self, $$props, $$invalidate) {
let client;
let debuggableClients;
let selected;
let $clientManager,
$$unsubscribe_clientManager = noop,
$$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(5, $clientManager = $$value)), clientManager);
$$self.$$.on_destroy.push(() => $$unsubscribe_clientManager());
let { clientManager } = $$props;
$$subscribe_clientManager();
const handleSelection = e => {
// Request to switch to the selected client.
const selectedClient = debuggableClients[e.target.value];
clientManager.switchToClient(selectedClient);
// Maintain focus on the client select menu after switching clients.
// Necessary because switching clients will usually trigger a mount/unmount.
const select = document.getElementById(selectId);
if (select) select.focus();
};
function select_change_handler() {
selected = select_value(this);
((($$invalidate(2, selected), $$invalidate(1, debuggableClients)), $$invalidate(4, client)), $$invalidate(5, $clientManager));
}
$$self.$$set = $$props => {
if ('clientManager' in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager));
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$clientManager*/ 32) {
$$invalidate(4, { client, debuggableClients } = $clientManager, client, ($$invalidate(1, debuggableClients), $$invalidate(5, $clientManager)));
}
if ($$self.$$.dirty & /*debuggableClients, client*/ 18) {
$$invalidate(2, selected = debuggableClients.indexOf(client));
}
};
return [
clientManager,
debuggableClients,
selected,
handleSelection,
client,
$clientManager,
select_change_handler
];
}
class ClientSwitcher extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$f, create_fragment$f, safe_not_equal, { clientManager: 0 }, add_css$8);
}
}
/* src/client/debug/main/Hotkey.svelte generated by Svelte v3.41.0 */
function add_css$9(target) {
append_styles(target, "svelte-1vfj1mn", ".key.svelte-1vfj1mn.svelte-1vfj1mn{display:flex;flex-direction:row;align-items:center}button.svelte-1vfj1mn.svelte-1vfj1mn{cursor:pointer;min-width:10px;padding-left:5px;padding-right:5px;height:20px;line-height:20px;text-align:center;border:1px solid #ccc;box-shadow:1px 1px 1px #888;background:#eee;color:#444}button.svelte-1vfj1mn.svelte-1vfj1mn:hover{background:#ddd}.key.active.svelte-1vfj1mn button.svelte-1vfj1mn{background:#ddd;border:1px solid #999;box-shadow:none}label.svelte-1vfj1mn.svelte-1vfj1mn{margin-left:10px}");
}
// (78:2) {#if label}
function create_if_block$5(ctx) {
let label_1;
let t0;
let t1;
let span;
let t2_value = `(shortcut: ${/*value*/ ctx[0]})` + "";
let t2;
return {
c() {
label_1 = element("label");
t0 = text(/*label*/ ctx[1]);
t1 = space();
span = element("span");
t2 = text(t2_value);
attr(span, "class", "screen-reader-only");
attr(label_1, "for", /*id*/ ctx[5]);
attr(label_1, "class", "svelte-1vfj1mn");
},
m(target, anchor) {
insert(target, label_1, anchor);
append(label_1, t0);
append(label_1, t1);
append(label_1, span);
append(span, t2);
},
p(ctx, dirty) {
if (dirty & /*label*/ 2) set_data(t0, /*label*/ ctx[1]);
if (dirty & /*value*/ 1 && t2_value !== (t2_value = `(shortcut: ${/*value*/ ctx[0]})` + "")) set_data(t2, t2_value);
},
d(detaching) {
if (detaching) detach(label_1);
}
};
}
function create_fragment$g(ctx) {
let div;
let button;
let t0;
let t1;
let mounted;
let dispose;
let if_block = /*label*/ ctx[1] && create_if_block$5(ctx);
return {
c() {
div = element("div");
button = element("button");
t0 = text(/*value*/ ctx[0]);
t1 = space();
if (if_block) if_block.c();
attr(button, "id", /*id*/ ctx[5]);
button.disabled = /*disable*/ ctx[2];
attr(button, "class", "svelte-1vfj1mn");
attr(div, "class", "key svelte-1vfj1mn");
toggle_class(div, "active", /*active*/ ctx[3]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, button);
append(button, t0);
append(div, t1);
if (if_block) if_block.m(div, null);
if (!mounted) {
dispose = [
listen(window, "keydown", /*Keypress*/ ctx[7]),
listen(button, "click", /*Activate*/ ctx[6])
];
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*value*/ 1) set_data(t0, /*value*/ ctx[0]);
if (dirty & /*disable*/ 4) {
button.disabled = /*disable*/ ctx[2];
}
if (/*label*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$5(ctx);
if_block.c();
if_block.m(div, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*active*/ 8) {
toggle_class(div, "active", /*active*/ ctx[3]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
if (if_block) if_block.d();
mounted = false;
run_all(dispose);
}
};
}
function instance$g($$self, $$props, $$invalidate) {
let $disableHotkeys;
let { value } = $$props;
let { onPress = null } = $$props;
let { label = null } = $$props;
let { disable = false } = $$props;
const { disableHotkeys } = getContext('hotkeys');
component_subscribe($$self, disableHotkeys, value => $$invalidate(9, $disableHotkeys = value));
let active = false;
let id = `key-${value}`;
function Deactivate() {
$$invalidate(3, active = false);
}
function Activate() {
$$invalidate(3, active = true);
setTimeout(Deactivate, 200);
if (onPress) {
setTimeout(onPress, 1);
}
}
function Keypress(e) {
if (!$disableHotkeys && !disable && !e.ctrlKey && !e.metaKey && e.key == value) {
e.preventDefault();
Activate();
}
}
$$self.$$set = $$props => {
if ('value' in $$props) $$invalidate(0, value = $$props.value);
if ('onPress' in $$props) $$invalidate(8, onPress = $$props.onPress);
if ('label' in $$props) $$invalidate(1, label = $$props.label);
if ('disable' in $$props) $$invalidate(2, disable = $$props.disable);
};
return [value, label, disable, active, disableHotkeys, id, Activate, Keypress, onPress];
}
class Hotkey extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$g,
create_fragment$g,
safe_not_equal,
{
value: 0,
onPress: 8,
label: 1,
disable: 2
},
add_css$9
);
}
}
/* src/client/debug/main/InteractiveFunction.svelte generated by Svelte v3.41.0 */
function add_css$a(target) {
append_styles(target, "svelte-1mppqmp", ".move.svelte-1mppqmp{display:flex;flex-direction:row;cursor:pointer;margin-left:10px;color:#666}.move.svelte-1mppqmp:hover{color:#333}.move.active.svelte-1mppqmp{color:#111;font-weight:bold}.arg-field.svelte-1mppqmp{outline:none;font-family:monospace}");
}
function create_fragment$h(ctx) {
let div;
let span0;
let t0;
let t1;
let span1;
let t3;
let span2;
let t4;
let span3;
let mounted;
let dispose;
return {
c() {
div = element("div");
span0 = element("span");
t0 = text(/*name*/ ctx[2]);
t1 = space();
span1 = element("span");
span1.textContent = "(";
t3 = space();
span2 = element("span");
t4 = space();
span3 = element("span");
span3.textContent = ")";
attr(span2, "class", "arg-field svelte-1mppqmp");
attr(span2, "contenteditable", "");
attr(div, "class", "move svelte-1mppqmp");
toggle_class(div, "active", /*active*/ ctx[3]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, span0);
append(span0, t0);
append(div, t1);
append(div, span1);
append(div, t3);
append(div, span2);
/*span2_binding*/ ctx[6](span2);
append(div, t4);
append(div, span3);
if (!mounted) {
dispose = [
listen(span2, "focus", function () {
if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments);
}),
listen(span2, "blur", function () {
if (is_function(/*Deactivate*/ ctx[1])) /*Deactivate*/ ctx[1].apply(this, arguments);
}),
listen(span2, "keypress", stop_propagation(keypress_handler)),
listen(span2, "keydown", /*OnKeyDown*/ ctx[5]),
listen(div, "click", function () {
if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments);
})
];
mounted = true;
}
},
p(new_ctx, [dirty]) {
ctx = new_ctx;
if (dirty & /*name*/ 4) set_data(t0, /*name*/ ctx[2]);
if (dirty & /*active*/ 8) {
toggle_class(div, "active", /*active*/ ctx[3]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
/*span2_binding*/ ctx[6](null);
mounted = false;
run_all(dispose);
}
};
}
const keypress_handler = () => {
};
function instance$h($$self, $$props, $$invalidate) {
let { Activate } = $$props;
let { Deactivate } = $$props;
let { name } = $$props;
let { active } = $$props;
let span;
const dispatch = createEventDispatcher();
function Submit() {
try {
const value = span.innerText;
let argArray = new Function(`return [${value}]`)();
dispatch('submit', argArray);
} catch(error) {
dispatch('error', error);
}
$$invalidate(4, span.innerText = '', span);
}
function OnKeyDown(e) {
if (e.key == 'Enter') {
e.preventDefault();
Submit();
}
if (e.key == 'Escape') {
e.preventDefault();
Deactivate();
}
}
afterUpdate(() => {
if (active) {
span.focus();
} else {
span.blur();
}
});
function span2_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
span = $$value;
$$invalidate(4, span);
});
}
$$self.$$set = $$props => {
if ('Activate' in $$props) $$invalidate(0, Activate = $$props.Activate);
if ('Deactivate' in $$props) $$invalidate(1, Deactivate = $$props.Deactivate);
if ('name' in $$props) $$invalidate(2, name = $$props.name);
if ('active' in $$props) $$invalidate(3, active = $$props.active);
};
return [Activate, Deactivate, name, active, span, OnKeyDown, span2_binding];
}
class InteractiveFunction extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$h,
create_fragment$h,
safe_not_equal,
{
Activate: 0,
Deactivate: 1,
name: 2,
active: 3
},
add_css$a
);
}
}
/* src/client/debug/main/Move.svelte generated by Svelte v3.41.0 */
function add_css$b(target) {
append_styles(target, "svelte-smqssc", ".move-error.svelte-smqssc{color:#a00;font-weight:bold}.wrapper.svelte-smqssc{display:flex;flex-direction:row;align-items:center}");
}
// (65:2) {#if error}
function create_if_block$6(ctx) {
let span;
let t;
return {
c() {
span = element("span");
t = text(/*error*/ ctx[2]);
attr(span, "class", "move-error svelte-smqssc");
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
},
p(ctx, dirty) {
if (dirty & /*error*/ 4) set_data(t, /*error*/ ctx[2]);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
function create_fragment$i(ctx) {
let div1;
let div0;
let hotkey;
let t0;
let interactivefunction;
let t1;
let current;
hotkey = new Hotkey({
props: {
value: /*shortcut*/ ctx[0],
onPress: /*Activate*/ ctx[4]
}
});
interactivefunction = new InteractiveFunction({
props: {
Activate: /*Activate*/ ctx[4],
Deactivate: /*Deactivate*/ ctx[5],
name: /*name*/ ctx[1],
active: /*active*/ ctx[3]
}
});
interactivefunction.$on("submit", /*Submit*/ ctx[6]);
interactivefunction.$on("error", /*Error*/ ctx[7]);
let if_block = /*error*/ ctx[2] && create_if_block$6(ctx);
return {
c() {
div1 = element("div");
div0 = element("div");
create_component(hotkey.$$.fragment);
t0 = space();
create_component(interactivefunction.$$.fragment);
t1 = space();
if (if_block) if_block.c();
attr(div0, "class", "wrapper svelte-smqssc");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, div0);
mount_component(hotkey, div0, null);
append(div0, t0);
mount_component(interactivefunction, div0, null);
append(div1, t1);
if (if_block) if_block.m(div1, null);
current = true;
},
p(ctx, [dirty]) {
const hotkey_changes = {};
if (dirty & /*shortcut*/ 1) hotkey_changes.value = /*shortcut*/ ctx[0];
hotkey.$set(hotkey_changes);
const interactivefunction_changes = {};
if (dirty & /*name*/ 2) interactivefunction_changes.name = /*name*/ ctx[1];
if (dirty & /*active*/ 8) interactivefunction_changes.active = /*active*/ ctx[3];
interactivefunction.$set(interactivefunction_changes);
if (/*error*/ ctx[2]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$6(ctx);
if_block.c();
if_block.m(div1, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i(local) {
if (current) return;
transition_in(hotkey.$$.fragment, local);
transition_in(interactivefunction.$$.fragment, local);
current = true;
},
o(local) {
transition_out(hotkey.$$.fragment, local);
transition_out(interactivefunction.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div1);
destroy_component(hotkey);
destroy_component(interactivefunction);
if (if_block) if_block.d();
}
};
}
function instance$i($$self, $$props, $$invalidate) {
let { shortcut } = $$props;
let { name } = $$props;
let { fn } = $$props;
const { disableHotkeys } = getContext('hotkeys');
let error$1 = '';
let active = false;
function Activate() {
disableHotkeys.set(true);
$$invalidate(3, active = true);
}
function Deactivate() {
disableHotkeys.set(false);
$$invalidate(2, error$1 = '');
$$invalidate(3, active = false);
}
function Submit(e) {
$$invalidate(2, error$1 = '');
Deactivate();
fn.apply(this, e.detail);
}
function Error(e) {
$$invalidate(2, error$1 = e.detail);
error(e.detail);
}
$$self.$$set = $$props => {
if ('shortcut' in $$props) $$invalidate(0, shortcut = $$props.shortcut);
if ('name' in $$props) $$invalidate(1, name = $$props.name);
if ('fn' in $$props) $$invalidate(8, fn = $$props.fn);
};
return [shortcut, name, error$1, active, Activate, Deactivate, Submit, Error, fn];
}
class Move extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$i, create_fragment$i, safe_not_equal, { shortcut: 0, name: 1, fn: 8 }, add_css$b);
}
}
/* src/client/debug/main/Controls.svelte generated by Svelte v3.41.0 */
function add_css$c(target) {
append_styles(target, "svelte-c3lavh", "ul.svelte-c3lavh{padding-left:0}li.svelte-c3lavh{list-style:none;margin:none;margin-bottom:5px}");
}
function create_fragment$j(ctx) {
let ul;
let li0;
let hotkey0;
let t0;
let li1;
let hotkey1;
let t1;
let li2;
let hotkey2;
let t2;
let li3;
let hotkey3;
let current;
hotkey0 = new Hotkey({
props: {
value: "1",
onPress: /*client*/ ctx[0].reset,
label: "reset"
}
});
hotkey1 = new Hotkey({
props: {
value: "2",
onPress: /*Save*/ ctx[2],
label: "save"
}
});
hotkey2 = new Hotkey({
props: {
value: "3",
onPress: /*Restore*/ ctx[3],
label: "restore"
}
});
hotkey3 = new Hotkey({
props: {
value: ".",
onPress: /*ToggleVisibility*/ ctx[1],
label: "hide"
}
});
return {
c() {
ul = element("ul");
li0 = element("li");
create_component(hotkey0.$$.fragment);
t0 = space();
li1 = element("li");
create_component(hotkey1.$$.fragment);
t1 = space();
li2 = element("li");
create_component(hotkey2.$$.fragment);
t2 = space();
li3 = element("li");
create_component(hotkey3.$$.fragment);
attr(li0, "class", "svelte-c3lavh");
attr(li1, "class", "svelte-c3lavh");
attr(li2, "class", "svelte-c3lavh");
attr(li3, "class", "svelte-c3lavh");
attr(ul, "id", "debug-controls");
attr(ul, "class", "controls svelte-c3lavh");
},
m(target, anchor) {
insert(target, ul, anchor);
append(ul, li0);
mount_component(hotkey0, li0, null);
append(ul, t0);
append(ul, li1);
mount_component(hotkey1, li1, null);
append(ul, t1);
append(ul, li2);
mount_component(hotkey2, li2, null);
append(ul, t2);
append(ul, li3);
mount_component(hotkey3, li3, null);
current = true;
},
p(ctx, [dirty]) {
const hotkey0_changes = {};
if (dirty & /*client*/ 1) hotkey0_changes.onPress = /*client*/ ctx[0].reset;
hotkey0.$set(hotkey0_changes);
const hotkey3_changes = {};
if (dirty & /*ToggleVisibility*/ 2) hotkey3_changes.onPress = /*ToggleVisibility*/ ctx[1];
hotkey3.$set(hotkey3_changes);
},
i(local) {
if (current) return;
transition_in(hotkey0.$$.fragment, local);
transition_in(hotkey1.$$.fragment, local);
transition_in(hotkey2.$$.fragment, local);
transition_in(hotkey3.$$.fragment, local);
current = true;
},
o(local) {
transition_out(hotkey0.$$.fragment, local);
transition_out(hotkey1.$$.fragment, local);
transition_out(hotkey2.$$.fragment, local);
transition_out(hotkey3.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_component(hotkey0);
destroy_component(hotkey1);
destroy_component(hotkey2);
destroy_component(hotkey3);
}
};
}
function instance$j($$self, $$props, $$invalidate) {
let { client } = $$props;
let { ToggleVisibility } = $$props;
function Save() {
// get state to persist and overwrite deltalog, _undo, and _redo
const state = client.getState();
const json = stringify({
...state,
_undo: [],
_redo: [],
deltalog: []
});
window.localStorage.setItem('gamestate', json);
window.localStorage.setItem('initialState', stringify(client.initialState));
}
function Restore() {
const gamestateJSON = window.localStorage.getItem('gamestate');
const initialStateJSON = window.localStorage.getItem('initialState');
if (gamestateJSON !== null && initialStateJSON !== null) {
const gamestate = parse(gamestateJSON);
const initialState = parse(initialStateJSON);
client.store.dispatch(sync({ state: gamestate, initialState }));
}
}
$$self.$$set = $$props => {
if ('client' in $$props) $$invalidate(0, client = $$props.client);
if ('ToggleVisibility' in $$props) $$invalidate(1, ToggleVisibility = $$props.ToggleVisibility);
};
return [client, ToggleVisibility, Save, Restore];
}
class Controls extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$j, create_fragment$j, safe_not_equal, { client: 0, ToggleVisibility: 1 }, add_css$c);
}
}
/* src/client/debug/main/PlayerInfo.svelte generated by Svelte v3.41.0 */
function add_css$d(target) {
append_styles(target, "svelte-19aan9p", ".player-box.svelte-19aan9p{display:flex;flex-direction:row}.player.svelte-19aan9p{cursor:pointer;text-align:center;width:30px;height:30px;line-height:30px;background:#eee;border:3px solid #fefefe;box-sizing:content-box;padding:0}.player.current.svelte-19aan9p{background:#555;color:#eee;font-weight:bold}.player.active.svelte-19aan9p{border:3px solid #ff7f50}");
}
function get_each_context$4(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
return child_ctx;
}
// (59:2) {#each players as player}
function create_each_block$4(ctx) {
let button;
let t0_value = /*player*/ ctx[7] + "";
let t0;
let t1;
let button_aria_label_value;
let mounted;
let dispose;
function click_handler() {
return /*click_handler*/ ctx[5](/*player*/ ctx[7]);
}
return {
c() {
button = element("button");
t0 = text(t0_value);
t1 = space();
attr(button, "class", "player svelte-19aan9p");
attr(button, "aria-label", button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7]));
toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer);
toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, t0);
append(button, t1);
if (!mounted) {
dispose = listen(button, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*players*/ 4 && t0_value !== (t0_value = /*player*/ ctx[7] + "")) set_data(t0, t0_value);
if (dirty & /*players*/ 4 && button_aria_label_value !== (button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7]))) {
attr(button, "aria-label", button_aria_label_value);
}
if (dirty & /*players, ctx*/ 5) {
toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer);
}
if (dirty & /*players, playerID*/ 6) {
toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]);
}
},
d(detaching) {
if (detaching) detach(button);
mounted = false;
dispose();
}
};
}
function create_fragment$k(ctx) {
let div;
let each_value = /*players*/ ctx[2];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$4(get_each_context$4(ctx, each_value, i));
}
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "player-box svelte-19aan9p");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
},
p(ctx, [dirty]) {
if (dirty & /*playerLabel, players, ctx, playerID, OnClick*/ 31) {
each_value = /*players*/ ctx[2];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$4(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$4(child_ctx);
each_blocks[i].c();
each_blocks[i].m(div, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
}
};
}
function instance$k($$self, $$props, $$invalidate) {
let { ctx } = $$props;
let { playerID } = $$props;
const dispatch = createEventDispatcher();
function OnClick(player) {
if (player == playerID) {
dispatch("change", { playerID: null });
} else {
dispatch("change", { playerID: player });
}
}
function playerLabel(player) {
const properties = [];
if (player == ctx.currentPlayer) properties.push('current');
if (player == playerID) properties.push('active');
let label = `Player ${player}`;
if (properties.length) label += ` (${properties.join(', ')})`;
return label;
}
let players;
const click_handler = player => OnClick(player);
$$self.$$set = $$props => {
if ('ctx' in $$props) $$invalidate(0, ctx = $$props.ctx);
if ('playerID' in $$props) $$invalidate(1, playerID = $$props.playerID);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*ctx*/ 1) {
$$invalidate(2, players = ctx
? [...Array(ctx.numPlayers).keys()].map(i => i.toString())
: []);
}
};
return [ctx, playerID, players, OnClick, playerLabel, click_handler];
}
class PlayerInfo extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$k, create_fragment$k, safe_not_equal, { ctx: 0, playerID: 1 }, add_css$d);
}
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = it.call(o);
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function AssignShortcuts(moveNames, blacklist) {
var shortcuts = {};
var taken = {};
var _iterator = _createForOfIteratorHelper(blacklist),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var c = _step.value;
taken[c] = true;
} // Try assigning the first char of each move as the shortcut.
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var t = taken;
var canUseFirstChar = true;
for (var name in moveNames) {
var shortcut = name[0];
if (t[shortcut]) {
canUseFirstChar = false;
break;
}
t[shortcut] = true;
shortcuts[name] = shortcut;
}
if (canUseFirstChar) {
return shortcuts;
} // If those aren't unique, use a-z.
t = taken;
var next = 97;
shortcuts = {};
for (var _name in moveNames) {
var _shortcut = String.fromCharCode(next);
while (t[_shortcut]) {
next++;
_shortcut = String.fromCharCode(next);
}
t[_shortcut] = true;
shortcuts[_name] = _shortcut;
}
return shortcuts;
}
/* src/client/debug/main/Main.svelte generated by Svelte v3.41.0 */
function add_css$e(target) {
append_styles(target, "svelte-146sq5f", ".tree.svelte-146sq5f{--json-tree-font-family:monospace;--json-tree-font-size:14px;--json-tree-null-color:#757575}.label.svelte-146sq5f{margin-bottom:0;text-transform:none}h3.svelte-146sq5f{text-transform:uppercase}ul.svelte-146sq5f{padding-left:0}li.svelte-146sq5f{list-style:none;margin:0;margin-bottom:5px}");
}
function get_each_context$5(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[10] = list[i][0];
child_ctx[11] = list[i][1];
return child_ctx;
}
// (78:4) {#each Object.entries(moves) as [name, fn]}
function create_each_block$5(ctx) {
let li;
let move;
let t;
let current;
move = new Move({
props: {
shortcut: /*shortcuts*/ ctx[8][/*name*/ ctx[10]],
fn: /*fn*/ ctx[11],
name: /*name*/ ctx[10]
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
t = space();
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
append(li, t);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*moves*/ 16) move_changes.shortcut = /*shortcuts*/ ctx[8][/*name*/ ctx[10]];
if (dirty & /*moves*/ 16) move_changes.fn = /*fn*/ ctx[11];
if (dirty & /*moves*/ 16) move_changes.name = /*name*/ ctx[10];
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (90:2) {#if ctx.activePlayers && events.endStage}
function create_if_block_2$2(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endStage",
shortcut: 7,
fn: /*events*/ ctx[5].endStage
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 32) move_changes.fn = /*events*/ ctx[5].endStage;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (95:2) {#if events.endTurn}
function create_if_block_1$2(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endTurn",
shortcut: 8,
fn: /*events*/ ctx[5].endTurn
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 32) move_changes.fn = /*events*/ ctx[5].endTurn;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (100:2) {#if ctx.phase && events.endPhase}
function create_if_block$7(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endPhase",
shortcut: 9,
fn: /*events*/ ctx[5].endPhase
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 32) move_changes.fn = /*events*/ ctx[5].endPhase;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
function create_fragment$l(ctx) {
let section0;
let h30;
let t1;
let controls;
let t2;
let section1;
let h31;
let t4;
let playerinfo;
let t5;
let section2;
let h32;
let t7;
let ul0;
let t8;
let section3;
let h33;
let t10;
let ul1;
let t11;
let t12;
let t13;
let section4;
let h34;
let t15;
let jsontree0;
let t16;
let section5;
let h35;
let t18;
let jsontree1;
let t19;
let clientswitcher;
let current;
controls = new Controls({
props: {
client: /*client*/ ctx[0],
ToggleVisibility: /*ToggleVisibility*/ ctx[2]
}
});
playerinfo = new PlayerInfo({
props: {
ctx: /*ctx*/ ctx[6],
playerID: /*playerID*/ ctx[3]
}
});
playerinfo.$on("change", /*change_handler*/ ctx[9]);
let each_value = Object.entries(/*moves*/ ctx[4]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$5(get_each_context$5(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block0 = /*ctx*/ ctx[6].activePlayers && /*events*/ ctx[5].endStage && create_if_block_2$2(ctx);
let if_block1 = /*events*/ ctx[5].endTurn && create_if_block_1$2(ctx);
let if_block2 = /*ctx*/ ctx[6].phase && /*events*/ ctx[5].endPhase && create_if_block$7(ctx);
jsontree0 = new Root({ props: { value: /*G*/ ctx[7] } });
jsontree1 = new Root({
props: { value: SanitizeCtx(/*ctx*/ ctx[6]) }
});
clientswitcher = new ClientSwitcher({
props: { clientManager: /*clientManager*/ ctx[1] }
});
return {
c() {
section0 = element("section");
h30 = element("h3");
h30.textContent = "Controls";
t1 = space();
create_component(controls.$$.fragment);
t2 = space();
section1 = element("section");
h31 = element("h3");
h31.textContent = "Players";
t4 = space();
create_component(playerinfo.$$.fragment);
t5 = space();
section2 = element("section");
h32 = element("h3");
h32.textContent = "Moves";
t7 = space();
ul0 = element("ul");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t8 = space();
section3 = element("section");
h33 = element("h3");
h33.textContent = "Events";
t10 = space();
ul1 = element("ul");
if (if_block0) if_block0.c();
t11 = space();
if (if_block1) if_block1.c();
t12 = space();
if (if_block2) if_block2.c();
t13 = space();
section4 = element("section");
h34 = element("h3");
h34.textContent = "G";
t15 = space();
create_component(jsontree0.$$.fragment);
t16 = space();
section5 = element("section");
h35 = element("h3");
h35.textContent = "ctx";
t18 = space();
create_component(jsontree1.$$.fragment);
t19 = space();
create_component(clientswitcher.$$.fragment);
attr(h30, "class", "svelte-146sq5f");
attr(h31, "class", "svelte-146sq5f");
attr(h32, "class", "svelte-146sq5f");
attr(ul0, "class", "svelte-146sq5f");
attr(h33, "class", "svelte-146sq5f");
attr(ul1, "class", "svelte-146sq5f");
attr(h34, "class", "label svelte-146sq5f");
attr(section4, "class", "tree svelte-146sq5f");
attr(h35, "class", "label svelte-146sq5f");
attr(section5, "class", "tree svelte-146sq5f");
},
m(target, anchor) {
insert(target, section0, anchor);
append(section0, h30);
append(section0, t1);
mount_component(controls, section0, null);
insert(target, t2, anchor);
insert(target, section1, anchor);
append(section1, h31);
append(section1, t4);
mount_component(playerinfo, section1, null);
insert(target, t5, anchor);
insert(target, section2, anchor);
append(section2, h32);
append(section2, t7);
append(section2, ul0);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(ul0, null);
}
insert(target, t8, anchor);
insert(target, section3, anchor);
append(section3, h33);
append(section3, t10);
append(section3, ul1);
if (if_block0) if_block0.m(ul1, null);
append(ul1, t11);
if (if_block1) if_block1.m(ul1, null);
append(ul1, t12);
if (if_block2) if_block2.m(ul1, null);
insert(target, t13, anchor);
insert(target, section4, anchor);
append(section4, h34);
append(section4, t15);
mount_component(jsontree0, section4, null);
insert(target, t16, anchor);
insert(target, section5, anchor);
append(section5, h35);
append(section5, t18);
mount_component(jsontree1, section5, null);
insert(target, t19, anchor);
mount_component(clientswitcher, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const controls_changes = {};
if (dirty & /*client*/ 1) controls_changes.client = /*client*/ ctx[0];
if (dirty & /*ToggleVisibility*/ 4) controls_changes.ToggleVisibility = /*ToggleVisibility*/ ctx[2];
controls.$set(controls_changes);
const playerinfo_changes = {};
if (dirty & /*ctx*/ 64) playerinfo_changes.ctx = /*ctx*/ ctx[6];
if (dirty & /*playerID*/ 8) playerinfo_changes.playerID = /*playerID*/ ctx[3];
playerinfo.$set(playerinfo_changes);
if (dirty & /*shortcuts, Object, moves*/ 272) {
each_value = Object.entries(/*moves*/ ctx[4]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$5(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$5(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(ul0, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*ctx*/ ctx[6].activePlayers && /*events*/ ctx[5].endStage) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*ctx, events*/ 96) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_2$2(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(ul1, t11);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
if (/*events*/ ctx[5].endTurn) {
if (if_block1) {
if_block1.p(ctx, dirty);
if (dirty & /*events*/ 32) {
transition_in(if_block1, 1);
}
} else {
if_block1 = create_if_block_1$2(ctx);
if_block1.c();
transition_in(if_block1, 1);
if_block1.m(ul1, t12);
}
} else if (if_block1) {
group_outros();
transition_out(if_block1, 1, 1, () => {
if_block1 = null;
});
check_outros();
}
if (/*ctx*/ ctx[6].phase && /*events*/ ctx[5].endPhase) {
if (if_block2) {
if_block2.p(ctx, dirty);
if (dirty & /*ctx, events*/ 96) {
transition_in(if_block2, 1);
}
} else {
if_block2 = create_if_block$7(ctx);
if_block2.c();
transition_in(if_block2, 1);
if_block2.m(ul1, null);
}
} else if (if_block2) {
group_outros();
transition_out(if_block2, 1, 1, () => {
if_block2 = null;
});
check_outros();
}
const jsontree0_changes = {};
if (dirty & /*G*/ 128) jsontree0_changes.value = /*G*/ ctx[7];
jsontree0.$set(jsontree0_changes);
const jsontree1_changes = {};
if (dirty & /*ctx*/ 64) jsontree1_changes.value = SanitizeCtx(/*ctx*/ ctx[6]);
jsontree1.$set(jsontree1_changes);
const clientswitcher_changes = {};
if (dirty & /*clientManager*/ 2) clientswitcher_changes.clientManager = /*clientManager*/ ctx[1];
clientswitcher.$set(clientswitcher_changes);
},
i(local) {
if (current) return;
transition_in(controls.$$.fragment, local);
transition_in(playerinfo.$$.fragment, local);
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
transition_in(if_block0);
transition_in(if_block1);
transition_in(if_block2);
transition_in(jsontree0.$$.fragment, local);
transition_in(jsontree1.$$.fragment, local);
transition_in(clientswitcher.$$.fragment, local);
current = true;
},
o(local) {
transition_out(controls.$$.fragment, local);
transition_out(playerinfo.$$.fragment, local);
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
transition_out(if_block0);
transition_out(if_block1);
transition_out(if_block2);
transition_out(jsontree0.$$.fragment, local);
transition_out(jsontree1.$$.fragment, local);
transition_out(clientswitcher.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(section0);
destroy_component(controls);
if (detaching) detach(t2);
if (detaching) detach(section1);
destroy_component(playerinfo);
if (detaching) detach(t5);
if (detaching) detach(section2);
destroy_each(each_blocks, detaching);
if (detaching) detach(t8);
if (detaching) detach(section3);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
if (if_block2) if_block2.d();
if (detaching) detach(t13);
if (detaching) detach(section4);
destroy_component(jsontree0);
if (detaching) detach(t16);
if (detaching) detach(section5);
destroy_component(jsontree1);
if (detaching) detach(t19);
destroy_component(clientswitcher, detaching);
}
};
}
function SanitizeCtx(ctx) {
let r = {};
for (const key in ctx) {
if (!key.startsWith('_')) {
r[key] = ctx[key];
}
}
return r;
}
function instance$l($$self, $$props, $$invalidate) {
let { client } = $$props;
let { clientManager } = $$props;
let { ToggleVisibility } = $$props;
const shortcuts = AssignShortcuts(client.moves, 'mlia');
let { playerID, moves, events } = client;
let ctx = {};
let G = {};
client.subscribe(state => {
if (state) $$invalidate(7, { G, ctx } = state, G, $$invalidate(6, ctx));
$$invalidate(3, { playerID, moves, events } = client, playerID, $$invalidate(4, moves), $$invalidate(5, events));
});
const change_handler = e => clientManager.switchPlayerID(e.detail.playerID);
$$self.$$set = $$props => {
if ('client' in $$props) $$invalidate(0, client = $$props.client);
if ('clientManager' in $$props) $$invalidate(1, clientManager = $$props.clientManager);
if ('ToggleVisibility' in $$props) $$invalidate(2, ToggleVisibility = $$props.ToggleVisibility);
};
return [
client,
clientManager,
ToggleVisibility,
playerID,
moves,
events,
ctx,
G,
shortcuts,
change_handler
];
}
class Main extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$l,
create_fragment$l,
safe_not_equal,
{
client: 0,
clientManager: 1,
ToggleVisibility: 2
},
add_css$e
);
}
}
/* src/client/debug/info/Item.svelte generated by Svelte v3.41.0 */
function add_css$f(target) {
append_styles(target, "svelte-13qih23", ".item.svelte-13qih23.svelte-13qih23{padding:10px}.item.svelte-13qih23.svelte-13qih23:not(:first-child){border-top:1px dashed #aaa}.item.svelte-13qih23 div.svelte-13qih23{float:right;text-align:right}");
}
function create_fragment$m(ctx) {
let div1;
let strong;
let t0;
let t1;
let div0;
let t2_value = JSON.stringify(/*value*/ ctx[1]) + "";
let t2;
return {
c() {
div1 = element("div");
strong = element("strong");
t0 = text(/*name*/ ctx[0]);
t1 = space();
div0 = element("div");
t2 = text(t2_value);
attr(div0, "class", "svelte-13qih23");
attr(div1, "class", "item svelte-13qih23");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, strong);
append(strong, t0);
append(div1, t1);
append(div1, div0);
append(div0, t2);
},
p(ctx, [dirty]) {
if (dirty & /*name*/ 1) set_data(t0, /*name*/ ctx[0]);
if (dirty & /*value*/ 2 && t2_value !== (t2_value = JSON.stringify(/*value*/ ctx[1]) + "")) set_data(t2, t2_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div1);
}
};
}
function instance$m($$self, $$props, $$invalidate) {
let { name } = $$props;
let { value } = $$props;
$$self.$$set = $$props => {
if ('name' in $$props) $$invalidate(0, name = $$props.name);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
};
return [name, value];
}
class Item extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$m, create_fragment$m, safe_not_equal, { name: 0, value: 1 }, add_css$f);
}
}
/* src/client/debug/info/Info.svelte generated by Svelte v3.41.0 */
function add_css$g(target) {
append_styles(target, "svelte-1yzq5o8", ".gameinfo.svelte-1yzq5o8{padding:10px}");
}
// (19:2) {#if client.multiplayer}
function create_if_block$8(ctx) {
let item;
let current;
item = new Item({
props: {
name: "isConnected",
value: /*$client*/ ctx[1].isConnected
}
});
return {
c() {
create_component(item.$$.fragment);
},
m(target, anchor) {
mount_component(item, target, anchor);
current = true;
},
p(ctx, dirty) {
const item_changes = {};
if (dirty & /*$client*/ 2) item_changes.value = /*$client*/ ctx[1].isConnected;
item.$set(item_changes);
},
i(local) {
if (current) return;
transition_in(item.$$.fragment, local);
current = true;
},
o(local) {
transition_out(item.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(item, detaching);
}
};
}
function create_fragment$n(ctx) {
let section;
let item0;
let t0;
let item1;
let t1;
let item2;
let t2;
let current;
item0 = new Item({
props: {
name: "matchID",
value: /*client*/ ctx[0].matchID
}
});
item1 = new Item({
props: {
name: "playerID",
value: /*client*/ ctx[0].playerID
}
});
item2 = new Item({
props: {
name: "isActive",
value: /*$client*/ ctx[1].isActive
}
});
let if_block = /*client*/ ctx[0].multiplayer && create_if_block$8(ctx);
return {
c() {
section = element("section");
create_component(item0.$$.fragment);
t0 = space();
create_component(item1.$$.fragment);
t1 = space();
create_component(item2.$$.fragment);
t2 = space();
if (if_block) if_block.c();
attr(section, "class", "gameinfo svelte-1yzq5o8");
},
m(target, anchor) {
insert(target, section, anchor);
mount_component(item0, section, null);
append(section, t0);
mount_component(item1, section, null);
append(section, t1);
mount_component(item2, section, null);
append(section, t2);
if (if_block) if_block.m(section, null);
current = true;
},
p(ctx, [dirty]) {
const item0_changes = {};
if (dirty & /*client*/ 1) item0_changes.value = /*client*/ ctx[0].matchID;
item0.$set(item0_changes);
const item1_changes = {};
if (dirty & /*client*/ 1) item1_changes.value = /*client*/ ctx[0].playerID;
item1.$set(item1_changes);
const item2_changes = {};
if (dirty & /*$client*/ 2) item2_changes.value = /*$client*/ ctx[1].isActive;
item2.$set(item2_changes);
if (/*client*/ ctx[0].multiplayer) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*client*/ 1) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$8(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(section, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(item0.$$.fragment, local);
transition_in(item1.$$.fragment, local);
transition_in(item2.$$.fragment, local);
transition_in(if_block);
current = true;
},
o(local) {
transition_out(item0.$$.fragment, local);
transition_out(item1.$$.fragment, local);
transition_out(item2.$$.fragment, local);
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(item0);
destroy_component(item1);
destroy_component(item2);
if (if_block) if_block.d();
}
};
}
function instance$n($$self, $$props, $$invalidate) {
let $client,
$$unsubscribe_client = noop,
$$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(1, $client = $$value)), client);
$$self.$$.on_destroy.push(() => $$unsubscribe_client());
let { client } = $$props;
$$subscribe_client();
let { clientManager } = $$props;
let { ToggleVisibility } = $$props;
$$self.$$set = $$props => {
if ('client' in $$props) $$subscribe_client($$invalidate(0, client = $$props.client));
if ('clientManager' in $$props) $$invalidate(2, clientManager = $$props.clientManager);
if ('ToggleVisibility' in $$props) $$invalidate(3, ToggleVisibility = $$props.ToggleVisibility);
};
return [client, $client, clientManager, ToggleVisibility];
}
class Info extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$n,
create_fragment$n,
safe_not_equal,
{
client: 0,
clientManager: 2,
ToggleVisibility: 3
},
add_css$g
);
}
}
/* src/client/debug/log/TurnMarker.svelte generated by Svelte v3.41.0 */
function add_css$h(target) {
append_styles(target, "svelte-6eza86", ".turn-marker.svelte-6eza86{display:flex;justify-content:center;align-items:center;grid-column:1;background:#555;color:#eee;text-align:center;font-weight:bold;border:1px solid #888}");
}
function create_fragment$o(ctx) {
let div;
let t;
return {
c() {
div = element("div");
t = text(/*turn*/ ctx[0]);
attr(div, "class", "turn-marker svelte-6eza86");
attr(div, "style", /*style*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*turn*/ 1) set_data(t, /*turn*/ ctx[0]);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$o($$self, $$props, $$invalidate) {
let { turn } = $$props;
let { numEvents } = $$props;
const style = `grid-row: span ${numEvents}`;
$$self.$$set = $$props => {
if ('turn' in $$props) $$invalidate(0, turn = $$props.turn);
if ('numEvents' in $$props) $$invalidate(2, numEvents = $$props.numEvents);
};
return [turn, style, numEvents];
}
class TurnMarker extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$o, create_fragment$o, safe_not_equal, { turn: 0, numEvents: 2 }, add_css$h);
}
}
/* src/client/debug/log/PhaseMarker.svelte generated by Svelte v3.41.0 */
function add_css$i(target) {
append_styles(target, "svelte-1t4xap", ".phase-marker.svelte-1t4xap{grid-column:3;background:#555;border:1px solid #888;color:#eee;text-align:center;font-weight:bold;padding-top:10px;padding-bottom:10px;text-orientation:sideways;writing-mode:vertical-rl;line-height:30px;width:100%}");
}
function create_fragment$p(ctx) {
let div;
let t_value = (/*phase*/ ctx[0] || '') + "";
let t;
return {
c() {
div = element("div");
t = text(t_value);
attr(div, "class", "phase-marker svelte-1t4xap");
attr(div, "style", /*style*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*phase*/ 1 && t_value !== (t_value = (/*phase*/ ctx[0] || '') + "")) set_data(t, t_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$p($$self, $$props, $$invalidate) {
let { phase } = $$props;
let { numEvents } = $$props;
const style = `grid-row: span ${numEvents}`;
$$self.$$set = $$props => {
if ('phase' in $$props) $$invalidate(0, phase = $$props.phase);
if ('numEvents' in $$props) $$invalidate(2, numEvents = $$props.numEvents);
};
return [phase, style, numEvents];
}
class PhaseMarker extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$p, create_fragment$p, safe_not_equal, { phase: 0, numEvents: 2 }, add_css$i);
}
}
/* src/client/debug/log/LogMetadata.svelte generated by Svelte v3.41.0 */
function create_fragment$q(ctx) {
let div;
return {
c() {
div = element("div");
div.textContent = `${/*renderedMetadata*/ ctx[0]}`;
},
m(target, anchor) {
insert(target, div, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$q($$self, $$props, $$invalidate) {
let { metadata } = $$props;
const renderedMetadata = metadata !== undefined
? JSON.stringify(metadata, null, 4)
: '';
$$self.$$set = $$props => {
if ('metadata' in $$props) $$invalidate(1, metadata = $$props.metadata);
};
return [renderedMetadata, metadata];
}
class LogMetadata extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$q, create_fragment$q, safe_not_equal, { metadata: 1 });
}
}
/* src/client/debug/log/LogEvent.svelte generated by Svelte v3.41.0 */
function add_css$j(target) {
append_styles(target, "svelte-vajd9z", ".log-event.svelte-vajd9z{grid-column:2;cursor:pointer;overflow:hidden;display:flex;flex-direction:column;justify-content:center;background:#fff;border:1px dotted #ccc;border-left:5px solid #ccc;padding:5px;text-align:center;color:#666;font-size:14px;min-height:25px;line-height:25px}.log-event.svelte-vajd9z:hover,.log-event.svelte-vajd9z:focus{border-style:solid;background:#eee}.log-event.pinned.svelte-vajd9z{border-style:solid;background:#eee;opacity:1}.args.svelte-vajd9z{text-align:left;white-space:pre-wrap}.player0.svelte-vajd9z{border-left-color:#ff851b}.player1.svelte-vajd9z{border-left-color:#7fdbff}.player2.svelte-vajd9z{border-left-color:#0074d9}.player3.svelte-vajd9z{border-left-color:#39cccc}.player4.svelte-vajd9z{border-left-color:#3d9970}.player5.svelte-vajd9z{border-left-color:#2ecc40}.player6.svelte-vajd9z{border-left-color:#01ff70}.player7.svelte-vajd9z{border-left-color:#ffdc00}.player8.svelte-vajd9z{border-left-color:#001f3f}.player9.svelte-vajd9z{border-left-color:#ff4136}.player10.svelte-vajd9z{border-left-color:#85144b}.player11.svelte-vajd9z{border-left-color:#f012be}.player12.svelte-vajd9z{border-left-color:#b10dc9}.player13.svelte-vajd9z{border-left-color:#111111}.player14.svelte-vajd9z{border-left-color:#aaaaaa}.player15.svelte-vajd9z{border-left-color:#dddddd}");
}
// (146:2) {:else}
function create_else_block$1(ctx) {
let logmetadata;
let current;
logmetadata = new LogMetadata({ props: { metadata: /*metadata*/ ctx[2] } });
return {
c() {
create_component(logmetadata.$$.fragment);
},
m(target, anchor) {
mount_component(logmetadata, target, anchor);
current = true;
},
p(ctx, dirty) {
const logmetadata_changes = {};
if (dirty & /*metadata*/ 4) logmetadata_changes.metadata = /*metadata*/ ctx[2];
logmetadata.$set(logmetadata_changes);
},
i(local) {
if (current) return;
transition_in(logmetadata.$$.fragment, local);
current = true;
},
o(local) {
transition_out(logmetadata.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(logmetadata, detaching);
}
};
}
// (144:2) {#if metadataComponent}
function create_if_block$9(ctx) {
let switch_instance;
let switch_instance_anchor;
let current;
var switch_value = /*metadataComponent*/ ctx[3];
function switch_props(ctx) {
return { props: { metadata: /*metadata*/ ctx[2] } };
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
if (switch_instance) create_component(switch_instance.$$.fragment);
switch_instance_anchor = empty();
},
m(target, anchor) {
if (switch_instance) {
mount_component(switch_instance, target, anchor);
}
insert(target, switch_instance_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const switch_instance_changes = {};
if (dirty & /*metadata*/ 4) switch_instance_changes.metadata = /*metadata*/ ctx[2];
if (switch_value !== (switch_value = /*metadataComponent*/ ctx[3])) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(switch_instance_anchor);
if (switch_instance) destroy_component(switch_instance, detaching);
}
};
}
function create_fragment$r(ctx) {
let button;
let div;
let t0;
let t1;
let t2;
let t3;
let t4;
let current_block_type_index;
let if_block;
let button_class_value;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$9, create_else_block$1];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*metadataComponent*/ ctx[3]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
button = element("button");
div = element("div");
t0 = text(/*actionType*/ ctx[4]);
t1 = text("(");
t2 = text(/*renderedArgs*/ ctx[6]);
t3 = text(")");
t4 = space();
if_block.c();
attr(div, "class", "args svelte-vajd9z");
attr(button, "class", button_class_value = "log-event player" + /*playerID*/ ctx[7] + " svelte-vajd9z");
toggle_class(button, "pinned", /*pinned*/ ctx[1]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, div);
append(div, t0);
append(div, t1);
append(div, t2);
append(div, t3);
append(button, t4);
if_blocks[current_block_type_index].m(button, null);
current = true;
if (!mounted) {
dispose = [
listen(button, "click", /*click_handler*/ ctx[9]),
listen(button, "mouseenter", /*mouseenter_handler*/ ctx[10]),
listen(button, "focus", /*focus_handler*/ ctx[11]),
listen(button, "mouseleave", /*mouseleave_handler*/ ctx[12]),
listen(button, "blur", /*blur_handler*/ ctx[13])
];
mounted = true;
}
},
p(ctx, [dirty]) {
if (!current || dirty & /*actionType*/ 16) set_data(t0, /*actionType*/ ctx[4]);
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
} else {
if_block.p(ctx, dirty);
}
transition_in(if_block, 1);
if_block.m(button, null);
}
if (dirty & /*pinned*/ 2) {
toggle_class(button, "pinned", /*pinned*/ ctx[1]);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(button);
if_blocks[current_block_type_index].d();
mounted = false;
run_all(dispose);
}
};
}
function instance$r($$self, $$props, $$invalidate) {
let { logIndex } = $$props;
let { action } = $$props;
let { pinned } = $$props;
let { metadata } = $$props;
let { metadataComponent } = $$props;
const dispatch = createEventDispatcher();
const args = action.payload.args;
const renderedArgs = Array.isArray(args)
? args.map(arg => JSON.stringify(arg, null, 2)).join(',')
: JSON.stringify(args, null, 2) || '';
const playerID = action.payload.playerID;
let actionType;
switch (action.type) {
case 'UNDO':
actionType = 'undo';
break;
case 'REDO':
actionType = 'redo';
case 'GAME_EVENT':
case 'MAKE_MOVE':
default:
actionType = action.payload.type;
break;
}
const click_handler = () => dispatch('click', { logIndex });
const mouseenter_handler = () => dispatch('mouseenter', { logIndex });
const focus_handler = () => dispatch('mouseenter', { logIndex });
const mouseleave_handler = () => dispatch('mouseleave');
const blur_handler = () => dispatch('mouseleave');
$$self.$$set = $$props => {
if ('logIndex' in $$props) $$invalidate(0, logIndex = $$props.logIndex);
if ('action' in $$props) $$invalidate(8, action = $$props.action);
if ('pinned' in $$props) $$invalidate(1, pinned = $$props.pinned);
if ('metadata' in $$props) $$invalidate(2, metadata = $$props.metadata);
if ('metadataComponent' in $$props) $$invalidate(3, metadataComponent = $$props.metadataComponent);
};
return [
logIndex,
pinned,
metadata,
metadataComponent,
actionType,
dispatch,
renderedArgs,
playerID,
action,
click_handler,
mouseenter_handler,
focus_handler,
mouseleave_handler,
blur_handler
];
}
class LogEvent extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$r,
create_fragment$r,
safe_not_equal,
{
logIndex: 0,
action: 8,
pinned: 1,
metadata: 2,
metadataComponent: 3
},
add_css$j
);
}
}
/* node_modules/svelte-icons/fa/FaArrowAltCircleDown.svelte generated by Svelte v3.41.0 */
function create_default_slot$1(ctx) {
let path;
return {
c() {
path = svg_element("path");
attr(path, "d", "M504 256c0 137-111 248-248 248S8 393 8 256 119 8 256 8s248 111 248 248zM212 140v116h-70.9c-10.7 0-16.1 13-8.5 20.5l114.9 114.3c4.7 4.7 12.2 4.7 16.9 0l114.9-114.3c7.6-7.6 2.2-20.5-8.5-20.5H300V140c0-6.6-5.4-12-12-12h-64c-6.6 0-12 5.4-12 12z");
},
m(target, anchor) {
insert(target, path, anchor);
},
d(detaching) {
if (detaching) detach(path);
}
};
}
function create_fragment$s(ctx) {
let iconbase;
let current;
const iconbase_spread_levels = [{ viewBox: "0 0 512 512" }, /*$$props*/ ctx[0]];
let iconbase_props = {
$$slots: { default: [create_default_slot$1] },
$$scope: { ctx }
};
for (let i = 0; i < iconbase_spread_levels.length; i += 1) {
iconbase_props = assign(iconbase_props, iconbase_spread_levels[i]);
}
iconbase = new IconBase({ props: iconbase_props });
return {
c() {
create_component(iconbase.$$.fragment);
},
m(target, anchor) {
mount_component(iconbase, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const iconbase_changes = (dirty & /*$$props*/ 1)
? get_spread_update(iconbase_spread_levels, [iconbase_spread_levels[0], get_spread_object(/*$$props*/ ctx[0])])
: {};
if (dirty & /*$$scope*/ 2) {
iconbase_changes.$$scope = { dirty, ctx };
}
iconbase.$set(iconbase_changes);
},
i(local) {
if (current) return;
transition_in(iconbase.$$.fragment, local);
current = true;
},
o(local) {
transition_out(iconbase.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(iconbase, detaching);
}
};
}
function instance$s($$self, $$props, $$invalidate) {
$$self.$$set = $$new_props => {
$$invalidate(0, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
};
$$props = exclude_internal_props($$props);
return [$$props];
}
class FaArrowAltCircleDown extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$s, create_fragment$s, safe_not_equal, {});
}
}
/* src/client/debug/mcts/Action.svelte generated by Svelte v3.41.0 */
function add_css$k(target) {
append_styles(target, "svelte-1a7time", "div.svelte-1a7time{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;max-width:500px}");
}
function create_fragment$t(ctx) {
let div;
let t;
return {
c() {
div = element("div");
t = text(/*text*/ ctx[0]);
attr(div, "alt", /*text*/ ctx[0]);
attr(div, "class", "svelte-1a7time");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*text*/ 1) set_data(t, /*text*/ ctx[0]);
if (dirty & /*text*/ 1) {
attr(div, "alt", /*text*/ ctx[0]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$t($$self, $$props, $$invalidate) {
let { action } = $$props;
let text;
$$self.$$set = $$props => {
if ('action' in $$props) $$invalidate(1, action = $$props.action);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*action*/ 2) {
{
const { type, args } = action.payload;
const argsFormatted = (args || []).join(',');
$$invalidate(0, text = `${type}(${argsFormatted})`);
}
}
};
return [text, action];
}
class Action extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$t, create_fragment$t, safe_not_equal, { action: 1 }, add_css$k);
}
}
/* src/client/debug/mcts/Table.svelte generated by Svelte v3.41.0 */
function add_css$l(target) {
append_styles(target, "svelte-ztcwsu", "table.svelte-ztcwsu.svelte-ztcwsu{font-size:12px;border-collapse:collapse;border:1px solid #ddd;padding:0}tr.svelte-ztcwsu.svelte-ztcwsu{cursor:pointer}tr.svelte-ztcwsu:hover td.svelte-ztcwsu{background:#eee}tr.selected.svelte-ztcwsu td.svelte-ztcwsu{background:#eee}td.svelte-ztcwsu.svelte-ztcwsu{padding:10px;height:10px;line-height:10px;font-size:12px;border:none}th.svelte-ztcwsu.svelte-ztcwsu{background:#888;color:#fff;padding:10px;text-align:center}");
}
function get_each_context$6(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[10] = list[i];
child_ctx[12] = i;
return child_ctx;
}
// (86:2) {#each children as child, i}
function create_each_block$6(ctx) {
let tr;
let td0;
let t0_value = /*child*/ ctx[10].value + "";
let t0;
let t1;
let td1;
let t2_value = /*child*/ ctx[10].visits + "";
let t2;
let t3;
let td2;
let action;
let t4;
let current;
let mounted;
let dispose;
action = new Action({
props: { action: /*child*/ ctx[10].parentAction }
});
function click_handler() {
return /*click_handler*/ ctx[6](/*child*/ ctx[10], /*i*/ ctx[12]);
}
function mouseout_handler() {
return /*mouseout_handler*/ ctx[7](/*i*/ ctx[12]);
}
function mouseover_handler() {
return /*mouseover_handler*/ ctx[8](/*child*/ ctx[10], /*i*/ ctx[12]);
}
return {
c() {
tr = element("tr");
td0 = element("td");
t0 = text(t0_value);
t1 = space();
td1 = element("td");
t2 = text(t2_value);
t3 = space();
td2 = element("td");
create_component(action.$$.fragment);
t4 = space();
attr(td0, "class", "svelte-ztcwsu");
attr(td1, "class", "svelte-ztcwsu");
attr(td2, "class", "svelte-ztcwsu");
attr(tr, "class", "svelte-ztcwsu");
toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0);
toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]);
},
m(target, anchor) {
insert(target, tr, anchor);
append(tr, td0);
append(td0, t0);
append(tr, t1);
append(tr, td1);
append(td1, t2);
append(tr, t3);
append(tr, td2);
mount_component(action, td2, null);
append(tr, t4);
current = true;
if (!mounted) {
dispose = [
listen(tr, "click", click_handler),
listen(tr, "mouseout", mouseout_handler),
listen(tr, "mouseover", mouseover_handler)
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if ((!current || dirty & /*children*/ 2) && t0_value !== (t0_value = /*child*/ ctx[10].value + "")) set_data(t0, t0_value);
if ((!current || dirty & /*children*/ 2) && t2_value !== (t2_value = /*child*/ ctx[10].visits + "")) set_data(t2, t2_value);
const action_changes = {};
if (dirty & /*children*/ 2) action_changes.action = /*child*/ ctx[10].parentAction;
action.$set(action_changes);
if (dirty & /*children*/ 2) {
toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0);
}
if (dirty & /*selectedIndex*/ 1) {
toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]);
}
},
i(local) {
if (current) return;
transition_in(action.$$.fragment, local);
current = true;
},
o(local) {
transition_out(action.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(tr);
destroy_component(action);
mounted = false;
run_all(dispose);
}
};
}
function create_fragment$u(ctx) {
let table;
let thead;
let t5;
let tbody;
let current;
let each_value = /*children*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$6(get_each_context$6(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
table = element("table");
thead = element("thead");
thead.innerHTML = `<th class="svelte-ztcwsu">Value</th>
<th class="svelte-ztcwsu">Visits</th>
<th class="svelte-ztcwsu">Action</th>`;
t5 = space();
tbody = element("tbody");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(table, "class", "svelte-ztcwsu");
},
m(target, anchor) {
insert(target, table, anchor);
append(table, thead);
append(table, t5);
append(table, tbody);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(tbody, null);
}
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*children, selectedIndex, Select, Preview*/ 15) {
each_value = /*children*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$6(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$6(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(tbody, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(table);
destroy_each(each_blocks, detaching);
}
};
}
function instance$u($$self, $$props, $$invalidate) {
let { root } = $$props;
let { selectedIndex = null } = $$props;
const dispatch = createEventDispatcher();
let parents = [];
let children = [];
function Select(node, i) {
dispatch('select', { node, selectedIndex: i });
}
function Preview(node, i) {
if (selectedIndex === null) {
dispatch('preview', { node });
}
}
const click_handler = (child, i) => Select(child, i);
const mouseout_handler = i => Preview(null);
const mouseover_handler = (child, i) => Preview(child);
$$self.$$set = $$props => {
if ('root' in $$props) $$invalidate(4, root = $$props.root);
if ('selectedIndex' in $$props) $$invalidate(0, selectedIndex = $$props.selectedIndex);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*root, parents*/ 48) {
{
let t = root;
$$invalidate(5, parents = []);
while (t.parent) {
const parent = t.parent;
const { type, args } = t.parentAction.payload;
const argsFormatted = (args || []).join(',');
const arrowText = `${type}(${argsFormatted})`;
parents.push({ parent, arrowText });
t = parent;
}
parents.reverse();
$$invalidate(1, children = [...root.children].sort((a, b) => a.visits < b.visits ? 1 : -1).slice(0, 50));
}
}
};
return [
selectedIndex,
children,
Select,
Preview,
root,
parents,
click_handler,
mouseout_handler,
mouseover_handler
];
}
class Table extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$u, create_fragment$u, safe_not_equal, { root: 4, selectedIndex: 0 }, add_css$l);
}
}
/* src/client/debug/mcts/MCTS.svelte generated by Svelte v3.41.0 */
function add_css$m(target) {
append_styles(target, "svelte-1f0amz4", ".visualizer.svelte-1f0amz4{display:flex;flex-direction:column;align-items:center;padding:50px}.preview.svelte-1f0amz4{opacity:0.5}.icon.svelte-1f0amz4{color:#777;width:32px;height:32px;margin-bottom:20px}");
}
function get_each_context$7(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[9] = list[i].node;
child_ctx[10] = list[i].selectedIndex;
child_ctx[12] = i;
return child_ctx;
}
// (50:4) {#if i !== 0}
function create_if_block_2$3(ctx) {
let div;
let arrow;
let current;
arrow = new FaArrowAltCircleDown({});
return {
c() {
div = element("div");
create_component(arrow.$$.fragment);
attr(div, "class", "icon svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
mount_component(arrow, div, null);
current = true;
},
i(local) {
if (current) return;
transition_in(arrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(arrow.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_component(arrow);
}
};
}
// (61:6) {:else}
function create_else_block$2(ctx) {
let table;
let current;
function select_handler_1(...args) {
return /*select_handler_1*/ ctx[7](/*i*/ ctx[12], ...args);
}
table = new Table({
props: {
root: /*node*/ ctx[9],
selectedIndex: /*selectedIndex*/ ctx[10]
}
});
table.$on("select", select_handler_1);
return {
c() {
create_component(table.$$.fragment);
},
m(target, anchor) {
mount_component(table, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const table_changes = {};
if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9];
if (dirty & /*nodes*/ 1) table_changes.selectedIndex = /*selectedIndex*/ ctx[10];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(table, detaching);
}
};
}
// (57:6) {#if i === nodes.length - 1}
function create_if_block_1$3(ctx) {
let table;
let current;
function select_handler(...args) {
return /*select_handler*/ ctx[5](/*i*/ ctx[12], ...args);
}
function preview_handler(...args) {
return /*preview_handler*/ ctx[6](/*i*/ ctx[12], ...args);
}
table = new Table({ props: { root: /*node*/ ctx[9] } });
table.$on("select", select_handler);
table.$on("preview", preview_handler);
return {
c() {
create_component(table.$$.fragment);
},
m(target, anchor) {
mount_component(table, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const table_changes = {};
if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(table, detaching);
}
};
}
// (49:2) {#each nodes as { node, selectedIndex }
function create_each_block$7(ctx) {
let t;
let section;
let current_block_type_index;
let if_block1;
let current;
let if_block0 = /*i*/ ctx[12] !== 0 && create_if_block_2$3();
const if_block_creators = [create_if_block_1$3, create_else_block$2];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*i*/ ctx[12] === /*nodes*/ ctx[0].length - 1) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
if (if_block0) if_block0.c();
t = space();
section = element("section");
if_block1.c();
},
m(target, anchor) {
if (if_block0) if_block0.m(target, anchor);
insert(target, t, anchor);
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
},
p(ctx, dirty) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block1 = if_blocks[current_block_type_index];
if (!if_block1) {
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block1.c();
} else {
if_block1.p(ctx, dirty);
}
transition_in(if_block1, 1);
if_block1.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t);
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
}
};
}
// (69:2) {#if preview}
function create_if_block$a(ctx) {
let div;
let arrow;
let t;
let section;
let table;
let current;
arrow = new FaArrowAltCircleDown({});
table = new Table({ props: { root: /*preview*/ ctx[1] } });
return {
c() {
div = element("div");
create_component(arrow.$$.fragment);
t = space();
section = element("section");
create_component(table.$$.fragment);
attr(div, "class", "icon svelte-1f0amz4");
attr(section, "class", "preview svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
mount_component(arrow, div, null);
insert(target, t, anchor);
insert(target, section, anchor);
mount_component(table, section, null);
current = true;
},
p(ctx, dirty) {
const table_changes = {};
if (dirty & /*preview*/ 2) table_changes.root = /*preview*/ ctx[1];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(arrow.$$.fragment, local);
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(arrow.$$.fragment, local);
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_component(arrow);
if (detaching) detach(t);
if (detaching) detach(section);
destroy_component(table);
}
};
}
function create_fragment$v(ctx) {
let div;
let t;
let current;
let each_value = /*nodes*/ ctx[0];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$7(get_each_context$7(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block = /*preview*/ ctx[1] && create_if_block$a(ctx);
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t = space();
if (if_block) if_block.c();
attr(div, "class", "visualizer svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
append(div, t);
if (if_block) if_block.m(div, null);
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*nodes, SelectNode, PreviewNode*/ 13) {
each_value = /*nodes*/ ctx[0];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$7(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$7(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div, t);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*preview*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*preview*/ 2) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$a(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(div, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
transition_in(if_block);
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
if (if_block) if_block.d();
}
};
}
function instance$v($$self, $$props, $$invalidate) {
let { metadata } = $$props;
let nodes = [];
let preview = null;
function SelectNode({ node, selectedIndex }, i) {
$$invalidate(1, preview = null);
$$invalidate(0, nodes[i].selectedIndex = selectedIndex, nodes);
$$invalidate(0, nodes = [...nodes.slice(0, i + 1), { node }]);
}
function PreviewNode({ node }, i) {
$$invalidate(1, preview = node);
}
const select_handler = (i, e) => SelectNode(e.detail, i);
const preview_handler = (i, e) => PreviewNode(e.detail);
const select_handler_1 = (i, e) => SelectNode(e.detail, i);
$$self.$$set = $$props => {
if ('metadata' in $$props) $$invalidate(4, metadata = $$props.metadata);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*metadata*/ 16) {
{
$$invalidate(0, nodes = [{ node: metadata }]);
}
}
};
return [
nodes,
preview,
SelectNode,
PreviewNode,
metadata,
select_handler,
preview_handler,
select_handler_1
];
}
class MCTS extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$v, create_fragment$v, safe_not_equal, { metadata: 4 }, add_css$m);
}
}
/* src/client/debug/log/Log.svelte generated by Svelte v3.41.0 */
function add_css$n(target) {
append_styles(target, "svelte-1pq5e4b", ".gamelog.svelte-1pq5e4b{display:grid;grid-template-columns:30px 1fr 30px;grid-auto-rows:auto;grid-auto-flow:column}");
}
function get_each_context$8(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[16] = list[i].phase;
child_ctx[18] = i;
return child_ctx;
}
function get_each_context_1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[19] = list[i].action;
child_ctx[20] = list[i].metadata;
child_ctx[18] = i;
return child_ctx;
}
function get_each_context_2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[22] = list[i].turn;
child_ctx[18] = i;
return child_ctx;
}
// (136:4) {#if i in turnBoundaries}
function create_if_block_1$4(ctx) {
let turnmarker;
let current;
turnmarker = new TurnMarker({
props: {
turn: /*turn*/ ctx[22],
numEvents: /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]]
}
});
return {
c() {
create_component(turnmarker.$$.fragment);
},
m(target, anchor) {
mount_component(turnmarker, target, anchor);
current = true;
},
p(ctx, dirty) {
const turnmarker_changes = {};
if (dirty & /*renderedLogEntries*/ 2) turnmarker_changes.turn = /*turn*/ ctx[22];
if (dirty & /*turnBoundaries*/ 8) turnmarker_changes.numEvents = /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]];
turnmarker.$set(turnmarker_changes);
},
i(local) {
if (current) return;
transition_in(turnmarker.$$.fragment, local);
current = true;
},
o(local) {
transition_out(turnmarker.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(turnmarker, detaching);
}
};
}
// (135:2) {#each renderedLogEntries as { turn }
function create_each_block_2(ctx) {
let if_block_anchor;
let current;
let if_block = /*i*/ ctx[18] in /*turnBoundaries*/ ctx[3] && create_if_block_1$4(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
if (/*i*/ ctx[18] in /*turnBoundaries*/ ctx[3]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*turnBoundaries*/ 8) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$4(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (141:2) {#each renderedLogEntries as { action, metadata }
function create_each_block_1(ctx) {
let logevent;
let current;
logevent = new LogEvent({
props: {
pinned: /*i*/ ctx[18] === /*pinned*/ ctx[2],
logIndex: /*i*/ ctx[18],
action: /*action*/ ctx[19],
metadata: /*metadata*/ ctx[20]
}
});
logevent.$on("click", /*OnLogClick*/ ctx[5]);
logevent.$on("mouseenter", /*OnMouseEnter*/ ctx[6]);
logevent.$on("mouseleave", /*OnMouseLeave*/ ctx[7]);
return {
c() {
create_component(logevent.$$.fragment);
},
m(target, anchor) {
mount_component(logevent, target, anchor);
current = true;
},
p(ctx, dirty) {
const logevent_changes = {};
if (dirty & /*pinned*/ 4) logevent_changes.pinned = /*i*/ ctx[18] === /*pinned*/ ctx[2];
if (dirty & /*renderedLogEntries*/ 2) logevent_changes.action = /*action*/ ctx[19];
if (dirty & /*renderedLogEntries*/ 2) logevent_changes.metadata = /*metadata*/ ctx[20];
logevent.$set(logevent_changes);
},
i(local) {
if (current) return;
transition_in(logevent.$$.fragment, local);
current = true;
},
o(local) {
transition_out(logevent.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(logevent, detaching);
}
};
}
// (153:4) {#if i in phaseBoundaries}
function create_if_block$b(ctx) {
let phasemarker;
let current;
phasemarker = new PhaseMarker({
props: {
phase: /*phase*/ ctx[16],
numEvents: /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]]
}
});
return {
c() {
create_component(phasemarker.$$.fragment);
},
m(target, anchor) {
mount_component(phasemarker, target, anchor);
current = true;
},
p(ctx, dirty) {
const phasemarker_changes = {};
if (dirty & /*renderedLogEntries*/ 2) phasemarker_changes.phase = /*phase*/ ctx[16];
if (dirty & /*phaseBoundaries*/ 16) phasemarker_changes.numEvents = /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]];
phasemarker.$set(phasemarker_changes);
},
i(local) {
if (current) return;
transition_in(phasemarker.$$.fragment, local);
current = true;
},
o(local) {
transition_out(phasemarker.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(phasemarker, detaching);
}
};
}
// (152:2) {#each renderedLogEntries as { phase }
function create_each_block$8(ctx) {
let if_block_anchor;
let current;
let if_block = /*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4] && create_if_block$b(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
if (/*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*phaseBoundaries*/ 16) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$b(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function create_fragment$w(ctx) {
let div;
let t0;
let t1;
let current;
let mounted;
let dispose;
let each_value_2 = /*renderedLogEntries*/ ctx[1];
let each_blocks_2 = [];
for (let i = 0; i < each_value_2.length; i += 1) {
each_blocks_2[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i));
}
const out = i => transition_out(each_blocks_2[i], 1, 1, () => {
each_blocks_2[i] = null;
});
let each_value_1 = /*renderedLogEntries*/ ctx[1];
let each_blocks_1 = [];
for (let i = 0; i < each_value_1.length; i += 1) {
each_blocks_1[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i));
}
const out_1 = i => transition_out(each_blocks_1[i], 1, 1, () => {
each_blocks_1[i] = null;
});
let each_value = /*renderedLogEntries*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$8(get_each_context$8(ctx, each_value, i));
}
const out_2 = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks_2.length; i += 1) {
each_blocks_2[i].c();
}
t0 = space();
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].c();
}
t1 = space();
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "gamelog svelte-1pq5e4b");
toggle_class(div, "pinned", /*pinned*/ ctx[2]);
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks_2.length; i += 1) {
each_blocks_2[i].m(div, null);
}
append(div, t0);
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].m(div, null);
}
append(div, t1);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
current = true;
if (!mounted) {
dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[8]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*renderedLogEntries, turnBoundaries*/ 10) {
each_value_2 = /*renderedLogEntries*/ ctx[1];
let i;
for (i = 0; i < each_value_2.length; i += 1) {
const child_ctx = get_each_context_2(ctx, each_value_2, i);
if (each_blocks_2[i]) {
each_blocks_2[i].p(child_ctx, dirty);
transition_in(each_blocks_2[i], 1);
} else {
each_blocks_2[i] = create_each_block_2(child_ctx);
each_blocks_2[i].c();
transition_in(each_blocks_2[i], 1);
each_blocks_2[i].m(div, t0);
}
}
group_outros();
for (i = each_value_2.length; i < each_blocks_2.length; i += 1) {
out(i);
}
check_outros();
}
if (dirty & /*pinned, renderedLogEntries, OnLogClick, OnMouseEnter, OnMouseLeave*/ 230) {
each_value_1 = /*renderedLogEntries*/ ctx[1];
let i;
for (i = 0; i < each_value_1.length; i += 1) {
const child_ctx = get_each_context_1(ctx, each_value_1, i);
if (each_blocks_1[i]) {
each_blocks_1[i].p(child_ctx, dirty);
transition_in(each_blocks_1[i], 1);
} else {
each_blocks_1[i] = create_each_block_1(child_ctx);
each_blocks_1[i].c();
transition_in(each_blocks_1[i], 1);
each_blocks_1[i].m(div, t1);
}
}
group_outros();
for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
out_1(i);
}
check_outros();
}
if (dirty & /*renderedLogEntries, phaseBoundaries*/ 18) {
each_value = /*renderedLogEntries*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$8(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$8(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out_2(i);
}
check_outros();
}
if (dirty & /*pinned*/ 4) {
toggle_class(div, "pinned", /*pinned*/ ctx[2]);
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value_2.length; i += 1) {
transition_in(each_blocks_2[i]);
}
for (let i = 0; i < each_value_1.length; i += 1) {
transition_in(each_blocks_1[i]);
}
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks_2 = each_blocks_2.filter(Boolean);
for (let i = 0; i < each_blocks_2.length; i += 1) {
transition_out(each_blocks_2[i]);
}
each_blocks_1 = each_blocks_1.filter(Boolean);
for (let i = 0; i < each_blocks_1.length; i += 1) {
transition_out(each_blocks_1[i]);
}
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks_2, detaching);
destroy_each(each_blocks_1, detaching);
destroy_each(each_blocks, detaching);
mounted = false;
dispose();
}
};
}
function instance$w($$self, $$props, $$invalidate) {
let $client,
$$unsubscribe_client = noop,
$$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(10, $client = $$value)), client);
$$self.$$.on_destroy.push(() => $$unsubscribe_client());
let { client } = $$props;
$$subscribe_client();
const { secondaryPane } = getContext('secondaryPane');
const reducer = CreateGameReducer({ game: client.game });
const initialState = client.getInitialState();
let { log } = $client;
let pinned = null;
function rewind(logIndex) {
let state = initialState;
for (let i = 0; i < log.length; i++) {
const { action, automatic } = log[i];
if (!automatic) {
state = reducer(state, action);
if (logIndex == 0) {
break;
}
logIndex--;
}
}
return {
G: state.G,
ctx: state.ctx,
plugins: state.plugins
};
}
function OnLogClick(e) {
const { logIndex } = e.detail;
const state = rewind(logIndex);
const renderedLogEntries = log.filter(e => !e.automatic);
client.overrideGameState(state);
if (pinned == logIndex) {
$$invalidate(2, pinned = null);
secondaryPane.set(null);
} else {
$$invalidate(2, pinned = logIndex);
const { metadata } = renderedLogEntries[logIndex].action.payload;
if (metadata) {
secondaryPane.set({ component: MCTS, metadata });
}
}
}
function OnMouseEnter(e) {
const { logIndex } = e.detail;
if (pinned === null) {
const state = rewind(logIndex);
client.overrideGameState(state);
}
}
function OnMouseLeave() {
if (pinned === null) {
client.overrideGameState(null);
}
}
function Reset() {
$$invalidate(2, pinned = null);
client.overrideGameState(null);
secondaryPane.set(null);
}
onDestroy(Reset);
function OnKeyDown(e) {
// ESC.
if (e.keyCode == 27) {
Reset();
}
}
let renderedLogEntries;
let turnBoundaries = {};
let phaseBoundaries = {};
$$self.$$set = $$props => {
if ('client' in $$props) $$subscribe_client($$invalidate(0, client = $$props.client));
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$client, log, renderedLogEntries*/ 1538) {
{
$$invalidate(9, log = $client.log);
$$invalidate(1, renderedLogEntries = log.filter(e => !e.automatic));
let eventsInCurrentPhase = 0;
let eventsInCurrentTurn = 0;
$$invalidate(3, turnBoundaries = {});
$$invalidate(4, phaseBoundaries = {});
for (let i = 0; i < renderedLogEntries.length; i++) {
const { action, payload, turn, phase } = renderedLogEntries[i];
eventsInCurrentTurn++;
eventsInCurrentPhase++;
if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].turn != turn) {
$$invalidate(3, turnBoundaries[i] = eventsInCurrentTurn, turnBoundaries);
eventsInCurrentTurn = 0;
}
if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].phase != phase) {
$$invalidate(4, phaseBoundaries[i] = eventsInCurrentPhase, phaseBoundaries);
eventsInCurrentPhase = 0;
}
}
}
}
};
return [
client,
renderedLogEntries,
pinned,
turnBoundaries,
phaseBoundaries,
OnLogClick,
OnMouseEnter,
OnMouseLeave,
OnKeyDown,
log,
$client
];
}
class Log extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$w, create_fragment$w, safe_not_equal, { client: 0 }, add_css$n);
}
}
/* src/client/debug/ai/Options.svelte generated by Svelte v3.41.0 */
function add_css$o(target) {
append_styles(target, "svelte-1fu900w", "label.svelte-1fu900w{color:#666}.option.svelte-1fu900w{margin-bottom:20px}.value.svelte-1fu900w{font-weight:bold;color:#000}input[type='checkbox'].svelte-1fu900w{vertical-align:middle}");
}
function get_each_context$9(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[6] = list[i][0];
child_ctx[7] = list[i][1];
child_ctx[8] = list;
child_ctx[9] = i;
return child_ctx;
}
// (44:47)
function create_if_block_1$5(ctx) {
let input;
let input_id_value;
let mounted;
let dispose;
function input_change_handler() {
/*input_change_handler*/ ctx[5].call(input, /*key*/ ctx[6]);
}
return {
c() {
input = element("input");
attr(input, "id", input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6]));
attr(input, "type", "checkbox");
attr(input, "class", "svelte-1fu900w");
},
m(target, anchor) {
insert(target, input, anchor);
input.checked = /*values*/ ctx[1][/*key*/ ctx[6]];
if (!mounted) {
dispose = [
listen(input, "change", input_change_handler),
listen(input, "change", /*OnChange*/ ctx[2])
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*bot*/ 1 && input_id_value !== (input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6]))) {
attr(input, "id", input_id_value);
}
if (dirty & /*values, Object, bot*/ 3) {
input.checked = /*values*/ ctx[1][/*key*/ ctx[6]];
}
},
d(detaching) {
if (detaching) detach(input);
mounted = false;
run_all(dispose);
}
};
}
// (41:4) {#if value.range}
function create_if_block$c(ctx) {
let span;
let t0_value = /*values*/ ctx[1][/*key*/ ctx[6]] + "";
let t0;
let t1;
let input;
let input_id_value;
let input_min_value;
let input_max_value;
let mounted;
let dispose;
function input_change_input_handler() {
/*input_change_input_handler*/ ctx[4].call(input, /*key*/ ctx[6]);
}
return {
c() {
span = element("span");
t0 = text(t0_value);
t1 = space();
input = element("input");
attr(span, "class", "value svelte-1fu900w");
attr(input, "id", input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6]));
attr(input, "type", "range");
attr(input, "min", input_min_value = /*value*/ ctx[7].range.min);
attr(input, "max", input_max_value = /*value*/ ctx[7].range.max);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t0);
insert(target, t1, anchor);
insert(target, input, anchor);
set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[6]]);
if (!mounted) {
dispose = [
listen(input, "change", input_change_input_handler),
listen(input, "input", input_change_input_handler),
listen(input, "change", /*OnChange*/ ctx[2])
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*values, bot*/ 3 && t0_value !== (t0_value = /*values*/ ctx[1][/*key*/ ctx[6]] + "")) set_data(t0, t0_value);
if (dirty & /*bot*/ 1 && input_id_value !== (input_id_value = /*makeID*/ ctx[3](/*key*/ ctx[6]))) {
attr(input, "id", input_id_value);
}
if (dirty & /*bot*/ 1 && input_min_value !== (input_min_value = /*value*/ ctx[7].range.min)) {
attr(input, "min", input_min_value);
}
if (dirty & /*bot*/ 1 && input_max_value !== (input_max_value = /*value*/ ctx[7].range.max)) {
attr(input, "max", input_max_value);
}
if (dirty & /*values, Object, bot*/ 3) {
set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[6]]);
}
},
d(detaching) {
if (detaching) detach(span);
if (detaching) detach(t1);
if (detaching) detach(input);
mounted = false;
run_all(dispose);
}
};
}
// (37:0) {#each Object.entries(bot.opts()) as [key, value]}
function create_each_block$9(ctx) {
let div;
let label;
let t0_value = /*key*/ ctx[6] + "";
let t0;
let label_for_value;
let t1;
let t2;
function select_block_type(ctx, dirty) {
if (/*value*/ ctx[7].range) return create_if_block$c;
if (typeof /*value*/ ctx[7].value === 'boolean') return create_if_block_1$5;
}
let current_block_type = select_block_type(ctx);
let if_block = current_block_type && current_block_type(ctx);
return {
c() {
div = element("div");
label = element("label");
t0 = text(t0_value);
t1 = space();
if (if_block) if_block.c();
t2 = space();
attr(label, "for", label_for_value = /*makeID*/ ctx[3](/*key*/ ctx[6]));
attr(label, "class", "svelte-1fu900w");
attr(div, "class", "option svelte-1fu900w");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, label);
append(label, t0);
append(div, t1);
if (if_block) if_block.m(div, null);
append(div, t2);
},
p(ctx, dirty) {
if (dirty & /*bot*/ 1 && t0_value !== (t0_value = /*key*/ ctx[6] + "")) set_data(t0, t0_value);
if (dirty & /*bot*/ 1 && label_for_value !== (label_for_value = /*makeID*/ ctx[3](/*key*/ ctx[6]))) {
attr(label, "for", label_for_value);
}
if (current_block_type === (current_block_type = select_block_type(ctx)) && if_block) {
if_block.p(ctx, dirty);
} else {
if (if_block) if_block.d(1);
if_block = current_block_type && current_block_type(ctx);
if (if_block) {
if_block.c();
if_block.m(div, t2);
}
}
},
d(detaching) {
if (detaching) detach(div);
if (if_block) {
if_block.d();
}
}
};
}
function create_fragment$x(ctx) {
let each_1_anchor;
let each_value = Object.entries(/*bot*/ ctx[0].opts());
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$9(get_each_context$9(ctx, each_value, i));
}
return {
c() {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
each_1_anchor = empty();
},
m(target, anchor) {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(target, anchor);
}
insert(target, each_1_anchor, anchor);
},
p(ctx, [dirty]) {
if (dirty & /*makeID, Object, bot, values, OnChange*/ 15) {
each_value = Object.entries(/*bot*/ ctx[0].opts());
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$9(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$9(child_ctx);
each_blocks[i].c();
each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
destroy_each(each_blocks, detaching);
if (detaching) detach(each_1_anchor);
}
};
}
function instance$x($$self, $$props, $$invalidate) {
let { bot } = $$props;
let values = {};
for (let [key, value] of Object.entries(bot.opts())) {
values[key] = value.value;
}
function OnChange() {
for (let [key, value] of Object.entries(values)) {
bot.setOpt(key, value);
}
}
const makeID = key => 'ai-option-' + key;
function input_change_input_handler(key) {
values[key] = to_number(this.value);
$$invalidate(1, values);
$$invalidate(0, bot);
}
function input_change_handler(key) {
values[key] = this.checked;
$$invalidate(1, values);
$$invalidate(0, bot);
}
$$self.$$set = $$props => {
if ('bot' in $$props) $$invalidate(0, bot = $$props.bot);
};
return [
bot,
values,
OnChange,
makeID,
input_change_input_handler,
input_change_handler
];
}
class Options extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$x, create_fragment$x, safe_not_equal, { bot: 0 }, add_css$o);
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Base class that bots can extend.
*/
class Bot {
constructor({ enumerate, seed, }) {
this.enumerateFn = enumerate;
this.seed = seed;
this.iterationCounter = 0;
this._opts = {};
}
addOpt({ key, range, initial, }) {
this._opts[key] = {
range,
value: initial,
};
}
getOpt(key) {
return this._opts[key].value;
}
setOpt(key, value) {
if (key in this._opts) {
this._opts[key].value = value;
}
}
opts() {
return this._opts;
}
enumerate(G, ctx, playerID) {
const actions = this.enumerateFn(G, ctx, playerID);
return actions.map((a) => {
if ('payload' in a) {
return a;
}
if ('move' in a) {
return makeMove(a.move, a.args, playerID);
}
if ('event' in a) {
return gameEvent(a.event, a.args, playerID);
}
});
}
random(arg) {
let number;
if (this.seed !== undefined) {
const seed = this.prngstate ? '' : this.seed;
const rand = alea(seed, this.prngstate);
number = rand();
this.prngstate = rand.state();
}
else {
number = Math.random();
}
if (arg) {
if (Array.isArray(arg)) {
const id = Math.floor(number * arg.length);
return arg[id];
}
else {
return Math.floor(number * arg);
}
}
return number;
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* The number of iterations to run before yielding to
* the JS event loop (in async mode).
*/
const CHUNK_SIZE = 25;
/**
* Bot that uses Monte-Carlo Tree Search to find promising moves.
*/
class MCTSBot extends Bot {
constructor({ enumerate, seed, objectives, game, iterations, playoutDepth, iterationCallback, }) {
super({ enumerate, seed });
if (objectives === undefined) {
objectives = () => ({});
}
this.objectives = objectives;
this.iterationCallback = iterationCallback || (() => { });
this.reducer = CreateGameReducer({ game });
this.iterations = iterations;
this.playoutDepth = playoutDepth;
this.addOpt({
key: 'async',
initial: false,
});
this.addOpt({
key: 'iterations',
initial: typeof iterations === 'number' ? iterations : 1000,
range: { min: 1, max: 2000 },
});
this.addOpt({
key: 'playoutDepth',
initial: typeof playoutDepth === 'number' ? playoutDepth : 50,
range: { min: 1, max: 100 },
});
}
createNode({ state, parentAction, parent, playerID, }) {
const { G, ctx } = state;
let actions = [];
let objectives = [];
if (playerID !== undefined) {
actions = this.enumerate(G, ctx, playerID);
objectives = this.objectives(G, ctx, playerID);
}
else if (ctx.activePlayers) {
for (const playerID in ctx.activePlayers) {
actions.push(...this.enumerate(G, ctx, playerID));
objectives.push(this.objectives(G, ctx, playerID));
}
}
else {
actions = this.enumerate(G, ctx, ctx.currentPlayer);
objectives = this.objectives(G, ctx, ctx.currentPlayer);
}
return {
state,
parent,
parentAction,
actions,
objectives,
children: [],
visits: 0,
value: 0,
};
}
select(node) {
// This node has unvisited children.
if (node.actions.length > 0) {
return node;
}
// This is a terminal node.
if (node.children.length === 0) {
return node;
}
let selectedChild = null;
let best = 0;
for (const child of node.children) {
const childVisits = child.visits + Number.EPSILON;
const uct = child.value / childVisits +
Math.sqrt((2 * Math.log(node.visits)) / childVisits);
if (selectedChild == null || uct > best) {
best = uct;
selectedChild = child;
}
}
return this.select(selectedChild);
}
expand(node) {
const actions = node.actions;
if (actions.length === 0 || node.state.ctx.gameover !== undefined) {
return node;
}
const id = this.random(actions.length);
const action = actions[id];
node.actions.splice(id, 1);
const childState = this.reducer(node.state, action);
const childNode = this.createNode({
state: childState,
parentAction: action,
parent: node,
});
node.children.push(childNode);
return childNode;
}
playout({ state }) {
let playoutDepth = this.getOpt('playoutDepth');
if (typeof this.playoutDepth === 'function') {
playoutDepth = this.playoutDepth(state.G, state.ctx);
}
for (let i = 0; i < playoutDepth && state.ctx.gameover === undefined; i++) {
const { G, ctx } = state;
let playerID = ctx.currentPlayer;
if (ctx.activePlayers) {
playerID = Object.keys(ctx.activePlayers)[0];
}
const moves = this.enumerate(G, ctx, playerID);
// Check if any objectives are met.
const objectives = this.objectives(G, ctx, playerID);
const score = Object.keys(objectives).reduce((score, key) => {
const objective = objectives[key];
if (objective.checker(G, ctx)) {
return score + objective.weight;
}
return score;
}, 0);
// If so, stop and return the score.
if (score > 0) {
return { score };
}
if (!moves || moves.length === 0) {
return undefined;
}
const id = this.random(moves.length);
const childState = this.reducer(state, moves[id]);
state = childState;
}
return state.ctx.gameover;
}
backpropagate(node, result = {}) {
node.visits++;
if (result.score !== undefined) {
node.value += result.score;
}
if (result.draw === true) {
node.value += 0.5;
}
if (node.parentAction &&
result.winner === node.parentAction.payload.playerID) {
node.value++;
}
if (node.parent) {
this.backpropagate(node.parent, result);
}
}
play(state, playerID) {
const root = this.createNode({ state, playerID });
let numIterations = this.getOpt('iterations');
if (typeof this.iterations === 'function') {
numIterations = this.iterations(state.G, state.ctx);
}
const getResult = () => {
let selectedChild = null;
for (const child of root.children) {
if (selectedChild == null || child.visits > selectedChild.visits) {
selectedChild = child;
}
}
const action = selectedChild && selectedChild.parentAction;
const metadata = root;
return { action, metadata };
};
return new Promise((resolve) => {
const iteration = () => {
for (let i = 0; i < CHUNK_SIZE && this.iterationCounter < numIterations; i++) {
const leaf = this.select(root);
const child = this.expand(leaf);
const result = this.playout(child);
this.backpropagate(child, result);
this.iterationCounter++;
}
this.iterationCallback({
iterationCounter: this.iterationCounter,
numIterations,
metadata: root,
});
};
this.iterationCounter = 0;
if (this.getOpt('async')) {
const asyncIteration = () => {
if (this.iterationCounter < numIterations) {
iteration();
setImmediate(asyncIteration);
}
else {
resolve(getResult());
}
};
asyncIteration();
}
else {
while (this.iterationCounter < numIterations) {
iteration();
}
resolve(getResult());
}
});
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Bot that picks a move at random.
*/
class RandomBot extends Bot {
play({ G, ctx }, playerID) {
const moves = this.enumerate(G, ctx, playerID);
return Promise.resolve({ action: this.random(moves) });
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Make a single move on the client with a bot.
*
* @param {...object} client - The game client.
* @param {...object} bot - The bot.
*/
async function Step(client, bot) {
const state = client.store.getState();
let playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
const { action, metadata } = await bot.play(state, playerID);
if (action) {
const a = {
...action,
payload: {
...action.payload,
metadata,
},
};
client.store.dispatch(a);
return a;
}
}
/**
* Simulates the game till the end or a max depth.
*
* @param {...object} game - The game object.
* @param {...object} bots - An array of bots.
* @param {...object} state - The game state to start from.
*/
async function Simulate({ game, bots, state, depth, }) {
if (depth === undefined)
depth = 10000;
const reducer = CreateGameReducer({ game });
let metadata = null;
let iter = 0;
while (state.ctx.gameover === undefined && iter < depth) {
let playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
const bot = bots instanceof Bot ? bots : bots[playerID];
const t = await bot.play(state, playerID);
if (!t.action) {
break;
}
metadata = t.metadata;
state = reducer(state, t.action);
iter++;
}
return { state, metadata };
}
/* src/client/debug/ai/AI.svelte generated by Svelte v3.41.0 */
function add_css$p(target) {
append_styles(target, "svelte-lifdi8", "ul.svelte-lifdi8{padding-left:0}li.svelte-lifdi8{list-style:none;margin:none;margin-bottom:5px}h3.svelte-lifdi8{text-transform:uppercase}label.svelte-lifdi8{color:#666}input[type='checkbox'].svelte-lifdi8{vertical-align:middle}");
}
function get_each_context$a(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
return child_ctx;
}
// (202:4) {:else}
function create_else_block$3(ctx) {
let p0;
let t1;
let p1;
return {
c() {
p0 = element("p");
p0.textContent = "No bots available.";
t1 = space();
p1 = element("p");
p1.innerHTML = `Follow the instructions
<a href="https://boardgame.io/documentation/#/tutorial?id=bots" target="_blank">here</a>
to set up bots.`;
},
m(target, anchor) {
insert(target, p0, anchor);
insert(target, t1, anchor);
insert(target, p1, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(p0);
if (detaching) detach(t1);
if (detaching) detach(p1);
}
};
}
// (200:4) {#if client.multiplayer}
function create_if_block_5(ctx) {
let p;
return {
c() {
p = element("p");
p.textContent = "The bot debugger is only available in singleplayer mode.";
},
m(target, anchor) {
insert(target, p, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(p);
}
};
}
// (150:2) {#if client.game.ai && !client.multiplayer}
function create_if_block$d(ctx) {
let section0;
let h30;
let t1;
let ul;
let li0;
let hotkey0;
let t2;
let li1;
let hotkey1;
let t3;
let li2;
let hotkey2;
let t4;
let section1;
let h31;
let t6;
let select;
let t7;
let show_if = Object.keys(/*bot*/ ctx[7].opts()).length;
let t8;
let if_block1_anchor;
let current;
let mounted;
let dispose;
hotkey0 = new Hotkey({
props: {
value: "1",
onPress: /*Reset*/ ctx[13],
label: "reset"
}
});
hotkey1 = new Hotkey({
props: {
value: "2",
onPress: /*Step*/ ctx[11],
label: "play"
}
});
hotkey2 = new Hotkey({
props: {
value: "3",
onPress: /*Simulate*/ ctx[12],
label: "simulate"
}
});
let each_value = Object.keys(/*bots*/ ctx[8]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$a(get_each_context$a(ctx, each_value, i));
}
let if_block0 = show_if && create_if_block_4(ctx);
let if_block1 = (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) && create_if_block_1$6(ctx);
return {
c() {
section0 = element("section");
h30 = element("h3");
h30.textContent = "Controls";
t1 = space();
ul = element("ul");
li0 = element("li");
create_component(hotkey0.$$.fragment);
t2 = space();
li1 = element("li");
create_component(hotkey1.$$.fragment);
t3 = space();
li2 = element("li");
create_component(hotkey2.$$.fragment);
t4 = space();
section1 = element("section");
h31 = element("h3");
h31.textContent = "Bot";
t6 = space();
select = element("select");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t7 = space();
if (if_block0) if_block0.c();
t8 = space();
if (if_block1) if_block1.c();
if_block1_anchor = empty();
attr(h30, "class", "svelte-lifdi8");
attr(li0, "class", "svelte-lifdi8");
attr(li1, "class", "svelte-lifdi8");
attr(li2, "class", "svelte-lifdi8");
attr(ul, "class", "svelte-lifdi8");
attr(h31, "class", "svelte-lifdi8");
if (/*selectedBot*/ ctx[4] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[17].call(select));
},
m(target, anchor) {
insert(target, section0, anchor);
append(section0, h30);
append(section0, t1);
append(section0, ul);
append(ul, li0);
mount_component(hotkey0, li0, null);
append(ul, t2);
append(ul, li1);
mount_component(hotkey1, li1, null);
append(ul, t3);
append(ul, li2);
mount_component(hotkey2, li2, null);
insert(target, t4, anchor);
insert(target, section1, anchor);
append(section1, h31);
append(section1, t6);
append(section1, select);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(select, null);
}
select_option(select, /*selectedBot*/ ctx[4]);
insert(target, t7, anchor);
if (if_block0) if_block0.m(target, anchor);
insert(target, t8, anchor);
if (if_block1) if_block1.m(target, anchor);
insert(target, if_block1_anchor, anchor);
current = true;
if (!mounted) {
dispose = [
listen(select, "change", /*select_change_handler*/ ctx[17]),
listen(select, "change", /*ChangeBot*/ ctx[10])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*Object, bots*/ 256) {
each_value = Object.keys(/*bots*/ ctx[8]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$a(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$a(child_ctx);
each_blocks[i].c();
each_blocks[i].m(select, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (dirty & /*selectedBot, Object, bots*/ 272) {
select_option(select, /*selectedBot*/ ctx[4]);
}
if (dirty & /*bot*/ 128) show_if = Object.keys(/*bot*/ ctx[7].opts()).length;
if (show_if) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*bot*/ 128) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_4(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(t8.parentNode, t8);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
if (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_1$6(ctx);
if_block1.c();
if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
i(local) {
if (current) return;
transition_in(hotkey0.$$.fragment, local);
transition_in(hotkey1.$$.fragment, local);
transition_in(hotkey2.$$.fragment, local);
transition_in(if_block0);
current = true;
},
o(local) {
transition_out(hotkey0.$$.fragment, local);
transition_out(hotkey1.$$.fragment, local);
transition_out(hotkey2.$$.fragment, local);
transition_out(if_block0);
current = false;
},
d(detaching) {
if (detaching) detach(section0);
destroy_component(hotkey0);
destroy_component(hotkey1);
destroy_component(hotkey2);
if (detaching) detach(t4);
if (detaching) detach(section1);
destroy_each(each_blocks, detaching);
if (detaching) detach(t7);
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t8);
if (if_block1) if_block1.d(detaching);
if (detaching) detach(if_block1_anchor);
mounted = false;
run_all(dispose);
}
};
}
// (169:8) {#each Object.keys(bots) as bot}
function create_each_block$a(ctx) {
let option;
let t_value = /*bot*/ ctx[7] + "";
let t;
let option_value_value;
return {
c() {
option = element("option");
t = text(t_value);
option.__value = option_value_value = /*bot*/ ctx[7];
option.value = option.__value;
},
m(target, anchor) {
insert(target, option, anchor);
append(option, t);
},
p: noop,
d(detaching) {
if (detaching) detach(option);
}
};
}
// (175:4) {#if Object.keys(bot.opts()).length}
function create_if_block_4(ctx) {
let section;
let h3;
let t1;
let label;
let t3;
let input;
let t4;
let options;
let current;
let mounted;
let dispose;
options = new Options({ props: { bot: /*bot*/ ctx[7] } });
return {
c() {
section = element("section");
h3 = element("h3");
h3.textContent = "Options";
t1 = space();
label = element("label");
label.textContent = "debug";
t3 = space();
input = element("input");
t4 = space();
create_component(options.$$.fragment);
attr(h3, "class", "svelte-lifdi8");
attr(label, "for", "ai-option-debug");
attr(label, "class", "svelte-lifdi8");
attr(input, "id", "ai-option-debug");
attr(input, "type", "checkbox");
attr(input, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, h3);
append(section, t1);
append(section, label);
append(section, t3);
append(section, input);
input.checked = /*debug*/ ctx[1];
append(section, t4);
mount_component(options, section, null);
current = true;
if (!mounted) {
dispose = [
listen(input, "change", /*input_change_handler*/ ctx[18]),
listen(input, "change", /*OnDebug*/ ctx[9])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*debug*/ 2) {
input.checked = /*debug*/ ctx[1];
}
const options_changes = {};
if (dirty & /*bot*/ 128) options_changes.bot = /*bot*/ ctx[7];
options.$set(options_changes);
},
i(local) {
if (current) return;
transition_in(options.$$.fragment, local);
current = true;
},
o(local) {
transition_out(options.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(options);
mounted = false;
run_all(dispose);
}
};
}
// (184:4) {#if botAction || iterationCounter}
function create_if_block_1$6(ctx) {
let section;
let h3;
let t1;
let t2;
let if_block0 = /*progress*/ ctx[2] && /*progress*/ ctx[2] < 1.0 && create_if_block_3$1(ctx);
let if_block1 = /*botAction*/ ctx[5] && create_if_block_2$4(ctx);
return {
c() {
section = element("section");
h3 = element("h3");
h3.textContent = "Result";
t1 = space();
if (if_block0) if_block0.c();
t2 = space();
if (if_block1) if_block1.c();
attr(h3, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, h3);
append(section, t1);
if (if_block0) if_block0.m(section, null);
append(section, t2);
if (if_block1) if_block1.m(section, null);
},
p(ctx, dirty) {
if (/*progress*/ ctx[2] && /*progress*/ ctx[2] < 1.0) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_3$1(ctx);
if_block0.c();
if_block0.m(section, t2);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (/*botAction*/ ctx[5]) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_2$4(ctx);
if_block1.c();
if_block1.m(section, null);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
d(detaching) {
if (detaching) detach(section);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
}
};
}
// (187:6) {#if progress && progress < 1.0}
function create_if_block_3$1(ctx) {
let progress_1;
return {
c() {
progress_1 = element("progress");
progress_1.value = /*progress*/ ctx[2];
},
m(target, anchor) {
insert(target, progress_1, anchor);
},
p(ctx, dirty) {
if (dirty & /*progress*/ 4) {
progress_1.value = /*progress*/ ctx[2];
}
},
d(detaching) {
if (detaching) detach(progress_1);
}
};
}
// (191:6) {#if botAction}
function create_if_block_2$4(ctx) {
let ul;
let li0;
let t0;
let t1;
let t2;
let li1;
let t3;
let t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + "";
let t4;
return {
c() {
ul = element("ul");
li0 = element("li");
t0 = text("Action: ");
t1 = text(/*botAction*/ ctx[5]);
t2 = space();
li1 = element("li");
t3 = text("Args: ");
t4 = text(t4_value);
attr(li0, "class", "svelte-lifdi8");
attr(li1, "class", "svelte-lifdi8");
attr(ul, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, ul, anchor);
append(ul, li0);
append(li0, t0);
append(li0, t1);
append(ul, t2);
append(ul, li1);
append(li1, t3);
append(li1, t4);
},
p(ctx, dirty) {
if (dirty & /*botAction*/ 32) set_data(t1, /*botAction*/ ctx[5]);
if (dirty & /*botActionArgs*/ 64 && t4_value !== (t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + "")) set_data(t4, t4_value);
},
d(detaching) {
if (detaching) detach(ul);
}
};
}
function create_fragment$y(ctx) {
let section;
let current_block_type_index;
let if_block;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$d, create_if_block_5, create_else_block$3];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*client*/ ctx[0].game.ai && !/*client*/ ctx[0].multiplayer) return 0;
if (/*client*/ ctx[0].multiplayer) return 1;
return 2;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
section = element("section");
if_block.c();
},
m(target, anchor) {
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
if (!mounted) {
dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[14]);
mounted = true;
}
},
p(ctx, [dirty]) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
} else {
if_block.p(ctx, dirty);
}
transition_in(if_block, 1);
if_block.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$y($$self, $$props, $$invalidate) {
let { client } = $$props;
let { clientManager } = $$props;
let { ToggleVisibility } = $$props;
const { secondaryPane } = getContext('secondaryPane');
const bots = { 'MCTS': MCTSBot, 'Random': RandomBot };
let debug = false;
let progress = null;
let iterationCounter = 0;
let metadata = null;
const iterationCallback = ({ iterationCounter: c, numIterations, metadata: m }) => {
$$invalidate(3, iterationCounter = c);
$$invalidate(2, progress = c / numIterations);
metadata = m;
if (debug && metadata) {
secondaryPane.set({ component: MCTS, metadata });
}
};
function OnDebug() {
if (debug && metadata) {
secondaryPane.set({ component: MCTS, metadata });
} else {
secondaryPane.set(null);
}
}
let bot;
if (client.game.ai) {
bot = new MCTSBot({
game: client.game,
enumerate: client.game.ai.enumerate,
iterationCallback
});
bot.setOpt('async', true);
}
let selectedBot;
let botAction;
let botActionArgs;
function ChangeBot() {
const botConstructor = bots[selectedBot];
$$invalidate(7, bot = new botConstructor({
game: client.game,
enumerate: client.game.ai.enumerate,
iterationCallback
}));
bot.setOpt('async', true);
$$invalidate(5, botAction = null);
metadata = null;
secondaryPane.set(null);
$$invalidate(3, iterationCounter = 0);
}
async function Step$1() {
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
const t = await Step(client, bot);
if (t) {
$$invalidate(5, botAction = t.payload.type);
$$invalidate(6, botActionArgs = t.payload.args);
}
}
function Simulate(iterations = 10000, sleepTimeout = 100) {
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
const step = async () => {
for (let i = 0; i < iterations; i++) {
const action = await Step(client, bot);
if (!action) break;
await new Promise(resolve => setTimeout(resolve, sleepTimeout));
}
};
return step();
}
function Exit() {
client.overrideGameState(null);
secondaryPane.set(null);
$$invalidate(1, debug = false);
}
function Reset() {
client.reset();
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
Exit();
}
function OnKeyDown(e) {
// ESC.
if (e.keyCode == 27) {
Exit();
}
}
onDestroy(Exit);
function select_change_handler() {
selectedBot = select_value(this);
$$invalidate(4, selectedBot);
$$invalidate(8, bots);
}
function input_change_handler() {
debug = this.checked;
$$invalidate(1, debug);
}
$$self.$$set = $$props => {
if ('client' in $$props) $$invalidate(0, client = $$props.client);
if ('clientManager' in $$props) $$invalidate(15, clientManager = $$props.clientManager);
if ('ToggleVisibility' in $$props) $$invalidate(16, ToggleVisibility = $$props.ToggleVisibility);
};
return [
client,
debug,
progress,
iterationCounter,
selectedBot,
botAction,
botActionArgs,
bot,
bots,
OnDebug,
ChangeBot,
Step$1,
Simulate,
Reset,
OnKeyDown,
clientManager,
ToggleVisibility,
select_change_handler,
input_change_handler
];
}
class AI extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$y,
create_fragment$y,
safe_not_equal,
{
client: 0,
clientManager: 15,
ToggleVisibility: 16
},
add_css$p
);
}
}
/* src/client/debug/Debug.svelte generated by Svelte v3.41.0 */
function add_css$q(target) {
append_styles(target, "svelte-8ymctk", ".debug-panel.svelte-8ymctk.svelte-8ymctk{position:fixed;color:#555;font-family:monospace;right:0;top:0;height:100%;font-size:14px;opacity:0.9;z-index:99999}.panel.svelte-8ymctk.svelte-8ymctk{display:flex;position:relative;flex-direction:row;height:100%}.visibility-toggle.svelte-8ymctk.svelte-8ymctk{position:absolute;box-sizing:border-box;top:7px;border:1px solid #ccc;border-radius:5px;width:48px;height:48px;padding:8px;background:white;color:#555;box-shadow:0 0 5px rgba(0, 0, 0, 0.2)}.visibility-toggle.svelte-8ymctk.svelte-8ymctk:hover,.visibility-toggle.svelte-8ymctk.svelte-8ymctk:focus{background:#eee}.opener.svelte-8ymctk.svelte-8ymctk{right:10px}.closer.svelte-8ymctk.svelte-8ymctk{left:-326px}@keyframes svelte-8ymctk-rotateFromZero{from{transform:rotateZ(0deg)}to{transform:rotateZ(180deg)}}.icon.svelte-8ymctk.svelte-8ymctk{display:flex;height:100%;animation:svelte-8ymctk-rotateFromZero 0.4s cubic-bezier(0.68, -0.55, 0.27, 1.55) 0s 1\n normal forwards}.closer.svelte-8ymctk .icon.svelte-8ymctk{animation-direction:reverse}.pane.svelte-8ymctk.svelte-8ymctk{flex-grow:2;overflow-x:hidden;overflow-y:scroll;background:#fefefe;padding:20px;border-left:1px solid #ccc;box-shadow:-1px 0 5px rgba(0, 0, 0, 0.2);box-sizing:border-box;width:280px}.secondary-pane.svelte-8ymctk.svelte-8ymctk{background:#fefefe;overflow-y:scroll}.debug-panel.svelte-8ymctk button,.debug-panel.svelte-8ymctk select{cursor:pointer;font-size:14px;font-family:monospace}.debug-panel.svelte-8ymctk select{background:#eee;border:1px solid #bbb;color:#555;padding:3px;border-radius:3px}.debug-panel.svelte-8ymctk section{margin-bottom:20px}.debug-panel.svelte-8ymctk .screen-reader-only{clip:rect(0 0 0 0);clip-path:inset(50%);height:1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px}");
}
// (194:2) {:else}
function create_else_block$4(ctx) {
let div1;
let button;
let span;
let chevron;
let button_intro;
let button_outro;
let t0;
let menu;
let t1;
let div0;
let switch_instance;
let t2;
let div1_transition;
let current;
let mounted;
let dispose;
chevron = new FaChevronRight({});
menu = new Menu({
props: {
panes: /*panes*/ ctx[6],
pane: /*pane*/ ctx[2]
}
});
menu.$on("change", /*MenuChange*/ ctx[8]);
var switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component;
function switch_props(ctx) {
return {
props: {
client: /*client*/ ctx[4],
clientManager: /*clientManager*/ ctx[0],
ToggleVisibility: /*ToggleVisibility*/ ctx[9]
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
let if_block = /*$secondaryPane*/ ctx[5] && create_if_block_1$7(ctx);
return {
c() {
div1 = element("div");
button = element("button");
span = element("span");
create_component(chevron.$$.fragment);
t0 = space();
create_component(menu.$$.fragment);
t1 = space();
div0 = element("div");
if (switch_instance) create_component(switch_instance.$$.fragment);
t2 = space();
if (if_block) if_block.c();
attr(span, "class", "icon svelte-8ymctk");
attr(span, "aria-hidden", "true");
attr(button, "class", "visibility-toggle closer svelte-8ymctk");
attr(button, "title", "Hide Debug Panel");
attr(div0, "class", "pane svelte-8ymctk");
attr(div0, "role", "region");
attr(div0, "aria-label", /*pane*/ ctx[2]);
attr(div0, "tabindex", "-1");
attr(div1, "class", "panel svelte-8ymctk");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, button);
append(button, span);
mount_component(chevron, span, null);
append(div1, t0);
mount_component(menu, div1, null);
append(div1, t1);
append(div1, div0);
if (switch_instance) {
mount_component(switch_instance, div0, null);
}
/*div0_binding*/ ctx[15](div0);
append(div1, t2);
if (if_block) if_block.m(div1, null);
current = true;
if (!mounted) {
dispose = listen(button, "click", /*ToggleVisibility*/ ctx[9]);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
const menu_changes = {};
if (dirty & /*pane*/ 4) menu_changes.pane = /*pane*/ ctx[2];
menu.$set(menu_changes);
const switch_instance_changes = {};
if (dirty & /*client*/ 16) switch_instance_changes.client = /*client*/ ctx[4];
if (dirty & /*clientManager*/ 1) switch_instance_changes.clientManager = /*clientManager*/ ctx[0];
if (switch_value !== (switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component)) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, div0, null);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
if (!current || dirty & /*pane*/ 4) {
attr(div0, "aria-label", /*pane*/ ctx[2]);
}
if (/*$secondaryPane*/ ctx[5]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*$secondaryPane*/ 32) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$7(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(div1, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(chevron.$$.fragment, local);
add_render_callback(() => {
if (button_outro) button_outro.end(1);
button_intro = create_in_transition(button, /*receive*/ ctx[13], { key: 'toggle' });
button_intro.start();
});
transition_in(menu.$$.fragment, local);
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
transition_in(if_block);
add_render_callback(() => {
if (!div1_transition) div1_transition = create_bidirectional_transition(div1, fly, { x: 400, .../*transitionOpts*/ ctx[11] }, true);
div1_transition.run(1);
});
current = true;
},
o(local) {
transition_out(chevron.$$.fragment, local);
if (button_intro) button_intro.invalidate();
button_outro = create_out_transition(button, /*send*/ ctx[12], { key: 'toggle' });
transition_out(menu.$$.fragment, local);
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
transition_out(if_block);
if (!div1_transition) div1_transition = create_bidirectional_transition(div1, fly, { x: 400, .../*transitionOpts*/ ctx[11] }, false);
div1_transition.run(0);
current = false;
},
d(detaching) {
if (detaching) detach(div1);
destroy_component(chevron);
if (detaching && button_outro) button_outro.end();
destroy_component(menu);
if (switch_instance) destroy_component(switch_instance);
/*div0_binding*/ ctx[15](null);
if (if_block) if_block.d();
if (detaching && div1_transition) div1_transition.end();
mounted = false;
dispose();
}
};
}
// (182:2) {#if !visible}
function create_if_block$e(ctx) {
let button;
let span;
let chevron;
let button_intro;
let button_outro;
let current;
let mounted;
let dispose;
chevron = new FaChevronRight({});
return {
c() {
button = element("button");
span = element("span");
create_component(chevron.$$.fragment);
attr(span, "class", "icon svelte-8ymctk");
attr(span, "aria-hidden", "true");
attr(button, "class", "visibility-toggle opener svelte-8ymctk");
attr(button, "title", "Show Debug Panel");
},
m(target, anchor) {
insert(target, button, anchor);
append(button, span);
mount_component(chevron, span, null);
current = true;
if (!mounted) {
dispose = listen(button, "click", /*ToggleVisibility*/ ctx[9]);
mounted = true;
}
},
p: noop,
i(local) {
if (current) return;
transition_in(chevron.$$.fragment, local);
add_render_callback(() => {
if (button_outro) button_outro.end(1);
button_intro = create_in_transition(button, /*receive*/ ctx[13], { key: 'toggle' });
button_intro.start();
});
current = true;
},
o(local) {
transition_out(chevron.$$.fragment, local);
if (button_intro) button_intro.invalidate();
button_outro = create_out_transition(button, /*send*/ ctx[12], { key: 'toggle' });
current = false;
},
d(detaching) {
if (detaching) detach(button);
destroy_component(chevron);
if (detaching && button_outro) button_outro.end();
mounted = false;
dispose();
}
};
}
// (222:6) {#if $secondaryPane}
function create_if_block_1$7(ctx) {
let div;
let switch_instance;
let current;
var switch_value = /*$secondaryPane*/ ctx[5].component;
function switch_props(ctx) {
return {
props: {
metadata: /*$secondaryPane*/ ctx[5].metadata
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
div = element("div");
if (switch_instance) create_component(switch_instance.$$.fragment);
attr(div, "class", "secondary-pane svelte-8ymctk");
},
m(target, anchor) {
insert(target, div, anchor);
if (switch_instance) {
mount_component(switch_instance, div, null);
}
current = true;
},
p(ctx, dirty) {
const switch_instance_changes = {};
if (dirty & /*$secondaryPane*/ 32) switch_instance_changes.metadata = /*$secondaryPane*/ ctx[5].metadata;
if (switch_value !== (switch_value = /*$secondaryPane*/ ctx[5].component)) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, div, null);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
if (switch_instance) destroy_component(switch_instance);
}
};
}
function create_fragment$z(ctx) {
let section;
let current_block_type_index;
let if_block;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$e, create_else_block$4];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (!/*visible*/ ctx[3]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
section = element("section");
if_block.c();
attr(section, "aria-label", "boardgame.io Debug Panel");
attr(section, "class", "debug-panel svelte-8ymctk");
},
m(target, anchor) {
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
if (!mounted) {
dispose = listen(window, "keypress", /*Keypress*/ ctx[10]);
mounted = true;
}
},
p(ctx, [dirty]) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
} else {
if_block.p(ctx, dirty);
}
transition_in(if_block, 1);
if_block.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$z($$self, $$props, $$invalidate) {
let client;
let $clientManager,
$$unsubscribe_clientManager = noop,
$$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(14, $clientManager = $$value)), clientManager);
let $secondaryPane;
$$self.$$.on_destroy.push(() => $$unsubscribe_clientManager());
let { clientManager } = $$props;
$$subscribe_clientManager();
const panes = {
main: {
label: 'Main',
shortcut: 'm',
component: Main
},
log: {
label: 'Log',
shortcut: 'l',
component: Log
},
info: {
label: 'Info',
shortcut: 'i',
component: Info
},
ai: {
label: 'AI',
shortcut: 'a',
component: AI
}
};
const disableHotkeys = writable(false);
const secondaryPane = writable(null);
component_subscribe($$self, secondaryPane, value => $$invalidate(5, $secondaryPane = value));
setContext('hotkeys', { disableHotkeys });
setContext('secondaryPane', { secondaryPane });
let paneDiv;
let pane = 'main';
function MenuChange(e) {
$$invalidate(2, pane = e.detail);
paneDiv.focus();
}
// Toggle debugger visibilty
function ToggleVisibility() {
$$invalidate(3, visible = !visible);
}
let visible = true;
function Keypress(e) {
if (e.key == '.') {
ToggleVisibility();
return;
}
// Set displayed pane
if (!visible) return;
Object.entries(panes).forEach(([key, { shortcut }]) => {
if (e.key == shortcut) {
$$invalidate(2, pane = key);
}
});
}
const transitionOpts = { duration: 150, easing: cubicOut };
const [send, receive] = crossfade(transitionOpts);
function div0_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
paneDiv = $$value;
$$invalidate(1, paneDiv);
});
}
$$self.$$set = $$props => {
if ('clientManager' in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager));
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$clientManager*/ 16384) {
$$invalidate(4, client = $clientManager.client);
}
};
return [
clientManager,
paneDiv,
pane,
visible,
client,
$secondaryPane,
panes,
secondaryPane,
MenuChange,
ToggleVisibility,
Keypress,
transitionOpts,
send,
receive,
$clientManager,
div0_binding
];
}
class Debug extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$z, create_fragment$z, safe_not_equal, { clientManager: 0 }, add_css$q);
}
}
/**
* Class to manage boardgame.io clients and limit debug panel rendering.
*/
class ClientManager {
constructor() {
this.debugPanel = null;
this.currentClient = null;
this.clients = new Map();
this.subscribers = new Map();
}
/**
* Register a client with the client manager.
*/
register(client) {
// Add client to clients map.
this.clients.set(client, client);
// Mount debug for this client (no-op if another debug is already mounted).
this.mountDebug(client);
this.notifySubscribers();
}
/**
* Unregister a client from the client manager.
*/
unregister(client) {
// Remove client from clients map.
this.clients.delete(client);
if (this.currentClient === client) {
// If the removed client owned the debug panel, unmount it.
this.unmountDebug();
// Mount debug panel for next available client.
for (const [client] of this.clients) {
if (this.debugPanel)
break;
this.mountDebug(client);
}
}
this.notifySubscribers();
}
/**
* Subscribe to the client manager state.
* Calls the passed callback each time the current client changes or a client
* registers/unregisters.
* Returns a function to unsubscribe from the state updates.
*/
subscribe(callback) {
const id = Symbol();
this.subscribers.set(id, callback);
callback(this.getState());
return () => {
this.subscribers.delete(id);
};
}
/**
* Switch to a client with a matching playerID.
*/
switchPlayerID(playerID) {
// For multiplayer clients, try switching control to a different client
// that is using the same transport layer.
if (this.currentClient.multiplayer) {
for (const [client] of this.clients) {
if (client.playerID === playerID &&
client.debugOpt !== false &&
client.multiplayer === this.currentClient.multiplayer) {
this.switchToClient(client);
return;
}
}
}
// If no client matches, update the playerID for the current client.
this.currentClient.updatePlayerID(playerID);
this.notifySubscribers();
}
/**
* Set the passed client as the active client for debugging.
*/
switchToClient(client) {
if (client === this.currentClient)
return;
this.unmountDebug();
this.mountDebug(client);
this.notifySubscribers();
}
/**
* Notify all subscribers of changes to the client manager state.
*/
notifySubscribers() {
const arg = this.getState();
this.subscribers.forEach((cb) => {
cb(arg);
});
}
/**
* Get the client manager state.
*/
getState() {
return {
client: this.currentClient,
debuggableClients: this.getDebuggableClients(),
};
}
/**
* Get an array of the registered clients that haven’t disabled the debug panel.
*/
getDebuggableClients() {
return [...this.clients.values()].filter((client) => client.debugOpt !== false);
}
/**
* Mount the debug panel using the passed client.
*/
mountDebug(client) {
if (client.debugOpt === false ||
this.debugPanel !== null ||
typeof document === 'undefined') {
return;
}
let DebugImpl;
let target = document.body;
if (process.env.NODE_ENV !== 'production') {
DebugImpl = Debug;
}
if (client.debugOpt && client.debugOpt !== true) {
DebugImpl = client.debugOpt.impl || DebugImpl;
target = client.debugOpt.target || target;
}
if (DebugImpl) {
this.currentClient = client;
this.debugPanel = new DebugImpl({
target,
props: { clientManager: this },
});
}
}
/**
* Unmount the debug panel.
*/
unmountDebug() {
this.debugPanel.$destroy();
this.debugPanel = null;
this.currentClient = null;
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Global client manager instance that all clients register with.
*/
const GlobalClientManager = new ClientManager();
/**
* Standardise the passed playerID, using currentPlayer if appropriate.
*/
function assumedPlayerID(playerID, store, multiplayer) {
// In singleplayer mode, if the client does not have a playerID
// associated with it, we attach the currentPlayer as playerID.
if (!multiplayer && (playerID === null || playerID === undefined)) {
const state = store.getState();
playerID = state.ctx.currentPlayer;
}
return playerID;
}
/**
* createDispatchers
*
* Create action dispatcher wrappers with bound playerID and credentials
*/
function createDispatchers(storeActionType, innerActionNames, store, playerID, credentials, multiplayer) {
const dispatchers = {};
for (const name of innerActionNames) {
dispatchers[name] = (...args) => {
const action = ActionCreators[storeActionType](name, args, assumedPlayerID(playerID, store, multiplayer), credentials);
store.dispatch(action);
};
}
return dispatchers;
}
// Creates a set of dispatchers to make moves.
const createMoveDispatchers = createDispatchers.bind(null, 'makeMove');
// Creates a set of dispatchers to dispatch game flow events.
const createEventDispatchers = createDispatchers.bind(null, 'gameEvent');
// Creates a set of dispatchers to dispatch actions to plugins.
const createPluginDispatchers = createDispatchers.bind(null, 'plugin');
/**
* Implementation of Client (see below).
*/
class _ClientImpl {
constructor({ game, debug, numPlayers, multiplayer, matchID: matchID, playerID, credentials, enhancer, }) {
this.game = ProcessGameConfig(game);
this.playerID = playerID;
this.matchID = matchID || 'default';
this.credentials = credentials;
this.multiplayer = multiplayer;
this.debugOpt = debug;
this.manager = GlobalClientManager;
this.gameStateOverride = null;
this.subscribers = {};
this._running = false;
this.reducer = CreateGameReducer({
game: this.game,
isClient: multiplayer !== undefined,
});
this.initialState = null;
if (!multiplayer) {
this.initialState = InitializeGame({ game: this.game, numPlayers });
}
this.reset = () => {
this.store.dispatch(reset(this.initialState));
};
this.undo = () => {
const undo$1 = undo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials);
this.store.dispatch(undo$1);
};
this.redo = () => {
const redo$1 = redo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials);
this.store.dispatch(redo$1);
};
this.log = [];
/**
* Middleware that manages the log object.
* Reducers generate deltalogs, which are log events
* that are the result of application of a single action.
* The master may also send back a deltalog or the entire
* log depending on the type of request.
* The middleware below takes care of all these cases while
* managing the log object.
*/
const LogMiddleware = (store) => (next) => (action) => {
const result = next(action);
const state = store.getState();
switch (action.type) {
case MAKE_MOVE:
case GAME_EVENT:
case UNDO:
case REDO: {
const deltalog = state.deltalog;
this.log = [...this.log, ...deltalog];
break;
}
case RESET: {
this.log = [];
break;
}
case PATCH:
case UPDATE: {
let id = -1;
if (this.log.length > 0) {
id = this.log[this.log.length - 1]._stateID;
}
let deltalog = action.deltalog || [];
// Filter out actions that are already present
// in the current log. This may occur when the
// client adds an entry to the log followed by
// the update from the master here.
deltalog = deltalog.filter((l) => l._stateID > id);
this.log = [...this.log, ...deltalog];
break;
}
case SYNC: {
this.initialState = action.initialState;
this.log = action.log || [];
break;
}
}
return result;
};
/**
* Middleware that intercepts actions and sends them to the master,
* which keeps the authoritative version of the state.
*/
const TransportMiddleware = (store) => (next) => (action) => {
const baseState = store.getState();
const result = next(action);
if (!('clientOnly' in action) &&
action.type !== STRIP_TRANSIENTS) {
this.transport.sendAction(baseState, action);
}
return result;
};
/**
* Middleware that intercepts actions and invokes the subscription callback.
*/
const SubscriptionMiddleware = () => (next) => (action) => {
const result = next(action);
this.notifySubscribers();
return result;
};
const middleware = applyMiddleware(TransientHandlingMiddleware, SubscriptionMiddleware, TransportMiddleware, LogMiddleware);
enhancer =
enhancer !== undefined ? compose(middleware, enhancer) : middleware;
this.store = createStore(this.reducer, this.initialState, enhancer);
if (!multiplayer)
multiplayer = DummyTransport;
this.transport = multiplayer({
transportDataCallback: (data) => this.receiveTransportData(data),
gameKey: game,
game: this.game,
matchID,
playerID,
credentials,
gameName: this.game.name,
numPlayers,
});
this.createDispatchers();
this.chatMessages = [];
this.sendChatMessage = (payload) => {
this.transport.sendChatMessage(this.matchID, {
id: nanoid(7),
sender: this.playerID,
payload: payload,
});
};
}
/** Handle incoming match data from a multiplayer transport. */
receiveMatchData(matchData) {
this.matchData = matchData;
this.notifySubscribers();
}
/** Handle an incoming chat message from a multiplayer transport. */
receiveChatMessage(message) {
this.chatMessages = [...this.chatMessages, message];
this.notifySubscribers();
}
/** Handle all incoming updates from a multiplayer transport. */
receiveTransportData(data) {
const [matchID] = data.args;
if (matchID !== this.matchID)
return;
switch (data.type) {
case 'sync': {
const [, syncInfo] = data.args;
const action = sync(syncInfo);
this.receiveMatchData(syncInfo.filteredMetadata);
this.store.dispatch(action);
break;
}
case 'update': {
const [, state, deltalog] = data.args;
const currentState = this.store.getState();
if (state._stateID >= currentState._stateID) {
const action = update$1(state, deltalog);
this.store.dispatch(action);
}
break;
}
case 'patch': {
const [, prevStateID, stateID, patch$1, deltalog] = data.args;
const currentStateID = this.store.getState()._stateID;
if (prevStateID !== currentStateID)
break;
const action = patch(prevStateID, stateID, patch$1, deltalog);
this.store.dispatch(action);
// Emit sync if patch apply failed.
if (this.store.getState()._stateID === currentStateID) {
this.transport.requestSync();
}
break;
}
case 'matchData': {
const [, matchData] = data.args;
this.receiveMatchData(matchData);
break;
}
case 'chat': {
const [, chatMessage] = data.args;
this.receiveChatMessage(chatMessage);
break;
}
}
}
notifySubscribers() {
Object.values(this.subscribers).forEach((fn) => fn(this.getState()));
}
overrideGameState(state) {
this.gameStateOverride = state;
this.notifySubscribers();
}
start() {
this.transport.connect();
this._running = true;
this.manager.register(this);
}
stop() {
this.transport.disconnect();
this._running = false;
this.manager.unregister(this);
}
subscribe(fn) {
const id = Object.keys(this.subscribers).length;
this.subscribers[id] = fn;
this.transport.subscribeToConnectionStatus(() => this.notifySubscribers());
if (this._running || !this.multiplayer) {
fn(this.getState());
}
// Return a handle that allows the caller to unsubscribe.
return () => {
delete this.subscribers[id];
};
}
getInitialState() {
return this.initialState;
}
getState() {
let state = this.store.getState();
if (this.gameStateOverride !== null) {
state = this.gameStateOverride;
}
// This is the state before a sync with the game master.
if (state === null) {
return state;
}
// isActive.
let isActive = true;
const isPlayerActive = this.game.flow.isPlayerActive(state.G, state.ctx, this.playerID);
if (this.multiplayer && !isPlayerActive) {
isActive = false;
}
if (!this.multiplayer &&
this.playerID !== null &&
this.playerID !== undefined &&
!isPlayerActive) {
isActive = false;
}
if (state.ctx.gameover !== undefined) {
isActive = false;
}
// Secrets are normally stripped on the server,
// but we also strip them here so that game developers
// can see their effects while prototyping.
// Do not strip again if this is a multiplayer game
// since the server has already stripped secret info. (issue #818)
if (!this.multiplayer) {
state = {
...state,
G: this.game.playerView(state.G, state.ctx, this.playerID),
plugins: PlayerView(state, this),
};
}
// Combine into return value.
return {
...state,
log: this.log,
isActive,
isConnected: this.transport.isConnected,
};
}
createDispatchers() {
this.moves = createMoveDispatchers(this.game.moveNames, this.store, this.playerID, this.credentials, this.multiplayer);
this.events = createEventDispatchers(this.game.flow.enabledEventNames, this.store, this.playerID, this.credentials, this.multiplayer);
this.plugins = createPluginDispatchers(this.game.pluginNames, this.store, this.playerID, this.credentials, this.multiplayer);
}
updatePlayerID(playerID) {
this.playerID = playerID;
this.createDispatchers();
this.transport.updatePlayerID(playerID);
this.notifySubscribers();
}
updateMatchID(matchID) {
this.matchID = matchID;
this.createDispatchers();
this.transport.updateMatchID(matchID);
this.notifySubscribers();
}
updateCredentials(credentials) {
this.credentials = credentials;
this.createDispatchers();
this.transport.updateCredentials(credentials);
this.notifySubscribers();
}
}
/**
* Client
*
* boardgame.io JS client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} matchID - The matchID that you want to connect to.
* @param {...object} playerID - The playerID associated with this client.
* @param {...string} credentials - The authentication credentials associated with this client.
*
* Returns:
* A JS object that provides an API to interact with the
* game by dispatching moves and events.
*/
function Client(opts) {
return new _ClientImpl(opts);
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Client
*
* boardgame.io React client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} debug - Enables the Debug UI.
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET,
* UNDO and REDO.
*/
function Client$1(opts) {
var _a;
const { game, numPlayers, board, multiplayer, enhancer } = opts;
let { loading, debug } = opts;
// Component that is displayed before the client has synced
// with the game master.
if (loading === undefined) {
const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting...");
loading = Loading;
}
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _a = class WrappedBoard extends React.Component {
constructor(props) {
super(props);
if (debug === undefined) {
debug = props.debug;
}
this.client = Client({
game,
debug,
numPlayers,
multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
enhancer,
});
}
componentDidMount() {
this.unsubscribe = this.client.subscribe(() => this.forceUpdate());
this.client.start();
}
componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
componentDidUpdate(prevProps) {
if (this.props.matchID != prevProps.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (this.props.playerID != prevProps.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (this.props.credentials != prevProps.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
render() {
const state = this.client.getState();
if (state === null) {
return React.createElement(loading);
}
let _board = null;
if (board) {
_board = React.createElement(board, {
...state,
...this.props,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
matchID: this.client.matchID,
playerID: this.client.playerID,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
log: this.client.log,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages,
});
}
return React.createElement("div", { className: "bgio-client" }, _board);
}
},
_a.propTypes = {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string,
// Enable / disable the Debug UI.
debug: PropTypes.any,
},
_a.defaultProps = {
matchID: 'default',
playerID: null,
credentials: null,
debug: true,
},
_a;
}
var _excluded = ["matchID", "playerID"];
/**
* Client
*
* boardgame.io React Native client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React Native component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE.
*/
function Client$2(opts) {
var _class, _temp;
var game = opts.game,
numPlayers = opts.numPlayers,
board = opts.board,
multiplayer = opts.multiplayer,
enhancer = opts.enhancer;
var loading = opts.loading; // Component that is displayed before the client has synced
// with the game master.
if (loading === undefined) {
var Loading = function Loading() {
return /*#__PURE__*/React.createElement(React.Fragment, null);
};
loading = Loading;
}
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _temp = _class = /*#__PURE__*/function (_React$Component) {
_inherits(WrappedBoard, _React$Component);
var _super = _createSuper(WrappedBoard);
function WrappedBoard(props) {
var _this;
_classCallCheck(this, WrappedBoard);
_this = _super.call(this, props);
_this.client = Client({
game: game,
numPlayers: numPlayers,
multiplayer: multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
debug: false,
enhancer: enhancer
});
return _this;
}
_createClass(WrappedBoard, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
this.unsubscribe = this.client.subscribe(function () {
return _this2.forceUpdate();
});
this.client.start();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.matchID != this.props.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (prevProps.playerID != this.props.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (prevProps.credentials != this.props.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
}, {
key: "render",
value: function render() {
var _board = null;
var state = this.client.getState();
if (state === null) {
return /*#__PURE__*/React.createElement(loading);
}
var _this$props = this.props,
matchID = _this$props.matchID,
playerID = _this$props.playerID,
rest = _objectWithoutProperties(_this$props, _excluded);
if (board) {
_board = /*#__PURE__*/React.createElement(board, _objectSpread2(_objectSpread2(_objectSpread2({}, state), rest), {}, {
matchID: matchID,
playerID: playerID,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
step: this.client.step,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages
}));
}
return _board;
}
}]);
return WrappedBoard;
}(React.Component), _defineProperty(_class, "propTypes", {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string
}), _defineProperty(_class, "defaultProps", {
matchID: 'default',
playerID: null,
credentials: null
}), _temp;
}
var Type;
(function (Type) {
Type[Type["SYNC"] = 0] = "SYNC";
Type[Type["ASYNC"] = 1] = "ASYNC";
})(Type || (Type = {}));
/**
* Type guard that checks if a storage implementation is synchronous.
*/
function isSynchronous(storageAPI) {
return storageAPI.type() === Type.SYNC;
}
class Sync {
type() {
return Type.SYNC;
}
/**
* Connect.
*/
connect() {
return;
}
/**
* Create a new match.
*
* This might just need to call setState and setMetadata in
* most implementations.
*
* However, it exists as a separate call so that the
* implementation can provision things differently when
* a match is created. For example, it might stow away the
* initial match state in a separate field for easier retrieval.
*/
/* istanbul ignore next */
createMatch(matchID, opts) {
if (this.createGame) {
console.warn('The database connector does not implement a createMatch method.', '\nUsing the deprecated createGame method instead.');
return this.createGame(matchID, opts);
}
else {
console.error('The database connector does not implement a createMatch method.');
}
}
/**
* Return all matches.
*/
/* istanbul ignore next */
listMatches(opts) {
if (this.listGames) {
console.warn('The database connector does not implement a listMatches method.', '\nUsing the deprecated listGames method instead.');
return this.listGames(opts);
}
else {
console.error('The database connector does not implement a listMatches method.');
}
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* InMemory data storage.
*/
class InMemory extends Sync {
/**
* Creates a new InMemory storage.
*/
constructor() {
super();
this.state = new Map();
this.initial = new Map();
this.metadata = new Map();
this.log = new Map();
}
/**
* Create a new match.
*
* @override
*/
createMatch(matchID, opts) {
this.initial.set(matchID, opts.initialState);
this.setState(matchID, opts.initialState);
this.setMetadata(matchID, opts.metadata);
}
/**
* Write the match metadata to the in-memory object.
*/
setMetadata(matchID, metadata) {
this.metadata.set(matchID, metadata);
}
/**
* Write the match state to the in-memory object.
*/
setState(matchID, state, deltalog) {
if (deltalog && deltalog.length > 0) {
const log = this.log.get(matchID) || [];
this.log.set(matchID, [...log, ...deltalog]);
}
this.state.set(matchID, state);
}
/**
* Fetches state for a particular matchID.
*/
fetch(matchID, opts) {
const result = {};
if (opts.state) {
result.state = this.state.get(matchID);
}
if (opts.metadata) {
result.metadata = this.metadata.get(matchID);
}
if (opts.log) {
result.log = this.log.get(matchID) || [];
}
if (opts.initialState) {
result.initialState = this.initial.get(matchID);
}
return result;
}
/**
* Remove the match state from the in-memory object.
*/
wipe(matchID) {
this.state.delete(matchID);
this.metadata.delete(matchID);
}
/**
* Return all keys.
*
* @override
*/
listMatches(opts) {
return [...this.metadata.entries()]
.filter(([, metadata]) => {
if (!opts) {
return true;
}
if (opts.gameName !== undefined &&
metadata.gameName !== opts.gameName) {
return false;
}
if (opts.where !== undefined) {
if (opts.where.isGameover !== undefined) {
const isGameover = metadata.gameover !== undefined;
if (isGameover !== opts.where.isGameover) {
return false;
}
}
if (opts.where.updatedBefore !== undefined &&
metadata.updatedAt >= opts.where.updatedBefore) {
return false;
}
if (opts.where.updatedAfter !== undefined &&
metadata.updatedAt <= opts.where.updatedAfter) {
return false;
}
}
return true;
})
.map(([key]) => key);
}
}
class WithLocalStorageMap extends Map {
constructor(key) {
super();
this.key = key;
const cache = JSON.parse(localStorage.getItem(this.key)) || [];
cache.forEach((entry) => this.set(...entry));
}
sync() {
const entries = [...this.entries()];
localStorage.setItem(this.key, JSON.stringify(entries));
}
set(key, value) {
super.set(key, value);
this.sync();
return this;
}
delete(key) {
const result = super.delete(key);
this.sync();
return result;
}
}
/**
* locaStorage data storage.
*/
class LocalStorage extends InMemory {
constructor(storagePrefix = 'bgio') {
super();
const StorageMap = (stateKey) => new WithLocalStorageMap(`${storagePrefix}_${stateKey}`);
this.state = StorageMap('state');
this.initial = StorageMap('initial');
this.metadata = StorageMap('metadata');
this.log = StorageMap('log');
}
}
/**
* Creates a new match metadata object.
*/
const createMetadata = ({ game, unlisted, setupData, numPlayers, }) => {
const metadata = {
gameName: game.name,
unlisted: !!unlisted,
players: {},
createdAt: Date.now(),
updatedAt: Date.now(),
};
if (setupData !== undefined)
metadata.setupData = setupData;
for (let playerIndex = 0; playerIndex < numPlayers; playerIndex++) {
metadata.players[playerIndex] = { id: playerIndex };
}
return metadata;
};
/**
* Creates initial state and metadata for a new match.
* If the provided `setupData` doesn’t pass the game’s validation,
* an error object is returned instead.
*/
const createMatch = ({ game, numPlayers, setupData, unlisted, }) => {
if (!numPlayers || typeof numPlayers !== 'number')
numPlayers = 2;
const setupDataError = game.validateSetupData && game.validateSetupData(setupData, numPlayers);
if (setupDataError !== undefined)
return { setupDataError };
const metadata = createMetadata({ game, numPlayers, setupData, unlisted });
const initialState = InitializeGame({ game, numPlayers, setupData });
return { metadata, initialState };
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Filter match data to get a player metadata object with credentials stripped.
*/
const filterMatchData = (matchData) => Object.values(matchData.players).map((player) => {
const { credentials, ...filteredData } = player;
return filteredData;
});
/**
* Remove player credentials from action payload
*/
const stripCredentialsFromAction = (action) => {
const { credentials, ...payload } = action.payload;
return { ...action, payload };
};
/**
* Master
*
* Class that runs the game and maintains the authoritative state.
* It uses the transportAPI to communicate with clients and the
* storageAPI to communicate with the database.
*/
class Master {
constructor(game, storageAPI, transportAPI, auth) {
this.game = ProcessGameConfig(game);
this.storageAPI = storageAPI;
this.transportAPI = transportAPI;
this.subscribeCallback = () => { };
this.auth = auth;
}
subscribe(fn) {
this.subscribeCallback = fn;
}
/**
* Called on each move / event made by the client.
* Computes the new value of the game state and returns it
* along with a deltalog.
*/
async onUpdate(credAction, stateID, matchID, playerID) {
if (!credAction || !credAction.payload) {
return { error: 'missing action or action payload' };
}
let metadata;
if (isSynchronous(this.storageAPI)) {
({ metadata } = this.storageAPI.fetch(matchID, { metadata: true }));
}
else {
({ metadata } = await this.storageAPI.fetch(matchID, { metadata: true }));
}
if (this.auth) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials: credAction.payload.credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized action' };
}
}
const action = stripCredentialsFromAction(credAction);
const key = matchID;
let state;
if (isSynchronous(this.storageAPI)) {
({ state } = this.storageAPI.fetch(key, { state: true }));
}
else {
({ state } = await this.storageAPI.fetch(key, { state: true }));
}
if (state === undefined) {
error(`game not found, matchID=[${key}]`);
return { error: 'game not found' };
}
if (state.ctx.gameover !== undefined) {
error(`game over - matchID=[${key}] - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
const reducer = CreateGameReducer({
game: this.game,
});
const middleware = applyMiddleware(TransientHandlingMiddleware);
const store = createStore(reducer, state, middleware);
// Only allow UNDO / REDO if there is exactly one player
// that can make moves right now and the person doing the
// action is that player.
if (action.type == UNDO || action.type == REDO) {
const hasActivePlayers = state.ctx.activePlayers !== null;
const isCurrentPlayer = state.ctx.currentPlayer === playerID;
if (
// If activePlayers is empty, non-current players can’t undo.
(!hasActivePlayers && !isCurrentPlayer) ||
// If player is not active or multiple players are active, can’t undo.
(hasActivePlayers &&
(state.ctx.activePlayers[playerID] === undefined ||
Object.keys(state.ctx.activePlayers).length > 1))) {
error(`playerID=[${playerID}] cannot undo / redo right now`);
return;
}
}
// Check whether the player is active.
if (!this.game.flow.isPlayerActive(state.G, state.ctx, playerID)) {
error(`player not active - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
// Get move for further checks
const move = action.type == MAKE_MOVE
? this.game.flow.getMove(state.ctx, action.payload.type, playerID)
: null;
// Check whether the player is allowed to make the move.
if (action.type == MAKE_MOVE && !move) {
error(`move not processed - canPlayerMakeMove=false - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
// Check if action's stateID is different than store's stateID
// and if move does not have ignoreStaleStateID truthy.
if (state._stateID !== stateID &&
!(move && IsLongFormMove(move) && move.ignoreStaleStateID)) {
error(`invalid stateID, was=[${stateID}], expected=[${state._stateID}]` +
` - playerID=[${playerID}] - action[${action.payload.type}]`);
return;
}
const prevState = store.getState();
// Update server's version of the store.
store.dispatch(action);
state = store.getState();
this.subscribeCallback({
state,
action,
matchID,
});
if (this.game.deltaState) {
this.transportAPI.sendAll({
type: 'patch',
args: [matchID, stateID, prevState, state],
});
}
else {
this.transportAPI.sendAll({
type: 'update',
args: [matchID, state],
});
}
const { deltalog, ...stateWithoutDeltalog } = state;
let newMetadata;
if (metadata &&
(metadata.gameover === undefined || metadata.gameover === null)) {
newMetadata = {
...metadata,
updatedAt: Date.now(),
};
if (state.ctx.gameover !== undefined) {
newMetadata.gameover = state.ctx.gameover;
}
}
if (isSynchronous(this.storageAPI)) {
this.storageAPI.setState(key, stateWithoutDeltalog, deltalog);
if (newMetadata)
this.storageAPI.setMetadata(key, newMetadata);
}
else {
const writes = [
this.storageAPI.setState(key, stateWithoutDeltalog, deltalog),
];
if (newMetadata) {
writes.push(this.storageAPI.setMetadata(key, newMetadata));
}
await Promise.all(writes);
}
}
/**
* Called when the client connects / reconnects.
* Returns the latest game state and the entire log.
*/
async onSync(matchID, playerID, credentials, numPlayers = 2) {
const key = matchID;
const fetchOpts = {
state: true,
metadata: true,
log: true,
initialState: true,
};
const fetchResult = isSynchronous(this.storageAPI)
? this.storageAPI.fetch(key, fetchOpts)
: await this.storageAPI.fetch(key, fetchOpts);
let { state, initialState, log, metadata } = fetchResult;
if (this.auth && playerID !== undefined && playerID !== null) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
// If the game doesn't exist, then create one on demand.
// TODO: Move this out of the sync call.
if (state === undefined) {
const match = createMatch({
game: this.game,
unlisted: true,
numPlayers,
setupData: undefined,
});
if ('setupDataError' in match) {
return { error: 'game requires setupData' };
}
initialState = state = match.initialState;
metadata = match.metadata;
this.subscribeCallback({ state, matchID });
if (isSynchronous(this.storageAPI)) {
this.storageAPI.createMatch(key, { initialState, metadata });
}
else {
await this.storageAPI.createMatch(key, { initialState, metadata });
}
}
const filteredMetadata = metadata ? filterMatchData(metadata) : undefined;
const syncInfo = {
state,
log,
filteredMetadata,
initialState,
};
this.transportAPI.send({
playerID,
type: 'sync',
args: [matchID, syncInfo],
});
return;
}
/**
* Called when a client connects or disconnects.
* Updates and sends out metadata to reflect the player’s connection status.
*/
async onConnectionChange(matchID, playerID, credentials, connected) {
const key = matchID;
// Ignore changes for clients without a playerID, e.g. spectators.
if (playerID === undefined || playerID === null) {
return;
}
let metadata;
if (isSynchronous(this.storageAPI)) {
({ metadata } = this.storageAPI.fetch(key, { metadata: true }));
}
else {
({ metadata } = await this.storageAPI.fetch(key, { metadata: true }));
}
if (metadata === undefined) {
error(`metadata not found for matchID=[${key}]`);
return { error: 'metadata not found' };
}
if (metadata.players[playerID] === undefined) {
error(`Player not in the match, matchID=[${key}] playerID=[${playerID}]`);
return { error: 'player not in the match' };
}
if (this.auth) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
metadata.players[playerID].isConnected = connected;
const filteredMetadata = filterMatchData(metadata);
this.transportAPI.sendAll({
type: 'matchData',
args: [matchID, filteredMetadata],
});
if (isSynchronous(this.storageAPI)) {
this.storageAPI.setMetadata(key, metadata);
}
else {
await this.storageAPI.setMetadata(key, metadata);
}
}
async onChatMessage(matchID, chatMessage, credentials) {
const key = matchID;
if (this.auth) {
const { metadata } = await this.storageAPI.fetch(key, {
metadata: true,
});
if (!(chatMessage && typeof chatMessage.sender === 'string')) {
return { error: 'unauthorized' };
}
const isAuthentic = await this.auth.authenticateCredentials({
playerID: chatMessage.sender,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
this.transportAPI.sendAll({
type: 'chat',
args: [matchID, chatMessage],
});
}
}
const applyPlayerView = (game, playerID, state) => ({
...state,
G: game.playerView(state.G, state.ctx, playerID),
plugins: PlayerView(state, { playerID, game }),
deltalog: undefined,
_undo: [],
_redo: [],
});
/** Gets a function that filters the TransportData for a given player and game. */
const getFilterPlayerView = (game) => (playerID, payload) => {
switch (payload.type) {
case 'patch': {
const [matchID, stateID, prevState, state] = payload.args;
const log = redactLog(state.deltalog, playerID);
const filteredState = applyPlayerView(game, playerID, state);
const newStateID = state._stateID;
const prevFilteredState = applyPlayerView(game, playerID, prevState);
const patch = createPatch(prevFilteredState, filteredState);
return {
type: 'patch',
args: [matchID, stateID, newStateID, patch, log],
};
}
case 'update': {
const [matchID, state] = payload.args;
const log = redactLog(state.deltalog, playerID);
const filteredState = applyPlayerView(game, playerID, state);
return {
type: 'update',
args: [matchID, filteredState, log],
};
}
case 'sync': {
const [matchID, syncInfo] = payload.args;
const filteredState = applyPlayerView(game, playerID, syncInfo.state);
const log = redactLog(syncInfo.log, playerID);
const newSyncInfo = {
...syncInfo,
state: filteredState,
log,
};
return {
type: 'sync',
args: [matchID, newSyncInfo],
};
}
default: {
return payload;
}
}
};
/**
* Redact the log.
*
* @param {Array} log - The game log (or deltalog).
* @param {String} playerID - The playerID that this log is
* to be sent to.
*/
function redactLog(log, playerID) {
if (log === undefined) {
return log;
}
return log.map((logEvent) => {
// filter for all other players and spectators.
if (playerID !== null && +playerID === +logEvent.action.payload.playerID) {
return logEvent;
}
if (logEvent.redact !== true) {
return logEvent;
}
const payload = {
...logEvent.action.payload,
args: null,
};
const filteredEvent = {
...logEvent,
action: { ...logEvent.action, payload },
};
const { redact, ...remaining } = filteredEvent;
return remaining;
});
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Returns null if it is not a bot's turn.
* Otherwise, returns a playerID of a bot that may play now.
*/
function GetBotPlayer(state, bots) {
if (state.ctx.gameover !== undefined) {
return null;
}
if (state.ctx.activePlayers) {
for (const key of Object.keys(bots)) {
if (key in state.ctx.activePlayers) {
return key;
}
}
}
else if (state.ctx.currentPlayer in bots) {
return state.ctx.currentPlayer;
}
return null;
}
/**
* Creates a local version of the master that the client
* can interact with.
*/
class LocalMaster extends Master {
constructor({ game, bots, storageKey, persist }) {
const clientCallbacks = {};
const initializedBots = {};
if (game && game.ai && bots) {
for (const playerID in bots) {
const bot = bots[playerID];
initializedBots[playerID] = new bot({
game,
enumerate: game.ai.enumerate,
seed: game.seed,
});
}
}
const send = ({ playerID, ...data }) => {
const callback = clientCallbacks[playerID];
if (callback !== undefined) {
callback(filterPlayerView(playerID, data));
}
};
const filterPlayerView = getFilterPlayerView(game);
const transportAPI = {
send,
sendAll: (payload) => {
for (const playerID in clientCallbacks) {
send({ playerID, ...payload });
}
},
};
const storage = persist ? new LocalStorage(storageKey) : new InMemory();
super(game, storage, transportAPI);
this.connect = (playerID, callback) => {
clientCallbacks[playerID] = callback;
};
this.subscribe(({ state, matchID }) => {
if (!bots) {
return;
}
const botPlayer = GetBotPlayer(state, initializedBots);
if (botPlayer !== null) {
setTimeout(async () => {
const botAction = await initializedBots[botPlayer].play(state, botPlayer);
await this.onUpdate(botAction.action, state._stateID, matchID, botAction.action.payload.playerID);
}, 100);
}
});
}
}
/**
* Local
*
* Transport interface that embeds a GameMaster within it
* that you can connect multiple clients to.
*/
class LocalTransport extends Transport {
/**
* Creates a new Mutiplayer instance.
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
*/
constructor({ master, ...opts }) {
super(opts);
this.master = master;
}
sendChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.master.onChatMessage(...args);
}
sendAction(state, action) {
this.master.onUpdate(action, state._stateID, this.matchID, this.playerID);
}
requestSync() {
this.master.onSync(this.matchID, this.playerID, this.credentials, this.numPlayers);
}
connect() {
this.setConnectionStatus(true);
this.master.connect(this.playerID, (data) => this.notifyClient(data));
this.requestSync();
}
disconnect() {
this.setConnectionStatus(false);
}
updateMatchID(id) {
this.matchID = id;
this.connect();
}
updatePlayerID(id) {
this.playerID = id;
this.connect();
}
updateCredentials(credentials) {
this.credentials = credentials;
this.connect();
}
}
/**
* Global map storing local master instances.
*/
const localMasters = new Map();
/**
* Create a local transport.
*/
function Local({ bots, persist, storageKey } = {}) {
return (transportOpts) => {
const { gameKey, game } = transportOpts;
let master;
const instance = localMasters.get(gameKey);
if (instance &&
instance.bots === bots &&
instance.storageKey === storageKey &&
instance.persist === persist) {
master = instance.master;
}
if (!master) {
master = new LocalMaster({ game, bots, persist, storageKey });
localMasters.set(gameKey, { master, bots, persist, storageKey });
}
return new LocalTransport({ master, ...transportOpts });
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const io = ioNamespace__default;
/**
* SocketIO
*
* Transport interface that interacts with the Master via socket.io.
*/
class SocketIOTransport extends Transport {
/**
* Creates a new Multiplayer instance.
* @param {object} socket - Override for unit tests.
* @param {object} socketOpts - Options to pass to socket.io.
* @param {object} store - Redux store
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} credentials - Authentication credentials
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
* @param {string} server - The game server in the form of 'hostname:port'. Defaults to the server serving the client if not provided.
*/
constructor({ socket, socketOpts, server, ...opts }) {
super(opts);
this.server = server;
this.socket = socket;
this.socketOpts = socketOpts;
}
sendAction(state, action) {
const args = [
action,
state._stateID,
this.matchID,
this.playerID,
];
this.socket.emit('update', ...args);
}
sendChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.socket.emit('chat', ...args);
}
connect() {
if (!this.socket) {
if (this.server) {
let server = this.server;
if (server.search(/^https?:\/\//) == -1) {
server = 'http://' + this.server;
}
if (server.slice(-1) != '/') {
// add trailing slash if not already present
server = server + '/';
}
this.socket = io(server + this.gameName, this.socketOpts);
}
else {
this.socket = io('/' + this.gameName, this.socketOpts);
}
}
// Called when another player makes a move and the
// master broadcasts the update as a patch to other clients (including
// this one).
this.socket.on('patch', (matchID, prevStateID, stateID, patch, deltalog) => {
this.notifyClient({
type: 'patch',
args: [matchID, prevStateID, stateID, patch, deltalog],
});
});
// Called when another player makes a move and the
// master broadcasts the update to other clients (including
// this one).
this.socket.on('update', (matchID, state, deltalog) => {
this.notifyClient({
type: 'update',
args: [matchID, state, deltalog],
});
});
// Called when the client first connects to the master
// and requests the current game state.
this.socket.on('sync', (matchID, syncInfo) => {
this.notifyClient({ type: 'sync', args: [matchID, syncInfo] });
});
// Called when new player joins the match or changes
// it's connection status
this.socket.on('matchData', (matchID, matchData) => {
this.notifyClient({ type: 'matchData', args: [matchID, matchData] });
});
this.socket.on('chat', (matchID, chatMessage) => {
this.notifyClient({ type: 'chat', args: [matchID, chatMessage] });
});
// Keep track of connection status.
this.socket.on('connect', () => {
// Initial sync to get game state.
this.requestSync();
this.setConnectionStatus(true);
});
this.socket.on('disconnect', () => {
this.setConnectionStatus(false);
});
}
disconnect() {
this.socket.close();
this.socket = null;
this.setConnectionStatus(false);
}
requestSync() {
if (this.socket) {
const args = [
this.matchID,
this.playerID,
this.credentials,
this.numPlayers,
];
this.socket.emit('sync', ...args);
}
}
updateMatchID(id) {
this.matchID = id;
this.requestSync();
}
updatePlayerID(id) {
this.playerID = id;
this.requestSync();
}
updateCredentials(credentials) {
this.credentials = credentials;
this.requestSync();
}
}
function SocketIO({ server, socketOpts } = {}) {
return (transportOpts) => new SocketIOTransport({
server,
socketOpts,
...transportOpts,
});
}
export { Client, Local, MCTSBot, RandomBot, Client$1 as ReactClient, Client$2 as ReactNativeClient, Simulate, SocketIO, Step, TurnOrder };
|
ajax/libs/material-ui/4.9.4/es/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(() => {
if (refA == null && refB == null) {
return null;
}
return refValue => {
setRef(refA, refValue);
setRef(refB, refValue);
};
}, [refA, refB]);
} |
ajax/libs/react-native-web/0.11.4/exports/ScrollView/ScrollViewBase.js | cdnjs/cdnjs | function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import debounce from 'debounce';
import StyleSheet from '../StyleSheet';
import View from '../View';
import ViewPropTypes from '../ViewPropTypes';
import React, { Component } from 'react';
import { bool, func, number } from 'prop-types';
var normalizeScrollEvent = function normalizeScrollEvent(e) {
return {
nativeEvent: {
contentOffset: {
get x() {
return e.target.scrollLeft;
},
get y() {
return e.target.scrollTop;
}
},
contentSize: {
get height() {
return e.target.scrollHeight;
},
get width() {
return e.target.scrollWidth;
}
},
layoutMeasurement: {
get height() {
return e.target.offsetHeight;
},
get width() {
return e.target.offsetWidth;
}
}
},
timeStamp: Date.now()
};
};
/**
* Encapsulates the Web-specific scroll throttling and disabling logic
*/
var ScrollViewBase =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(ScrollViewBase, _Component);
function ScrollViewBase() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _Component.call.apply(_Component, [this].concat(args)) || this;
_this._debouncedOnScrollEnd = debounce(_this._handleScrollEnd, 100);
_this._state = {
isScrolling: false,
scrollLastTick: 0
};
_this._createPreventableScrollHandler = function (handler) {
return function (e) {
if (_this.props.scrollEnabled) {
if (handler) {
handler(e);
}
} else {
// To disable scrolling in all browsers except Chrome
e.preventDefault();
}
};
};
_this._handleScroll = function (e) {
e.persist();
e.stopPropagation();
var scrollEventThrottle = _this.props.scrollEventThrottle; // A scroll happened, so the scroll bumps the debounce.
_this._debouncedOnScrollEnd(e);
if (_this._state.isScrolling) {
// Scroll last tick may have changed, check if we need to notify
if (_this._shouldEmitScrollEvent(_this._state.scrollLastTick, scrollEventThrottle)) {
_this._handleScrollTick(e);
}
} else {
// Weren't scrolling, so we must have just started
_this._handleScrollStart(e);
}
};
_this._setViewRef = function (element) {
_this._viewRef = element;
};
return _this;
}
var _proto = ScrollViewBase.prototype;
_proto.setNativeProps = function setNativeProps(props) {
if (this._viewRef) {
this._viewRef.setNativeProps(props);
}
};
_proto.render = function render() {
var _this$props = this.props,
scrollEnabled = _this$props.scrollEnabled,
style = _this$props.style,
alwaysBounceHorizontal = _this$props.alwaysBounceHorizontal,
alwaysBounceVertical = _this$props.alwaysBounceVertical,
automaticallyAdjustContentInsets = _this$props.automaticallyAdjustContentInsets,
bounces = _this$props.bounces,
bouncesZoom = _this$props.bouncesZoom,
canCancelContentTouches = _this$props.canCancelContentTouches,
centerContent = _this$props.centerContent,
contentInset = _this$props.contentInset,
contentInsetAdjustmentBehavior = _this$props.contentInsetAdjustmentBehavior,
contentOffset = _this$props.contentOffset,
decelerationRate = _this$props.decelerationRate,
directionalLockEnabled = _this$props.directionalLockEnabled,
endFillColor = _this$props.endFillColor,
indicatorStyle = _this$props.indicatorStyle,
keyboardShouldPersistTaps = _this$props.keyboardShouldPersistTaps,
maximumZoomScale = _this$props.maximumZoomScale,
minimumZoomScale = _this$props.minimumZoomScale,
onMomentumScrollBegin = _this$props.onMomentumScrollBegin,
onMomentumScrollEnd = _this$props.onMomentumScrollEnd,
onScrollBeginDrag = _this$props.onScrollBeginDrag,
onScrollEndDrag = _this$props.onScrollEndDrag,
overScrollMode = _this$props.overScrollMode,
pinchGestureEnabled = _this$props.pinchGestureEnabled,
removeClippedSubviews = _this$props.removeClippedSubviews,
scrollEventThrottle = _this$props.scrollEventThrottle,
scrollIndicatorInsets = _this$props.scrollIndicatorInsets,
scrollPerfTag = _this$props.scrollPerfTag,
scrollsToTop = _this$props.scrollsToTop,
showsHorizontalScrollIndicator = _this$props.showsHorizontalScrollIndicator,
showsVerticalScrollIndicator = _this$props.showsVerticalScrollIndicator,
snapToInterval = _this$props.snapToInterval,
snapToAlignment = _this$props.snapToAlignment,
zoomScale = _this$props.zoomScale,
other = _objectWithoutPropertiesLoose(_this$props, ["scrollEnabled", "style", "alwaysBounceHorizontal", "alwaysBounceVertical", "automaticallyAdjustContentInsets", "bounces", "bouncesZoom", "canCancelContentTouches", "centerContent", "contentInset", "contentInsetAdjustmentBehavior", "contentOffset", "decelerationRate", "directionalLockEnabled", "endFillColor", "indicatorStyle", "keyboardShouldPersistTaps", "maximumZoomScale", "minimumZoomScale", "onMomentumScrollBegin", "onMomentumScrollEnd", "onScrollBeginDrag", "onScrollEndDrag", "overScrollMode", "pinchGestureEnabled", "removeClippedSubviews", "scrollEventThrottle", "scrollIndicatorInsets", "scrollPerfTag", "scrollsToTop", "showsHorizontalScrollIndicator", "showsVerticalScrollIndicator", "snapToInterval", "snapToAlignment", "zoomScale"]);
var hideScrollbar = showsHorizontalScrollIndicator === false || showsVerticalScrollIndicator === false;
return React.createElement(View, _extends({}, other, {
onScroll: this._handleScroll,
onTouchMove: this._createPreventableScrollHandler(this.props.onTouchMove),
onWheel: this._createPreventableScrollHandler(this.props.onWheel),
ref: this._setViewRef,
style: [style, !scrollEnabled && styles.scrollDisabled, hideScrollbar && styles.hideScrollbar]
}));
};
_proto._handleScrollStart = function _handleScrollStart(e) {
this._state.isScrolling = true;
this._state.scrollLastTick = Date.now();
};
_proto._handleScrollTick = function _handleScrollTick(e) {
var onScroll = this.props.onScroll;
this._state.scrollLastTick = Date.now();
if (onScroll) {
onScroll(normalizeScrollEvent(e));
}
};
_proto._handleScrollEnd = function _handleScrollEnd(e) {
var onScroll = this.props.onScroll;
this._state.isScrolling = false;
if (onScroll) {
onScroll(normalizeScrollEvent(e));
}
};
_proto._shouldEmitScrollEvent = function _shouldEmitScrollEvent(lastTick, eventThrottle) {
var timeSinceLastTick = Date.now() - lastTick;
return eventThrottle > 0 && timeSinceLastTick >= eventThrottle;
};
return ScrollViewBase;
}(Component); // Chrome doesn't support e.preventDefault in this case; touch-action must be
// used to disable scrolling.
// https://developers.google.com/web/updates/2017/01/scrolling-intervention
ScrollViewBase.defaultProps = {
scrollEnabled: true,
scrollEventThrottle: 0
};
export { ScrollViewBase as default };
ScrollViewBase.propTypes = process.env.NODE_ENV !== "production" ? _objectSpread({}, ViewPropTypes, {
onMomentumScrollBegin: func,
onMomentumScrollEnd: func,
onScroll: func,
onScrollBeginDrag: func,
onScrollEndDrag: func,
onTouchMove: func,
onWheel: func,
removeClippedSubviews: bool,
scrollEnabled: bool,
scrollEventThrottle: number,
showsHorizontalScrollIndicator: bool,
showsVerticalScrollIndicator: bool
}) : {};
var styles = StyleSheet.create({
scrollDisabled: {
touchAction: 'none'
},
hideScrollbar: {
scrollbarWidth: 'none'
}
}); |
ajax/libs/material-ui/4.9.4/esm/internal/svg-icons/ArrowDownward.js | cdnjs/cdnjs | import React from 'react';
import createSvgIcon from './createSvgIcon';
/**
* @ignore - internal component.
*/
export default createSvgIcon(React.createElement("path", {
d: "M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z"
}), 'ArrowDownward'); |
ajax/libs/primereact/6.5.0-rc.2/tieredmenu/tieredmenu.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { DomHandler, classNames, ObjectUtils, ZIndexUtils, ConnectedOverlayScrollHandler } from 'primereact/utils';
import { Ripple } from 'primereact/ripple';
import { CSSTransition } from 'primereact/csstransition';
import OverlayEventBus from 'primereact/overlayeventbus';
import { Portal } from 'primereact/portal';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var propTypes = {exports: {}};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret$1;
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = ReactPropTypesSecret_1;
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} shim.isRequired = shim;
function getShim() {
return shim;
} // Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
propTypes.exports = factoryWithThrowingShims();
}
var PropTypes = propTypes.exports;
function _createSuper$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 TieredMenuSub = /*#__PURE__*/function (_Component) {
_inherits(TieredMenuSub, _Component);
var _super = _createSuper$1(TieredMenuSub);
function TieredMenuSub(props) {
var _this;
_classCallCheck(this, TieredMenuSub);
_this = _super.call(this, props);
_this.state = {
activeItem: null
};
_this.onLeafClick = _this.onLeafClick.bind(_assertThisInitialized(_this));
_this.onChildItemKeyDown = _this.onChildItemKeyDown.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(TieredMenuSub, [{
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.parentActive && !this.props.parentActive) {
this.setState({
activeItem: null
});
}
if (this.props.parentActive && !this.props.root) {
this.position();
}
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
if (!this.documentClickListener) {
this.documentClickListener = function (event) {
if (_this2.element && !_this2.element.contains(event.target)) {
_this2.setState({
activeItem: null
});
}
};
document.addEventListener('click', this.documentClickListener);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.documentClickListener) {
document.removeEventListener('click', this.documentClickListener);
this.documentClickListener = null;
}
}
}, {
key: "position",
value: function position() {
if (this.element) {
var parentItem = this.element.parentElement;
var containerOffset = DomHandler.getOffset(parentItem);
var viewport = DomHandler.getViewport();
var sublistWidth = this.element.offsetParent ? this.element.offsetWidth : DomHandler.getHiddenElementOuterWidth(this.element);
var itemOuterWidth = DomHandler.getOuterWidth(parentItem.children[0]);
if (parseInt(containerOffset.left, 10) + itemOuterWidth + sublistWidth > viewport.width - DomHandler.calculateScrollbarWidth()) {
DomHandler.addClass(this.element, 'p-submenu-list-flipped');
}
}
}
}, {
key: "onItemMouseEnter",
value: function onItemMouseEnter(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (this.props.root) {
if (this.state.activeItem || this.props.popup) {
this.setState({
activeItem: item
});
}
} else {
this.setState({
activeItem: item
});
}
}
}, {
key: "onItemClick",
value: function onItemClick(event, item) {
if (item.disabled) {
event.preventDefault();
return;
}
if (!item.url) {
event.preventDefault();
}
if (item.command) {
item.command({
originalEvent: event,
item: item
});
}
if (this.props.root) {
if (item.items) {
if (this.state.activeItem && item === this.state.activeItem) {
this.setState({
activeItem: null
});
} else {
this.setState({
activeItem: item
});
}
}
}
if (!item.items) {
this.onLeafClick();
}
}
}, {
key: "onItemKeyDown",
value: function onItemKeyDown(event, item) {
var listItem = event.currentTarget.parentElement;
switch (event.which) {
//down
case 40:
var nextItem = this.findNextItem(listItem);
if (nextItem) {
nextItem.children[0].focus();
}
event.preventDefault();
break;
//up
case 38:
var prevItem = this.findPrevItem(listItem);
if (prevItem) {
prevItem.children[0].focus();
}
event.preventDefault();
break;
//right
case 39:
if (item.items) {
this.setState({
activeItem: item
});
setTimeout(function () {
listItem.children[1].children[0].children[0].focus();
}, 50);
}
event.preventDefault();
break;
}
if (this.props.onKeyDown) {
this.props.onKeyDown(event, listItem);
}
}
}, {
key: "onChildItemKeyDown",
value: function onChildItemKeyDown(event, childListItem) {
//left
if (event.which === 37) {
this.setState({
activeItem: null
});
childListItem.parentElement.previousElementSibling.focus();
}
}
}, {
key: "findNextItem",
value: function findNextItem(item) {
var nextItem = item.nextElementSibling;
if (nextItem) return DomHandler.hasClass(nextItem, 'p-disabled') || !DomHandler.hasClass(nextItem, 'p-menuitem') ? this.findNextItem(nextItem) : nextItem;else return null;
}
}, {
key: "findPrevItem",
value: function findPrevItem(item) {
var prevItem = item.previousElementSibling;
if (prevItem) return DomHandler.hasClass(prevItem, 'p-disabled') || !DomHandler.hasClass(prevItem, 'p-menuitem') ? this.findPrevItem(prevItem) : prevItem;else return null;
}
}, {
key: "onLeafClick",
value: function onLeafClick() {
this.setState({
activeItem: null
});
if (this.props.onLeafClick) {
this.props.onLeafClick();
}
}
}, {
key: "renderSeparator",
value: function renderSeparator(index) {
return /*#__PURE__*/React.createElement("li", {
key: 'separator_' + index,
className: "p-menu-separator",
role: "separator"
});
}
}, {
key: "renderSubmenu",
value: function renderSubmenu(item) {
if (item.items) {
return /*#__PURE__*/React.createElement(TieredMenuSub, {
model: item.items,
onLeafClick: this.onLeafClick,
popup: this.props.popup,
onKeyDown: this.onChildItemKeyDown,
parentActive: item === this.state.activeItem
});
}
return null;
}
}, {
key: "renderMenuitem",
value: function renderMenuitem(item, index) {
var _this3 = this;
var active = this.state.activeItem === item;
var className = classNames('p-menuitem', {
'p-menuitem-active': active
}, item.className);
var linkClassName = classNames('p-menuitem-link', {
'p-disabled': item.disabled
});
var iconClassName = classNames('p-menuitem-icon', item.icon);
var submenuIconClassName = 'p-submenu-icon pi pi-angle-right';
var icon = item.icon && /*#__PURE__*/React.createElement("span", {
className: iconClassName
});
var label = item.label && /*#__PURE__*/React.createElement("span", {
className: "p-menuitem-text"
}, item.label);
var submenuIcon = item.items && /*#__PURE__*/React.createElement("span", {
className: submenuIconClassName
});
var submenu = this.renderSubmenu(item);
var content = /*#__PURE__*/React.createElement("a", {
href: item.url || '#',
className: linkClassName,
target: item.target,
role: "menuitem",
"aria-haspopup": item.items != null,
onClick: function onClick(event) {
return _this3.onItemClick(event, item);
},
onKeyDown: function onKeyDown(event) {
return _this3.onItemKeyDown(event, item);
},
"aria-disabled": item.disabled
}, icon, label, submenuIcon, /*#__PURE__*/React.createElement(Ripple, null));
if (item.template) {
var defaultContentOptions = {
onClick: function onClick(event) {
return _this3.onItemClick(event, item);
},
onKeyDown: function onKeyDown(event) {
return _this3.onItemKeyDown(event, item);
},
className: linkClassName,
labelClassName: 'p-menuitem-text',
iconClassName: iconClassName,
submenuIconClassName: submenuIconClassName,
element: content,
props: this.props,
active: active
};
content = ObjectUtils.getJSXElement(item.template, item, defaultContentOptions);
}
return /*#__PURE__*/React.createElement("li", {
key: item.label + '_' + index,
className: className,
style: item.style,
onMouseEnter: function onMouseEnter(event) {
return _this3.onItemMouseEnter(event, item);
},
role: "none"
}, content, submenu);
}
}, {
key: "renderItem",
value: function renderItem(item, index) {
if (item.separator) return this.renderSeparator(index);else return this.renderMenuitem(item, index);
}
}, {
key: "renderMenu",
value: function renderMenu() {
var _this4 = this;
if (this.props.model) {
return this.props.model.map(function (item, index) {
return _this4.renderItem(item, index);
});
}
return null;
}
}, {
key: "render",
value: function render() {
var _this5 = this;
var className = classNames({
'p-submenu-list': !this.props.root
});
var submenu = this.renderMenu();
return /*#__PURE__*/React.createElement("ul", {
ref: function ref(el) {
return _this5.element = el;
},
className: className,
role: this.props.root ? 'menubar' : 'menu',
"aria-orientation": "horizontal"
}, submenu);
}
}]);
return TieredMenuSub;
}(Component);
_defineProperty(TieredMenuSub, "defaultProps", {
model: null,
root: false,
className: null,
popup: false,
onLeafClick: null,
onKeyDown: null,
parentActive: false
});
_defineProperty(TieredMenuSub, "propTypes", {
model: PropTypes.any,
root: PropTypes.bool,
className: PropTypes.string,
popup: PropTypes.bool,
onLeafClick: PropTypes.func,
onKeyDown: PropTypes.func,
parentActive: PropTypes.bool
});
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 TieredMenu = /*#__PURE__*/function (_Component) {
_inherits(TieredMenu, _Component);
var _super = _createSuper(TieredMenu);
function TieredMenu(props) {
var _this;
_classCallCheck(this, TieredMenu);
_this = _super.call(this, props);
_this.state = {
visible: !props.popup
};
_this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this));
_this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this));
_this.onExit = _this.onExit.bind(_assertThisInitialized(_this));
_this.onExited = _this.onExited.bind(_assertThisInitialized(_this));
_this.onPanelClick = _this.onPanelClick.bind(_assertThisInitialized(_this));
_this.menuRef = /*#__PURE__*/React.createRef();
return _this;
}
_createClass(TieredMenu, [{
key: "onPanelClick",
value: function onPanelClick(event) {
if (this.props.popup) {
OverlayEventBus.emit('overlay-click', {
originalEvent: event,
target: this.target
});
}
}
}, {
key: "toggle",
value: function toggle(event) {
if (this.props.popup) {
if (this.state.visible) this.hide(event);else this.show(event);
}
}
}, {
key: "show",
value: function show(event) {
var _this2 = this;
this.target = event.currentTarget;
var currentEvent = event;
this.setState({
visible: true
}, function () {
if (_this2.props.onShow) {
_this2.props.onShow(currentEvent);
}
});
}
}, {
key: "hide",
value: function hide(event) {
var _this3 = this;
var currentEvent = event;
this.setState({
visible: false
}, function () {
if (_this3.props.onHide) {
_this3.props.onHide(currentEvent);
}
});
}
}, {
key: "onEnter",
value: function onEnter() {
if (this.props.autoZIndex) {
ZIndexUtils.set('menu', this.menuRef.current, this.props.baseZIndex);
}
DomHandler.absolutePosition(this.menuRef.current, this.target);
}
}, {
key: "onEntered",
value: function onEntered() {
this.bindDocumentListeners();
this.bindScrollListener();
}
}, {
key: "onExit",
value: function onExit() {
this.target = null;
this.unbindDocumentListeners();
this.unbindScrollListener();
}
}, {
key: "onExited",
value: function onExited() {
ZIndexUtils.clear(this.menuRef.current);
}
}, {
key: "bindDocumentListeners",
value: function bindDocumentListeners() {
this.bindDocumentClickListener();
this.bindDocumentResizeListener();
}
}, {
key: "unbindDocumentListeners",
value: function unbindDocumentListeners() {
this.unbindDocumentClickListener();
this.unbindDocumentResizeListener();
}
}, {
key: "bindDocumentClickListener",
value: function bindDocumentClickListener() {
var _this4 = this;
if (!this.documentClickListener) {
this.documentClickListener = function (event) {
if (_this4.props.popup && _this4.state.visible && _this4.menuRef.current && !_this4.menuRef.current.contains(event.target)) {
_this4.hide(event);
}
};
document.addEventListener('click', this.documentClickListener);
}
}
}, {
key: "unbindDocumentClickListener",
value: function unbindDocumentClickListener() {
if (this.documentClickListener) {
document.removeEventListener('click', this.documentClickListener);
this.documentClickListener = null;
}
}
}, {
key: "bindDocumentResizeListener",
value: function bindDocumentResizeListener() {
var _this5 = this;
if (!this.documentResizeListener) {
this.documentResizeListener = function (event) {
if (_this5.state.visible && !DomHandler.isAndroid()) {
_this5.hide(event);
}
};
window.addEventListener('resize', this.documentResizeListener);
}
}
}, {
key: "unbindDocumentResizeListener",
value: function unbindDocumentResizeListener() {
if (this.documentResizeListener) {
window.removeEventListener('resize', this.documentResizeListener);
this.documentResizeListener = null;
}
}
}, {
key: "bindScrollListener",
value: function bindScrollListener() {
var _this6 = this;
if (!this.scrollHandler) {
this.scrollHandler = new ConnectedOverlayScrollHandler(this.target, function (event) {
if (_this6.state.visible) {
_this6.hide(event);
}
});
}
this.scrollHandler.bindScrollListener();
}
}, {
key: "unbindScrollListener",
value: function unbindScrollListener() {
if (this.scrollHandler) {
this.scrollHandler.unbindScrollListener();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.unbindDocumentListeners();
if (this.scrollHandler) {
this.scrollHandler.destroy();
this.scrollHandler = null;
}
ZIndexUtils.clear(this.menuRef.current);
}
}, {
key: "renderElement",
value: function renderElement() {
var className = classNames('p-tieredmenu p-component', {
'p-tieredmenu-overlay': this.props.popup
}, this.props.className);
return /*#__PURE__*/React.createElement(CSSTransition, {
nodeRef: this.menuRef,
classNames: "p-connected-overlay",
in: this.state.visible,
timeout: {
enter: 120,
exit: 100
},
options: this.props.transitionOptions,
unmountOnExit: true,
onEnter: this.onEnter,
onEntered: this.onEntered,
onExit: this.onExit,
onExited: this.onExited
}, /*#__PURE__*/React.createElement("div", {
ref: this.menuRef,
id: this.props.id,
className: className,
style: this.props.style,
onClick: this.onPanelClick
}, /*#__PURE__*/React.createElement(TieredMenuSub, {
model: this.props.model,
root: true,
popup: this.props.popup
})));
}
}, {
key: "render",
value: function render() {
var element = this.renderElement();
return this.props.popup ? /*#__PURE__*/React.createElement(Portal, {
element: element,
appendTo: this.props.appendTo
}) : element;
}
}]);
return TieredMenu;
}(Component);
_defineProperty(TieredMenu, "defaultProps", {
id: null,
model: null,
popup: false,
style: null,
className: null,
autoZIndex: true,
baseZIndex: 0,
appendTo: null,
transitionOptions: null,
onShow: null,
onHide: null
});
_defineProperty(TieredMenu, "propTypes", {
id: PropTypes.string,
model: PropTypes.array,
popup: PropTypes.bool,
style: PropTypes.object,
className: PropTypes.string,
autoZIndex: PropTypes.bool,
baseZIndex: PropTypes.number,
appendTo: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
transitionOptions: PropTypes.object,
onShow: PropTypes.func,
onHide: PropTypes.func
});
export { TieredMenu };
|
ajax/libs/primereact/7.2.0/progressspinner/progressspinner.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { classNames } from 'primereact/utils';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var ProgressSpinner = /*#__PURE__*/function (_Component) {
_inherits(ProgressSpinner, _Component);
var _super = _createSuper(ProgressSpinner);
function ProgressSpinner() {
_classCallCheck(this, ProgressSpinner);
return _super.apply(this, arguments);
}
_createClass(ProgressSpinner, [{
key: "render",
value: function render() {
var spinnerClass = classNames('p-progress-spinner', this.props.className);
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
style: this.props.style,
className: spinnerClass,
role: "alert",
"aria-busy": true
}, /*#__PURE__*/React.createElement("svg", {
className: "p-progress-spinner-svg",
viewBox: "25 25 50 50",
style: {
animationDuration: this.props.animationDuration
}
}, /*#__PURE__*/React.createElement("circle", {
className: "p-progress-spinner-circle",
cx: "50",
cy: "50",
r: "20",
fill: this.props.fill,
strokeWidth: this.props.strokeWidth,
strokeMiterlimit: "10"
})));
}
}]);
return ProgressSpinner;
}(Component);
_defineProperty(ProgressSpinner, "defaultProps", {
id: null,
style: null,
className: null,
strokeWidth: "2",
fill: "none",
animationDuration: "2s"
});
export { ProgressSpinner };
|
ajax/libs/material-ui/4.9.4/esm/internal/svg-icons/createSvgIcon.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import React from 'react';
import SvgIcon from '../../SvgIcon';
export default function createSvgIcon(path, displayName) {
var Component = React.memo(React.forwardRef(function (props, ref) {
return React.createElement(SvgIcon, _extends({}, props, {
ref: ref
}), path);
}));
if (process.env.NODE_ENV !== 'production') {
Component.displayName = "".concat(displayName, "Icon");
}
Component.muiName = SvgIcon.muiName;
return Component;
} |
ajax/libs/material-ui/4.9.4/es/Input/Input.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { refType } from '@material-ui/utils';
import InputBase from '../InputBase';
import withStyles from '../styles/withStyles';
export const styles = theme => {
const light = theme.palette.type === 'light';
const bottomLineColor = light ? 'rgba(0, 0, 0, 0.42)' : 'rgba(255, 255, 255, 0.7)';
return {
/* Styles applied to the root element. */
root: {
position: 'relative'
},
/* Styles applied to the root element if the component is a descendant of `FormControl`. */
formControl: {
'label + &': {
marginTop: 16
}
},
/* Styles applied to the root element if the component is focused. */
focused: {},
/* Styles applied to the root element if `disabled={true}`. */
disabled: {},
/* Styles applied to the root element if color secondary. */
colorSecondary: {
'&$underline:after': {
borderBottomColor: theme.palette.secondary.main
}
},
/* Styles applied to the root element if `disableUnderline={false}`. */
underline: {
'&:after': {
borderBottom: `2px solid ${theme.palette.primary.main}`,
left: 0,
bottom: 0,
// Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242
content: '""',
position: 'absolute',
right: 0,
transform: 'scaleX(0)',
transition: theme.transitions.create('transform', {
duration: theme.transitions.duration.shorter,
easing: theme.transitions.easing.easeOut
}),
pointerEvents: 'none' // Transparent to the hover style.
},
'&$focused:after': {
transform: 'scaleX(1)'
},
'&$error:after': {
borderBottomColor: theme.palette.error.main,
transform: 'scaleX(1)' // error is always underlined in red
},
'&:before': {
borderBottom: `1px solid ${bottomLineColor}`,
left: 0,
bottom: 0,
// Doing the other way around crash on IE 11 "''" https://github.com/cssinjs/jss/issues/242
content: '"\\00a0"',
position: 'absolute',
right: 0,
transition: theme.transitions.create('border-bottom-color', {
duration: theme.transitions.duration.shorter
}),
pointerEvents: 'none' // Transparent to the hover style.
},
'&:hover:not($disabled):before': {
borderBottom: `2px solid ${theme.palette.text.primary}`,
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
borderBottom: `1px solid ${bottomLineColor}`
}
},
'&$disabled:before': {
borderBottomStyle: 'dotted'
}
},
/* Pseudo-class applied to the root element if `error={true}`. */
error: {},
/* Styles applied to the `input` element if `margin="dense"`. */
marginDense: {},
/* Styles applied to the root element if `multiline={true}`. */
multiline: {},
/* Styles applied to the root element if `fullWidth={true}`. */
fullWidth: {},
/* Styles applied to the `input` element. */
input: {},
/* Styles applied to the `input` element if `margin="dense"`. */
inputMarginDense: {},
/* Styles applied to the `input` element if `multiline={true}`. */
inputMultiline: {},
/* Styles applied to the `input` element if `type="search"`. */
inputTypeSearch: {}
};
};
const Input = React.forwardRef(function Input(props, ref) {
const {
disableUnderline,
classes,
fullWidth = false,
inputComponent = 'input',
multiline = false,
type = 'text'
} = props,
other = _objectWithoutPropertiesLoose(props, ["disableUnderline", "classes", "fullWidth", "inputComponent", "multiline", "type"]);
return React.createElement(InputBase, _extends({
classes: _extends({}, classes, {
root: clsx(classes.root, !disableUnderline && classes.underline),
underline: null
}),
fullWidth: fullWidth,
inputComponent: inputComponent,
multiline: multiline,
ref: ref,
type: type
}, other));
});
process.env.NODE_ENV !== "production" ? Input.propTypes = {
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete: PropTypes.string,
/**
* If `true`, the `input` element will be focused during the first mount.
*/
autoFocus: PropTypes.bool,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* The CSS class name of the wrapper element.
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['primary', 'secondary']),
/**
* The default `input` element value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the `input` element will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the input will not have an underline.
*/
disableUnderline: PropTypes.bool,
/**
* End `InputAdornment` for this component.
*/
endAdornment: PropTypes.node,
/**
* If `true`, the input will indicate an error. This is normally obtained via context from
* FormControl.
*/
error: PropTypes.bool,
/**
* If `true`, the input will take up the full width of its container.
*/
fullWidth: PropTypes.bool,
/**
* The id of the `input` element.
*/
id: PropTypes.string,
/**
* The component used for the native input.
* Either a string to use a DOM element or a component.
*/
inputComponent: PropTypes.elementType,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
*/
inputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* If `dense`, will adjust vertical spacing. This is normally obtained via context from
* FormControl.
*/
margin: PropTypes.oneOf(['dense', 'none']),
/**
* If `true`, a textarea element will be rendered.
*/
multiline: PropTypes.bool,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
/**
* Callback fired when the value is changed.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* The short hint displayed in the input before the user enters a value.
*/
placeholder: PropTypes.string,
/**
* It prevents the user from changing the value of the field
* (not from interacting with the field).
*/
readOnly: PropTypes.bool,
/**
* If `true`, the `input` element will be required.
*/
required: PropTypes.bool,
/**
* Number of rows to display when multiline option is set to true.
*/
rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Maximum number of rows to display when multiline option is set to true.
*/
rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Start `InputAdornment` for this component.
*/
startAdornment: PropTypes.node,
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
*/
type: PropTypes.string,
/**
* The value of the `input` element, required for a controlled component.
*/
value: PropTypes.any
} : void 0;
Input.muiName = 'Input';
export default withStyles(styles, {
name: 'MuiInput'
})(Input); |
ajax/libs/material-ui/4.9.2/esm/Fade/Fade.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 { Transition } from 'react-transition-group';
import { duration } from '../styles/transitions';
import useTheme from '../styles/useTheme';
import { reflow, getTransitionProps } from '../transitions/utils';
import useForkRef from '../utils/useForkRef';
var styles = {
entering: {
opacity: 1
},
entered: {
opacity: 1
}
};
var defaultTimeout = {
enter: duration.enteringScreen,
exit: duration.leavingScreen
};
/**
* The Fade transition is used by the [Modal](/components/modal/) component.
* It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
*/
var Fade = React.forwardRef(function Fade(props, ref) {
var children = props.children,
inProp = props.in,
onEnter = props.onEnter,
onExit = props.onExit,
style = props.style,
_props$timeout = props.timeout,
timeout = _props$timeout === void 0 ? defaultTimeout : _props$timeout,
other = _objectWithoutProperties(props, ["children", "in", "onEnter", "onExit", "style", "timeout"]);
var theme = useTheme();
var handleRef = useForkRef(children.ref, ref);
var handleEnter = function handleEnter(node, isAppearing) {
reflow(node); // So the animation always start from the start.
var transitionProps = getTransitionProps({
style: style,
timeout: timeout
}, {
mode: 'enter'
});
node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);
node.style.transition = theme.transitions.create('opacity', transitionProps);
if (onEnter) {
onEnter(node, isAppearing);
}
};
var handleExit = function handleExit(node) {
var transitionProps = getTransitionProps({
style: style,
timeout: timeout
}, {
mode: 'exit'
});
node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);
node.style.transition = theme.transitions.create('opacity', transitionProps);
if (onExit) {
onExit(node);
}
};
return React.createElement(Transition, _extends({
appear: true,
in: inProp,
onEnter: handleEnter,
onExit: handleExit,
timeout: timeout
}, other), function (state, childProps) {
return React.cloneElement(children, _extends({
style: _extends({
opacity: 0,
visibility: state === 'exited' && !inProp ? 'hidden' : undefined
}, styles[state], {}, style, {}, children.props.style),
ref: handleRef
}, childProps));
});
});
process.env.NODE_ENV !== "production" ? Fade.propTypes = {
/**
* A single child content element.
*/
children: PropTypes.element,
/**
* If `true`, the component will transition in.
*/
in: PropTypes.bool,
/**
* @ignore
*/
onEnter: PropTypes.func,
/**
* @ignore
*/
onExit: PropTypes.func,
/**
* @ignore
*/
style: PropTypes.object,
/**
* The duration for the transition, in milliseconds.
* You may specify a single timeout for all transitions, or individually with an object.
*/
timeout: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
enter: PropTypes.number,
exit: PropTypes.number
})])
} : void 0;
export default Fade; |
ajax/libs/primereact/6.5.1/csstransition/csstransition.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { CSSTransition as CSSTransition$1 } from 'react-transition-group';
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var CSSTransition = /*#__PURE__*/function (_Component) {
_inherits(CSSTransition, _Component);
var _super = _createSuper(CSSTransition);
function CSSTransition(props) {
var _this;
_classCallCheck(this, CSSTransition);
_this = _super.call(this, props);
_this.onEnter = _this.onEnter.bind(_assertThisInitialized(_this));
_this.onEntering = _this.onEntering.bind(_assertThisInitialized(_this));
_this.onEntered = _this.onEntered.bind(_assertThisInitialized(_this));
_this.onExit = _this.onExit.bind(_assertThisInitialized(_this));
_this.onExiting = _this.onExiting.bind(_assertThisInitialized(_this));
_this.onExited = _this.onExited.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(CSSTransition, [{
key: "onEnter",
value: function onEnter(node, isAppearing) {
this.props.onEnter && this.props.onEnter(node, isAppearing); // component
this.props.options && this.props.options.onEnter && this.props.options.onEnter(node, isAppearing); // user option
}
}, {
key: "onEntering",
value: function onEntering(node, isAppearing) {
this.props.onEntering && this.props.onEntering(node, isAppearing); // component
this.props.options && this.props.options.onEntering && this.props.options.onEntering(node, isAppearing); // user option
}
}, {
key: "onEntered",
value: function onEntered(node, isAppearing) {
this.props.onEntered && this.props.onEntered(node, isAppearing); // component
this.props.options && this.props.options.onEntered && this.props.options.onEntered(node, isAppearing); // user option
}
}, {
key: "onExit",
value: function onExit(node) {
this.props.onExit && this.props.onExit(node); // component
this.props.options && this.props.options.onExit && this.props.options.onExit(node); // user option
}
}, {
key: "onExiting",
value: function onExiting(node) {
this.props.onExiting && this.props.onExiting(node); // component
this.props.options && this.props.options.onExiting && this.props.options.onExiting(node); // user option
}
}, {
key: "onExited",
value: function onExited(node) {
this.props.onExited && this.props.onExited(node); // component
this.props.options && this.props.options.onExited && this.props.options.onExited(node); // user option
}
}, {
key: "render",
value: function render() {
var immutableProps = {
nodeRef: this.props.nodeRef,
in: this.props.in,
onEnter: this.onEnter,
onEntering: this.onEntering,
onEntered: this.onEntered,
onExit: this.onExit,
onExiting: this.onExiting,
onExited: this.onExited
};
var mutableProps = {
classNames: this.props.classNames,
timeout: this.props.timeout,
unmountOnExit: this.props.unmountOnExit
};
var props = _objectSpread(_objectSpread(_objectSpread({}, mutableProps), this.props.options || {}), immutableProps);
return /*#__PURE__*/React.createElement(CSSTransition$1, props, this.props.children);
}
}]);
return CSSTransition;
}(Component);
export { CSSTransition };
|
ajax/libs/material-ui/4.9.14/es/RootRef/RootRef.js | cdnjs/cdnjs | import * as React from 'react';
import * as ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import { exactProp, refType } from '@material-ui/utils';
import setRef from '../utils/setRef';
/**
* ⚠️⚠️⚠️
* If you want the DOM element of a Material-UI component check out
* [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element)
* first.
*
* This component uses `findDOMNode` which is deprecated in React.StrictMode.
*
* Helper component to allow attaching a ref to a
* wrapped element to access the underlying DOM element.
*
* It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801.
* For example:
* ```jsx
* import React from 'react';
* import RootRef from '@material-ui/core/RootRef';
*
* function MyComponent() {
* const domRef = React.useRef();
*
* React.useEffect(() => {
* console.log(domRef.current); // DOM node
* }, []);
*
* return (
* <RootRef rootRef={domRef}>
* <SomeChildComponent />
* </RootRef>
* );
* }
* ```
*/
class RootRef extends React.Component {
componentDidMount() {
this.ref = ReactDOM.findDOMNode(this);
setRef(this.props.rootRef, this.ref);
}
componentDidUpdate(prevProps) {
const ref = ReactDOM.findDOMNode(this);
if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) {
if (prevProps.rootRef !== this.props.rootRef) {
setRef(prevProps.rootRef, null);
}
this.ref = ref;
setRef(this.props.rootRef, this.ref);
}
}
componentWillUnmount() {
this.ref = null;
setRef(this.props.rootRef, null);
}
render() {
return this.props.children;
}
}
process.env.NODE_ENV !== "production" ? RootRef.propTypes = {
/**
* The wrapped element.
*/
children: PropTypes.element.isRequired,
/**
* A ref that points to the first DOM node of the wrapped element.
*/
rootRef: refType.isRequired
} : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== "production" ? RootRef.propTypes = exactProp(RootRef.propTypes) : void 0;
}
export default RootRef; |
ajax/libs/primereact/6.5.1/timeline/timeline.esm.js | cdnjs/cdnjs | import React, { Component } from 'react';
import { ObjectUtils, classNames } from 'primereact/core';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
var Timeline = /*#__PURE__*/function (_Component) {
_inherits(Timeline, _Component);
var _super = _createSuper(Timeline);
function Timeline() {
_classCallCheck(this, Timeline);
return _super.apply(this, arguments);
}
_createClass(Timeline, [{
key: "getKey",
value: function getKey(item, index) {
return this.props.dataKey ? ObjectUtils.resolveFieldData(item, this.props.dataKey) : "pr_id__".concat(index);
}
}, {
key: "renderEvents",
value: function renderEvents() {
var _this = this;
return this.props.value && this.props.value.map(function (item, index) {
var opposite = ObjectUtils.getJSXElement(_this.props.opposite, item, index);
var marker = ObjectUtils.getJSXElement(_this.props.marker, item, index) || /*#__PURE__*/React.createElement("div", {
className: "p-timeline-event-marker"
});
var connector = index !== _this.props.value.length - 1 && /*#__PURE__*/React.createElement("div", {
className: "p-timeline-event-connector"
});
var content = ObjectUtils.getJSXElement(_this.props.content, item, index);
return /*#__PURE__*/React.createElement("div", {
key: _this.getKey(item, index),
className: "p-timeline-event"
}, /*#__PURE__*/React.createElement("div", {
className: "p-timeline-event-opposite"
}, opposite), /*#__PURE__*/React.createElement("div", {
className: "p-timeline-event-separator"
}, marker, connector), /*#__PURE__*/React.createElement("div", {
className: "p-timeline-event-content"
}, content));
});
}
}, {
key: "render",
value: function render() {
var _classNames;
var containerClassName = classNames('p-timeline p-component', (_classNames = {}, _defineProperty(_classNames, "p-timeline-".concat(this.props.align), true), _defineProperty(_classNames, "p-timeline-".concat(this.props.layout), true), _classNames), this.props.className);
var events = this.renderEvents();
return /*#__PURE__*/React.createElement("div", {
id: this.props.id,
className: containerClassName,
style: this.props.style
}, events);
}
}]);
return Timeline;
}(Component);
_defineProperty(Timeline, "defaultProps", {
id: null,
value: null,
align: 'left',
layout: 'vertical',
dataKey: null,
className: null,
style: null,
opposite: null,
marker: null,
content: null
});
export { Timeline };
|
ajax/libs/material-ui/4.9.4/esm/SvgIcon/SvgIcon.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: {
userSelect: 'none',
width: '1em',
height: '1em',
display: 'inline-block',
fill: 'currentColor',
flexShrink: 0,
fontSize: theme.typography.pxToRem(24),
transition: theme.transitions.create('fill', {
duration: theme.transitions.duration.shorter
})
},
/* 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="action"`. */
colorAction: {
color: theme.palette.action.active
},
/* Styles applied to the root element if `color="error"`. */
colorError: {
color: theme.palette.error.main
},
/* Styles applied to the root element if `color="disabled"`. */
colorDisabled: {
color: theme.palette.action.disabled
},
/* Styles applied to the root element if `fontSize="inherit"`. */
fontSizeInherit: {
fontSize: 'inherit'
},
/* Styles applied to the root element if `fontSize="small"`. */
fontSizeSmall: {
fontSize: theme.typography.pxToRem(20)
},
/* Styles applied to the root element if `fontSize="large"`. */
fontSizeLarge: {
fontSize: theme.typography.pxToRem(35)
}
};
};
var SvgIcon = React.forwardRef(function SvgIcon(props, ref) {
var children = props.children,
classes = props.classes,
className = props.className,
_props$color = props.color,
color = _props$color === void 0 ? 'inherit' : _props$color,
_props$component = props.component,
Component = _props$component === void 0 ? 'svg' : _props$component,
_props$fontSize = props.fontSize,
fontSize = _props$fontSize === void 0 ? 'default' : _props$fontSize,
htmlColor = props.htmlColor,
titleAccess = props.titleAccess,
_props$viewBox = props.viewBox,
viewBox = _props$viewBox === void 0 ? '0 0 24 24' : _props$viewBox,
other = _objectWithoutProperties(props, ["children", "classes", "className", "color", "component", "fontSize", "htmlColor", "titleAccess", "viewBox"]);
return React.createElement(Component, _extends({
className: clsx(classes.root, className, color !== 'inherit' && classes["color".concat(capitalize(color))], fontSize !== 'default' && classes["fontSize".concat(capitalize(fontSize))]),
focusable: "false",
viewBox: viewBox,
color: htmlColor,
"aria-hidden": titleAccess ? undefined : 'true',
role: titleAccess ? 'img' : 'presentation',
ref: ref
}, other), children, titleAccess ? React.createElement("title", null, titleAccess) : null);
});
process.env.NODE_ENV !== "production" ? SvgIcon.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* Node passed into the SVG element.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* You can use the `htmlColor` prop to apply a color attribute to the SVG element.
*/
color: PropTypes.oneOf(['action', 'disabled', 'error', 'inherit', 'primary', 'secondary']),
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: PropTypes.elementType,
/**
* The fontSize applied to the icon. Defaults to 24px, but can be configure to inherit font size.
*/
fontSize: PropTypes.oneOf(['default', 'inherit', 'large', 'small']),
/**
* Applies a color attribute to the SVG element.
*/
htmlColor: PropTypes.string,
/**
* The shape-rendering attribute. The behavior of the different options is described on the
* [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering).
* If you are having issues with blurry icons you should investigate this property.
*/
shapeRendering: PropTypes.string,
/**
* Provides a human-readable title for the element that contains it.
* https://www.w3.org/TR/SVG-access/#Equivalent
*/
titleAccess: PropTypes.string,
/**
* Allows you to redefine what the coordinates without units mean inside an SVG element.
* For example, if the SVG element is 500 (width) by 200 (height),
* and you pass viewBox="0 0 50 20",
* this means that the coordinates inside the SVG will go from the top left corner (0,0)
* to bottom right (50,20) and each unit will be worth 10px.
*/
viewBox: PropTypes.string
} : void 0;
SvgIcon.muiName = 'SvgIcon';
export default withStyles(styles, {
name: 'MuiSvgIcon'
})(SvgIcon); |
ajax/libs/react-native-web/0.0.0-e886427e3/exports/createElement/index.js | cdnjs/cdnjs | /**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import AccessibilityUtil from '../../modules/AccessibilityUtil';
import createDOMProps from '../../modules/createDOMProps';
import React from 'react';
var createElement = function createElement(component, props) {
// Use equivalent platform elements where possible.
var accessibilityComponent;
if (component && component.constructor === String) {
accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props);
}
var Component = accessibilityComponent || component;
var domProps = createDOMProps(Component, props);
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
children[_key - 2] = arguments[_key];
}
return /*#__PURE__*/React.createElement.apply(React, [Component, domProps].concat(children));
};
export default createElement; |
ajax/libs/react-instantsearch/6.0.0/Connectors.js | cdnjs/cdnjs | /*! React InstantSearch 6.0.0 | © Algolia, inc. | https://github.com/algolia/react-instantsearch */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
(global = global || self, factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Connectors = {}), global.React));
}(this, function (exports, React) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _typeof2(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof2 = function _typeof2(obj) { return typeof obj; }; } else { _typeof2 = function _typeof2(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof2(obj); }
function _typeof(obj) {
if (typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol") {
_typeof = function _typeof(obj) {
return _typeof2(obj);
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof2(obj);
};
}
return _typeof(obj);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
var isArray = Array.isArray;
var keyList = Object.keys;
var hasProp = Object.prototype.hasOwnProperty;
var fastDeepEqual = function equal(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
var arrA = isArray(a)
, arrB = isArray(b)
, i
, length
, key;
if (arrA && arrB) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;)
if (!equal(a[i], b[i])) return false;
return true;
}
if (arrA != arrB) return false;
var dateA = a instanceof Date
, dateB = b instanceof Date;
if (dateA != dateB) return false;
if (dateA && dateB) return a.getTime() == b.getTime();
var regexpA = a instanceof RegExp
, regexpB = b instanceof RegExp;
if (regexpA != regexpB) return false;
if (regexpA && regexpB) return a.toString() == b.toString();
var keys = keyList(a);
length = keys.length;
if (length !== keyList(b).length)
return false;
for (i = length; i-- !== 0;)
if (!hasProp.call(b, keys[i])) return false;
for (i = length; i-- !== 0;) {
key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
return a!==a && b!==b;
};
var shallowEqual = function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
} // Test for A's keys different from B.
var hasOwn = Object.prototype.hasOwnProperty;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
};
var getDisplayName = function getDisplayName(Component) {
return Component.displayName || Component.name || 'UnknownComponent';
};
var isPlainObject = function isPlainObject(value) {
return _typeof(value) === 'object' && value !== null && !Array.isArray(value);
};
var removeEmptyKey = function removeEmptyKey(obj) {
Object.keys(obj).forEach(function (key) {
var value = obj[key];
if (!isPlainObject(value)) {
return;
}
if (!objectHasKeys(value)) {
delete obj[key];
} else {
removeEmptyKey(value);
}
});
return obj;
};
function addAbsolutePositions(hits, hitsPerPage, page) {
return hits.map(function (hit, index) {
return _objectSpread({}, hit, {
__position: hitsPerPage * page + index + 1
});
});
}
function addQueryID(hits, queryID) {
if (!queryID) {
return hits;
}
return hits.map(function (hit) {
return _objectSpread({}, hit, {
__queryID: queryID
});
});
}
function find(array, comparator) {
if (!Array.isArray(array)) {
return undefined;
}
for (var i = 0; i < array.length; i++) {
if (comparator(array[i])) {
return array[i];
}
}
return undefined;
}
function objectHasKeys(object) {
return object && Object.keys(object).length > 0;
} // https://github.com/babel/babel/blob/3aaafae053fa75febb3aa45d45b6f00646e30ba4/packages/babel-helpers/src/helpers.js#L604-L620
function omit(source, excluded) {
if (source === null || source === undefined) {
return {};
}
var target = {};
var sourceKeys = Object.keys(source);
for (var i = 0; i < sourceKeys.length; i++) {
var _key = sourceKeys[i];
if (excluded.indexOf(_key) >= 0) {
// eslint-disable-next-line no-continue
continue;
}
target[_key] = source[_key];
}
return target;
}
/**
* Retrieve the value at a path of the object:
*
* @example
* getPropertyByPath(
* { test: { this: { function: [{ now: { everyone: true } }] } } },
* 'test.this.function[0].now.everyone'
* ); // true
*
* getPropertyByPath(
* { test: { this: { function: [{ now: { everyone: true } }] } } },
* ['test', 'this', 'function', 0, 'now', 'everyone']
* ); // true
*
* @param object Source object to query
* @param path either an array of properties, or a string form of the properties, separated by .
*/
var getPropertyByPath = function getPropertyByPath(object, path) {
return (Array.isArray(path) ? path : path.replace(/\[(\d+)]/g, '.$1').split('.')).reduce(function (current, key) {
return current ? current[key] : undefined;
}, object);
};
var _createContext = React.createContext({
onInternalStateUpdate: function onInternalStateUpdate() {
return undefined;
},
createHrefForState: function createHrefForState() {
return '#';
},
onSearchForFacetValues: function onSearchForFacetValues() {
return undefined;
},
onSearchStateChange: function onSearchStateChange() {
return undefined;
},
onSearchParameters: function onSearchParameters() {
return undefined;
},
store: {},
widgetsManager: {},
mainTargetedIndex: ''
}),
InstantSearchConsumer = _createContext.Consumer,
InstantSearchProvider = _createContext.Provider;
var _createContext2 = React.createContext(undefined),
IndexConsumer = _createContext2.Consumer,
IndexProvider = _createContext2.Provider;
/**
* Connectors are the HOC used to transform React components
* into InstantSearch widgets.
* In order to simplify the construction of such connectors
* `createConnector` takes a description and transform it into
* a connector.
* @param {ConnectorDescription} connectorDesc the description of the connector
* @return {Connector} a function that wraps a component into
* an instantsearch connected one.
*/
function createConnectorWithoutContext(connectorDesc) {
if (!connectorDesc.displayName) {
throw new Error('`createConnector` requires you to provide a `displayName` property.');
}
var isWidget = typeof connectorDesc.getSearchParameters === 'function' || typeof connectorDesc.getMetadata === 'function' || typeof connectorDesc.transitionState === 'function';
return function (Composed) {
var Connector =
/*#__PURE__*/
function (_Component) {
_inherits(Connector, _Component);
function Connector(props) {
var _this;
_classCallCheck(this, Connector);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Connector).call(this, props));
_defineProperty(_assertThisInitialized(_this), "unsubscribe", void 0);
_defineProperty(_assertThisInitialized(_this), "unregisterWidget", void 0);
_defineProperty(_assertThisInitialized(_this), "isUnmounting", false);
_defineProperty(_assertThisInitialized(_this), "state", {
providedProps: _this.getProvidedProps(_this.props)
});
_defineProperty(_assertThisInitialized(_this), "refine", function () {
var _ref;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this.props.contextValue.onInternalStateUpdate( // refine will always be defined here because the prop is only given conditionally
(_ref = connectorDesc.refine).call.apply(_ref, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args)));
});
_defineProperty(_assertThisInitialized(_this), "createURL", function () {
var _ref2;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _this.props.contextValue.createHrefForState( // refine will always be defined here because the prop is only given conditionally
(_ref2 = connectorDesc.refine).call.apply(_ref2, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args)));
});
_defineProperty(_assertThisInitialized(_this), "searchForFacetValues", function () {
var _ref3;
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
_this.props.contextValue.onSearchForFacetValues( // searchForFacetValues will always be defined here because the prop is only given conditionally
(_ref3 = connectorDesc.searchForFacetValues).call.apply(_ref3, [_assertThisInitialized(_this), _this.props, _this.props.contextValue.store.getState().widgets].concat(args)));
});
if (connectorDesc.getSearchParameters) {
_this.props.contextValue.onSearchParameters(connectorDesc.getSearchParameters.bind(_assertThisInitialized(_this)), {
ais: _this.props.contextValue,
multiIndexContext: _this.props.indexContextValue
}, _this.props);
}
return _this;
}
_createClass(Connector, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
this.unsubscribe = this.props.contextValue.store.subscribe(function () {
if (!_this2.isUnmounting) {
_this2.setState({
providedProps: _this2.getProvidedProps(_this2.props)
});
}
});
if (isWidget) {
this.unregisterWidget = this.props.contextValue.widgetsManager.registerWidget(this);
}
}
}, {
key: "shouldComponentUpdate",
value: function shouldComponentUpdate(nextProps, nextState) {
if (typeof connectorDesc.shouldComponentUpdate === 'function') {
return connectorDesc.shouldComponentUpdate.call(this, this.props, nextProps, this.state, nextState);
}
var propsEqual = shallowEqual(this.props, nextProps);
if (this.state.providedProps === null || nextState.providedProps === null) {
if (this.state.providedProps === nextState.providedProps) {
return !propsEqual;
}
return true;
}
return !propsEqual || !shallowEqual(this.state.providedProps, nextState.providedProps);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (!fastDeepEqual(prevProps, this.props)) {
this.setState({
providedProps: this.getProvidedProps(this.props)
});
if (isWidget) {
this.props.contextValue.widgetsManager.update();
if (typeof connectorDesc.transitionState === 'function') {
this.props.contextValue.onSearchStateChange(connectorDesc.transitionState.call(this, this.props, this.props.contextValue.store.getState().widgets, this.props.contextValue.store.getState().widgets));
}
}
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.isUnmounting = true;
if (this.unsubscribe) {
this.unsubscribe();
}
if (this.unregisterWidget) {
this.unregisterWidget();
if (typeof connectorDesc.cleanUp === 'function') {
var nextState = connectorDesc.cleanUp.call(this, this.props, this.props.contextValue.store.getState().widgets);
this.props.contextValue.store.setState(_objectSpread({}, this.props.contextValue.store.getState(), {
widgets: nextState
}));
this.props.contextValue.onSearchStateChange(removeEmptyKey(nextState));
}
}
}
}, {
key: "getProvidedProps",
value: function getProvidedProps(props) {
var _this$props$contextVa = this.props.contextValue.store.getState(),
widgets = _this$props$contextVa.widgets,
results = _this$props$contextVa.results,
resultsFacetValues = _this$props$contextVa.resultsFacetValues,
searching = _this$props$contextVa.searching,
searchingForFacetValues = _this$props$contextVa.searchingForFacetValues,
isSearchStalled = _this$props$contextVa.isSearchStalled,
metadata = _this$props$contextVa.metadata,
error = _this$props$contextVa.error;
var searchResults = {
results: results,
searching: searching,
searchingForFacetValues: searchingForFacetValues,
isSearchStalled: isSearchStalled,
error: error
};
return connectorDesc.getProvidedProps.call(this, props, widgets, searchResults, metadata, // @MAJOR: move this attribute on the `searchResults` it doesn't
// makes sense to have it into a separate argument. The search
// flags are on the object why not the results?
resultsFacetValues);
}
}, {
key: "getSearchParameters",
value: function getSearchParameters(searchParameters) {
if (typeof connectorDesc.getSearchParameters === 'function') {
return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.props.contextValue.store.getState().widgets);
}
return null;
}
}, {
key: "getMetadata",
value: function getMetadata(nextWidgetsState) {
if (typeof connectorDesc.getMetadata === 'function') {
return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState);
}
return {};
}
}, {
key: "transitionState",
value: function transitionState(prevWidgetsState, nextWidgetsState) {
if (typeof connectorDesc.transitionState === 'function') {
return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState);
}
return nextWidgetsState;
}
}, {
key: "render",
value: function render() {
var _this$props = this.props,
contextValue = _this$props.contextValue,
props = _objectWithoutProperties(_this$props, ["contextValue"]);
var providedProps = this.state.providedProps;
if (providedProps === null) {
return null;
}
var refineProps = typeof connectorDesc.refine === 'function' ? {
refine: this.refine,
createURL: this.createURL
} : {};
var searchForFacetValuesProps = typeof connectorDesc.searchForFacetValues === 'function' ? {
searchForItems: this.searchForFacetValues
} : {};
return React__default.createElement(Composed, _extends({}, props, providedProps, refineProps, searchForFacetValuesProps));
}
}]);
return Connector;
}(React.Component);
_defineProperty(Connector, "displayName", "".concat(connectorDesc.displayName, "(").concat(getDisplayName(Composed), ")"));
_defineProperty(Connector, "propTypes", connectorDesc.propTypes);
_defineProperty(Connector, "defaultProps", connectorDesc.defaultProps);
return Connector;
};
}
var createConnectorWithContext = function createConnectorWithContext(connectorDesc) {
return function (Composed) {
var Connector = createConnectorWithoutContext(connectorDesc)(Composed);
var ConnectorWrapper = function ConnectorWrapper(props) {
return React__default.createElement(InstantSearchConsumer, null, function (contextValue) {
return React__default.createElement(IndexConsumer, null, function (indexContextValue) {
return React__default.createElement(Connector, _extends({
contextValue: contextValue,
indexContextValue: indexContextValue
}, props));
});
});
};
return ConnectorWrapper;
};
};
var HIGHLIGHT_TAGS = {
highlightPreTag: "<ais-highlight-0000000000>",
highlightPostTag: "</ais-highlight-0000000000>"
};
/**
* Parses an highlighted attribute into an array of objects with the string value, and
* a boolean that indicated if this part is highlighted.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightedValue - highlighted attribute as returned by Algolia highlight feature
* @return {object[]} - An array of {value: string, isHighlighted: boolean}.
*/
function parseHighlightedAttribute(_ref) {
var preTag = _ref.preTag,
postTag = _ref.postTag,
_ref$highlightedValue = _ref.highlightedValue,
highlightedValue = _ref$highlightedValue === void 0 ? '' : _ref$highlightedValue;
var splitByPreTag = highlightedValue.split(preTag);
var firstValue = splitByPreTag.shift();
var elements = firstValue === '' ? [] : [{
value: firstValue,
isHighlighted: false
}];
if (postTag === preTag) {
var isHighlighted = true;
splitByPreTag.forEach(function (split) {
elements.push({
value: split,
isHighlighted: isHighlighted
});
isHighlighted = !isHighlighted;
});
} else {
splitByPreTag.forEach(function (split) {
var splitByPostTag = split.split(postTag);
elements.push({
value: splitByPostTag[0],
isHighlighted: true
});
if (splitByPostTag[1] !== '') {
elements.push({
value: splitByPostTag[1],
isHighlighted: false
});
}
});
}
return elements;
}
/**
* Find an highlighted attribute given an `attribute` and an `highlightProperty`, parses it,
* and provided an array of objects with the string value and a boolean if this
* value is highlighted.
*
* In order to use this feature, highlight must be activated in the configuration of
* the index. The `preTag` and `postTag` attributes are respectively highlightPreTag and
* highlightPostTag in Algolia configuration.
*
* @param {string} preTag - string used to identify the start of an highlighted value
* @param {string} postTag - string used to identify the end of an highlighted value
* @param {string} highlightProperty - the property that contains the highlight structure in the results
* @param {string} attribute - the highlighted attribute to look for
* @param {object} hit - the actual hit returned by Algolia.
* @return {object[]} - An array of {value: string, isHighlighted: boolean}.
*/
function parseAlgoliaHit(_ref2) {
var _ref2$preTag = _ref2.preTag,
preTag = _ref2$preTag === void 0 ? '<em>' : _ref2$preTag,
_ref2$postTag = _ref2.postTag,
postTag = _ref2$postTag === void 0 ? '</em>' : _ref2$postTag,
highlightProperty = _ref2.highlightProperty,
attribute = _ref2.attribute,
hit = _ref2.hit;
if (!hit) throw new Error('`hit`, the matching record, must be provided');
var highlightObject = getPropertyByPath(hit[highlightProperty], attribute) || {};
if (Array.isArray(highlightObject)) {
return highlightObject.map(function (item) {
return parseHighlightedAttribute({
preTag: preTag,
postTag: postTag,
highlightedValue: item.value
});
});
}
return parseHighlightedAttribute({
preTag: preTag,
postTag: postTag,
highlightedValue: highlightObject.value
});
}
function getIndexId(context) {
return hasMultipleIndices(context) ? context.multiIndexContext.targetedIndex : context.ais.mainTargetedIndex;
}
function getResults(searchResults, context) {
if (searchResults.results) {
if (searchResults.results.hits) {
return searchResults.results;
}
var indexId = getIndexId(context);
if (searchResults.results[indexId]) {
return searchResults.results[indexId];
}
}
return null;
}
function hasMultipleIndices(context) {
return context && context.multiIndexContext;
} // eslint-disable-next-line max-params
function refineValue(searchState, nextRefinement, context, resetPage, namespace) {
if (hasMultipleIndices(context)) {
var indexId = getIndexId(context);
return namespace ? refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) : refineMultiIndex(searchState, nextRefinement, indexId, resetPage);
} else {
// When we have a multi index page with shared widgets we should also
// reset their page to 1 if the resetPage is provided. Otherwise the
// indices will always be reset
// see: https://github.com/algolia/react-instantsearch/issues/310
// see: https://github.com/algolia/react-instantsearch/issues/637
if (searchState.indices && resetPage) {
Object.keys(searchState.indices).forEach(function (targetedIndex) {
searchState = refineValue(searchState, {
page: 1
}, {
multiIndexContext: {
targetedIndex: targetedIndex
}
}, true, namespace);
});
}
return namespace ? refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) : refineSingleIndex(searchState, nextRefinement, resetPage);
}
}
function refineMultiIndex(searchState, nextRefinement, indexId, resetPage) {
var page = resetPage ? {
page: 1
} : undefined;
var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], nextRefinement, page))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, nextRefinement, page)));
return _objectSpread({}, searchState, {
indices: state
});
}
function refineSingleIndex(searchState, nextRefinement, resetPage) {
var page = resetPage ? {
page: 1
} : undefined;
return _objectSpread({}, searchState, nextRefinement, page);
} // eslint-disable-next-line max-params
function refineMultiIndexWithNamespace(searchState, nextRefinement, indexId, resetPage, namespace) {
var _objectSpread4;
var page = resetPage ? {
page: 1
} : undefined;
var state = searchState.indices && searchState.indices[indexId] ? _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, searchState.indices[indexId], (_objectSpread4 = {}, _defineProperty(_objectSpread4, namespace, _objectSpread({}, searchState.indices[indexId][namespace], nextRefinement)), _defineProperty(_objectSpread4, "page", 1), _objectSpread4)))) : _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread(_defineProperty({}, namespace, nextRefinement), page)));
return _objectSpread({}, searchState, {
indices: state
});
}
function refineSingleIndexWithNamespace(searchState, nextRefinement, resetPage, namespace) {
var page = resetPage ? {
page: 1
} : undefined;
return _objectSpread({}, searchState, _defineProperty({}, namespace, _objectSpread({}, searchState[namespace], nextRefinement)), page);
}
function getNamespaceAndAttributeName(id) {
var parts = id.match(/^([^.]*)\.(.*)/);
var namespace = parts && parts[1];
var attributeName = parts && parts[2];
return {
namespace: namespace,
attributeName: attributeName
};
}
function hasRefinements(_ref) {
var multiIndex = _ref.multiIndex,
indexId = _ref.indexId,
namespace = _ref.namespace,
attributeName = _ref.attributeName,
id = _ref.id,
searchState = _ref.searchState;
if (multiIndex && namespace) {
return searchState.indices && searchState.indices[indexId] && searchState.indices[indexId][namespace] && Object.hasOwnProperty.call(searchState.indices[indexId][namespace], attributeName);
}
if (multiIndex) {
return searchState.indices && searchState.indices[indexId] && Object.hasOwnProperty.call(searchState.indices[indexId], id);
}
if (namespace) {
return searchState[namespace] && Object.hasOwnProperty.call(searchState[namespace], attributeName);
}
return Object.hasOwnProperty.call(searchState, id);
}
function getRefinements(_ref2) {
var multiIndex = _ref2.multiIndex,
indexId = _ref2.indexId,
namespace = _ref2.namespace,
attributeName = _ref2.attributeName,
id = _ref2.id,
searchState = _ref2.searchState;
if (multiIndex && namespace) {
return searchState.indices[indexId][namespace][attributeName];
}
if (multiIndex) {
return searchState.indices[indexId][id];
}
if (namespace) {
return searchState[namespace][attributeName];
}
return searchState[id];
}
function getCurrentRefinementValue(props, searchState, context, id, defaultValue) {
var indexId = getIndexId(context);
var _getNamespaceAndAttri = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri.namespace,
attributeName = _getNamespaceAndAttri.attributeName;
var multiIndex = hasMultipleIndices(context);
var args = {
multiIndex: multiIndex,
indexId: indexId,
namespace: namespace,
attributeName: attributeName,
id: id,
searchState: searchState
};
var hasRefinementsValue = hasRefinements(args);
if (hasRefinementsValue) {
return getRefinements(args);
}
if (props.defaultRefinement) {
return props.defaultRefinement;
}
return defaultValue;
}
function cleanUpValue(searchState, context, id) {
var indexId = getIndexId(context);
var _getNamespaceAndAttri2 = getNamespaceAndAttributeName(id),
namespace = _getNamespaceAndAttri2.namespace,
attributeName = _getNamespaceAndAttri2.attributeName;
if (hasMultipleIndices(context) && Boolean(searchState.indices)) {
return cleanUpValueWithMultiIndex({
attribute: attributeName,
searchState: searchState,
indexId: indexId,
id: id,
namespace: namespace
});
}
return cleanUpValueWithSingleIndex({
attribute: attributeName,
searchState: searchState,
id: id,
namespace: namespace
});
}
function cleanUpValueWithSingleIndex(_ref3) {
var searchState = _ref3.searchState,
id = _ref3.id,
namespace = _ref3.namespace,
attribute = _ref3.attribute;
if (namespace) {
return _objectSpread({}, searchState, _defineProperty({}, namespace, omit(searchState[namespace], [attribute])));
}
return omit(searchState, [id]);
}
function cleanUpValueWithMultiIndex(_ref4) {
var searchState = _ref4.searchState,
indexId = _ref4.indexId,
id = _ref4.id,
namespace = _ref4.namespace,
attribute = _ref4.attribute;
var indexSearchState = searchState.indices[indexId];
if (namespace && indexSearchState) {
return _objectSpread({}, searchState, {
indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, _objectSpread({}, indexSearchState, _defineProperty({}, namespace, omit(indexSearchState[namespace], [attribute])))))
});
}
if (indexSearchState) {
return _objectSpread({}, searchState, {
indices: _objectSpread({}, searchState.indices, _defineProperty({}, indexId, omit(indexSearchState, [id])))
});
}
return searchState;
}
function getId() {
return 'configure';
}
var connectConfigure = createConnectorWithContext({
displayName: 'AlgoliaConfigure',
getProvidedProps: function getProvidedProps() {
return {};
},
getSearchParameters: function getSearchParameters(searchParameters, props) {
var children = props.children,
contextValue = props.contextValue,
indexContextValue = props.indexContextValue,
items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]);
return searchParameters.setQueryParameters(items);
},
transitionState: function transitionState(props, prevSearchState, nextSearchState) {
var id = getId();
var children = props.children,
contextValue = props.contextValue,
indexContextValue = props.indexContextValue,
items = _objectWithoutProperties(props, ["children", "contextValue", "indexContextValue"]);
var propKeys = Object.keys(props);
var nonPresentKeys = this._props ? Object.keys(this._props).filter(function (prop) {
return propKeys.indexOf(prop) === -1;
}) : [];
this._props = props;
var nextValue = _defineProperty({}, id, _objectSpread({}, omit(nextSearchState[id], nonPresentKeys), items));
return refineValue(nextSearchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
var id = getId();
var indexId = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var subState = hasMultipleIndices({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) && searchState.indices ? searchState.indices[indexId] : searchState;
var configureKeys = subState && subState[id] ? Object.keys(subState[id]) : [];
var configureState = configureKeys.reduce(function (acc, item) {
if (!props[item]) {
acc[item] = subState[id][item];
}
return acc;
}, {});
var nextValue = _defineProperty({}, id, configureState);
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
var global$1 = (typeof global !== "undefined" ? global :
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window : {});
if (typeof global$1.setTimeout === 'function') ;
if (typeof global$1.clearTimeout === 'function') ;
// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
var performance = global$1.performance || {};
var performanceNow =
performance.now ||
performance.mozNow ||
performance.msNow ||
performance.oNow ||
performance.webkitNow ||
function(){ return (new Date()).getTime() };
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
}
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
function emptyFunction() {}
var factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret_1) {
// It is still safe when called from React.
return;
}
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} shim.isRequired = shim;
function getShim() {
return shim;
} // Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim
};
ReactPropTypes.checkPropTypes = emptyFunction;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = factoryWithThrowingShims();
}
});
function clone(value) {
if (_typeof(value) === 'object' && value !== null) {
return _merge(Array.isArray(value) ? [] : {}, value);
}
return value;
}
function isObjectOrArrayOrFunction(value) {
return typeof value === 'function' || Array.isArray(value) || Object.prototype.toString.call(value) === '[object Object]';
}
function _merge(target, source) {
if (target === source) {
return target;
}
for (var key in source) {
if (!Object.prototype.hasOwnProperty.call(source, key)) {
continue;
}
var sourceVal = source[key];
var targetVal = target[key];
if (typeof targetVal !== 'undefined' && typeof sourceVal === 'undefined') {
continue;
}
if (isObjectOrArrayOrFunction(targetVal) && isObjectOrArrayOrFunction(sourceVal)) {
target[key] = _merge(targetVal, sourceVal);
} else {
target[key] = clone(sourceVal);
}
}
return target;
}
/**
* This method is like Object.assign, but recursively merges own and inherited
* enumerable keyed properties of source objects into the destination object.
*
* NOTE: this behaves like lodash/merge, but:
* - does mutate functions if they are a source
* - treats non-plain objects as plain
* - does not work for circular objects
* - treats sparse arrays as sparse
* - does not convert Array-like objects (Arguments, NodeLists, etc.) to arrays
*
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
*/
function merge(target) {
if (!isObjectOrArrayOrFunction(target)) {
target = {};
}
for (var i = 1, l = arguments.length; i < l; i++) {
var source = arguments[i];
if (isObjectOrArrayOrFunction(source)) {
_merge(target, source);
}
}
return target;
}
module.exports = merge;
var merge$1 = /*#__PURE__*/Object.freeze({
});
var defaultsPure = function defaultsPure() {
var sources = Array.prototype.slice.call(arguments);
return sources.reduceRight(function (acc, source) {
Object.keys(Object(source)).forEach(function (key) {
if (source[key] !== undefined) {
acc[key] = source[key];
}
});
return acc;
}, {});
};
function intersection(arr1, arr2) {
return arr1.filter(function (value, index) {
return arr2.indexOf(value) > -1 && arr1.indexOf(value) === index
/* skips duplicates */
;
});
}
var intersection_1 = intersection;
var find$1 = function find(array, comparator) {
if (!Array.isArray(array)) {
return undefined;
}
for (var i = 0; i < array.length; i++) {
if (comparator(array[i])) {
return array[i];
}
}
};
function valToNumber(v) {
if (typeof v === 'number') {
return v;
} else if (typeof v === 'string') {
return parseFloat(v);
} else if (Array.isArray(v)) {
return v.map(valToNumber);
}
throw new Error('The value should be a number, a parsable string or an array of those.');
}
var valToNumber_1 = valToNumber;
function _objectWithoutPropertiesLoose$1(source, excluded) {
if (source === null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key;
var i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var omit$1 = _objectWithoutPropertiesLoose$1;
function objectHasKeys$1(obj) {
return obj && Object.keys(obj).length > 0;
}
var objectHasKeys_1 = objectHasKeys$1;
/**
* Functions to manipulate refinement lists
*
* The RefinementList is not formally defined through a prototype but is based
* on a specific structure.
*
* @module SearchParameters.refinementList
*
* @typedef {string[]} SearchParameters.refinementList.Refinements
* @typedef {Object.<string, SearchParameters.refinementList.Refinements>} SearchParameters.refinementList.RefinementList
*/
var lib = {
/**
* Adds a refinement to a RefinementList
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement, if the value is not a string it will be converted
* @return {RefinementList} a new and updated refinement list
*/
addRefinement: function addRefinement(refinementList, attribute, value) {
if (lib.isRefined(refinementList, attribute, value)) {
return refinementList;
}
var valueAsString = '' + value;
var facetRefinement = !refinementList[attribute] ? [valueAsString] : refinementList[attribute].concat(valueAsString);
var mod = {};
mod[attribute] = facetRefinement;
return defaultsPure({}, mod, refinementList);
},
/**
* Removes refinement(s) for an attribute:
* - if the value is specified removes the refinement for the value on the attribute
* - if no value is specified removes all the refinements for this attribute
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} [value] the value of the refinement
* @return {RefinementList} a new and updated refinement lst
*/
removeRefinement: function removeRefinement(refinementList, attribute, value) {
if (value === undefined) {
// we use the "filter" form of clearRefinement, since it leaves empty values as-is
// the form with a string will remove the attribute completely
return lib.clearRefinement(refinementList, function (v, f) {
return attribute === f;
});
}
var valueAsString = '' + value;
return lib.clearRefinement(refinementList, function (v, f) {
return attribute === f && valueAsString === v;
});
},
/**
* Toggles the refinement value for an attribute.
* @param {RefinementList} refinementList the initial list
* @param {string} attribute the attribute to refine
* @param {string} value the value of the refinement
* @return {RefinementList} a new and updated list
*/
toggleRefinement: function toggleRefinement(refinementList, attribute, value) {
if (value === undefined) throw new Error('toggleRefinement should be used with a value');
if (lib.isRefined(refinementList, attribute, value)) {
return lib.removeRefinement(refinementList, attribute, value);
}
return lib.addRefinement(refinementList, attribute, value);
},
/**
* Clear all or parts of a RefinementList. Depending on the arguments, three
* kinds of behavior can happen:
* - if no attribute is provided: clears the whole list
* - if an attribute is provided as a string: clears the list for the specific attribute
* - if an attribute is provided as a function: discards the elements for which the function returns true
* @param {RefinementList} refinementList the initial list
* @param {string} [attribute] the attribute or function to discard
* @param {string} [refinementType] optional parameter to give more context to the attribute function
* @return {RefinementList} a new and updated refinement list
*/
clearRefinement: function clearRefinement(refinementList, attribute, refinementType) {
if (attribute === undefined) {
if (!objectHasKeys_1(refinementList)) {
return refinementList;
}
return {};
} else if (typeof attribute === 'string') {
if (!(refinementList[attribute] && refinementList[attribute].length > 0)) {
return refinementList;
}
return omit$1(refinementList, attribute);
} else if (typeof attribute === 'function') {
var hasChanged = false;
var newRefinementList = Object.keys(refinementList).reduce(function (memo, key) {
var values = refinementList[key] || [];
var facetList = values.filter(function (value) {
return !attribute(value, key, refinementType);
});
if (facetList.length !== values.length) {
hasChanged = true;
}
memo[key] = facetList;
return memo;
}, {});
if (hasChanged) return newRefinementList;
return refinementList;
}
},
/**
* Test if the refinement value is used for the attribute. If no refinement value
* is provided, test if the refinementList contains any refinement for the
* given attribute.
* @param {RefinementList} refinementList the list of refinement
* @param {string} attribute name of the attribute
* @param {string} [refinementValue] value of the filter/refinement
* @return {boolean}
*/
isRefined: function isRefined(refinementList, attribute, refinementValue) {
var containsRefinements = !!refinementList[attribute] && refinementList[attribute].length > 0;
if (refinementValue === undefined || !containsRefinements) {
return containsRefinements;
}
var refinementValueAsString = '' + refinementValue;
return refinementList[attribute].indexOf(refinementValueAsString) !== -1;
}
};
var RefinementList = lib;
/**
* isEqual, but only for numeric refinement values, possible values:
* - 5
* - [5]
* - [[5]]
* - [[5,5],[4]]
*/
function isEqualNumericRefinement(a, b) {
if (Array.isArray(a) && Array.isArray(b)) {
return a.length === b.length && a.every(function (el, i) {
return isEqualNumericRefinement(b[i], el);
});
}
return a === b;
}
/**
* like _.find but using deep equality to be able to use it
* to find arrays.
* @private
* @param {any[]} array array to search into (elements are base or array of base)
* @param {any} searchedValue the value we're looking for (base or array of base)
* @return {any} the searched value or undefined
*/
function findArray(array, searchedValue) {
return find$1(array, function (currentValue) {
return isEqualNumericRefinement(currentValue, searchedValue);
});
}
/**
* The facet list is the structure used to store the list of values used to
* filter a single attribute.
* @typedef {string[]} SearchParameters.FacetList
*/
/**
* Structure to store numeric filters with the operator as the key. The supported operators
* are `=`, `>`, `<`, `>=`, `<=` and `!=`.
* @typedef {Object.<string, Array.<number|number[]>>} SearchParameters.OperatorList
*/
/**
* SearchParameters is the data structure that contains all the information
* usable for making a search to Algolia API. It doesn't do the search itself,
* nor does it contains logic about the parameters.
* It is an immutable object, therefore it has been created in a way that each
* changes does not change the object itself but returns a copy with the
* modification.
* This object should probably not be instantiated outside of the helper. It will
* be provided when needed. This object is documented for reference as you'll
* get it from events generated by the {@link AlgoliaSearchHelper}.
* If need be, instantiate the Helper from the factory function {@link SearchParameters.make}
* @constructor
* @classdesc contains all the parameters of a search
* @param {object|SearchParameters} newParameters existing parameters or partial object
* for the properties of a new SearchParameters
* @see SearchParameters.make
* @example <caption>SearchParameters of the first query in
* <a href="http://demos.algolia.com/instant-search-demo/">the instant search demo</a></caption>
{
"query": "",
"disjunctiveFacets": [
"customerReviewCount",
"category",
"salePrice_range",
"manufacturer"
],
"maxValuesPerFacet": 30,
"page": 0,
"hitsPerPage": 10,
"facets": [
"type",
"shipping"
]
}
*/
function SearchParameters(newParameters) {
var params = newParameters ? SearchParameters._parseNumbers(newParameters) : {};
/**
* This attribute contains the list of all the conjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.facets = params.facets || [];
/**
* This attribute contains the list of all the disjunctive facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* @member {string[]}
*/
this.disjunctiveFacets = params.disjunctiveFacets || [];
/**
* This attribute contains the list of all the hierarchical facets
* used. This list will be added to requested facets in the
* [facets attribute](https://www.algolia.com/doc/rest-api/search#param-facets) sent to algolia.
* Hierarchical facets are a sub type of disjunctive facets that
* let you filter faceted attributes hierarchically.
* @member {string[]|object[]}
*/
this.hierarchicalFacets = params.hierarchicalFacets || []; // Refinements
/**
* This attribute contains all the filters that need to be
* applied on the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsRefinements = params.facetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* excluded from the conjunctive facets. Each facet must be properly
* defined in the `facets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters excluded for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.facetsExcludes = params.facetsExcludes || {};
/**
* This attribute contains all the filters that need to be
* applied on the disjunctive facets. Each facet must be properly
* defined in the `disjunctiveFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.disjunctiveFacetsRefinements = params.disjunctiveFacetsRefinements || {};
/**
* This attribute contains all the filters that need to be
* applied on the numeric attributes.
*
* The key is the name of the attribute, and the value is the
* filters to apply to this attribute.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `numericFilters` attribute.
* @member {Object.<string, SearchParameters.OperatorList>}
*/
this.numericRefinements = params.numericRefinements || {};
/**
* This attribute contains all the tags used to refine the query.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `tagFilters` attribute.
* @member {string[]}
*/
this.tagRefinements = params.tagRefinements || [];
/**
* This attribute contains all the filters that need to be
* applied on the hierarchical facets. Each facet must be properly
* defined in the `hierarchicalFacets` attribute.
*
* The key is the name of the facet, and the `FacetList` contains all
* filters selected for the associated facet name. The FacetList values
* are structured as a string that contain the values for each level
* separated by the configured separator.
*
* When querying algolia, the values stored in this attribute will
* be translated into the `facetFilters` attribute.
* @member {Object.<string, SearchParameters.FacetList>}
*/
this.hierarchicalFacetsRefinements = params.hierarchicalFacetsRefinements || {};
var self = this;
Object.keys(params).forEach(function (paramName) {
var isKeyKnown = SearchParameters.PARAMETERS.indexOf(paramName) !== -1;
var isValueDefined = params[paramName] !== undefined;
if (!isKeyKnown && isValueDefined) {
self[paramName] = params[paramName];
}
});
}
/**
* List all the properties in SearchParameters and therefore all the known Algolia properties
* This doesn't contain any beta/hidden features.
* @private
*/
SearchParameters.PARAMETERS = Object.keys(new SearchParameters());
/**
* @private
* @param {object} partialState full or part of a state
* @return {object} a new object with the number keys as number
*/
SearchParameters._parseNumbers = function (partialState) {
// Do not reparse numbers in SearchParameters, they ought to be parsed already
if (partialState instanceof SearchParameters) return partialState;
var numbers = {};
var numberKeys = ['aroundPrecision', 'aroundRadius', 'getRankingInfo', 'minWordSizefor2Typos', 'minWordSizefor1Typo', 'page', 'maxValuesPerFacet', 'distinct', 'minimumAroundRadius', 'hitsPerPage', 'minProximity'];
numberKeys.forEach(function (k) {
var value = partialState[k];
if (typeof value === 'string') {
var parsedValue = parseFloat(value); // global isNaN is ok to use here, value is only number or NaN
numbers[k] = isNaN(parsedValue) ? value : parsedValue;
}
}); // there's two formats of insideBoundingBox, we need to parse
// the one which is an array of float geo rectangles
if (Array.isArray(partialState.insideBoundingBox)) {
numbers.insideBoundingBox = partialState.insideBoundingBox.map(function (geoRect) {
return geoRect.map(function (value) {
return parseFloat(value);
});
});
}
if (partialState.numericRefinements) {
var numericRefinements = {};
Object.keys(partialState.numericRefinements).forEach(function (attribute) {
var operators = partialState.numericRefinements[attribute] || {};
numericRefinements[attribute] = {};
Object.keys(operators).forEach(function (operator) {
var values = operators[operator];
var parsedValues = values.map(function (v) {
if (Array.isArray(v)) {
return v.map(function (vPrime) {
if (typeof vPrime === 'string') {
return parseFloat(vPrime);
}
return vPrime;
});
} else if (typeof v === 'string') {
return parseFloat(v);
}
return v;
});
numericRefinements[attribute][operator] = parsedValues;
});
});
numbers.numericRefinements = numericRefinements;
}
return merge$1({}, partialState, numbers);
};
/**
* Factory for SearchParameters
* @param {object|SearchParameters} newParameters existing parameters or partial
* object for the properties of a new SearchParameters
* @return {SearchParameters} frozen instance of SearchParameters
*/
SearchParameters.make = function makeSearchParameters(newParameters) {
var instance = new SearchParameters(newParameters);
var hierarchicalFacets = newParameters.hierarchicalFacets || [];
hierarchicalFacets.forEach(function (facet) {
if (facet.rootPath) {
var currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length > 0 && currentRefinement[0].indexOf(facet.rootPath) !== 0) {
instance = instance.clearRefinements(facet.name);
} // get it again in case it has been cleared
currentRefinement = instance.getHierarchicalRefinement(facet.name);
if (currentRefinement.length === 0) {
instance = instance.toggleHierarchicalFacetRefinement(facet.name, facet.rootPath);
}
}
});
return instance;
};
/**
* Validates the new parameters based on the previous state
* @param {SearchParameters} currentState the current state
* @param {object|SearchParameters} parameters the new parameters to set
* @return {Error|null} Error if the modification is invalid, null otherwise
*/
SearchParameters.validate = function (currentState, parameters) {
var params = parameters || {};
if (currentState.tagFilters && params.tagRefinements && params.tagRefinements.length > 0) {
return new Error('[Tags] Cannot switch from the managed tag API to the advanced API. It is probably ' + 'an error, if it is really what you want, you should first clear the tags with clearTags method.');
}
if (currentState.tagRefinements.length > 0 && params.tagFilters) {
return new Error('[Tags] Cannot switch from the advanced tag API to the managed API. It is probably ' + 'an error, if it is not, you should first clear the tags with clearTags method.');
}
if (currentState.numericFilters && params.numericRefinements && objectHasKeys_1(params.numericRefinements)) {
return new Error("[Numeric filters] Can't switch from the advanced to the managed API. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.');
}
if (objectHasKeys_1(currentState.numericRefinements) && params.numericFilters) {
return new Error("[Numeric filters] Can't switch from the managed API to the advanced. It" + ' is probably an error, if this is really what you want, you have to first' + ' clear the numeric filters.');
}
return null;
};
SearchParameters.prototype = {
constructor: SearchParameters,
/**
* Remove all refinements (disjunctive + conjunctive + excludes + numeric filters)
* @method
* @param {undefined|string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {SearchParameters}
*/
clearRefinements: function clearRefinements(attribute) {
var clear = RefinementList.clearRefinement;
var patch = {
numericRefinements: this._clearNumericRefinements(attribute),
facetsRefinements: clear(this.facetsRefinements, attribute, 'conjunctiveFacet'),
facetsExcludes: clear(this.facetsExcludes, attribute, 'exclude'),
disjunctiveFacetsRefinements: clear(this.disjunctiveFacetsRefinements, attribute, 'disjunctiveFacet'),
hierarchicalFacetsRefinements: clear(this.hierarchicalFacetsRefinements, attribute, 'hierarchicalFacet')
};
if (patch.numericRefinements === this.numericRefinements && patch.facetsRefinements === this.facetsRefinements && patch.facetsExcludes === this.facetsExcludes && patch.disjunctiveFacetsRefinements === this.disjunctiveFacetsRefinements && patch.hierarchicalFacetsRefinements === this.hierarchicalFacetsRefinements) {
return this;
}
return this.setQueryParameters(patch);
},
/**
* Remove all the refined tags from the SearchParameters
* @method
* @return {SearchParameters}
*/
clearTags: function clearTags() {
if (this.tagFilters === undefined && this.tagRefinements.length === 0) return this;
return this.setQueryParameters({
tagFilters: undefined,
tagRefinements: []
});
},
/**
* Set the index.
* @method
* @param {string} index the index name
* @return {SearchParameters}
*/
setIndex: function setIndex(index) {
if (index === this.index) return this;
return this.setQueryParameters({
index: index
});
},
/**
* Query setter
* @method
* @param {string} newQuery value for the new query
* @return {SearchParameters}
*/
setQuery: function setQuery(newQuery) {
if (newQuery === this.query) return this;
return this.setQueryParameters({
query: newQuery
});
},
/**
* Page setter
* @method
* @param {number} newPage new page number
* @return {SearchParameters}
*/
setPage: function setPage(newPage) {
if (newPage === this.page) return this;
return this.setQueryParameters({
page: newPage
});
},
/**
* Facets setter
* The facets are the simple facets, used for conjunctive (and) faceting.
* @method
* @param {string[]} facets all the attributes of the algolia records used for conjunctive faceting
* @return {SearchParameters}
*/
setFacets: function setFacets(facets) {
return this.setQueryParameters({
facets: facets
});
},
/**
* Disjunctive facets setter
* Change the list of disjunctive (or) facets the helper chan handle.
* @method
* @param {string[]} facets all the attributes of the algolia records used for disjunctive faceting
* @return {SearchParameters}
*/
setDisjunctiveFacets: function setDisjunctiveFacets(facets) {
return this.setQueryParameters({
disjunctiveFacets: facets
});
},
/**
* HitsPerPage setter
* Hits per page represents the number of hits retrieved for this query
* @method
* @param {number} n number of hits retrieved per page of results
* @return {SearchParameters}
*/
setHitsPerPage: function setHitsPerPage(n) {
if (this.hitsPerPage === n) return this;
return this.setQueryParameters({
hitsPerPage: n
});
},
/**
* typoTolerance setter
* Set the value of typoTolerance
* @method
* @param {string} typoTolerance new value of typoTolerance ("true", "false", "min" or "strict")
* @return {SearchParameters}
*/
setTypoTolerance: function setTypoTolerance(typoTolerance) {
if (this.typoTolerance === typoTolerance) return this;
return this.setQueryParameters({
typoTolerance: typoTolerance
});
},
/**
* Add a numeric filter for a given attribute
* When value is an array, they are combined with OR
* When value is a single value, it will combined with AND
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} operator operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number | number[]} value value of the filter
* @return {SearchParameters}
* @example
* // for price = 50 or 40
* searchparameter.addNumericRefinement('price', '=', [50, 40]);
* @example
* // for size = 38 and 40
* searchparameter.addNumericRefinement('size', '=', 38);
* searchparameter.addNumericRefinement('size', '=', 40);
*/
addNumericRefinement: function addNumericRefinement(attribute, operator, v) {
var value = valToNumber_1(v);
if (this.isNumericRefined(attribute, operator, value)) return this;
var mod = merge$1({}, this.numericRefinements);
mod[attribute] = merge$1({}, mod[attribute]);
if (mod[attribute][operator]) {
// Array copy
mod[attribute][operator] = mod[attribute][operator].slice(); // Add the element. Concat can't be used here because value can be an array.
mod[attribute][operator].push(value);
} else {
mod[attribute][operator] = [value];
}
return this.setQueryParameters({
numericRefinements: mod
});
},
/**
* Get the list of conjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getConjunctiveRefinements: function getConjunctiveRefinements(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
return [];
}
return this.facetsRefinements[facetName] || [];
},
/**
* Get the list of disjunctive refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getDisjunctiveRefinements: function getDisjunctiveRefinements(facetName) {
if (!this.isDisjunctiveFacet(facetName)) {
return [];
}
return this.disjunctiveFacetsRefinements[facetName] || [];
},
/**
* Get the list of hierarchical refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getHierarchicalRefinement: function getHierarchicalRefinement(facetName) {
// we send an array but we currently do not support multiple
// hierarchicalRefinements for a hierarchicalFacet
return this.hierarchicalFacetsRefinements[facetName] || [];
},
/**
* Get the list of exclude refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {string[]} list of refinements
*/
getExcludeRefinements: function getExcludeRefinements(facetName) {
if (!this.isConjunctiveFacet(facetName)) {
return [];
}
return this.facetsExcludes[facetName] || [];
},
/**
* Remove all the numeric filter for a given (attribute, operator)
* @method
* @param {string} attribute attribute to set the filter on
* @param {string} [operator] operator of the filter (possible values: =, >, >=, <, <=, !=)
* @param {number} [number] the value to be removed
* @return {SearchParameters}
*/
removeNumericRefinement: function removeNumericRefinement(attribute, operator, paramValue) {
if (paramValue !== undefined) {
if (!this.isNumericRefined(attribute, operator, paramValue)) {
return this;
}
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function (value, key) {
return key === attribute && value.op === operator && isEqualNumericRefinement(value.val, valToNumber_1(paramValue));
})
});
} else if (operator !== undefined) {
if (!this.isNumericRefined(attribute, operator)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function (value, key) {
return key === attribute && value.op === operator;
})
});
}
if (!this.isNumericRefined(attribute)) return this;
return this.setQueryParameters({
numericRefinements: this._clearNumericRefinements(function (value, key) {
return key === attribute;
})
});
},
/**
* Get the list of numeric refinements for a single facet
* @param {string} facetName name of the attribute used for faceting
* @return {SearchParameters.OperatorList[]} list of refinements
*/
getNumericRefinements: function getNumericRefinements(facetName) {
return this.numericRefinements[facetName] || {};
},
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute attribute in the record
* @param {string} operator operator applied on the refined values
* @return {Array.<number|number[]>} refined values
*/
getNumericRefinement: function getNumericRefinement(attribute, operator) {
return this.numericRefinements[attribute] && this.numericRefinements[attribute][operator];
},
/**
* Clear numeric filters.
* @method
* @private
* @param {string|SearchParameters.clearCallback} [attribute] optional string or function
* - If not given, means to clear all the filters.
* - If `string`, means to clear all refinements for the `attribute` named filter.
* - If `function`, means to clear all the refinements that return truthy values.
* @return {Object.<string, OperatorList>}
*/
_clearNumericRefinements: function _clearNumericRefinements(attribute) {
if (attribute === undefined) {
if (!objectHasKeys_1(this.numericRefinements)) {
return this.numericRefinements;
}
return {};
} else if (typeof attribute === 'string') {
if (!objectHasKeys_1(this.numericRefinements[attribute])) {
return this.numericRefinements;
}
return omit$1(this.numericRefinements, attribute);
} else if (typeof attribute === 'function') {
var hasChanged = false;
var numericRefinements = this.numericRefinements;
var newNumericRefinements = Object.keys(numericRefinements).reduce(function (memo, key) {
var operators = numericRefinements[key];
var operatorList = {};
operators = operators || {};
Object.keys(operators).forEach(function (operator) {
var values = operators[operator] || [];
var outValues = [];
values.forEach(function (value) {
var predicateResult = attribute({
val: value,
op: operator
}, key, 'numeric');
if (!predicateResult) outValues.push(value);
});
if (outValues.length !== values.length) {
hasChanged = true;
}
operatorList[operator] = outValues;
});
memo[key] = operatorList;
return memo;
}, {});
if (hasChanged) return newNumericRefinements;
return this.numericRefinements;
}
},
/**
* Add a facet to the facets attribute of the helper configuration, if it
* isn't already present.
* @method
* @param {string} facet facet name to add
* @return {SearchParameters}
*/
addFacet: function addFacet(facet) {
if (this.isConjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
facets: this.facets.concat([facet])
});
},
/**
* Add a disjunctive facet to the disjunctiveFacets attribute of the helper
* configuration, if it isn't already present.
* @method
* @param {string} facet disjunctive facet name to add
* @return {SearchParameters}
*/
addDisjunctiveFacet: function addDisjunctiveFacet(facet) {
if (this.isDisjunctiveFacet(facet)) {
return this;
}
return this.setQueryParameters({
disjunctiveFacets: this.disjunctiveFacets.concat([facet])
});
},
/**
* Add a hierarchical facet to the hierarchicalFacets attribute of the helper
* configuration.
* @method
* @param {object} hierarchicalFacet hierarchical facet to add
* @return {SearchParameters}
* @throws will throw an error if a hierarchical facet with the same name was already declared
*/
addHierarchicalFacet: function addHierarchicalFacet(hierarchicalFacet) {
if (this.isHierarchicalFacet(hierarchicalFacet.name)) {
throw new Error('Cannot declare two hierarchical facets with the same name: `' + hierarchicalFacet.name + '`');
}
return this.setQueryParameters({
hierarchicalFacets: this.hierarchicalFacets.concat([hierarchicalFacet])
});
},
/**
* Add a refinement on a "normal" facet
* @method
* @param {string} facet attribute to apply the faceting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addFacetRefinement: function addFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.addRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Exclude a value from a "normal" facet
* @method
* @param {string} facet attribute to apply the exclusion on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addExcludeRefinement: function addExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.addRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Adds a refinement on a disjunctive facet.
* @method
* @param {string} facet attribute to apply the faceting on
* @param {string} value value of the attribute (will be converted to string)
* @return {SearchParameters}
*/
addDisjunctiveFacetRefinement: function addDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.addRefinement(this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* addTagRefinement adds a tag to the list used to filter the results
* @param {string} tag tag to be added
* @return {SearchParameters}
*/
addTagRefinement: function addTagRefinement(tag) {
if (this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: this.tagRefinements.concat(tag)
};
return this.setQueryParameters(modification);
},
/**
* Remove a facet from the facets attribute of the helper configuration, if it
* is present.
* @method
* @param {string} facet facet name to remove
* @return {SearchParameters}
*/
removeFacet: function removeFacet(facet) {
if (!this.isConjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
facets: this.facets.filter(function (f) {
return f !== facet;
})
});
},
/**
* Remove a disjunctive facet from the disjunctiveFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet disjunctive facet name to remove
* @return {SearchParameters}
*/
removeDisjunctiveFacet: function removeDisjunctiveFacet(facet) {
if (!this.isDisjunctiveFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
disjunctiveFacets: this.disjunctiveFacets.filter(function (f) {
return f !== facet;
})
});
},
/**
* Remove a hierarchical facet from the hierarchicalFacets attribute of the
* helper configuration, if it is present.
* @method
* @param {string} facet hierarchical facet name to remove
* @return {SearchParameters}
*/
removeHierarchicalFacet: function removeHierarchicalFacet(facet) {
if (!this.isHierarchicalFacet(facet)) {
return this;
}
return this.clearRefinements(facet).setQueryParameters({
hierarchicalFacets: this.hierarchicalFacets.filter(function (f) {
return f.name !== facet;
})
});
},
/**
* Remove a refinement set on facet. If a value is provided, it will clear the
* refinement for the given value, otherwise it will clear all the refinement
* values for the faceted attribute.
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} [value] value used to filter
* @return {SearchParameters}
*/
removeFacetRefinement: function removeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsRefinements, facet, value)) return this;
return this.setQueryParameters({
facetsRefinements: RefinementList.removeRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Remove a negative refinement on a facet
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeExcludeRefinement: function removeExcludeRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.facetsExcludes, facet, value)) return this;
return this.setQueryParameters({
facetsExcludes: RefinementList.removeRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Remove a refinement on a disjunctive facet
* @method
* @param {string} facet name of the attribute used for faceting
* @param {string} value value used to filter
* @return {SearchParameters}
*/
removeDisjunctiveFacetRefinement: function removeDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
if (!RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value)) return this;
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.removeRefinement(this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Remove a tag from the list of tag refinements
* @method
* @param {string} tag the tag to remove
* @return {SearchParameters}
*/
removeTagRefinement: function removeTagRefinement(tag) {
if (!this.isTagRefined(tag)) return this;
var modification = {
tagRefinements: this.tagRefinements.filter(function (t) {
return t !== tag;
})
};
return this.setQueryParameters(modification);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
* @deprecated since version 2.19.0, see {@link SearchParameters#toggleFacetRefinement}
*/
toggleRefinement: function toggleRefinement(facet, value) {
return this.toggleFacetRefinement(facet, value);
},
/**
* Generic toggle refinement method to use with facet, disjunctive facets
* and hierarchical facets
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {SearchParameters}
* @throws will throw an error if the facet is not declared in the settings of the helper
*/
toggleFacetRefinement: function toggleFacetRefinement(facet, value) {
if (this.isHierarchicalFacet(facet)) {
return this.toggleHierarchicalFacetRefinement(facet, value);
} else if (this.isConjunctiveFacet(facet)) {
return this.toggleConjunctiveFacetRefinement(facet, value);
} else if (this.isDisjunctiveFacet(facet)) {
return this.toggleDisjunctiveFacetRefinement(facet, value);
}
throw new Error('Cannot refine the undeclared facet ' + facet + '; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets');
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleConjunctiveFacetRefinement: function toggleConjunctiveFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsRefinements: RefinementList.toggleRefinement(this.facetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleExcludeFacetRefinement: function toggleExcludeFacetRefinement(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the facets attribute of the helper configuration');
}
return this.setQueryParameters({
facetsExcludes: RefinementList.toggleRefinement(this.facetsExcludes, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleDisjunctiveFacetRefinement: function toggleDisjunctiveFacetRefinement(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
throw new Error(facet + ' is not defined in the disjunctiveFacets attribute of the helper configuration');
}
return this.setQueryParameters({
disjunctiveFacetsRefinements: RefinementList.toggleRefinement(this.disjunctiveFacetsRefinements, facet, value)
});
},
/**
* Switch the refinement applied over a facet/value
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {SearchParameters}
*/
toggleHierarchicalFacetRefinement: function toggleHierarchicalFacetRefinement(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
throw new Error(facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration');
}
var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facet));
var mod = {};
var upOneOrMultipleLevel = this.hierarchicalFacetsRefinements[facet] !== undefined && this.hierarchicalFacetsRefinements[facet].length > 0 && ( // remove current refinement:
// refinement was 'beer > IPA', call is toggleRefine('beer > IPA'), refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0] === value || // remove a parent refinement of the current refinement:
// - refinement was 'beer > IPA > Flying dog'
// - call is toggleRefine('beer > IPA')
// - refinement should be `beer`
this.hierarchicalFacetsRefinements[facet][0].indexOf(value + separator) === 0);
if (upOneOrMultipleLevel) {
if (value.indexOf(separator) === -1) {
// go back to root level
mod[facet] = [];
} else {
mod[facet] = [value.slice(0, value.lastIndexOf(separator))];
}
} else {
mod[facet] = [value];
}
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaultsPure({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Adds a refinement on a hierarchical facet.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is refined
*/
addHierarchicalFacetRefinement: function addHierarchicalFacetRefinement(facet, path) {
if (this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is already refined.');
}
if (!this.isHierarchicalFacet(facet)) {
throw new Error(facet + ' is not defined in the hierarchicalFacets attribute of the helper configuration.');
}
var mod = {};
mod[facet] = [path];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaultsPure({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {SearchParameter} the new state
* @throws Error if the facet is not defined or if the facet is not refined
*/
removeHierarchicalFacetRefinement: function removeHierarchicalFacetRefinement(facet) {
if (!this.isHierarchicalFacetRefined(facet)) {
throw new Error(facet + ' is not refined.');
}
var mod = {};
mod[facet] = [];
return this.setQueryParameters({
hierarchicalFacetsRefinements: defaultsPure({}, mod, this.hierarchicalFacetsRefinements)
});
},
/**
* Switch the tag refinement
* @method
* @param {string} tag the tag to remove or add
* @return {SearchParameters}
*/
toggleTagRefinement: function toggleTagRefinement(tag) {
if (this.isTagRefined(tag)) {
return this.removeTagRefinement(tag);
}
return this.addTagRefinement(tag);
},
/**
* Test if the facet name is from one of the disjunctive facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isDisjunctiveFacet: function isDisjunctiveFacet(facet) {
return this.disjunctiveFacets.indexOf(facet) > -1;
},
/**
* Test if the facet name is from one of the hierarchical facets
* @method
* @param {string} facetName facet name to test
* @return {boolean}
*/
isHierarchicalFacet: function isHierarchicalFacet(facetName) {
return this.getHierarchicalFacetByName(facetName) !== undefined;
},
/**
* Test if the facet name is from one of the conjunctive/normal facets
* @method
* @param {string} facet facet name to test
* @return {boolean}
*/
isConjunctiveFacet: function isConjunctiveFacet(facet) {
return this.facets.indexOf(facet) > -1;
},
/**
* Returns true if the facet is refined, either for a specific value or in
* general.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value, optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isFacetRefined: function isFacetRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
return false;
}
return RefinementList.isRefined(this.facetsRefinements, facet, value);
},
/**
* Returns true if the facet contains exclusions or if a specific value is
* excluded.
*
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} returns true if refined
*/
isExcludeRefined: function isExcludeRefined(facet, value) {
if (!this.isConjunctiveFacet(facet)) {
return false;
}
return RefinementList.isRefined(this.facetsExcludes, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value optional, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isDisjunctiveFacetRefined: function isDisjunctiveFacetRefined(facet, value) {
if (!this.isDisjunctiveFacet(facet)) {
return false;
}
return RefinementList.isRefined(this.disjunctiveFacetsRefinements, facet, value);
},
/**
* Returns true if the facet contains a refinement, or if a value passed is a
* refinement for the facet.
* @method
* @param {string} facet name of the attribute for used for faceting
* @param {string} value optional, will test if the value is used for refinement
* if there is one, otherwise will test if the facet contains any refinement
* @return {boolean}
*/
isHierarchicalFacetRefined: function isHierarchicalFacetRefined(facet, value) {
if (!this.isHierarchicalFacet(facet)) {
return false;
}
var refinements = this.getHierarchicalRefinement(facet);
if (!value) {
return refinements.length > 0;
}
return refinements.indexOf(value) !== -1;
},
/**
* Test if the triple (attribute, operator, value) is already refined.
* If only the attribute and the operator are provided, it tests if the
* contains any refinement value.
* @method
* @param {string} attribute attribute for which the refinement is applied
* @param {string} [operator] operator of the refinement
* @param {string} [value] value of the refinement
* @return {boolean} true if it is refined
*/
isNumericRefined: function isNumericRefined(attribute, operator, value) {
if (value === undefined && operator === undefined) {
return !!this.numericRefinements[attribute];
}
var isOperatorDefined = this.numericRefinements[attribute] && this.numericRefinements[attribute][operator] !== undefined;
if (value === undefined || !isOperatorDefined) {
return isOperatorDefined;
}
var parsedValue = valToNumber_1(value);
var isAttributeValueDefined = findArray(this.numericRefinements[attribute][operator], parsedValue) !== undefined;
return isOperatorDefined && isAttributeValueDefined;
},
/**
* Returns true if the tag refined, false otherwise
* @method
* @param {string} tag the tag to check
* @return {boolean}
*/
isTagRefined: function isTagRefined(tag) {
return this.tagRefinements.indexOf(tag) !== -1;
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedDisjunctiveFacets: function getRefinedDisjunctiveFacets() {
var self = this; // attributes used for numeric filter can also be disjunctive
var disjunctiveNumericRefinedFacets = intersection_1(Object.keys(this.numericRefinements).filter(function (facet) {
return Object.keys(self.numericRefinements[facet]).length > 0;
}), this.disjunctiveFacets);
return Object.keys(this.disjunctiveFacetsRefinements).filter(function (facet) {
return self.disjunctiveFacetsRefinements[facet].length > 0;
}).concat(disjunctiveNumericRefinedFacets).concat(this.getRefinedHierarchicalFacets());
},
/**
* Returns the list of all disjunctive facets refined
* @method
* @param {string} facet name of the attribute used for faceting
* @param {value} value value used for filtering
* @return {string[]}
*/
getRefinedHierarchicalFacets: function getRefinedHierarchicalFacets() {
var self = this;
return intersection_1( // enforce the order between the two arrays,
// so that refinement name index === hierarchical facet index
this.hierarchicalFacets.map(function (facet) {
return facet.name;
}), Object.keys(this.hierarchicalFacetsRefinements).filter(function (facet) {
return self.hierarchicalFacetsRefinements[facet].length > 0;
}));
},
/**
* Returned the list of all disjunctive facets not refined
* @method
* @return {string[]}
*/
getUnrefinedDisjunctiveFacets: function getUnrefinedDisjunctiveFacets() {
var refinedFacets = this.getRefinedDisjunctiveFacets();
return this.disjunctiveFacets.filter(function (f) {
return refinedFacets.indexOf(f) === -1;
});
},
managedParameters: ['index', 'facets', 'disjunctiveFacets', 'facetsRefinements', 'facetsExcludes', 'disjunctiveFacetsRefinements', 'numericRefinements', 'tagRefinements', 'hierarchicalFacets', 'hierarchicalFacetsRefinements'],
getQueryParams: function getQueryParams() {
var managedParameters = this.managedParameters;
var queryParams = {};
var self = this;
Object.keys(this).forEach(function (paramName) {
var paramValue = self[paramName];
if (managedParameters.indexOf(paramName) === -1 && paramValue !== undefined) {
queryParams[paramName] = paramValue;
}
});
return queryParams;
},
/**
* Let the user set a specific value for a given parameter. Will return the
* same instance if the parameter is invalid or if the value is the same as the
* previous one.
* @method
* @param {string} parameter the parameter name
* @param {any} value the value to be set, must be compliant with the definition
* of the attribute on the object
* @return {SearchParameters} the updated state
*/
setQueryParameter: function setParameter(parameter, value) {
if (this[parameter] === value) return this;
var modification = {};
modification[parameter] = value;
return this.setQueryParameters(modification);
},
/**
* Let the user set any of the parameters with a plain object.
* @method
* @param {object} params all the keys and the values to be updated
* @return {SearchParameters} a new updated instance
*/
setQueryParameters: function setQueryParameters(params) {
if (!params) return this;
var error = SearchParameters.validate(this, params);
if (error) {
throw error;
}
var self = this;
var nextWithNumbers = SearchParameters._parseNumbers(params);
var previousPlainObject = Object.keys(this).reduce(function (acc, key) {
acc[key] = self[key];
return acc;
}, {});
var nextPlainObject = Object.keys(nextWithNumbers).reduce(function (previous, key) {
var isPreviousValueDefined = previous[key] !== undefined;
var isNextValueDefined = nextWithNumbers[key] !== undefined;
if (isPreviousValueDefined && !isNextValueDefined) {
return omit$1(previous, [key]);
}
if (isNextValueDefined) {
previous[key] = nextWithNumbers[key];
}
return previous;
}, previousPlainObject);
return new this.constructor(nextPlainObject);
},
/**
* Returns a new instance with the page reset. Two scenarios possible:
* the page is omitted -> return the given instance
* the page is set -> return a new instance with a page of 0
* @return {SearchParameters} a new updated instance
*/
resetPage: function resetPage() {
if (this.page === undefined) {
return this;
}
return this.setPage(0);
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSortBy: function _getHierarchicalFacetSortBy(hierarchicalFacet) {
return hierarchicalFacet.sortBy || ['isRefined:desc', 'name:asc'];
},
/**
* Helper function to get the hierarchicalFacet separator or the default one (`>`)
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.separator or `>` as default
*/
_getHierarchicalFacetSeparator: function _getHierarchicalFacetSeparator(hierarchicalFacet) {
return hierarchicalFacet.separator || ' > ';
},
/**
* Helper function to get the hierarchicalFacet prefix path or null
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.rootPath or null as default
*/
_getHierarchicalRootPath: function _getHierarchicalRootPath(hierarchicalFacet) {
return hierarchicalFacet.rootPath || null;
},
/**
* Helper function to check if we show the parent level of the hierarchicalFacet
* @private
* @param {object} hierarchicalFacet
* @return {string} returns the hierarchicalFacet.showParentLevel or true as default
*/
_getHierarchicalShowParentLevel: function _getHierarchicalShowParentLevel(hierarchicalFacet) {
if (typeof hierarchicalFacet.showParentLevel === 'boolean') {
return hierarchicalFacet.showParentLevel;
}
return true;
},
/**
* Helper function to get the hierarchicalFacet by it's name
* @param {string} hierarchicalFacetName
* @return {object} a hierarchicalFacet
*/
getHierarchicalFacetByName: function getHierarchicalFacetByName(hierarchicalFacetName) {
return find$1(this.hierarchicalFacets, function (f) {
return f.name === hierarchicalFacetName;
});
},
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
getHierarchicalFacetBreadcrumb: function getHierarchicalFacetBreadcrumb(facetName) {
if (!this.isHierarchicalFacet(facetName)) {
return [];
}
var refinement = this.getHierarchicalRefinement(facetName)[0];
if (!refinement) return [];
var separator = this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(facetName));
var path = refinement.split(separator);
return path.map(function (part) {
return part.trim();
});
},
toString: function toString() {
return JSON.stringify(this, null, 2);
}
};
/**
* Callback used for clearRefinement method
* @callback SearchParameters.clearCallback
* @param {OperatorList|FacetList} value the value of the filter
* @param {string} key the current attribute name
* @param {string} type `numeric`, `disjunctiveFacet`, `conjunctiveFacet`, `hierarchicalFacet` or `exclude`
* depending on the type of facet
* @return {boolean} `true` if the element should be removed. `false` otherwise.
*/
var SearchParameters_1 = SearchParameters;
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined;
var valIsNull = value === null;
var othIsDefined = other !== undefined;
var othIsNull = other === null;
if (!othIsNull && value > other || valIsNull && othIsDefined || !valIsDefined) {
return 1;
}
if (!valIsNull && value < other || othIsNull && valIsDefined || !othIsDefined) {
return -1;
}
}
return 0;
}
/**
* @param {Array<object>} collection object with keys in attributes
* @param {Array<string>} iteratees attributes
* @param {Array<string>} orders asc | desc
*/
function orderBy(collection, iteratees, orders) {
if (!Array.isArray(collection)) {
return [];
}
if (!Array.isArray(orders)) {
orders = [];
}
var result = collection.map(function (value, index) {
return {
criteria: iteratees.map(function (iteratee) {
return value[iteratee];
}),
index: index,
value: value
};
});
result.sort(function comparer(object, other) {
var index = -1;
while (++index < object.criteria.length) {
var res = compareAscending(object.criteria[index], other.criteria[index]);
if (res) {
if (index >= orders.length) {
return res;
}
if (orders[index] === 'desc') {
return -res;
}
return res;
}
} // This ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
});
return result.map(function (res) {
return res.value;
});
}
var orderBy_1 = orderBy;
var compact = function compact(array) {
if (!Array.isArray(array)) {
return [];
}
return array.filter(Boolean);
};
var findIndex = function find(array, comparator) {
if (!Array.isArray(array)) {
return -1;
}
for (var i = 0; i < array.length; i++) {
if (comparator(array[i])) {
return i;
}
}
return -1;
};
/**
* Transform sort format from user friendly notation to lodash format
* @param {string[]} sortBy array of predicate of the form "attribute:order"
* @param {string[]} [defaults] array of predicate of the form "attribute:order"
* @return {array.<string[]>} array containing 2 elements : attributes, orders
*/
var formatSort = function formatSort(sortBy, defaults) {
var defaultInstructions = (defaults || []).map(function (sort) {
return sort.split(':');
});
return sortBy.reduce(function preparePredicate(out, sort) {
var sortInstruction = sort.split(':');
var matchingDefault = find$1(defaultInstructions, function (defaultInstruction) {
return defaultInstruction[0] === sortInstruction[0];
});
if (sortInstruction.length > 1 || !matchingDefault) {
out[0].push(sortInstruction[0]);
out[1].push(sortInstruction[1]);
return out;
}
out[0].push(matchingDefault[0]);
out[1].push(matchingDefault[1]);
return out;
}, [[], []]);
};
var generateHierarchicalTree_1 = generateTrees;
function generateTrees(state) {
return function generate(hierarchicalFacetResult, hierarchicalFacetIndex) {
var hierarchicalFacet = state.hierarchicalFacets[hierarchicalFacetIndex];
var hierarchicalFacetRefinement = state.hierarchicalFacetsRefinements[hierarchicalFacet.name] && state.hierarchicalFacetsRefinements[hierarchicalFacet.name][0] || '';
var hierarchicalSeparator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var hierarchicalRootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var hierarchicalShowParentLevel = state._getHierarchicalShowParentLevel(hierarchicalFacet);
var sortBy = formatSort(state._getHierarchicalFacetSortBy(hierarchicalFacet));
var rootExhaustive = hierarchicalFacetResult.every(function (facetResult) {
return facetResult.exhaustive;
});
var generateTreeFn = generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, hierarchicalFacetRefinement);
var results = hierarchicalFacetResult;
if (hierarchicalRootPath) {
results = hierarchicalFacetResult.slice(hierarchicalRootPath.split(hierarchicalSeparator).length);
}
return results.reduce(generateTreeFn, {
name: state.hierarchicalFacets[hierarchicalFacetIndex].name,
count: null,
// root level, no count
isRefined: true,
// root level, always refined
path: null,
// root level, no path
exhaustive: rootExhaustive,
data: null
});
};
}
function generateHierarchicalTree(sortBy, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel, currentRefinement) {
return function generateTree(hierarchicalTree, hierarchicalFacetResult, currentHierarchicalLevel) {
var parent = hierarchicalTree;
if (currentHierarchicalLevel > 0) {
var level = 0;
parent = hierarchicalTree;
while (level < currentHierarchicalLevel) {
/**
* @type {object[]]} hierarchical data
*/
var data = parent && Array.isArray(parent.data) ? parent.data : [];
parent = find$1(data, function (subtree) {
return subtree.isRefined;
});
level++;
}
} // we found a refined parent, let's add current level data under it
if (parent) {
// filter values in case an object has multiple categories:
// {
// categories: {
// level0: ['beers', 'bières'],
// level1: ['beers > IPA', 'bières > Belges']
// }
// }
//
// If parent refinement is `beers`, then we do not want to have `bières > Belges`
// showing up
var picked = Object.keys(hierarchicalFacetResult.data).map(function (facetValue) {
return [facetValue, hierarchicalFacetResult.data[facetValue]];
}).filter(function (tuple) {
var facetValue = tuple[0];
return onlyMatchingTree(facetValue, parent.path || hierarchicalRootPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel);
});
parent.data = orderBy_1(picked.map(function (tuple) {
var facetValue = tuple[0];
var facetCount = tuple[1];
return format(facetCount, facetValue, hierarchicalSeparator, currentRefinement, hierarchicalFacetResult.exhaustive);
}), sortBy[0], sortBy[1]);
}
return hierarchicalTree;
};
}
function onlyMatchingTree(facetValue, parentPath, currentRefinement, hierarchicalSeparator, hierarchicalRootPath, hierarchicalShowParentLevel) {
// we want the facetValue is a child of hierarchicalRootPath
if (hierarchicalRootPath && (facetValue.indexOf(hierarchicalRootPath) !== 0 || hierarchicalRootPath === facetValue)) {
return false;
} // we always want root levels (only when there is no prefix path)
return !hierarchicalRootPath && facetValue.indexOf(hierarchicalSeparator) === -1 || // if there is a rootPath, being root level mean 1 level under rootPath
hierarchicalRootPath && facetValue.split(hierarchicalSeparator).length - hierarchicalRootPath.split(hierarchicalSeparator).length === 1 || // if current refinement is a root level and current facetValue is a root level,
// keep the facetValue
facetValue.indexOf(hierarchicalSeparator) === -1 && currentRefinement.indexOf(hierarchicalSeparator) === -1 || // currentRefinement is a child of the facet value
currentRefinement.indexOf(facetValue) === 0 || // facetValue is a child of the current parent, add it
facetValue.indexOf(parentPath + hierarchicalSeparator) === 0 && (hierarchicalShowParentLevel || facetValue.indexOf(currentRefinement) === 0);
}
function format(facetCount, facetValue, hierarchicalSeparator, currentRefinement, exhaustive) {
var parts = facetValue.split(hierarchicalSeparator);
return {
name: parts[parts.length - 1].trim(),
path: facetValue,
count: facetCount,
isRefined: currentRefinement === facetValue || currentRefinement.indexOf(facetValue + hierarchicalSeparator) === 0,
exhaustive: exhaustive,
data: null
};
}
/**
* @typedef SearchResults.Facet
* @type {object}
* @property {string} name name of the attribute in the record
* @property {object} data the faceting data: value, number of entries
* @property {object} stats undefined unless facet_stats is retrieved from algolia
*/
/**
* @typedef SearchResults.HierarchicalFacet
* @type {object}
* @property {string} name name of the current value given the hierarchical level, trimmed.
* If root node, you get the facet name
* @property {number} count number of objects matching this hierarchical value
* @property {string} path the current hierarchical value full path
* @property {boolean} isRefined `true` if the current value was refined, `false` otherwise
* @property {HierarchicalFacet[]} data sub values for the current level
*/
/**
* @typedef SearchResults.FacetValue
* @type {object}
* @property {string} name the facet value itself
* @property {number} count times this facet appears in the results
* @property {boolean} isRefined is the facet currently selected
* @property {boolean} isExcluded is the facet currently excluded (only for conjunctive facets)
*/
/**
* @typedef Refinement
* @type {object}
* @property {string} type the type of filter used:
* `numeric`, `facet`, `exclude`, `disjunctive`, `hierarchical`
* @property {string} attributeName name of the attribute used for filtering
* @property {string} name the value of the filter
* @property {number} numericValue the value as a number. Only for numeric filters.
* @property {string} operator the operator used. Only for numeric filters.
* @property {number} count the number of computed hits for this filter. Only on facets.
* @property {boolean} exhaustive if the count is exhaustive
*/
/**
* @param {string[]} attributes
*/
function getIndices(attributes) {
var indices = {};
attributes.forEach(function (val, idx) {
indices[val] = idx;
});
return indices;
}
function assignFacetStats(dest, facetStats, key) {
if (facetStats && facetStats[key]) {
dest.stats = facetStats[key];
}
}
/**
* @typedef {Object} HierarchicalFacet
* @property {string} name
* @property {string[]} attributes
*/
/**
* @param {HierarchicalFacet[]} hierarchicalFacets
* @param {string} hierarchicalAttributeName
*/
function findMatchingHierarchicalFacetFromAttributeName(hierarchicalFacets, hierarchicalAttributeName) {
return find$1(hierarchicalFacets, function facetKeyMatchesAttribute(hierarchicalFacet) {
var facetNames = hierarchicalFacet.attributes || [];
return facetNames.indexOf(hierarchicalAttributeName) > -1;
});
}
/*eslint-disable */
/**
* Constructor for SearchResults
* @class
* @classdesc SearchResults contains the results of a query to Algolia using the
* {@link AlgoliaSearchHelper}.
* @param {SearchParameters} state state that led to the response
* @param {array.<object>} results the results from algolia client
* @example <caption>SearchResults of the first query in
* <a href="http://demos.algolia.com/instant-search-demo">the instant search demo</a></caption>
{
"hitsPerPage": 10,
"processingTimeMS": 2,
"facets": [
{
"name": "type",
"data": {
"HardGood": 6627,
"BlackTie": 550,
"Music": 665,
"Software": 131,
"Game": 456,
"Movie": 1571
},
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"Free shipping": 5507
},
"name": "shipping"
}
],
"hits": [
{
"thumbnailImage": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_54x108_s.gif",
"_highlightResult": {
"shortDescription": {
"matchLevel": "none",
"value": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"matchedWords": []
},
"category": {
"matchLevel": "none",
"value": "Computer Security Software",
"matchedWords": []
},
"manufacturer": {
"matchedWords": [],
"value": "Webroot",
"matchLevel": "none"
},
"name": {
"value": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"matchedWords": [],
"matchLevel": "none"
}
},
"image": "http://img.bbystatic.com/BestBuy_US/images/products/1688/1688832_105x210_sc.jpg",
"shipping": "Free shipping",
"bestSellingRank": 4,
"shortDescription": "Safeguard your PC, Mac, Android and iOS devices with comprehensive Internet protection",
"url": "http://www.bestbuy.com/site/webroot-secureanywhere-internet-security-3-devi…d=1219060687969&skuId=1688832&cmp=RMX&ky=2d3GfEmNIzjA0vkzveHdZEBgpPCyMnLTJ",
"name": "Webroot SecureAnywhere Internet Security (3-Device) (1-Year Subscription) - Mac/Windows",
"category": "Computer Security Software",
"salePrice_range": "1 - 50",
"objectID": "1688832",
"type": "Software",
"customerReviewCount": 5980,
"salePrice": 49.99,
"manufacturer": "Webroot"
},
....
],
"nbHits": 10000,
"disjunctiveFacets": [
{
"exhaustive": false,
"data": {
"5": 183,
"12": 112,
"7": 149,
...
},
"name": "customerReviewCount",
"stats": {
"max": 7461,
"avg": 157.939,
"min": 1
}
},
{
"data": {
"Printer Ink": 142,
"Wireless Speakers": 60,
"Point & Shoot Cameras": 48,
...
},
"name": "category",
"exhaustive": false
},
{
"exhaustive": false,
"data": {
"> 5000": 2,
"1 - 50": 6524,
"501 - 2000": 566,
"201 - 500": 1501,
"101 - 200": 1360,
"2001 - 5000": 47
},
"name": "salePrice_range"
},
{
"data": {
"Dynex™": 202,
"Insignia™": 230,
"PNY": 72,
...
},
"name": "manufacturer",
"exhaustive": false
}
],
"query": "",
"nbPages": 100,
"page": 0,
"index": "bestbuy"
}
**/
/*eslint-enable */
function SearchResults(state, results) {
var mainSubResponse = results[0];
this._rawResults = results;
/**
* query used to generate the results
* @member {string}
*/
this.query = mainSubResponse.query;
/**
* The query as parsed by the engine given all the rules.
* @member {string}
*/
this.parsedQuery = mainSubResponse.parsedQuery;
/**
* all the records that match the search parameters. Each record is
* augmented with a new attribute `_highlightResult`
* which is an object keyed by attribute and with the following properties:
* - `value` : the value of the facet highlighted (html)
* - `matchLevel`: full, partial or none depending on how the query terms match
* @member {object[]}
*/
this.hits = mainSubResponse.hits;
/**
* index where the results come from
* @member {string}
*/
this.index = mainSubResponse.index;
/**
* number of hits per page requested
* @member {number}
*/
this.hitsPerPage = mainSubResponse.hitsPerPage;
/**
* total number of hits of this query on the index
* @member {number}
*/
this.nbHits = mainSubResponse.nbHits;
/**
* total number of pages with respect to the number of hits per page and the total number of hits
* @member {number}
*/
this.nbPages = mainSubResponse.nbPages;
/**
* current page
* @member {number}
*/
this.page = mainSubResponse.page;
/**
* sum of the processing time of all the queries
* @member {number}
*/
this.processingTimeMS = results.reduce(function (sum, result) {
return result.processingTimeMS === undefined ? sum : sum + result.processingTimeMS;
}, 0);
/**
* The position if the position was guessed by IP.
* @member {string}
* @example "48.8637,2.3615",
*/
this.aroundLatLng = mainSubResponse.aroundLatLng;
/**
* The radius computed by Algolia.
* @member {string}
* @example "126792922",
*/
this.automaticRadius = mainSubResponse.automaticRadius;
/**
* String identifying the server used to serve this request.
*
* getRankingInfo needs to be set to `true` for this to be returned
*
* @member {string}
* @example "c7-use-2.algolia.net",
*/
this.serverUsed = mainSubResponse.serverUsed;
/**
* Boolean that indicates if the computation of the counts did time out.
* @deprecated
* @member {boolean}
*/
this.timeoutCounts = mainSubResponse.timeoutCounts;
/**
* Boolean that indicates if the computation of the hits did time out.
* @deprecated
* @member {boolean}
*/
this.timeoutHits = mainSubResponse.timeoutHits;
/**
* True if the counts of the facets is exhaustive
* @member {boolean}
*/
this.exhaustiveFacetsCount = mainSubResponse.exhaustiveFacetsCount;
/**
* True if the number of hits is exhaustive
* @member {boolean}
*/
this.exhaustiveNbHits = mainSubResponse.exhaustiveNbHits;
/**
* Contains the userData if they are set by a [query rule](https://www.algolia.com/doc/guides/query-rules/query-rules-overview/).
* @member {object[]}
*/
this.userData = mainSubResponse.userData;
/**
* queryID is the unique identifier of the query used to generate the current search results.
* This value is only available if the `clickAnalytics` search parameter is set to `true`.
* @member {string}
*/
this.queryID = mainSubResponse.queryID;
/**
* disjunctive facets results
* @member {SearchResults.Facet[]}
*/
this.disjunctiveFacets = [];
/**
* disjunctive facets results
* @member {SearchResults.HierarchicalFacet[]}
*/
this.hierarchicalFacets = state.hierarchicalFacets.map(function initFutureTree() {
return [];
});
/**
* other facets results
* @member {SearchResults.Facet[]}
*/
this.facets = [];
var disjunctiveFacets = state.getRefinedDisjunctiveFacets();
var facetsIndices = getIndices(state.facets);
var disjunctiveFacetsIndices = getIndices(state.disjunctiveFacets);
var nextDisjunctiveResult = 1;
var self = this; // Since we send request only for disjunctive facets that have been refined,
// we get the facets information from the first, general, response.
var mainFacets = mainSubResponse.facets || {};
Object.keys(mainFacets).forEach(function (facetKey) {
var facetValueObject = mainFacets[facetKey];
var hierarchicalFacet = findMatchingHierarchicalFacetFromAttributeName(state.hierarchicalFacets, facetKey);
if (hierarchicalFacet) {
// Place the hierarchicalFacet data at the correct index depending on
// the attributes order that was defined at the helper initialization
var facetIndex = hierarchicalFacet.attributes.indexOf(facetKey);
var idxAttributeName = findIndex(state.hierarchicalFacets, function (f) {
return f.name === hierarchicalFacet.name;
});
self.hierarchicalFacets[idxAttributeName][facetIndex] = {
attribute: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
} else {
var isFacetDisjunctive = state.disjunctiveFacets.indexOf(facetKey) !== -1;
var isFacetConjunctive = state.facets.indexOf(facetKey) !== -1;
var position;
if (isFacetDisjunctive) {
position = disjunctiveFacetsIndices[facetKey];
self.disjunctiveFacets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], mainSubResponse.facets_stats, facetKey);
}
if (isFacetConjunctive) {
position = facetsIndices[facetKey];
self.facets[position] = {
name: facetKey,
data: facetValueObject,
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
assignFacetStats(self.facets[position], mainSubResponse.facets_stats, facetKey);
}
}
}); // Make sure we do not keep holes within the hierarchical facets
this.hierarchicalFacets = compact(this.hierarchicalFacets); // aggregate the refined disjunctive facets
disjunctiveFacets.forEach(function (disjunctiveFacet) {
var result = results[nextDisjunctiveResult];
var facets = result && result.facets ? result.facets : {};
var hierarchicalFacet = state.getHierarchicalFacetByName(disjunctiveFacet); // There should be only item in facets.
Object.keys(facets).forEach(function (dfacet) {
var facetResults = facets[dfacet];
var position;
if (hierarchicalFacet) {
position = findIndex(state.hierarchicalFacets, function (f) {
return f.name === hierarchicalFacet.name;
});
var attributeIndex = findIndex(self.hierarchicalFacets[position], function (f) {
return f.attribute === dfacet;
}); // previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
}
self.hierarchicalFacets[position][attributeIndex].data = merge$1({}, self.hierarchicalFacets[position][attributeIndex].data, facetResults);
} else {
position = disjunctiveFacetsIndices[dfacet];
var dataFromMainRequest = mainSubResponse.facets && mainSubResponse.facets[dfacet] || {};
self.disjunctiveFacets[position] = {
name: dfacet,
data: defaultsPure({}, facetResults, dataFromMainRequest),
exhaustive: result.exhaustiveFacetsCount
};
assignFacetStats(self.disjunctiveFacets[position], result.facets_stats, dfacet);
if (state.disjunctiveFacetsRefinements[dfacet]) {
state.disjunctiveFacetsRefinements[dfacet].forEach(function (refinementValue) {
// add the disjunctive refinements if it is no more retrieved
if (!self.disjunctiveFacets[position].data[refinementValue] && state.disjunctiveFacetsRefinements[dfacet].indexOf(refinementValue) > -1) {
self.disjunctiveFacets[position].data[refinementValue] = 0;
}
});
}
}
});
nextDisjunctiveResult++;
}); // if we have some root level values for hierarchical facets, merge them
state.getRefinedHierarchicalFacets().forEach(function (refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are already at a root refinement (or no refinement at all), there is no
// root level values request
if (currentRefinement.length === 0 || currentRefinement[0].split(separator).length < 2) {
return;
}
var result = results[nextDisjunctiveResult];
var facets = result && result.facets ? result.facets : {};
Object.keys(facets).forEach(function (dfacet) {
var facetResults = facets[dfacet];
var position = findIndex(state.hierarchicalFacets, function (f) {
return f.name === hierarchicalFacet.name;
});
var attributeIndex = findIndex(self.hierarchicalFacets[position], function (f) {
return f.attribute === dfacet;
}); // previous refinements and no results so not able to find it
if (attributeIndex === -1) {
return;
} // when we always get root levels, if the hits refinement is `beers > IPA` (count: 5),
// then the disjunctive values will be `beers` (count: 100),
// but we do not want to display
// | beers (100)
// > IPA (5)
// We want
// | beers (5)
// > IPA (5)
var defaultData = {};
if (currentRefinement.length > 0) {
var root = currentRefinement[0].split(separator)[0];
defaultData[root] = self.hierarchicalFacets[position][attributeIndex].data[root];
}
self.hierarchicalFacets[position][attributeIndex].data = defaultsPure(defaultData, facetResults, self.hierarchicalFacets[position][attributeIndex].data);
});
nextDisjunctiveResult++;
}); // add the excludes
Object.keys(state.facetsExcludes).forEach(function (facetName) {
var excludes = state.facetsExcludes[facetName];
var position = facetsIndices[facetName];
self.facets[position] = {
name: facetName,
data: mainSubResponse.facets[facetName],
exhaustive: mainSubResponse.exhaustiveFacetsCount
};
excludes.forEach(function (facetValue) {
self.facets[position] = self.facets[position] || {
name: facetName
};
self.facets[position].data = self.facets[position].data || {};
self.facets[position].data[facetValue] = 0;
});
});
/**
* @type {Array}
*/
this.hierarchicalFacets = this.hierarchicalFacets.map(generateHierarchicalTree_1(state));
/**
* @type {Array}
*/
this.facets = compact(this.facets);
/**
* @type {Array}
*/
this.disjunctiveFacets = compact(this.disjunctiveFacets);
this._state = state;
}
/**
* Get a facet object with its name
* @deprecated
* @param {string} name name of the faceted attribute
* @return {SearchResults.Facet} the facet object
*/
SearchResults.prototype.getFacetByName = function (name) {
function predicate(facet) {
return facet.name === name;
}
return find$1(this.facets, predicate) || find$1(this.disjunctiveFacets, predicate) || find$1(this.hierarchicalFacets, predicate);
};
/**
* Get the facet values of a specified attribute from a SearchResults object.
* @private
* @param {SearchResults} results the search results to search in
* @param {string} attribute name of the faceted attribute to search for
* @return {array|object} facet values. For the hierarchical facets it is an object.
*/
function extractNormalizedFacetValues(results, attribute) {
function predicate(facet) {
return facet.name === attribute;
}
if (results._state.isConjunctiveFacet(attribute)) {
var facet = find$1(results.facets, predicate);
if (!facet) return [];
return Object.keys(facet.data).map(function (name) {
return {
name: name,
count: facet.data[name],
isRefined: results._state.isFacetRefined(attribute, name),
isExcluded: results._state.isExcludeRefined(attribute, name)
};
});
} else if (results._state.isDisjunctiveFacet(attribute)) {
var disjunctiveFacet = find$1(results.disjunctiveFacets, predicate);
if (!disjunctiveFacet) return [];
return Object.keys(disjunctiveFacet.data).map(function (name) {
return {
name: name,
count: disjunctiveFacet.data[name],
isRefined: results._state.isDisjunctiveFacetRefined(attribute, name)
};
});
} else if (results._state.isHierarchicalFacet(attribute)) {
return find$1(results.hierarchicalFacets, predicate);
}
}
/**
* Sort nodes of a hierarchical facet results
* @private
* @param {HierarchicalFacet} node node to upon which we want to apply the sort
*/
function recSort(sortFn, node) {
if (!node.data || node.data.length === 0) {
return node;
}
var children = node.data.map(function (childNode) {
return recSort(sortFn, childNode);
});
var sortedChildren = sortFn(children);
var newNode = merge$1({}, node, {
data: sortedChildren
});
return newNode;
}
SearchResults.DEFAULT_SORT = ['isRefined:desc', 'count:desc', 'name:asc'];
function vanillaSortFn(order, data) {
return data.sort(order);
}
/**
* Get a the list of values for a given facet attribute. Those values are sorted
* refinement first, descending count (bigger value on top), and name ascending
* (alphabetical order). The sort formula can overridden using either string based
* predicates or a function.
*
* This method will return all the values returned by the Algolia engine plus all
* the values already refined. This means that it can happen that the
* `maxValuesPerFacet` [configuration](https://www.algolia.com/doc/rest-api/search#param-maxValuesPerFacet)
* might not be respected if you have facet values that are already refined.
* @param {string} attribute attribute name
* @param {object} opts configuration options.
* @param {Array.<string> | function} opts.sortBy
* When using strings, it consists of
* the name of the [FacetValue](#SearchResults.FacetValue) or the
* [HierarchicalFacet](#SearchResults.HierarchicalFacet) attributes with the
* order (`asc` or `desc`). For example to order the value by count, the
* argument would be `['count:asc']`.
*
* If only the attribute name is specified, the ordering defaults to the one
* specified in the default value for this attribute.
*
* When not specified, the order is
* ascending. This parameter can also be a function which takes two facet
* values and should return a number, 0 if equal, 1 if the first argument is
* bigger or -1 otherwise.
*
* The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']`
* @return {FacetValue[]|HierarchicalFacet|undefined} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('result', function(event){
* //get values ordered only by name ascending using the string predicate
* event.results.getFacetValues('city', {sortBy: ['name:asc']});
* //get values ordered only by count ascending using a function
* event.results.getFacetValues('city', {
* // this is equivalent to ['count:asc']
* sortBy: function(a, b) {
* if (a.count === b.count) return 0;
* if (a.count > b.count) return 1;
* if (b.count > a.count) return -1;
* }
* });
* });
*/
SearchResults.prototype.getFacetValues = function (attribute, opts) {
var facetValues = extractNormalizedFacetValues(this, attribute);
if (!facetValues) {
return undefined;
}
var options = defaultsPure({}, opts, {
sortBy: SearchResults.DEFAULT_SORT
});
if (Array.isArray(options.sortBy)) {
var order = formatSort(options.sortBy, SearchResults.DEFAULT_SORT);
if (Array.isArray(facetValues)) {
return orderBy_1(facetValues, order[0], order[1]);
} // If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(function (hierarchicalFacetValues) {
return orderBy_1(hierarchicalFacetValues, order[0], order[1]);
}, facetValues);
} else if (typeof options.sortBy === 'function') {
if (Array.isArray(facetValues)) {
return facetValues.sort(options.sortBy);
} // If facetValues is not an array, it's an object thus a hierarchical facet object
return recSort(function (data) {
return vanillaSortFn(options.sortBy, data);
}, facetValues);
}
throw new Error('options.sortBy is optional but if defined it must be ' + 'either an array of string (predicates) or a sorting function');
};
/**
* Returns the facet stats if attribute is defined and the facet contains some.
* Otherwise returns undefined.
* @param {string} attribute name of the faceted attribute
* @return {object} The stats of the facet
*/
SearchResults.prototype.getFacetStats = function (attribute) {
if (this._state.isConjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.facets, attribute);
} else if (this._state.isDisjunctiveFacet(attribute)) {
return getFacetStatsIfAvailable(this.disjunctiveFacets, attribute);
}
return undefined;
};
/**
* @typedef {Object} FacetListItem
* @property {string} name
*/
/**
* @param {FacetListItem[]} facetList (has more items, but enough for here)
* @param {string} facetName
*/
function getFacetStatsIfAvailable(facetList, facetName) {
var data = find$1(facetList, function (facet) {
return facet.name === facetName;
});
return data && data.stats;
}
/**
* Returns all refinements for all filters + tags. It also provides
* additional information: count and exhaustiveness for each filter.
*
* See the [refinement type](#Refinement) for an exhaustive view of the available
* data.
*
* Note that for a numeric refinement, results are grouped per operator, this
* means that it will return responses for operators which are empty.
*
* @return {Array.<Refinement>} all the refinements
*/
SearchResults.prototype.getRefinements = function () {
var state = this._state;
var results = this;
var res = [];
Object.keys(state.facetsRefinements).forEach(function (attributeName) {
state.facetsRefinements[attributeName].forEach(function (name) {
res.push(getRefinement(state, 'facet', attributeName, name, results.facets));
});
});
Object.keys(state.facetsExcludes).forEach(function (attributeName) {
state.facetsExcludes[attributeName].forEach(function (name) {
res.push(getRefinement(state, 'exclude', attributeName, name, results.facets));
});
});
Object.keys(state.disjunctiveFacetsRefinements).forEach(function (attributeName) {
state.disjunctiveFacetsRefinements[attributeName].forEach(function (name) {
res.push(getRefinement(state, 'disjunctive', attributeName, name, results.disjunctiveFacets));
});
});
Object.keys(state.hierarchicalFacetsRefinements).forEach(function (attributeName) {
state.hierarchicalFacetsRefinements[attributeName].forEach(function (name) {
res.push(getHierarchicalRefinement(state, attributeName, name, results.hierarchicalFacets));
});
});
Object.keys(state.numericRefinements).forEach(function (attributeName) {
var operators = state.numericRefinements[attributeName];
Object.keys(operators).forEach(function (operator) {
operators[operator].forEach(function (value) {
res.push({
type: 'numeric',
attributeName: attributeName,
name: value,
numericValue: value,
operator: operator
});
});
});
});
state.tagRefinements.forEach(function (name) {
res.push({
type: 'tag',
attributeName: '_tags',
name: name
});
});
return res;
};
/**
* @typedef {Object} Facet
* @property {string} name
* @property {Object} data
* @property {boolean} exhaustive
*/
/**
* @param {*} state
* @param {*} type
* @param {string} attributeName
* @param {*} name
* @param {Facet[]} resultsFacets
*/
function getRefinement(state, type, attributeName, name, resultsFacets) {
var facet = find$1(resultsFacets, function (f) {
return f.name === attributeName;
});
var count = facet && facet.data && facet.data[name] ? facet.data[name] : 0;
var exhaustive = facet && facet.exhaustive || false;
return {
type: type,
attributeName: attributeName,
name: name,
count: count,
exhaustive: exhaustive
};
}
/**
* @param {*} state
* @param {string} attributeName
* @param {*} name
* @param {Facet[]} resultsFacets
*/
function getHierarchicalRefinement(state, attributeName, name, resultsFacets) {
var facetDeclaration = state.getHierarchicalFacetByName(attributeName);
var separator = state._getHierarchicalFacetSeparator(facetDeclaration);
var split = name.split(separator);
var rootFacet = find$1(resultsFacets, function (facet) {
return facet.name === attributeName;
});
var facet = split.reduce(function (intermediateFacet, part) {
var newFacet = intermediateFacet && find$1(intermediateFacet.data, function (f) {
return f.name === part;
});
return newFacet !== undefined ? newFacet : intermediateFacet;
}, rootFacet);
var count = facet && facet.count || 0;
var exhaustive = facet && facet.exhaustive || false;
var path = facet && facet.path || '';
return {
type: 'hierarchical',
attributeName: attributeName,
name: path,
count: count,
exhaustive: exhaustive
};
}
var SearchResults_1 = SearchResults;
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
var events = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
function inherits(ctor, superCtor) {
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
var inherits_1 = inherits;
/**
* A DerivedHelper is a way to create sub requests to
* Algolia from a main helper.
* @class
* @classdesc The DerivedHelper provides an event based interface for search callbacks:
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
*/
function DerivedHelper(mainHelper, fn) {
this.main = mainHelper;
this.fn = fn;
this.lastResults = null;
}
inherits_1(DerivedHelper, events.EventEmitter);
/**
* Detach this helper from the main helper
* @return {undefined}
* @throws Error if the derived helper is already detached
*/
DerivedHelper.prototype.detach = function () {
this.removeAllListeners();
this.main.detachDerivedHelper(this);
};
DerivedHelper.prototype.getModifiedState = function (parameters) {
return this.fn(parameters);
};
var DerivedHelper_1 = DerivedHelper;
var requestBuilder = {
/**
* Get all the queries to send to the client, those queries can used directly
* with the Algolia client.
* @private
* @return {object[]} The queries
*/
_getQueries: function getQueries(index, state) {
var queries = []; // One query for the hits
queries.push({
indexName: index,
params: requestBuilder._getHitsSearchParams(state)
}); // One for each disjunctive facets
state.getRefinedDisjunctiveFacets().forEach(function (refinedFacet) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet)
});
}); // maybe more to get the root level of hierarchical facets when activated
state.getRefinedHierarchicalFacets().forEach(function (refinedFacet) {
var hierarchicalFacet = state.getHierarchicalFacetByName(refinedFacet);
var currentRefinement = state.getHierarchicalRefinement(refinedFacet); // if we are deeper than level 0 (starting from `beer > IPA`)
// we want to get the root values
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (currentRefinement.length > 0 && currentRefinement[0].split(separator).length > 1) {
queries.push({
indexName: index,
params: requestBuilder._getDisjunctiveFacetSearchParams(state, refinedFacet, true)
});
}
});
return queries;
},
/**
* Build search parameters used to fetch hits
* @private
* @return {object.<string, any>}
*/
_getHitsSearchParams: function _getHitsSearchParams(state) {
var facets = state.facets.concat(state.disjunctiveFacets).concat(requestBuilder._getHitsHierarchicalFacetsAttributes(state));
var facetFilters = requestBuilder._getFacetFilters(state);
var numericFilters = requestBuilder._getNumericFilters(state);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
facets: facets,
tagFilters: tagFilters
};
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
return merge$1({}, state.getQueryParams(), additionalParams);
},
/**
* Build search parameters used to fetch a disjunctive facet
* @private
* @param {string} facet the associated facet name
* @param {boolean} hierarchicalRootLevel ?? FIXME
* @return {object}
*/
_getDisjunctiveFacetSearchParams: function _getDisjunctiveFacetSearchParams(state, facet, hierarchicalRootLevel) {
var facetFilters = requestBuilder._getFacetFilters(state, facet, hierarchicalRootLevel);
var numericFilters = requestBuilder._getNumericFilters(state, facet);
var tagFilters = requestBuilder._getTagFilters(state);
var additionalParams = {
hitsPerPage: 1,
page: 0,
attributesToRetrieve: [],
attributesToHighlight: [],
attributesToSnippet: [],
tagFilters: tagFilters,
analytics: false,
clickAnalytics: false
};
var hierarchicalFacet = state.getHierarchicalFacetByName(facet);
if (hierarchicalFacet) {
additionalParams.facets = requestBuilder._getDisjunctiveHierarchicalFacetAttribute(state, hierarchicalFacet, hierarchicalRootLevel);
} else {
additionalParams.facets = facet;
}
if (numericFilters.length > 0) {
additionalParams.numericFilters = numericFilters;
}
if (facetFilters.length > 0) {
additionalParams.facetFilters = facetFilters;
}
return merge$1({}, state.getQueryParams(), additionalParams);
},
/**
* Return the numeric filters in an algolia request fashion
* @private
* @param {string} [facetName] the name of the attribute for which the filters should be excluded
* @return {string[]} the numeric filters in the algolia format
*/
_getNumericFilters: function _getNumericFilters(state, facetName) {
if (state.numericFilters) {
return state.numericFilters;
}
var numericFilters = [];
Object.keys(state.numericRefinements).forEach(function (attribute) {
var operators = state.numericRefinements[attribute] || {};
Object.keys(operators).forEach(function (operator) {
var values = operators[operator] || [];
if (facetName !== attribute) {
values.forEach(function (value) {
if (Array.isArray(value)) {
var vs = value.map(function (v) {
return attribute + operator + v;
});
numericFilters.push(vs);
} else {
numericFilters.push(attribute + operator + value);
}
});
}
});
});
return numericFilters;
},
/**
* Return the tags filters depending
* @private
* @return {string}
*/
_getTagFilters: function _getTagFilters(state) {
if (state.tagFilters) {
return state.tagFilters;
}
return state.tagRefinements.join(',');
},
/**
* Build facetFilters parameter based on current refinements. The array returned
* contains strings representing the facet filters in the algolia format.
* @private
* @param {string} [facet] if set, the current disjunctive facet
* @return {array.<string>}
*/
_getFacetFilters: function _getFacetFilters(state, facet, hierarchicalRootLevel) {
var facetFilters = [];
var facetsRefinements = state.facetsRefinements || {};
Object.keys(facetsRefinements).forEach(function (facetName) {
var facetValues = facetsRefinements[facetName] || [];
facetValues.forEach(function (facetValue) {
facetFilters.push(facetName + ':' + facetValue);
});
});
var facetsExcludes = state.facetsExcludes || {};
Object.keys(facetsExcludes).forEach(function (facetName) {
var facetValues = facetsExcludes[facetName] || [];
facetValues.forEach(function (facetValue) {
facetFilters.push(facetName + ':-' + facetValue);
});
});
var disjunctiveFacetsRefinements = state.disjunctiveFacetsRefinements || {};
Object.keys(disjunctiveFacetsRefinements).forEach(function (facetName) {
var facetValues = disjunctiveFacetsRefinements[facetName] || [];
if (facetName === facet || !facetValues || facetValues.length === 0) {
return;
}
var orFilters = [];
facetValues.forEach(function (facetValue) {
orFilters.push(facetName + ':' + facetValue);
});
facetFilters.push(orFilters);
});
var hierarchicalFacetsRefinements = state.hierarchicalFacetsRefinements || {};
Object.keys(hierarchicalFacetsRefinements).forEach(function (facetName) {
var facetValues = hierarchicalFacetsRefinements[facetName] || [];
var facetValue = facetValues[0];
if (facetValue === undefined) {
return;
}
var hierarchicalFacet = state.getHierarchicalFacetByName(facetName);
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeToRefine;
var attributesIndex; // we ask for parent facet values only when the `facet` is the current hierarchical facet
if (facet === facetName) {
// if we are at the root level already, no need to ask for facet values, we get them from
// the hits query
if (facetValue.indexOf(separator) === -1 || !rootPath && hierarchicalRootLevel === true || rootPath && rootPath.split(separator).length === facetValue.split(separator).length) {
return;
}
if (!rootPath) {
attributesIndex = facetValue.split(separator).length - 2;
facetValue = facetValue.slice(0, facetValue.lastIndexOf(separator));
} else {
attributesIndex = rootPath.split(separator).length - 1;
facetValue = rootPath;
}
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
} else {
attributesIndex = facetValue.split(separator).length - 1;
attributeToRefine = hierarchicalFacet.attributes[attributesIndex];
}
if (attributeToRefine) {
facetFilters.push([attributeToRefine + ':' + facetValue]);
}
});
return facetFilters;
},
_getHitsHierarchicalFacetsAttributes: function _getHitsHierarchicalFacetsAttributes(state) {
var out = [];
return state.hierarchicalFacets.reduce( // ask for as much levels as there's hierarchical refinements
function getHitsAttributesForHierarchicalFacet(allAttributes, hierarchicalFacet) {
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0]; // if no refinement, ask for root level
if (!hierarchicalRefinement) {
allAttributes.push(hierarchicalFacet.attributes[0]);
return allAttributes;
}
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
var level = hierarchicalRefinement.split(separator).length;
var newAttributes = hierarchicalFacet.attributes.slice(0, level + 1);
return allAttributes.concat(newAttributes);
}, out);
},
_getDisjunctiveHierarchicalFacetAttribute: function _getDisjunctiveHierarchicalFacetAttribute(state, hierarchicalFacet, rootLevel) {
var separator = state._getHierarchicalFacetSeparator(hierarchicalFacet);
if (rootLevel === true) {
var rootPath = state._getHierarchicalRootPath(hierarchicalFacet);
var attributeIndex = 0;
if (rootPath) {
attributeIndex = rootPath.split(separator).length;
}
return [hierarchicalFacet.attributes[attributeIndex]];
}
var hierarchicalRefinement = state.getHierarchicalRefinement(hierarchicalFacet.name)[0] || ''; // if refinement is 'beers > IPA > Flying dog',
// then we want `facets: ['beers > IPA']` as disjunctive facet (parent level values)
var parentLevel = hierarchicalRefinement.split(separator).length - 1;
return hierarchicalFacet.attributes.slice(0, parentLevel + 1);
},
getSearchForFacetQuery: function getSearchForFacetQuery(facetName, query, maxFacetHits, state) {
var stateForSearchForFacetValues = state.isDisjunctiveFacet(facetName) ? state.clearRefinements(facetName) : state;
var searchForFacetSearchParameters = {
facetQuery: query,
facetName: facetName
};
if (typeof maxFacetHits === 'number') {
searchForFacetSearchParameters.maxFacetHits = maxFacetHits;
}
return merge$1({}, requestBuilder._getHitsSearchParams(stateForSearchForFacetValues), searchForFacetSearchParameters);
}
};
var requestBuilder_1 = requestBuilder;
var version = '0.0.0-6ac260d';
/**
* Event triggered when a parameter is set or updated
* @event AlgoliaSearchHelper#event:change
* @property {object} event
* @property {SearchParameters} event.state the current parameters with the latest changes applied
* @property {SearchResults} event.results the previous results received from Algolia. `null` before the first request
* @example
* helper.on('change', function(event) {
* console.log('The parameters have changed');
* });
*/
/**
* Event triggered when a main search is sent to Algolia
* @event AlgoliaSearchHelper#event:search
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search
* @property {SearchResults} event.results the results from the previous search. `null` if it is the first search.
* @example
* helper.on('search', function(event) {
* console.log('Search sent');
* });
*/
/**
* Event triggered when a search using `searchForFacetValues` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchForFacetValues
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search it is the first search.
* @property {string} event.facet the facet searched into
* @property {string} event.query the query used to search in the facets
* @example
* helper.on('searchForFacetValues', function(event) {
* console.log('searchForFacetValues sent');
* });
*/
/**
* Event triggered when a search using `searchOnce` is sent to Algolia
* @event AlgoliaSearchHelper#event:searchOnce
* @property {object} event
* @property {SearchParameters} event.state the parameters used for this search it is the first search.
* @example
* helper.on('searchOnce', function(event) {
* console.log('searchOnce sent');
* });
*/
/**
* Event triggered when the results are retrieved from Algolia
* @event AlgoliaSearchHelper#event:result
* @property {object} event
* @property {SearchResults} event.results the results received from Algolia
* @property {SearchParameters} event.state the parameters used to query Algolia. Those might be different from the one in the helper instance (for example if the network is unreliable).
* @example
* helper.on('result', function(event) {
* console.log('Search results received');
* });
*/
/**
* Event triggered when Algolia sends back an error. For example, if an unknown parameter is
* used, the error can be caught using this event.
* @event AlgoliaSearchHelper#event:error
* @property {object} event
* @property {Error} event.error the error returned by the Algolia.
* @example
* helper.on('error', function(event) {
* console.log('Houston we got a problem.');
* });
*/
/**
* Event triggered when the queue of queries have been depleted (with any result or outdated queries)
* @event AlgoliaSearchHelper#event:searchQueueEmpty
* @example
* helper.on('searchQueueEmpty', function() {
* console.log('No more search pending');
* // This is received before the result event if we're not expecting new results
* });
*
* helper.search();
*/
/**
* Initialize a new AlgoliaSearchHelper
* @class
* @classdesc The AlgoliaSearchHelper is a class that ease the management of the
* search. It provides an event based interface for search callbacks:
* - change: when the internal search state is changed.
* This event contains a {@link SearchParameters} object and the
* {@link SearchResults} of the last result if any.
* - search: when a search is triggered using the `search()` method.
* - result: when the response is retrieved from Algolia and is processed.
* This event contains a {@link SearchResults} object and the
* {@link SearchParameters} corresponding to this answer.
* - error: when the response is an error. This event contains the error returned by the server.
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the index name to query
* @param {SearchParameters | object} options an object defining the initial
* config of the search. It doesn't have to be a {SearchParameters},
* just an object containing the properties you need from it.
*/
function AlgoliaSearchHelper(client, index, options) {
if (typeof client.addAlgoliaAgent === 'function') {
client.addAlgoliaAgent('JS Helper (' + version + ')');
}
this.setClient(client);
var opts = options || {};
opts.index = index;
this.state = SearchParameters_1.make(opts);
this.lastResults = null;
this._queryId = 0;
this._lastQueryIdReceived = -1;
this.derivedHelpers = [];
this._currentNbQueries = 0;
}
inherits_1(AlgoliaSearchHelper, events.EventEmitter);
/**
* Start the search with the parameters set in the state. When the
* method is called, it triggers a `search` event. The results will
* be available through the `result` event. If an error occurs, an
* `error` will be fired instead.
* @return {AlgoliaSearchHelper}
* @fires search
* @fires result
* @fires error
* @chainable
*/
AlgoliaSearchHelper.prototype.search = function () {
this._search({
onlyWithDerivedHelpers: false
});
return this;
};
AlgoliaSearchHelper.prototype.searchOnlyWithDerivedHelpers = function () {
this._search({
onlyWithDerivedHelpers: true
});
return this;
};
/**
* Gets the search query parameters that would be sent to the Algolia Client
* for the hits
* @return {object} Query Parameters
*/
AlgoliaSearchHelper.prototype.getQuery = function () {
var state = this.state;
return requestBuilder_1._getHitsSearchParams(state);
};
/**
* Start a search using a modified version of the current state. This method does
* not trigger the helper lifecycle and does not modify the state kept internally
* by the helper. This second aspect means that the next search call will be the
* same as a search call before calling searchOnce.
* @param {object} options can contain all the parameters that can be set to SearchParameters
* plus the index
* @param {function} [callback] optional callback executed when the response from the
* server is back.
* @return {promise|undefined} if a callback is passed the method returns undefined
* otherwise it returns a promise containing an object with two keys :
* - content with a SearchResults
* - state with the state used for the query as a SearchParameters
* @example
* // Changing the number of records returned per page to 1
* // This example uses the callback API
* var state = helper.searchOnce({hitsPerPage: 1},
* function(error, content, state) {
* // if an error occurred it will be passed in error, otherwise its value is null
* // content contains the results formatted as a SearchResults
* // state is the instance of SearchParameters used for this search
* });
* @example
* // Changing the number of records returned per page to 1
* // This example uses the promise API
* var state1 = helper.searchOnce({hitsPerPage: 1})
* .then(promiseHandler);
*
* function promiseHandler(res) {
* // res contains
* // {
* // content : SearchResults
* // state : SearchParameters (the one used for this specific search)
* // }
* }
*/
AlgoliaSearchHelper.prototype.searchOnce = function (options, cb) {
var tempState = !options ? this.state : this.state.setQueryParameters(options);
var queries = requestBuilder_1._getQueries(tempState.index, tempState);
var self = this;
this._currentNbQueries++;
this.emit('searchOnce', {
state: tempState
});
if (cb) {
this.client.search(queries).then(function (content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) {
self.emit('searchQueueEmpty');
}
cb(null, new SearchResults_1(tempState, content.results), tempState);
}).catch(function (err) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) {
self.emit('searchQueueEmpty');
}
cb(err, null, tempState);
});
return undefined;
}
return this.client.search(queries).then(function (content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
return {
content: new SearchResults_1(tempState, content.results),
state: tempState,
_originalResponse: content
};
}, function (e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Structure of each result when using
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* @typedef FacetSearchHit
* @type {object}
* @property {string} value the facet value
* @property {string} highlighted the facet value highlighted with the query string
* @property {number} count number of occurrence of this facet value
* @property {boolean} isRefined true if the value is already refined
*/
/**
* Structure of the data resolved by the
* [`searchForFacetValues()`](reference.html#AlgoliaSearchHelper#searchForFacetValues)
* promise.
* @typedef FacetSearchResult
* @type {object}
* @property {FacetSearchHit} facetHits the results for this search for facet values
* @property {number} processingTimeMS time taken by the query inside the engine
*/
/**
* Search for facet values based on an query and the name of a faceted attribute. This
* triggers a search and will return a promise. On top of using the query, it also sends
* the parameters from the state so that the search is narrowed down to only the possible values.
*
* See the description of [FacetSearchResult](reference.html#FacetSearchResult)
* @param {string} facet the name of the faceted attribute
* @param {string} query the string query for the search
* @param {number} [maxFacetHits] the maximum number values returned. Should be > 0 and <= 100
* @param {object} [userState] the set of custom parameters to use on top of the current state. Setting a property to `undefined` removes
* it in the generated query.
* @return {promise.<FacetSearchResult>} the results of the search
*/
AlgoliaSearchHelper.prototype.searchForFacetValues = function (facet, query, maxFacetHits, userState) {
var clientHasSFFV = typeof this.client.searchForFacetValues === 'function';
if (!clientHasSFFV && typeof this.client.initIndex !== 'function') {
throw new Error('search for facet values (searchable) was called, but this client does not have a function client.searchForFacetValues or client.initIndex(index).searchForFacetValues');
}
var state = this.state.setQueryParameters(userState || {});
var isDisjunctive = state.isDisjunctiveFacet(facet);
var algoliaQuery = requestBuilder_1.getSearchForFacetQuery(facet, query, maxFacetHits, state);
this._currentNbQueries++;
var self = this;
this.emit('searchForFacetValues', {
state: state,
facet: facet,
query: query
});
var searchForFacetValuesPromise = clientHasSFFV ? this.client.searchForFacetValues([{
indexName: state.index,
params: algoliaQuery
}]) : this.client.initIndex(state.index).searchForFacetValues(algoliaQuery);
return searchForFacetValuesPromise.then(function addIsRefined(content) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
content = Array.isArray(content) ? content[0] : content;
content.facetHits.forEach(function (f) {
f.isRefined = isDisjunctive ? state.isDisjunctiveFacetRefined(facet, f.value) : state.isFacetRefined(facet, f.value);
});
return content;
}, function (e) {
self._currentNbQueries--;
if (self._currentNbQueries === 0) self.emit('searchQueueEmpty');
throw e;
});
};
/**
* Sets the text query used for the search.
*
* This method resets the current page to 0.
* @param {string} q the user query
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setQuery = function (q) {
this._change({
state: this.state.resetPage().setQuery(q),
isPageReset: true
});
return this;
};
/**
* Remove all the types of refinements except tags. A string can be provided to remove
* only the refinements of a specific attribute. For more advanced use case, you can
* provide a function instead. This function should follow the
* [clearCallback definition](#SearchParameters.clearCallback).
*
* This method resets the current page to 0.
* @param {string} [name] optional name of the facet / attribute on which we want to remove all refinements
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* // Removing all the refinements
* helper.clearRefinements().search();
* @example
* // Removing all the filters on a the category attribute.
* helper.clearRefinements('category').search();
* @example
* // Removing only the exclude filters on the category facet.
* helper.clearRefinements(function(value, attribute, type) {
* return type === 'exclude' && attribute === 'category';
* }).search();
*/
AlgoliaSearchHelper.prototype.clearRefinements = function (name) {
this._change({
state: this.state.resetPage().clearRefinements(name),
isPageReset: true
});
return this;
};
/**
* Remove all the tag filters.
*
* This method resets the current page to 0.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.clearTags = function () {
this._change({
state: this.state.resetPage().clearTags(),
isPageReset: true
});
return this;
};
/**
* Adds a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addDisjunctiveFacetRefinement = function (facet, value) {
this._change({
state: this.state.resetPage().addDisjunctiveFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addDisjunctiveRefine = function () {
return this.addDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Adds a refinement on a hierarchical facet. It will throw
* an exception if the facet is not defined or if the facet
* is already refined.
*
* This method resets the current page to 0.
* @param {string} facet the facet name
* @param {string} path the hierarchical facet path
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is refined
* @chainable
* @fires change
*/
AlgoliaSearchHelper.prototype.addHierarchicalFacetRefinement = function (facet, value) {
this._change({
state: this.state.resetPage().addHierarchicalFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* Adds a an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} operator the operator of the filter
* @param {number} value the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addNumericRefinement = function (attribute, operator, value) {
this._change({
state: this.state.resetPage().addNumericRefinement(attribute, operator, value),
isPageReset: true
});
return this;
};
/**
* Adds a filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetRefinement = function (facet, value) {
this._change({
state: this.state.resetPage().addFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetRefinement}
*/
AlgoliaSearchHelper.prototype.addRefine = function () {
return this.addFacetRefinement.apply(this, arguments);
};
/**
* Adds a an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value (will be converted to string)
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addFacetExclusion = function (facet, value) {
this._change({
state: this.state.resetPage().addExcludeRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#addFacetExclusion}
*/
AlgoliaSearchHelper.prototype.addExclude = function () {
return this.addFacetExclusion.apply(this, arguments);
};
/**
* Adds a tag filter with the `tag` provided. If the
* filter is already set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag the tag to add to the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.addTag = function (tag) {
this._change({
state: this.state.resetPage().addTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Removes an numeric filter to an attribute with the `operator` and `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* Some parameters are optional, triggering different behavior:
* - if the value is not provided, then all the numeric value will be removed for the
* specified attribute/operator couple.
* - if the operator is not provided either, then all the numeric filter on this attribute
* will be removed.
*
* This method resets the current page to 0.
* @param {string} attribute the attribute on which the numeric filter applies
* @param {string} [operator] the operator of the filter
* @param {number} [value] the value of the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeNumericRefinement = function (attribute, operator, value) {
this._change({
state: this.state.resetPage().removeNumericRefinement(attribute, operator, value),
isPageReset: true
});
return this;
};
/**
* Removes a disjunctive filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveFacetRefinement = function (facet, value) {
this._change({
state: this.state.resetPage().removeDisjunctiveFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeDisjunctiveFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeDisjunctiveRefine = function () {
return this.removeDisjunctiveFacetRefinement.apply(this, arguments);
};
/**
* Removes the refinement set on a hierarchical facet.
* @param {string} facet the facet name
* @return {AlgoliaSearchHelper}
* @throws Error if the facet is not defined or if the facet is not refined
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeHierarchicalFacetRefinement = function (facet) {
this._change({
state: this.state.resetPage().removeHierarchicalFacetRefinement(facet),
isPageReset: true
});
return this;
};
/**
* Removes a filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetRefinement = function (facet, value) {
this._change({
state: this.state.resetPage().removeFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetRefinement}
*/
AlgoliaSearchHelper.prototype.removeRefine = function () {
return this.removeFacetRefinement.apply(this, arguments);
};
/**
* Removes an exclusion filter to a faceted attribute with the `value` provided. If the
* filter is not set, it doesn't change the filters.
*
* If the value is omitted, then this method will remove all the filters for the
* attribute.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} [value] the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeFacetExclusion = function (facet, value) {
this._change({
state: this.state.resetPage().removeExcludeRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#removeFacetExclusion}
*/
AlgoliaSearchHelper.prototype.removeExclude = function () {
return this.removeFacetExclusion.apply(this, arguments);
};
/**
* Removes a tag filter with the `tag` provided. If the
* filter is not set, it doesn't change the filters.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove from the filter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.removeTag = function (tag) {
this._change({
state: this.state.resetPage().removeTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Adds or removes an exclusion filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetExclusion = function (facet, value) {
this._change({
state: this.state.resetPage().toggleExcludeFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetExclusion}
*/
AlgoliaSearchHelper.prototype.toggleExclude = function () {
return this.toggleFacetExclusion.apply(this, arguments);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
* @deprecated since version 2.19.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefinement = function (facet, value) {
return this.toggleFacetRefinement(facet, value);
};
/**
* Adds or removes a filter to a faceted attribute with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method can be used for conjunctive, disjunctive and hierarchical filters.
*
* This method resets the current page to 0.
* @param {string} facet the facet to refine
* @param {string} value the associated value
* @return {AlgoliaSearchHelper}
* @throws Error will throw an error if the facet is not declared in the settings of the helper
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleFacetRefinement = function (facet, value) {
this._change({
state: this.state.resetPage().toggleFacetRefinement(facet, value),
isPageReset: true
});
return this;
};
/**
* @deprecated since version 2.4.0, see {@link AlgoliaSearchHelper#toggleFacetRefinement}
*/
AlgoliaSearchHelper.prototype.toggleRefine = function () {
return this.toggleFacetRefinement.apply(this, arguments);
};
/**
* Adds or removes a tag filter with the `value` provided. If
* the value is set then it removes it, otherwise it adds the filter.
*
* This method resets the current page to 0.
* @param {string} tag tag to remove or add
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.toggleTag = function (tag) {
this._change({
state: this.state.resetPage().toggleTagRefinement(tag),
isPageReset: true
});
return this;
};
/**
* Increments the page number by one.
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setPage(0).nextPage().getPage();
* // returns 1
*/
AlgoliaSearchHelper.prototype.nextPage = function () {
var page = this.state.page || 0;
return this.setPage(page + 1);
};
/**
* Decrements the page number by one.
* @fires change
* @return {AlgoliaSearchHelper}
* @chainable
* @example
* helper.setPage(1).previousPage().getPage();
* // returns 0
*/
AlgoliaSearchHelper.prototype.previousPage = function () {
var page = this.state.page || 0;
return this.setPage(page - 1);
};
/**
* @private
*/
function setCurrentPage(page) {
if (page < 0) throw new Error('Page requested below 0.');
this._change({
state: this.state.setPage(page),
isPageReset: false
});
return this;
}
/**
* Change the current page
* @deprecated
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setCurrentPage = setCurrentPage;
/**
* Updates the current page.
* @function
* @param {number} page The page number
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setPage = setCurrentPage;
/**
* Updates the name of the index that will be targeted by the query.
*
* This method resets the current page to 0.
* @param {string} name the index name
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setIndex = function (name) {
this._change({
state: this.state.resetPage().setIndex(name),
isPageReset: true
});
return this;
};
/**
* Update a parameter of the search. This method reset the page
*
* The complete list of parameters is available on the
* [Algolia website](https://www.algolia.com/doc/rest#query-an-index).
* The most commonly used parameters have their own [shortcuts](#query-parameters-shortcuts)
* or benefit from higher-level APIs (all the kind of filters and facets have their own API)
*
* This method resets the current page to 0.
* @param {string} parameter name of the parameter to update
* @param {any} value new value of the parameter
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
* @example
* helper.setQueryParameter('hitsPerPage', 20).search();
*/
AlgoliaSearchHelper.prototype.setQueryParameter = function (parameter, value) {
this._change({
state: this.state.resetPage().setQueryParameter(parameter, value),
isPageReset: true
});
return this;
};
/**
* Set the whole state (warning: will erase previous state)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @fires change
* @chainable
*/
AlgoliaSearchHelper.prototype.setState = function (newState) {
this._change({
state: SearchParameters_1.make(newState),
isPageReset: false
});
return this;
};
/**
* Override the current state without triggering a change event.
* Do not use this method unless you know what you are doing. (see the example
* for a legit use case)
* @param {SearchParameters} newState the whole new state
* @return {AlgoliaSearchHelper}
* @example
* helper.on('change', function(state){
* // In this function you might want to find a way to store the state in the url/history
* updateYourURL(state)
* })
* window.onpopstate = function(event){
* // This is naive though as you should check if the state is really defined etc.
* helper.overrideStateWithoutTriggeringChangeEvent(event.state).search()
* }
* @chainable
*/
AlgoliaSearchHelper.prototype.overrideStateWithoutTriggeringChangeEvent = function (newState) {
this.state = new SearchParameters_1(newState);
return this;
};
/**
* Check if an attribute has any numeric, conjunctive, disjunctive or hierarchical filters.
* @param {string} attribute the name of the attribute
* @return {boolean} true if the attribute is filtered by at least one value
* @example
* // hasRefinements works with numeric, conjunctive, disjunctive and hierarchical filters
* helper.hasRefinements('price'); // false
* helper.addNumericRefinement('price', '>', 100);
* helper.hasRefinements('price'); // true
*
* helper.hasRefinements('color'); // false
* helper.addFacetRefinement('color', 'blue');
* helper.hasRefinements('color'); // true
*
* helper.hasRefinements('material'); // false
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* helper.hasRefinements('material'); // true
*
* helper.hasRefinements('categories'); // false
* helper.toggleFacetRefinement('categories', 'kitchen > knife');
* helper.hasRefinements('categories'); // true
*
*/
AlgoliaSearchHelper.prototype.hasRefinements = function (attribute) {
if (objectHasKeys_1(this.state.getNumericRefinements(attribute))) {
return true;
} else if (this.state.isConjunctiveFacet(attribute)) {
return this.state.isFacetRefined(attribute);
} else if (this.state.isDisjunctiveFacet(attribute)) {
return this.state.isDisjunctiveFacetRefined(attribute);
} else if (this.state.isHierarchicalFacet(attribute)) {
return this.state.isHierarchicalFacetRefined(attribute);
} // there's currently no way to know that the user did call `addNumericRefinement` at some point
// thus we cannot distinguish if there once was a numeric refinement that was cleared
// so we will return false in every other situations to be consistent
// while what we should do here is throw because we did not find the attribute in any type
// of refinement
return false;
};
/**
* Check if a value is excluded for a specific faceted attribute. If the value
* is omitted then the function checks if there is any excluding refinements.
*
* @param {string} facet name of the attribute for used for faceting
* @param {string} [value] optional value. If passed will test that this value
* is filtering the given facet.
* @return {boolean} true if refined
* @example
* helper.isExcludeRefined('color'); // false
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // false
*
* helper.addFacetExclusion('color', 'red');
*
* helper.isExcludeRefined('color'); // true
* helper.isExcludeRefined('color', 'blue') // false
* helper.isExcludeRefined('color', 'red') // true
*/
AlgoliaSearchHelper.prototype.isExcluded = function (facet, value) {
return this.state.isExcludeRefined(facet, value);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasRefinements}
*/
AlgoliaSearchHelper.prototype.isDisjunctiveRefined = function (facet, value) {
return this.state.isDisjunctiveFacetRefined(facet, value);
};
/**
* Check if the string is a currently filtering tag.
* @param {string} tag tag to check
* @return {boolean}
*/
AlgoliaSearchHelper.prototype.hasTag = function (tag) {
return this.state.isTagRefined(tag);
};
/**
* @deprecated since 2.4.0, see {@link AlgoliaSearchHelper#hasTag}
*/
AlgoliaSearchHelper.prototype.isTagRefined = function () {
return this.hasTagRefinements.apply(this, arguments);
};
/**
* Get the name of the currently used index.
* @return {string}
* @example
* helper.setIndex('highestPrice_products').getIndex();
* // returns 'highestPrice_products'
*/
AlgoliaSearchHelper.prototype.getIndex = function () {
return this.state.index;
};
function getCurrentPage() {
return this.state.page;
}
/**
* Get the currently selected page
* @deprecated
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getCurrentPage = getCurrentPage;
/**
* Get the currently selected page
* @function
* @return {number} the current page
*/
AlgoliaSearchHelper.prototype.getPage = getCurrentPage;
/**
* Get all the tags currently set to filters the results.
*
* @return {string[]} The list of tags currently set.
*/
AlgoliaSearchHelper.prototype.getTags = function () {
return this.state.tagRefinements;
};
/**
* Get the list of refinements for a given attribute. This method works with
* conjunctive, disjunctive, excluding and numerical filters.
*
* See also SearchResults#getRefinements
*
* @param {string} facetName attribute name used for faceting
* @return {Array.<FacetRefinement|NumericRefinement>} All Refinement are objects that contain a value, and
* a type. Numeric also contains an operator.
* @example
* helper.addNumericRefinement('price', '>', 100);
* helper.getRefinements('price');
* // [
* // {
* // "value": [
* // 100
* // ],
* // "operator": ">",
* // "type": "numeric"
* // }
* // ]
* @example
* helper.addFacetRefinement('color', 'blue');
* helper.addFacetExclusion('color', 'red');
* helper.getRefinements('color');
* // [
* // {
* // "value": "blue",
* // "type": "conjunctive"
* // },
* // {
* // "value": "red",
* // "type": "exclude"
* // }
* // ]
* @example
* helper.addDisjunctiveFacetRefinement('material', 'plastic');
* // [
* // {
* // "value": "plastic",
* // "type": "disjunctive"
* // }
* // ]
*/
AlgoliaSearchHelper.prototype.getRefinements = function (facetName) {
var refinements = [];
if (this.state.isConjunctiveFacet(facetName)) {
var conjRefinements = this.state.getConjunctiveRefinements(facetName);
conjRefinements.forEach(function (r) {
refinements.push({
value: r,
type: 'conjunctive'
});
});
var excludeRefinements = this.state.getExcludeRefinements(facetName);
excludeRefinements.forEach(function (r) {
refinements.push({
value: r,
type: 'exclude'
});
});
} else if (this.state.isDisjunctiveFacet(facetName)) {
var disjRefinements = this.state.getDisjunctiveRefinements(facetName);
disjRefinements.forEach(function (r) {
refinements.push({
value: r,
type: 'disjunctive'
});
});
}
var numericRefinements = this.state.getNumericRefinements(facetName);
Object.keys(numericRefinements).forEach(function (operator) {
var value = numericRefinements[operator];
refinements.push({
value: value,
operator: operator,
type: 'numeric'
});
});
return refinements;
};
/**
* Return the current refinement for the (attribute, operator)
* @param {string} attribute attribute in the record
* @param {string} operator operator applied on the refined values
* @return {Array.<number|number[]>} refined values
*/
AlgoliaSearchHelper.prototype.getNumericRefinement = function (attribute, operator) {
return this.state.getNumericRefinement(attribute, operator);
};
/**
* Get the current breadcrumb for a hierarchical facet, as an array
* @param {string} facetName Hierarchical facet name
* @return {array.<string>} the path as an array of string
*/
AlgoliaSearchHelper.prototype.getHierarchicalFacetBreadcrumb = function (facetName) {
return this.state.getHierarchicalFacetBreadcrumb(facetName);
}; // /////////// PRIVATE
/**
* Perform the underlying queries
* @private
* @return {undefined}
* @fires search
* @fires result
* @fires error
*/
AlgoliaSearchHelper.prototype._search = function (options) {
var state = this.state;
var states = [];
var mainQueries = [];
if (!options.onlyWithDerivedHelpers) {
mainQueries = requestBuilder_1._getQueries(state.index, state);
states.push({
state: state,
queriesCount: mainQueries.length,
helper: this
});
this.emit('search', {
state: state,
results: this.lastResults
});
}
var derivedQueries = this.derivedHelpers.map(function (derivedHelper) {
var derivedState = derivedHelper.getModifiedState(state);
var derivedStateQueries = requestBuilder_1._getQueries(derivedState.index, derivedState);
states.push({
state: derivedState,
queriesCount: derivedStateQueries.length,
helper: derivedHelper
});
derivedHelper.emit('search', {
state: derivedState,
results: derivedHelper.lastResults
});
return derivedStateQueries;
});
var queries = Array.prototype.concat.apply(mainQueries, derivedQueries);
var queryId = this._queryId++;
this._currentNbQueries++;
try {
this.client.search(queries).then(this._dispatchAlgoliaResponse.bind(this, states, queryId)).catch(this._dispatchAlgoliaError.bind(this, queryId));
} catch (error) {
// If we reach this part, we're in an internal error state
this.emit('error', {
error: error
});
}
};
/**
* Transform the responses as sent by the server and transform them into a user
* usable object that merge the results of all the batch requests. It will dispatch
* over the different helper + derived helpers (when there are some).
* @private
* @param {array.<{SearchParameters, AlgoliaQueries, AlgoliaSearchHelper}>}
* state state used for to generate the request
* @param {number} queryId id of the current request
* @param {object} content content of the response
* @return {undefined}
*/
AlgoliaSearchHelper.prototype._dispatchAlgoliaResponse = function (states, queryId, content) {
// FIXME remove the number of outdated queries discarded instead of just one
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._currentNbQueries -= queryId - this._lastQueryIdReceived;
this._lastQueryIdReceived = queryId;
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
var results = content.results.slice();
states.forEach(function (s) {
var state = s.state;
var queriesCount = s.queriesCount;
var helper = s.helper;
var specificResults = results.splice(0, queriesCount);
var formattedResponse = helper.lastResults = new SearchResults_1(state, specificResults);
helper.emit('result', {
results: formattedResponse,
state: state
});
});
};
AlgoliaSearchHelper.prototype._dispatchAlgoliaError = function (queryId, error) {
if (queryId < this._lastQueryIdReceived) {
// Outdated answer
return;
}
this._currentNbQueries -= queryId - this._lastQueryIdReceived;
this._lastQueryIdReceived = queryId;
this.emit('error', {
error: error
});
if (this._currentNbQueries === 0) this.emit('searchQueueEmpty');
};
AlgoliaSearchHelper.prototype.containsRefinement = function (query, facetFilters, numericFilters, tagFilters) {
return query || facetFilters.length !== 0 || numericFilters.length !== 0 || tagFilters.length !== 0;
};
/**
* Test if there are some disjunctive refinements on the facet
* @private
* @param {string} facet the attribute to test
* @return {boolean}
*/
AlgoliaSearchHelper.prototype._hasDisjunctiveRefinements = function (facet) {
return this.state.disjunctiveRefinements[facet] && this.state.disjunctiveRefinements[facet].length > 0;
};
AlgoliaSearchHelper.prototype._change = function (event) {
var state = event.state;
var isPageReset = event.isPageReset;
if (state !== this.state) {
this.state = state;
this.emit('change', {
state: this.state,
results: this.lastResults,
isPageReset: isPageReset
});
}
};
/**
* Clears the cache of the underlying Algolia client.
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.clearCache = function () {
this.client.clearCache && this.client.clearCache();
return this;
};
/**
* Updates the internal client instance. If the reference of the clients
* are equal then no update is actually done.
* @param {AlgoliaSearch} newClient an AlgoliaSearch client
* @return {AlgoliaSearchHelper}
*/
AlgoliaSearchHelper.prototype.setClient = function (newClient) {
if (this.client === newClient) return this;
if (typeof newClient.addAlgoliaAgent === 'function') {
newClient.addAlgoliaAgent('JS Helper (' + version + ')');
}
this.client = newClient;
return this;
};
/**
* Gets the instance of the currently used client.
* @return {AlgoliaSearch}
*/
AlgoliaSearchHelper.prototype.getClient = function () {
return this.client;
};
/**
* Creates an derived instance of the Helper. A derived helper
* is a way to request other indices synchronised with the lifecycle
* of the main Helper. This mechanism uses the multiqueries feature
* of Algolia to aggregate all the requests in a single network call.
*
* This method takes a function that is used to create a new SearchParameter
* that will be used to create requests to Algolia. Those new requests
* are created just before the `search` event. The signature of the function
* is `SearchParameters -> SearchParameters`.
*
* This method returns a new DerivedHelper which is an EventEmitter
* that fires the same `search`, `result` and `error` events. Those
* events, however, will receive data specific to this DerivedHelper
* and the SearchParameters that is returned by the call of the
* parameter function.
* @param {function} fn SearchParameters -> SearchParameters
* @return {DerivedHelper}
*/
AlgoliaSearchHelper.prototype.derive = function (fn) {
var derivedHelper = new DerivedHelper_1(this, fn);
this.derivedHelpers.push(derivedHelper);
return derivedHelper;
};
/**
* This method detaches a derived Helper from the main one. Prefer using the one from the
* derived helper itself, to remove the event listeners too.
* @private
* @return {undefined}
* @throws Error
*/
AlgoliaSearchHelper.prototype.detachDerivedHelper = function (derivedHelper) {
var pos = this.derivedHelpers.indexOf(derivedHelper);
if (pos === -1) throw new Error('Derived helper already detached');
this.derivedHelpers.splice(pos, 1);
};
/**
* This method returns true if there is currently at least one on-going search.
* @return {boolean} true if there is a search pending
*/
AlgoliaSearchHelper.prototype.hasPendingRequests = function () {
return this._currentNbQueries > 0;
};
/**
* @typedef AlgoliaSearchHelper.NumericRefinement
* @type {object}
* @property {number[]} value the numbers that are used for filtering this attribute with
* the operator specified.
* @property {string} operator the faceting data: value, number of entries
* @property {string} type will be 'numeric'
*/
/**
* @typedef AlgoliaSearchHelper.FacetRefinement
* @type {object}
* @property {string} value the string use to filter the attribute
* @property {string} type the type of filter: 'conjunctive', 'disjunctive', 'exclude'
*/
var algoliasearch_helper = AlgoliaSearchHelper;
/**
* The algoliasearchHelper module is the function that will let its
* contains everything needed to use the Algoliasearch
* Helper. It is a also a function that instanciate the helper.
* To use the helper, you also need the Algolia JS client v3.
* @example
* //using the UMD build
* var client = algoliasearch('latency', '6be0576ff61c053d5f9a3225e2a90f76');
* var helper = algoliasearchHelper(client, 'bestbuy', {
* facets: ['shipping'],
* disjunctiveFacets: ['category']
* });
* helper.on('result', function(event) {
* console.log(event.results);
* });
* helper
* .toggleFacetRefinement('category', 'Movies & TV Shows')
* .toggleFacetRefinement('shipping', 'Free shipping')
* .search();
* @example
* // The helper is an event emitter using the node API
* helper.on('result', updateTheResults);
* helper.once('result', updateTheResults);
* helper.removeListener('result', updateTheResults);
* helper.removeAllListeners('result');
* @module algoliasearchHelper
* @param {AlgoliaSearch} client an AlgoliaSearch client
* @param {string} index the name of the index to query
* @param {SearchParameters|object} opts an object defining the initial config of the search. It doesn't have to be a {SearchParameters}, just an object containing the properties you need from it.
* @return {AlgoliaSearchHelper}
*/
function algoliasearchHelper(client, index, opts) {
return new algoliasearch_helper(client, index, opts);
}
/**
* The version currently used
* @member module:algoliasearchHelper.version
* @type {number}
*/
algoliasearchHelper.version = version;
/**
* Constructor for the Helper.
* @member module:algoliasearchHelper.AlgoliaSearchHelper
* @type {AlgoliaSearchHelper}
*/
algoliasearchHelper.AlgoliaSearchHelper = algoliasearch_helper;
/**
* Constructor for the object containing all the parameters of the search.
* @member module:algoliasearchHelper.SearchParameters
* @type {SearchParameters}
*/
algoliasearchHelper.SearchParameters = SearchParameters_1;
/**
* Constructor for the object containing the results of the search.
* @member module:algoliasearchHelper.SearchResults
* @type {SearchResults}
*/
algoliasearchHelper.SearchResults = SearchResults_1;
var algoliasearchHelper_1 = algoliasearchHelper;
var getId$1 = function getId() {
return 'query';
};
function getCurrentRefinement(props, searchState, context) {
var id = getId$1();
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, '');
if (currentRefinement) {
return currentRefinement;
}
return '';
}
function getHits(searchResults) {
if (searchResults.results) {
if (searchResults.results.hits && Array.isArray(searchResults.results.hits)) {
return addAbsolutePositions(addQueryID(searchResults.results.hits, searchResults.results.queryID), searchResults.results.hitsPerPage, searchResults.results.page);
} else {
return Object.keys(searchResults.results).reduce(function (hits, index) {
return [].concat(_toConsumableArray(hits), [{
index: index,
hits: addAbsolutePositions(addQueryID(searchResults.results[index].hits, searchResults.results[index].queryID), searchResults.results[index].hitsPerPage, searchResults.results[index].page)
}]);
}, []);
}
} else {
return [];
}
}
function _refine(props, searchState, nextRefinement, context) {
var id = getId$1();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage);
}
function _cleanUp(props, searchState, context) {
return cleanUpValue(searchState, context, getId$1());
}
/**
* connectAutoComplete connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* prop to a [Configure](guide/Search_parameters.html) widget.
* @name connectAutoComplete
* @kind connector
* @propType {string} [defaultRefinement] - Provide a default value for the query
* @providedPropType {array.<object>} hits - the records that matched the search state
* @providedPropType {function} refine - a function to change the query
* @providedPropType {string} currentRefinement - the query to search for
*/
var connectAutoComplete = createConnectorWithContext({
displayName: 'AlgoliaAutoComplete',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
return {
hits: getHits(searchResults),
currentRefinement: getCurrentRefinement(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
})
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
/**
* AutoComplete needs to be considered as a widget to trigger a search,
* even if no other widgets are used.
*
* To be considered as a widget you need either:
* - getSearchParameters
* - getMetadata
* - transitionState
*
* See: createConnector.tsx
*/
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}));
}
});
var getId$2 = function getId(props) {
return props.attributes[0];
};
var namespace = 'hierarchicalMenu';
function _refine$1(props, searchState, nextRefinement, context) {
var id = getId$2(props);
var nextValue = _defineProperty({}, id, nextRefinement || '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace);
}
function transformValue(values) {
return values.reduce(function (acc, item) {
if (item.isRefined) {
acc.push({
label: item.name,
// If dealing with a nested "items", "value" is equal to the previous value concatenated with the current label
// If dealing with the first level, "value" is equal to the current label
value: item.path
}); // Create a variable in order to keep the same acc for the recursion, otherwise "reduce" returns a new one
if (item.data) {
acc = acc.concat(transformValue(item.data));
}
}
return acc;
}, []);
}
/**
* The breadcrumb component is s a type of secondary navigation scheme that
* reveals the user’s location in a website or web application.
*
* @name connectBreadcrumb
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a Breadcrumb of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Breadcrumb can display.
*/
var connectBreadcrumb = createConnectorWithContext({
displayName: 'AlgoliaBreadcrumb',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error("Invalid prop ".concat(propName, " supplied to ").concat(componentName, ". Expected an Array of Strings"));
}
return undefined;
},
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var id = getId$2(props);
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
canRefine: false
};
}
var values = results.getFacetValues(id);
var items = values.data ? transformValue(values.data) : [];
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
canRefine: transformedItems.length > 0,
items: transformedItems
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$1(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
/**
* connectCurrentRefinements connector provides the logic to build a widget that will
* give the user the ability to remove all or some of the filters that were
* set.
* @name connectCurrentRefinements
* @kind connector
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @propType {function} [clearsQuery=false] - Pass true to also clear the search query
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {array.<{label: string, attribute: string, currentRefinement: string || object, items: array, value: function}>} items - all the filters, the `value` is to pass to the `refine` function for removing all currentrefinements, `label` is for the display. When existing several refinements for the same atribute name, then you get a nested `items` object that contains a `label` and a `value` function to use to remove a single filter. `attribute` and `currentRefinement` are metadata containing row values.
* @providedPropType {string} query - the search query
*/
var connectCurrentRefinements = createConnectorWithContext({
displayName: 'AlgoliaCurrentRefinements',
propTypes: {
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata) {
var items = metadata.reduce(function (res, meta) {
if (typeof meta.items !== 'undefined') {
if (!props.clearsQuery && meta.id === 'query') {
return res;
} else {
if (props.clearsQuery && meta.id === 'query' && meta.items[0].currentRefinement === '') {
return res;
}
return res.concat(meta.items.map(function (item) {
return _objectSpread({}, item, {
id: meta.id,
index: meta.index
});
}));
}
}
return res;
}, []);
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems,
canRefine: transformedItems.length > 0
};
},
refine: function refine(props, searchState, items) {
// `value` corresponds to our internal clear function computed in each connector metadata.
var refinementsToClear = items instanceof Array ? items.map(function (item) {
return item.value;
}) : [items];
return refinementsToClear.reduce(function (res, clear) {
return clear(res);
}, searchState);
}
});
/**
* The GeoSearch connector provides the logic to build a widget that will display the results on a map.
* It also provides a way to search for results based on their position. The connector provides function to manage the search experience (search on map interaction).
* @name connectGeoSearch
* @kind connector
* @requirements Note that the GeoSearch connector uses the [geosearch](https://www.algolia.com/doc/guides/searching/geo-search) capabilities of Algolia.
* Your hits **must** have a `_geoloc` attribute in order to be passed to the rendering function. Currently, the feature is not compatible with multiple values in the `_geoloc` attribute
* (e.g. a restaurant with multiple locations). In that case you can duplicate your records and use the [distinct](https://www.algolia.com/doc/guides/ranking/distinct) feature of Algolia to only retrieve unique results.
* @propType {{ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } }} [defaultRefinement] - Default search state of the widget containing the bounds for the map
* @providedPropType {function({ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } })} refine - a function to toggle the refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {array.<object>} hits - the records that matched the search
* @providedPropType {boolean} isRefinedWithMap - true if the current refinement is set with the map bounds
* @providedPropType {{ northEast: { lat: number, lng: number }, southWest: { lat: number, lng: number } }} [currentRefinement] - the refinement currently applied
* @providedPropType {{ lat: number, lng: number }} [position] - the position of the search
*/
// To control the map with an external widget the other widget
// **must** write the value in the attribute `aroundLatLng`
var getBoundingBoxId = function getBoundingBoxId() {
return 'boundingBox';
};
var getAroundLatLngId = function getAroundLatLngId() {
return 'aroundLatLng';
};
var getConfigureAroundLatLngId = function getConfigureAroundLatLngId() {
return 'configure.aroundLatLng';
};
var currentRefinementToString = function currentRefinementToString(currentRefinement) {
return [currentRefinement.northEast.lat, currentRefinement.northEast.lng, currentRefinement.southWest.lat, currentRefinement.southWest.lng].join();
};
var stringToCurrentRefinement = function stringToCurrentRefinement(value) {
var values = value.split(',');
return {
northEast: {
lat: parseFloat(values[0]),
lng: parseFloat(values[1])
},
southWest: {
lat: parseFloat(values[2]),
lng: parseFloat(values[3])
}
};
};
var latLngRegExp = /^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/;
var stringToPosition = function stringToPosition(value) {
var pattern = value.match(latLngRegExp);
return {
lat: parseFloat(pattern[1]),
lng: parseFloat(pattern[2])
};
};
var getCurrentRefinement$1 = function getCurrentRefinement(props, searchState, context) {
var refinement = getCurrentRefinementValue(props, searchState, context, getBoundingBoxId(), {});
if (!objectHasKeys(refinement)) {
return;
} // eslint-disable-next-line consistent-return
return {
northEast: {
lat: parseFloat(refinement.northEast.lat),
lng: parseFloat(refinement.northEast.lng)
},
southWest: {
lat: parseFloat(refinement.southWest.lat),
lng: parseFloat(refinement.southWest.lng)
}
};
};
var getCurrentPosition = function getCurrentPosition(props, searchState, context) {
var defaultRefinement = props.defaultRefinement,
propsWithoutDefaultRefinement = _objectWithoutProperties(props, ["defaultRefinement"]);
var aroundLatLng = getCurrentRefinementValue(propsWithoutDefaultRefinement, searchState, context, getAroundLatLngId());
if (!aroundLatLng) {
// Fallback on `configure.aroundLatLng`
var configureAroundLatLng = getCurrentRefinementValue(propsWithoutDefaultRefinement, searchState, context, getConfigureAroundLatLngId());
return configureAroundLatLng && stringToPosition(configureAroundLatLng);
}
return aroundLatLng;
};
var _refine$2 = function refine(searchState, nextValue, context) {
var resetPage = true;
var nextRefinement = _defineProperty({}, getBoundingBoxId(), nextValue);
return refineValue(searchState, nextRefinement, context, resetPage);
};
var connectGeoSearch = createConnectorWithContext({
displayName: 'AlgoliaGeoSearch',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var context = {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
};
var results = getResults(searchResults, context); // We read it from both because the SearchParameters & the searchState are not always
// in sync. When we set the refinement the searchState is used but when we clear the refinement
// the SearchParameters is used. In the first case when we render, the results are not there
// so we can't find the value from the results. The most up to date value is the searchState.
// But when we clear the refinement the searchState is immediately cleared even when the items
// retrieved are still the one from the previous query with the bounding box. It leads to some
// issue with the position of the map. We should rely on 1 source of truth or at least always
// be sync.
var currentRefinementFromSearchState = getCurrentRefinement$1(props, searchState, context);
var currentRefinementFromSearchParameters = results && results._state.insideBoundingBox && stringToCurrentRefinement(results._state.insideBoundingBox) || undefined;
var currentPositionFromSearchState = getCurrentPosition(props, searchState, context);
var currentPositionFromSearchParameters = results && results._state.aroundLatLng && stringToPosition(results._state.aroundLatLng) || undefined;
var currentRefinement = currentRefinementFromSearchState || currentRefinementFromSearchParameters;
var position = currentPositionFromSearchState || currentPositionFromSearchParameters;
return {
hits: !results ? [] : results.hits.filter(function (_) {
return Boolean(_._geoloc);
}),
isRefinedWithMap: Boolean(currentRefinement),
currentRefinement: currentRefinement,
position: position
};
},
refine: function refine(props, searchState, nextValue) {
return _refine$2(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var currentRefinement = getCurrentRefinement$1(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (!currentRefinement) {
return searchParameters;
}
return searchParameters.setQueryParameter('insideBoundingBox', currentRefinementToString(currentRefinement));
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, getBoundingBoxId());
},
getMetadata: function getMetadata(props, searchState) {
var items = [];
var id = getBoundingBoxId();
var context = {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
};
var index = getIndexId(context);
var nextRefinement = {};
var currentRefinement = getCurrentRefinement$1(props, searchState, context);
if (currentRefinement) {
items.push({
label: "".concat(id, ": ").concat(currentRefinementToString(currentRefinement)),
value: function value(nextState) {
return _refine$2(nextState, nextRefinement, context);
},
currentRefinement: currentRefinement
});
}
return {
id: id,
index: index,
items: items
};
},
shouldComponentUpdate: function shouldComponentUpdate() {
return true;
}
});
var getId$3 = function getId(props) {
return props.attributes[0];
};
var namespace$1 = 'hierarchicalMenu';
function getCurrentRefinement$2(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$1, ".").concat(getId$3(props)), null);
if (currentRefinement === '') {
return null;
}
return currentRefinement;
}
function getValue(path, props, searchState, context) {
var id = props.id,
attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel;
var currentRefinement = getCurrentRefinement$2(props, searchState, context);
var nextRefinement;
if (currentRefinement === null) {
nextRefinement = path;
} else {
var tmpSearchParameters = new algoliasearchHelper_1.SearchParameters({
hierarchicalFacets: [{
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}]
});
nextRefinement = tmpSearchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement).toggleHierarchicalFacetRefinement(id, path).getHierarchicalRefinement(id)[0];
}
return nextRefinement;
}
function transformValue$1(value, props, searchState, context) {
return value.map(function (v) {
return {
label: v.name,
value: getValue(v.path, props, searchState, context),
count: v.count,
isRefined: v.isRefined,
items: v.data && transformValue$1(v.data, props, searchState, context)
};
});
}
var truncate = function truncate() {
var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var limit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
return items.slice(0, limit).map(function () {
var item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Array.isArray(item.items) ? _objectSpread({}, item, {
items: truncate(item.items, limit)
}) : item;
});
};
function _refine$3(props, searchState, nextRefinement, context) {
var id = getId$3(props);
var nextValue = _defineProperty({}, id, nextRefinement || '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$1);
}
function _cleanUp$1(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$1, ".").concat(getId$3(props)));
}
var sortBy = ['name:asc'];
/**
* connectHierarchicalMenu connector provides the logic to build a widget that will
* give the user the ability to explore a tree-like structure.
* This is commonly used for multi-level categorization of products on e-commerce
* websites. From a UX point of view, we suggest not displaying more than two levels deep.
* @name connectHierarchicalMenu
* @requirements To use this widget, your attributes must be formatted in a specific way.
* If you want for example to have a hiearchical menu of categories, objects in your index
* should be formatted this way:
*
* ```json
* {
* "categories.lvl0": "products",
* "categories.lvl1": "products > fruits",
* "categories.lvl2": "products > fruits > citrus"
* }
* ```
*
* It's also possible to provide more than one path for each level:
*
* ```json
* {
* "categories.lvl0": ["products", "goods"],
* "categories.lvl1": ["products > fruits", "goods > to eat"]
* }
* ```
*
* All attributes passed to the `attributes` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
*
* @kind connector
* @propType {array.<string>} attributes - List of attributes to use to generate the hierarchy of the menu. See the example for the convention to follow.
* @propType {string} [defaultRefinement] - the item value selected by default
* @propType {boolean} [showMore=false] - Flag to activate the show more button, for toggling the number of items between limit and showMoreLimit.
* @propType {number} [limit=10] - The maximum number of items displayed.
* @propType {number} [showMoreLimit=20] - The maximum number of items displayed when the user triggers the show more. Not considered if `showMore` is false.
* @propType {string} [separator='>'] - Specifies the level separator used in the data.
* @propType {string} [rootPath=null] - The path to use if the first level is not the root level.
* @propType {boolean} [showParentLevel=true] - Flag to set if the parent level should be displayed.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{items: object, count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the HierarchicalMenu can display. items has the same shape as parent items.
*/
var connectHierarchicalMenu = createConnectorWithContext({
displayName: 'AlgoliaHierarchicalMenu',
propTypes: {
attributes: function attributes(props, propName, componentName) {
var isNotString = function isNotString(val) {
return typeof val !== 'string';
};
if (!Array.isArray(props[propName]) || props[propName].some(isNotString) || props[propName].length < 1) {
return new Error("Invalid prop ".concat(propName, " supplied to ").concat(componentName, ". Expected an Array of Strings"));
}
return undefined;
},
separator: propTypes.string,
rootPath: propTypes.string,
showParentLevel: propTypes.bool,
defaultRefinement: propTypes.string,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
transformItems: propTypes.func
},
defaultProps: {
showMore: false,
limit: 10,
showMoreLimit: 20,
separator: ' > ',
rootPath: null,
showParentLevel: true
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var showMore = props.showMore,
limit = props.limit,
showMoreLimit = props.showMoreLimit;
var id = getId$3(props);
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var isFacetPresent = Boolean(results) && Boolean(results.getFacetByName(id));
if (!isFacetPresent) {
return {
items: [],
currentRefinement: getCurrentRefinement$2(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: false
};
}
var itemsLimit = showMore ? showMoreLimit : limit;
var value = results.getFacetValues(id, {
sortBy: sortBy
});
var items = value.data ? transformValue$1(value.data, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) : [];
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: truncate(transformedItems, itemsLimit),
currentRefinement: getCurrentRefinement$2(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: transformedItems.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$3(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$1(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attributes = props.attributes,
separator = props.separator,
rootPath = props.rootPath,
showParentLevel = props.showParentLevel,
showMore = props.showMore,
limit = props.limit,
showMoreLimit = props.showMoreLimit,
contextValue = props.contextValue;
var id = getId$3(props);
var itemsLimit = showMore ? showMoreLimit : limit;
searchParameters = searchParameters.addHierarchicalFacet({
name: id,
attributes: attributes,
separator: separator,
rootPath: rootPath,
showParentLevel: showParentLevel
}).setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, itemsLimit)
});
var currentRefinement = getCurrentRefinement$2(props, searchState, {
ais: contextValue,
multiIndexContext: props.indexContextValue
});
if (currentRefinement !== null) {
searchParameters = searchParameters.toggleHierarchicalFacetRefinement(id, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var rootAttribute = props.attributes[0];
var id = getId$3(props);
var currentRefinement = getCurrentRefinement$2(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = !currentRefinement ? [] : [{
label: "".concat(rootAttribute, ": ").concat(currentRefinement),
attribute: rootAttribute,
value: function value(nextState) {
return _refine$3(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: currentRefinement
}];
return {
id: id,
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: items
};
}
});
var highlight = function highlight(_ref) {
var attribute = _ref.attribute,
hit = _ref.hit,
highlightProperty = _ref.highlightProperty,
_ref$preTag = _ref.preTag,
preTag = _ref$preTag === void 0 ? HIGHLIGHT_TAGS.highlightPreTag : _ref$preTag,
_ref$postTag = _ref.postTag,
postTag = _ref$postTag === void 0 ? HIGHLIGHT_TAGS.highlightPostTag : _ref$postTag;
return parseAlgoliaHit({
attribute: attribute,
highlightProperty: highlightProperty,
hit: hit,
preTag: preTag,
postTag: postTag
});
};
/**
* connectHighlight connector provides the logic to create an highlighter
* component that will retrieve, parse and render an highlighted attribute
* from an Algolia hit.
* @name connectHighlight
* @kind connector
* @category connector
* @providedPropType {function} highlight - function to retrieve and parse an attribute from a hit. It takes a configuration object with 3 attributes: `highlightProperty` which is the property that contains the highlight structure from the records, `attribute` which is the name of the attribute (it can be either a string or an array of strings) to look for and `hit` which is the hit from Algolia. It returns an array of objects `{value: string, isHighlighted: boolean}`. If the element that corresponds to the attribute is an array of strings, it will return a nested array of objects.
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, SearchBox, Hits, connectHighlight } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const CustomHighlight = connectHighlight(
* ({ highlight, attribute, hit, highlightProperty }) => {
* const highlights = highlight({
* highlightProperty: '_highlightResult',
* attribute,
* hit
* });
*
* return highlights.map(part => part.isHighlighted ? (
* <mark>{part.value}</mark>
* ) : (
* <span>{part.value}</span>
* ));
* }
* );
*
* const Hit = ({ hit }) => (
* <p>
* <CustomHighlight attribute="name" hit={hit} />
* </p>
* );
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <SearchBox defaultRefinement="pho" />
* <Hits hitComponent={Hit} />
* </InstantSearch>
* );
*/
var connectHighlight = createConnectorWithContext({
displayName: 'AlgoliaHighlighter',
propTypes: {},
getProvidedProps: function getProvidedProps() {
return {
highlight: highlight
};
}
});
/**
* connectHits connector provides the logic to create connected
* components that will render the results retrieved from
* Algolia.
*
* To configure the number of hits retrieved, use [HitsPerPage widget](widgets/HitsPerPage.html),
* [connectHitsPerPage connector](connectors/connectHitsPerPage.html) or pass the hitsPerPage
* prop to a [Configure](guide/Search_parameters.html) widget.
*
* **Warning:** you will need to use the **objectID** property available on every hit as a key
* when iterating over them. This will ensure you have the best possible UI experience
* especially on slow networks.
* @name connectHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, Highlight, connectHits } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
* const CustomHits = connectHits(({ hits }) => (
* <div>
* {hits.map(hit =>
* <p key={hit.objectID}>
* <Highlight attribute="name" hit={hit} />
* </p>
* )}
* </div>
* ));
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <CustomHits />
* </InstantSearch>
* );
*/
var connectHits = createConnectorWithContext({
displayName: 'AlgoliaHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (!results) {
return {
hits: []
};
}
var hitsWithPositions = addAbsolutePositions(results.hits, results.hitsPerPage, results.page);
var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID);
return {
hits: hitsWithPositionsAndQueryID
};
},
/**
* Hits needs to be considered as a widget to trigger a search,
* even if no other widgets are used.
*
* To be considered as a widget you need either:
* - getSearchParameters
* - getMetadata
* - transitionState
*
* See: createConnector.tsx
*/
getSearchParameters: function getSearchParameters(searchParameters) {
return searchParameters;
}
});
function getId$4() {
return 'hitsPerPage';
}
function getCurrentRefinement$3(props, searchState, context) {
var id = getId$4();
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null);
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
}
/**
* connectHitsPerPage connector provides the logic to create connected
* components that will allow a user to choose to display more or less results from Algolia.
* @name connectHitsPerPage
* @kind connector
* @propType {number} defaultRefinement - The number of items selected by default
* @propType {{value: number, label: string}[]} items - List of hits per page options.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: number}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
var connectHitsPerPage = createConnectorWithContext({
displayName: 'AlgoliaHitsPerPage',
propTypes: {
defaultRefinement: propTypes.number.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string,
value: propTypes.number.isRequired
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement$3(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _objectSpread({}, item, {
isRefined: true
}) : _objectSpread({}, item, {
isRefined: false
});
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId$4();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, getId$4());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setHitsPerPage(getCurrentRefinement$3(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}));
},
getMetadata: function getMetadata() {
return {
id: getId$4()
};
}
});
function getId$5() {
return 'page';
}
function getCurrentRefinement$4(props, searchState, context) {
var id = getId$5();
var page = 1;
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page);
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
}
/**
* InfiniteHits connector provides the logic to create connected
* components that will render an continuous list of results retrieved from
* Algolia. This connector provides a function to load more results.
* @name connectInfiniteHits
* @kind connector
* @providedPropType {array.<object>} hits - the records that matched the search state
* @providedPropType {boolean} hasMore - indicates if there are more pages to load
* @providedPropType {function} refine - call to load more results
*/
var connectInfiniteHits = createConnectorWithContext({
displayName: 'AlgoliaInfiniteHits',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var _this = this;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
this._allResults = this._allResults || [];
this._prevState = this._prevState || {};
if (!results) {
return {
hits: [],
hasPrevious: false,
hasMore: false,
refine: function refine() {},
refinePrevious: function refinePrevious() {},
refineNext: function refineNext() {}
};
}
var page = results.page,
hits = results.hits,
hitsPerPage = results.hitsPerPage,
nbPages = results.nbPages,
_results$_state = results._state;
_results$_state = _results$_state === void 0 ? {} : _results$_state;
var p = _results$_state.page,
currentState = _objectWithoutProperties(_results$_state, ["page"]);
var hitsWithPositions = addAbsolutePositions(hits, hitsPerPage, page);
var hitsWithPositionsAndQueryID = addQueryID(hitsWithPositions, results.queryID);
if (this._firstReceivedPage === undefined || !fastDeepEqual(currentState, this._prevState)) {
this._allResults = _toConsumableArray(hitsWithPositionsAndQueryID);
this._firstReceivedPage = page;
this._lastReceivedPage = page;
} else if (this._lastReceivedPage < page) {
this._allResults = [].concat(_toConsumableArray(this._allResults), _toConsumableArray(hitsWithPositionsAndQueryID));
this._lastReceivedPage = page;
} else if (this._firstReceivedPage > page) {
this._allResults = [].concat(_toConsumableArray(hitsWithPositionsAndQueryID), _toConsumableArray(this._allResults));
this._firstReceivedPage = page;
}
this._prevState = currentState;
var hasPrevious = this._firstReceivedPage > 0;
var lastPageIndex = nbPages - 1;
var hasMore = page < lastPageIndex;
var refinePrevious = function refinePrevious(event) {
return _this.refine(event, _this._firstReceivedPage - 1);
};
var refineNext = function refineNext(event) {
return _this.refine(event, _this._lastReceivedPage + 1);
};
return {
hits: this._allResults,
hasPrevious: hasPrevious,
hasMore: hasMore,
refinePrevious: refinePrevious,
refineNext: refineNext
};
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQueryParameters({
page: getCurrentRefinement$4(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) - 1
});
},
refine: function refine(props, searchState, event, index) {
if (index === undefined && this._lastReceivedPage !== undefined) {
index = this._lastReceivedPage + 1;
} else if (index === undefined) {
index = getCurrentRefinement$4(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
var id = getId$5();
var nextValue = _defineProperty({}, id, index + 1);
var resetPage = false;
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, resetPage);
}
});
var namespace$2 = 'menu';
function getId$6(props) {
return props.attribute;
}
function getCurrentRefinement$5(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$2, ".").concat(getId$6(props)), null);
if (currentRefinement === '') {
return null;
}
return currentRefinement;
}
function getValue$1(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement$5(props, searchState, context);
return name === currentRefinement ? '' : name;
}
function getLimit(_ref) {
var showMore = _ref.showMore,
limit = _ref.limit,
showMoreLimit = _ref.showMoreLimit;
return showMore ? showMoreLimit : limit;
}
function _refine$4(props, searchState, nextRefinement, context) {
var id = getId$6(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$2);
}
function _cleanUp$2(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$2, ".").concat(getId$6(props)));
}
var defaultSortBy = ['count:desc', 'name:asc'];
/**
* connectMenu connector provides the logic to build a widget that will
* give the user the ability to choose a single value for a specific facet.
* @name connectMenu
* @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @kind connector
* @propType {string} attribute - the name of the attribute in the record
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limit=10] - the minimum number of diplayed items
* @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string} [defaultRefinement] - the value of the item selected by default
* @propType {boolean} [searchable=false] - allow search inside values
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the Menu can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
*/
var connectMenu = createConnectorWithContext({
displayName: 'AlgoliaMenu',
propTypes: {
attribute: propTypes.string.isRequired,
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
defaultRefinement: propTypes.string,
transformItems: propTypes.func,
searchable: propTypes.bool
},
defaultProps: {
showMore: false,
limit: 10,
showMoreLimit: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, meta, searchForFacetValuesResults) {
var attribute = props.attribute,
searchable = props.searchable,
indexContextValue = props.indexContextValue;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search)
if (searchable && indexContextValue) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: canRefine
};
}
var items;
if (isFromSearch) {
items = searchForFacetValuesResults[attribute].map(function (v) {
return {
label: v.value,
value: getValue$1(v.value, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
_highlightResult: {
label: {
value: v.highlighted
}
},
count: v.count,
isRefined: v.isRefined
};
});
} else {
items = results.getFacetValues(attribute, {
sortBy: searchable ? undefined : defaultSortBy
}).map(function (v) {
return {
label: v.name,
value: getValue$1(v.name, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
count: v.count,
isRefined: v.isRefined
};
});
}
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, getLimit(props)),
currentRefinement: getCurrentRefinement$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: transformedItems.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$4(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return {
facetName: props.attribute,
query: nextRefinement,
maxFacetHits: getLimit(props)
};
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$2(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute;
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit(props))
});
searchParameters = searchParameters.addDisjunctiveFacet(attribute);
var currentRefinement = getCurrentRefinement$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (currentRefinement !== null) {
searchParameters = searchParameters.addDisjunctiveFacetRefinement(attribute, currentRefinement);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$6(props);
var currentRefinement = getCurrentRefinement$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return {
id: id,
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: currentRefinement === null ? [] : [{
label: "".concat(props.attribute, ": ").concat(currentRefinement),
attribute: props.attribute,
value: function value(nextState) {
return _refine$4(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: currentRefinement
}]
};
}
});
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function stringifyItem(item) {
if (typeof item.start === 'undefined' && typeof item.end === 'undefined') {
return '';
}
return "".concat(item.start ? item.start : '', ":").concat(item.end ? item.end : '');
}
function parseItem(value) {
if (value.length === 0) {
return {
start: null,
end: null
};
}
var _value$split = value.split(':'),
_value$split2 = _slicedToArray(_value$split, 2),
startStr = _value$split2[0],
endStr = _value$split2[1];
return {
start: startStr.length > 0 ? parseInt(startStr, 10) : null,
end: endStr.length > 0 ? parseInt(endStr, 10) : null
};
}
var namespace$3 = 'multiRange';
function getId$7(props) {
return props.attribute;
}
function getCurrentRefinement$6(props, searchState, context) {
return getCurrentRefinementValue(props, searchState, context, "".concat(namespace$3, ".").concat(getId$7(props)), '');
}
function isRefinementsRangeIncludesInsideItemRange(stats, start, end) {
return stats.min > start && stats.min < end || stats.max > start && stats.max < end;
}
function isItemRangeIncludedInsideRefinementsRange(stats, start, end) {
return start > stats.min && start < stats.max || end > stats.min && end < stats.max;
}
function itemHasRefinement(attribute, results, value) {
var stats = results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null;
var range = value.split(':');
var start = Number(range[0]) === 0 || value === '' ? Number.NEGATIVE_INFINITY : Number(range[0]);
var end = Number(range[1]) === 0 || value === '' ? Number.POSITIVE_INFINITY : Number(range[1]);
return !(Boolean(stats) && (isRefinementsRangeIncludesInsideItemRange(stats, start, end) || isItemRangeIncludedInsideRefinementsRange(stats, start, end)));
}
function _refine$5(props, searchState, nextRefinement, context) {
var nextValue = _defineProperty({}, getId$7(props), nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$3);
}
function _cleanUp$3(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$3, ".").concat(getId$7(props)));
}
/**
* connectNumericMenu connector provides the logic to build a widget that will
* give the user the ability to select a range value for a numeric attribute.
* Ranges are defined statically.
* @name connectNumericMenu
* @requirements The attribute passed to the `attribute` prop must be holding numerical values.
* @kind connector
* @propType {string} attribute - the name of the attribute in the records
* @propType {{label: string, start: number, end: number}[]} items - List of options. With a text label, and upper and lower bounds.
* @propType {string} [defaultRefinement] - the value of the item selected by default, follow the shape of a `string` with a pattern of `'{start}:{end}'`.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied. follow the shape of a `string` with a pattern of `'{start}:{end}'` which corresponds to the current selected item. For instance, when the selected item is `{start: 10, end: 20}`, the searchState of the widget is `'10:20'`. When `start` isn't defined, the searchState of the widget is `':{end}'`, and the same way around when `end` isn't defined. However, when neither `start` nor `end` are defined, the searchState is an empty string.
* @providedPropType {array.<{isRefined: boolean, label: string, value: string, isRefined: boolean, noRefinement: boolean}>} items - the list of ranges the NumericMenu can display.
*/
var connectNumericMenu = createConnectorWithContext({
displayName: 'AlgoliaNumericMenu',
propTypes: {
id: propTypes.string,
attribute: propTypes.string.isRequired,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.node,
start: propTypes.number,
end: propTypes.number
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attribute = props.attribute;
var currentRefinement = getCurrentRefinement$6(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = props.items.map(function (item) {
var value = stringifyItem(item);
return {
label: item.label,
value: value,
isRefined: value === currentRefinement,
noRefinement: results ? itemHasRefinement(getId$7(props), results, value) : false
};
});
var stats = results && results.getFacetByName(attribute) ? results.getFacetStats(attribute) : null;
var refinedItem = find(items, function (item) {
return item.isRefined === true;
});
if (!items.some(function (item) {
return item.value === '';
})) {
items.push({
value: '',
isRefined: refinedItem === undefined,
noRefinement: !stats,
label: 'All'
});
}
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems,
currentRefinement: currentRefinement,
canRefine: transformedItems.length > 0 && transformedItems.some(function (item) {
return item.noRefinement === false;
})
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$5(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$3(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute;
var _parseItem = parseItem(getCurrentRefinement$6(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
})),
start = _parseItem.start,
end = _parseItem.end;
searchParameters = searchParameters.addDisjunctiveFacet(attribute);
if (start) {
searchParameters = searchParameters.addNumericRefinement(attribute, '>=', start);
}
if (end) {
searchParameters = searchParameters.addNumericRefinement(attribute, '<=', end);
}
return searchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$7(props);
var value = getCurrentRefinement$6(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = [];
var index = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (value !== '') {
var _find = find(props.items, function (item) {
return stringifyItem(item) === value;
}),
label = _find.label;
items.push({
label: "".concat(props.attribute, ": ").concat(label),
attribute: props.attribute,
currentRefinement: label,
value: function value(nextState) {
return _refine$5(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
}
return {
id: id,
index: index,
items: items
};
}
});
function getId$8() {
return 'page';
}
function getCurrentRefinement$7(props, searchState, context) {
var id = getId$8();
var page = 1;
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, page);
if (typeof currentRefinement === 'string') {
return parseInt(currentRefinement, 10);
}
return currentRefinement;
}
function _refine$6(props, searchState, nextPage, context) {
var id = getId$8();
var nextValue = _defineProperty({}, id, nextPage);
var resetPage = false;
return refineValue(searchState, nextValue, context, resetPage);
}
/**
* connectPagination connector provides the logic to build a widget that will
* let the user displays hits corresponding to a certain page.
* @name connectPagination
* @kind connector
* @propType {boolean} [showFirst=true] - Display the first page link.
* @propType {boolean} [showLast=false] - Display the last page link.
* @propType {boolean} [showPrevious=true] - Display the previous page link.
* @propType {boolean} [showNext=true] - Display the next page link.
* @propType {number} [padding=3] - How many page links to display around the current page.
* @propType {number} [totalPages=Infinity] - Maximum number of pages to display.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {number} nbPages - the total of existing pages
* @providedPropType {number} currentRefinement - the page refinement currently applied
*/
var connectPagination = createConnectorWithContext({
displayName: 'AlgoliaPagination',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (!results) {
return null;
}
var nbPages = results.nbPages;
return {
nbPages: nbPages,
currentRefinement: getCurrentRefinement$7(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: nbPages > 1
};
},
refine: function refine(props, searchState, nextPage) {
return _refine$6(props, searchState, nextPage, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, getId$8());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setPage(getCurrentRefinement$7(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}) - 1);
},
getMetadata: function getMetadata() {
return {
id: getId$8()
};
}
});
/**
* connectPoweredBy connector provides the logic to build a widget that
* will display a link to algolia.
* @name connectPoweredBy
* @kind connector
* @providedPropType {string} url - the url to redirect to algolia
*/
var connectPoweredBy = createConnectorWithContext({
displayName: 'AlgoliaPoweredBy',
getProvidedProps: function getProvidedProps() {
var hostname = typeof window === 'undefined' ? '' : window.location.hostname;
var url = 'https://www.algolia.com/?' + 'utm_source=react-instantsearch&' + 'utm_medium=website&' + "utm_content=".concat(hostname, "&") + 'utm_campaign=poweredby';
return {
url: url
};
}
});
/**
* connectRange connector provides the logic to create connected
* components that will give the ability for a user to refine results using
* a numeric range.
* @name connectRange
* @kind connector
* @requirements The attribute passed to the `attribute` prop must be present in “attributes for faceting”
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* The values inside the attribute must be JavaScript numbers (not strings).
* @propType {string} attribute - Name of the attribute for faceting
* @propType {{min?: number, max?: number}} [defaultRefinement] - Default searchState of the widget containing the start and the end of the range.
* @propType {number} [min] - Minimum value. When this isn't set, the minimum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [max] - Maximum value. When this isn't set, the maximum value will be automatically computed by Algolia using the data in the index.
* @propType {number} [precision=0] - Number of digits after decimal point to use.
* @providedPropType {function} refine - a function to select a range.
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string} currentRefinement - the refinement currently applied
* @providedPropType {number} min - the minimum value available.
* @providedPropType {number} max - the maximum value available.
* @providedPropType {number} precision - Number of digits after decimal point to use.
*/
function getId$9(props) {
return props.attribute;
}
var namespace$4 = 'range';
function getCurrentRange(boundaries, stats, precision) {
var pow = Math.pow(10, precision);
var min;
if (typeof boundaries.min === 'number' && isFinite(boundaries.min)) {
min = boundaries.min;
} else if (typeof stats.min === 'number' && isFinite(stats.min)) {
min = stats.min;
} else {
min = undefined;
}
var max;
if (typeof boundaries.max === 'number' && isFinite(boundaries.max)) {
max = boundaries.max;
} else if (typeof stats.max === 'number' && isFinite(stats.max)) {
max = stats.max;
} else {
max = undefined;
}
return {
min: min !== undefined ? Math.floor(min * pow) / pow : min,
max: max !== undefined ? Math.ceil(max * pow) / pow : max
};
}
function getCurrentRefinement$8(props, searchState, currentRange, context) {
var _getCurrentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$4, ".").concat(getId$9(props)), {}),
min = _getCurrentRefinement.min,
max = _getCurrentRefinement.max;
var isFloatPrecision = Boolean(props.precision);
var nextMin = min;
if (typeof nextMin === 'string') {
nextMin = isFloatPrecision ? parseFloat(nextMin) : parseInt(nextMin, 10);
}
var nextMax = max;
if (typeof nextMax === 'string') {
nextMax = isFloatPrecision ? parseFloat(nextMax) : parseInt(nextMax, 10);
}
var refinement = {
min: nextMin,
max: nextMax
};
var hasMinBound = props.min !== undefined;
var hasMaxBound = props.max !== undefined;
var hasMinRefinment = refinement.min !== undefined;
var hasMaxRefinment = refinement.max !== undefined;
if (hasMinBound && hasMinRefinment && refinement.min < currentRange.min) {
throw Error("You can't provide min value lower than range.");
}
if (hasMaxBound && hasMaxRefinment && refinement.max > currentRange.max) {
throw Error("You can't provide max value greater than range.");
}
if (hasMinBound && !hasMinRefinment) {
refinement.min = currentRange.min;
}
if (hasMaxBound && !hasMaxRefinment) {
refinement.max = currentRange.max;
}
return refinement;
}
function getCurrentRefinementWithRange(refinement, range) {
return {
min: refinement.min !== undefined ? refinement.min : range.min,
max: refinement.max !== undefined ? refinement.max : range.max
};
}
function nextValueForRefinement(hasBound, isReset, range, value) {
var next;
if (!hasBound && range === value) {
next = undefined;
} else if (hasBound && isReset) {
next = range;
} else {
next = value;
}
return next;
}
function _refine$7(props, searchState, nextRefinement, currentRange, context) {
var nextMin = nextRefinement.min,
nextMax = nextRefinement.max;
var currentMinRange = currentRange.min,
currentMaxRange = currentRange.max;
var isMinReset = nextMin === undefined || nextMin === '';
var isMaxReset = nextMax === undefined || nextMax === '';
var nextMinAsNumber = !isMinReset ? parseFloat(nextMin) : undefined;
var nextMaxAsNumber = !isMaxReset ? parseFloat(nextMax) : undefined;
var isNextMinValid = isMinReset || isFinite(nextMinAsNumber);
var isNextMaxValid = isMaxReset || isFinite(nextMaxAsNumber);
if (!isNextMinValid || !isNextMaxValid) {
throw Error("You can't provide non finite values to the range connector.");
}
if (nextMinAsNumber < currentMinRange) {
throw Error("You can't provide min value lower than range.");
}
if (nextMaxAsNumber > currentMaxRange) {
throw Error("You can't provide max value greater than range.");
}
var id = getId$9(props);
var resetPage = true;
var nextValue = _defineProperty({}, id, {
min: nextValueForRefinement(props.min !== undefined, isMinReset, currentMinRange, nextMinAsNumber),
max: nextValueForRefinement(props.max !== undefined, isMaxReset, currentMaxRange, nextMaxAsNumber)
});
return refineValue(searchState, nextValue, context, resetPage, namespace$4);
}
function _cleanUp$4(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$4, ".").concat(getId$9(props)));
}
var connectRange = createConnectorWithContext({
displayName: 'AlgoliaRange',
propTypes: {
id: propTypes.string,
attribute: propTypes.string.isRequired,
defaultRefinement: propTypes.shape({
min: propTypes.number,
max: propTypes.number
}),
min: propTypes.number,
max: propTypes.number,
precision: propTypes.number,
header: propTypes.node,
footer: propTypes.node
},
defaultProps: {
precision: 0
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attribute = props.attribute,
precision = props.precision,
minBound = props.min,
maxBound = props.max;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var hasFacet = results && results.getFacetByName(attribute);
var stats = hasFacet ? results.getFacetStats(attribute) || {} : {};
var facetValues = hasFacet ? results.getFacetValues(attribute) : [];
var count = facetValues.map(function (v) {
return {
value: v.name,
count: v.count
};
});
var _getCurrentRange = getCurrentRange({
min: minBound,
max: maxBound
}, stats, precision),
rangeMin = _getCurrentRange.min,
rangeMax = _getCurrentRange.max; // The searchState is not always in sync with the helper state. For example
// when we set boundaries on the first render the searchState don't have
// the correct refinement. If this behavior change in the upcoming version
// we could store the range inside the searchState instead of rely on `this`.
this._currentRange = {
min: rangeMin,
max: rangeMax
};
var currentRefinement = getCurrentRefinement$8(props, searchState, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return {
min: rangeMin,
max: rangeMax,
canRefine: count.length > 0,
currentRefinement: getCurrentRefinementWithRange(currentRefinement, this._currentRange),
count: count,
precision: precision
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$7(props, searchState, nextRefinement, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$4(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(params, props, searchState) {
var attribute = props.attribute;
var _getCurrentRefinement2 = getCurrentRefinement$8(props, searchState, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
min = _getCurrentRefinement2.min,
max = _getCurrentRefinement2.max;
params = params.addDisjunctiveFacet(attribute);
if (min !== undefined) {
params = params.addNumericRefinement(attribute, '>=', min);
}
if (max !== undefined) {
params = params.addNumericRefinement(attribute, '<=', max);
}
return params;
},
getMetadata: function getMetadata(props, searchState) {
var _this = this;
var _this$_currentRange = this._currentRange,
minRange = _this$_currentRange.min,
maxRange = _this$_currentRange.max;
var _getCurrentRefinement3 = getCurrentRefinement$8(props, searchState, this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
minValue = _getCurrentRefinement3.min,
maxValue = _getCurrentRefinement3.max;
var items = [];
var hasMin = minValue !== undefined;
var hasMax = maxValue !== undefined;
var shouldDisplayMinLabel = hasMin && minValue !== minRange;
var shouldDisplayMaxLabel = hasMax && maxValue !== maxRange;
if (shouldDisplayMinLabel || shouldDisplayMaxLabel) {
var fragments = [hasMin ? "".concat(minValue, " <= ") : '', props.attribute, hasMax ? " <= ".concat(maxValue) : ''];
items.push({
label: fragments.join(''),
attribute: props.attribute,
value: function value(nextState) {
return _refine$7(props, nextState, {}, _this._currentRange, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: getCurrentRefinementWithRange({
min: minValue,
max: maxValue
}, {
min: minRange,
max: maxRange
})
});
}
return {
id: getId$9(props),
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: items
};
}
});
var namespace$5 = 'refinementList';
function getId$a(props) {
return props.attribute;
}
function getCurrentRefinement$9(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$5, ".").concat(getId$a(props)), []);
if (typeof currentRefinement !== 'string') {
return currentRefinement;
}
if (currentRefinement) {
return [currentRefinement];
}
return [];
}
function getValue$2(name, props, searchState, context) {
var currentRefinement = getCurrentRefinement$9(props, searchState, context);
var isAnewValue = currentRefinement.indexOf(name) === -1;
var nextRefinement = isAnewValue ? currentRefinement.concat([name]) // cannot use .push(), it mutates
: currentRefinement.filter(function (selectedValue) {
return selectedValue !== name;
}); // cannot use .splice(), it mutates
return nextRefinement;
}
function getLimit$1(_ref) {
var showMore = _ref.showMore,
limit = _ref.limit,
showMoreLimit = _ref.showMoreLimit;
return showMore ? showMoreLimit : limit;
}
function _refine$8(props, searchState, nextRefinement, context) {
var id = getId$a(props); // Setting the value to an empty string ensures that it is persisted in
// the URL as an empty value.
// This is necessary in the case where `defaultRefinement` contains one
// item and we try to deselect it. `nextSelected` would be an empty array,
// which would not be persisted to the URL.
// {foo: ['bar']} => "foo[0]=bar"
// {foo: []} => ""
var nextValue = _defineProperty({}, id, nextRefinement.length > 0 ? nextRefinement : '');
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$5);
}
function _cleanUp$5(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$5, ".").concat(getId$a(props)));
}
/**
* connectRefinementList connector provides the logic to build a widget that will
* give the user the ability to choose multiple values for a specific facet.
* @name connectRefinementList
* @kind connector
* @requirements The attribute passed to the `attribute` prop must be present in "attributes for faceting"
* on the Algolia dashboard or configured as `attributesForFaceting` via a set settings call to the Algolia API.
* @propType {string} attribute - the name of the attribute in the record
* @propType {boolean} [searchable=false] - allow search inside values
* @propType {string} [operator=or] - How to apply the refinements. Possible values: 'or' or 'and'.
* @propType {boolean} [showMore=false] - true if the component should display a button that will expand the number of items
* @propType {number} [limit=10] - the minimum number of displayed items
* @propType {number} [showMoreLimit=20] - the maximun number of displayed items. Only used when showMore is set to `true`
* @propType {string[]} defaultRefinement - the values of the items selected by default. The searchState of this widget takes the form of a list of `string`s, which correspond to the values of all selected refinements. However, when there are no refinements selected, the value of the searchState is an empty string.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{count: number, isRefined: boolean, label: string, value: string}>} items - the list of items the RefinementList can display.
* @providedPropType {function} searchForItems - a function to toggle a search inside items values
* @providedPropType {boolean} isFromSearch - a boolean that says if the `items` props contains facet values from the global search or from the search inside items.
* @providedPropType {boolean} canRefine - a boolean that says whether you can refine
*/
var sortBy$1 = ['isRefined', 'count:desc', 'name:asc'];
var connectRefinementList = createConnectorWithContext({
displayName: 'AlgoliaRefinementList',
propTypes: {
id: propTypes.string,
attribute: propTypes.string.isRequired,
operator: propTypes.oneOf(['and', 'or']),
showMore: propTypes.bool,
limit: propTypes.number,
showMoreLimit: propTypes.number,
defaultRefinement: propTypes.arrayOf(propTypes.oneOfType([propTypes.string, propTypes.number])),
searchable: propTypes.bool,
transformItems: propTypes.func
},
defaultProps: {
operator: 'or',
showMore: false,
limit: 10,
showMoreLimit: 20
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults, metadata, searchForFacetValuesResults) {
var attribute = props.attribute,
searchable = props.searchable,
indexContextValue = props.indexContextValue;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var canRefine = Boolean(results) && Boolean(results.getFacetByName(attribute));
var isFromSearch = Boolean(searchForFacetValuesResults && searchForFacetValuesResults[attribute] && searchForFacetValuesResults.query !== ''); // Search For Facet Values is not available with derived helper (used for multi index search)
if (searchable && indexContextValue) {
throw new Error('react-instantsearch: searching in *List is not available when used inside a' + ' multi index context');
}
if (!canRefine) {
return {
items: [],
currentRefinement: getCurrentRefinement$9(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
canRefine: canRefine,
isFromSearch: isFromSearch,
searchable: searchable
};
}
var items = isFromSearch ? searchForFacetValuesResults[attribute].map(function (v) {
return {
label: v.value,
value: getValue$2(v.value, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
_highlightResult: {
label: {
value: v.highlighted
}
},
count: v.count,
isRefined: v.isRefined
};
}) : results.getFacetValues(attribute, {
sortBy: sortBy$1
}).map(function (v) {
return {
label: v.name,
value: getValue$2(v.name, props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
count: v.count,
isRefined: v.isRefined
};
});
var transformedItems = props.transformItems ? props.transformItems(items) : items;
return {
items: transformedItems.slice(0, getLimit$1(props)),
currentRefinement: getCurrentRefinement$9(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isFromSearch: isFromSearch,
searchable: searchable,
canRefine: transformedItems.length > 0
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$8(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
searchForFacetValues: function searchForFacetValues(props, searchState, nextRefinement) {
return {
facetName: props.attribute,
query: nextRefinement,
maxFacetHits: getLimit$1(props)
};
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$5(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute,
operator = props.operator;
var addKey = operator === 'and' ? 'addFacet' : 'addDisjunctiveFacet';
var addRefinementKey = "".concat(addKey, "Refinement");
searchParameters = searchParameters.setQueryParameters({
maxValuesPerFacet: Math.max(searchParameters.maxValuesPerFacet || 0, getLimit$1(props))
});
searchParameters = searchParameters[addKey](attribute);
return getCurrentRefinement$9(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}).reduce(function (res, val) {
return res[addRefinementKey](attribute, val);
}, searchParameters);
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$a(props);
var context = {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
};
return {
id: id,
index: getIndexId(context),
items: getCurrentRefinement$9(props, searchState, context).length > 0 ? [{
attribute: props.attribute,
label: "".concat(props.attribute, ": "),
currentRefinement: getCurrentRefinement$9(props, searchState, context),
value: function value(nextState) {
return _refine$8(props, nextState, [], context);
},
items: getCurrentRefinement$9(props, searchState, context).map(function (item) {
return {
label: "".concat(item),
value: function value(nextState) {
var nextSelectedItems = getCurrentRefinement$9(props, nextState, context).filter(function (other) {
return other !== item;
});
return _refine$8(props, searchState, nextSelectedItems, context);
}
};
})
}] : []
};
}
});
/**
* connectScrollTo connector provides the logic to build a widget that will
* let the page scroll to a certain point.
* @name connectScrollTo
* @kind connector
* @propType {string} [scrollOn="page"] - Widget searchState key on which to listen for changes, default to the pagination widget.
* @providedPropType {any} value - the current refinement applied to the widget listened by scrollTo
* @providedPropType {boolean} hasNotChanged - indicates whether the refinement came from the scrollOn argument (for instance page by default)
*/
var connectScrollTo = createConnectorWithContext({
displayName: 'AlgoliaScrollTo',
propTypes: {
scrollOn: propTypes.string
},
defaultProps: {
scrollOn: 'page'
},
getProvidedProps: function getProvidedProps(props, searchState) {
var id = props.scrollOn;
var value = getCurrentRefinementValue(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, id, null);
if (!this._prevSearchState) {
this._prevSearchState = {};
} // Get the subpart of the state that interest us
if (hasMultipleIndices({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
})) {
searchState = searchState.indices ? searchState.indices[getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
})] : {};
} // if there is a change in the app that has been triggered by another element
// than "props.scrollOn (id) or the Configure widget, we need to keep track of
// the search state to know if there's a change in the app that was not triggered
// by the props.scrollOn (id) or the Configure widget. This is useful when
// using ScrollTo in combination of Pagination. As pagination can be change
// by every widget, we want to scroll only if it cames from the pagination
// widget itself. We also remove the configure key from the search state to
// do this comparison because for now configure values are not present in the
// search state before a first refinement has been made and will false the results.
// See: https://github.com/algolia/react-instantsearch/issues/164
var cleanedSearchState = omit(searchState, ['configure', id]);
var hasNotChanged = shallowEqual(this._prevSearchState, cleanedSearchState);
this._prevSearchState = cleanedSearchState;
return {
value: value,
hasNotChanged: hasNotChanged
};
}
});
function getId$b() {
return 'query';
}
function getCurrentRefinement$a(props, searchState, context) {
var id = getId$b();
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, '');
if (currentRefinement) {
return currentRefinement;
}
return '';
}
function _refine$9(props, searchState, nextRefinement, context) {
var id = getId$b();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage);
}
function _cleanUp$6(props, searchState, context) {
return cleanUpValue(searchState, context, getId$b());
}
/**
* connectSearchBox connector provides the logic to build a widget that will
* let the user search for a query
* @name connectSearchBox
* @kind connector
* @propType {string} [defaultRefinement] - Provide a default value for the query
* @providedPropType {function} refine - a function to change the current query
* @providedPropType {string} currentRefinement - the current query used
* @providedPropType {boolean} isSearchStalled - a flag that indicates if InstantSearch has detected that searches are stalled
*/
var connectSearchBox = createConnectorWithContext({
displayName: 'AlgoliaSearchBox',
propTypes: {
defaultRefinement: propTypes.string
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
return {
currentRefinement: getCurrentRefinement$a(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
isSearchStalled: searchResults.isSearchStalled
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$9(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$6(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
return searchParameters.setQuery(getCurrentRefinement$a(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}));
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$b();
var currentRefinement = getCurrentRefinement$a(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return {
id: id,
index: getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}),
items: currentRefinement === null ? [] : [{
label: "".concat(id, ": ").concat(currentRefinement),
value: function value(nextState) {
return _refine$9(props, nextState, '', {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
currentRefinement: currentRefinement
}]
};
}
});
function getId$c() {
return 'sortBy';
}
function getCurrentRefinement$b(props, searchState, context) {
var id = getId$c();
var currentRefinement = getCurrentRefinementValue(props, searchState, context, id, null);
if (currentRefinement) {
return currentRefinement;
}
return null;
}
/**
* The connectSortBy connector provides the logic to build a widget that will
* display a list of indices. This allows a user to change how the hits are being sorted.
* @name connectSortBy
* @requirements Algolia handles sorting by creating replica indices. [Read more about sorting](https://www.algolia.com/doc/guides/relevance/sorting/) on
* the Algolia website.
* @kind connector
* @propType {string} defaultRefinement - The default selected index.
* @propType {{value: string, label: string}[]} items - The list of indexes to search in.
* @propType {function} [transformItems] - Function to modify the items being displayed, e.g. for filtering or sorting them. Takes an items as parameter and expects it back in return.
* @providedPropType {function} refine - a function to remove a single filter
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
* @providedPropType {string[]} currentRefinement - the refinement currently applied
* @providedPropType {array.<{isRefined: boolean, label?: string, value: string}>} items - the list of items the HitsPerPage can display. If no label provided, the value will be displayed.
*/
var connectSortBy = createConnectorWithContext({
displayName: 'AlgoliaSortBy',
propTypes: {
defaultRefinement: propTypes.string,
items: propTypes.arrayOf(propTypes.shape({
label: propTypes.string,
value: propTypes.string.isRequired
})).isRequired,
transformItems: propTypes.func
},
getProvidedProps: function getProvidedProps(props, searchState) {
var currentRefinement = getCurrentRefinement$b(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = props.items.map(function (item) {
return item.value === currentRefinement ? _objectSpread({}, item, {
isRefined: true
}) : _objectSpread({}, item, {
isRefined: false
});
});
return {
items: props.transformItems ? props.transformItems(items) : items,
currentRefinement: currentRefinement
};
},
refine: function refine(props, searchState, nextRefinement) {
var id = getId$c();
var nextValue = _defineProperty({}, id, nextRefinement);
var resetPage = true;
return refineValue(searchState, nextValue, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, resetPage);
},
cleanUp: function cleanUp(props, searchState) {
return cleanUpValue(searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
}, getId$c());
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var selectedIndex = getCurrentRefinement$b(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return searchParameters.setIndex(selectedIndex);
},
getMetadata: function getMetadata() {
return {
id: getId$c()
};
}
});
/**
* The `connectStateResults` connector provides a way to access the `searchState` and the `searchResults`
* of InstantSearch.
* For instance this connector allows you to create results/noResults or query/noQuery pages.
* @name connectStateResults
* @kind connector
* @providedPropType {object} searchState - The search state of the instant search component. <br/><br/> See: [Search state structure](https://community.algolia.com/react-instantsearch/guide/Search_state.html)
* @providedPropType {object} searchResults - The search results. <br/><br/> In case of multiple indices: if used under `<Index>`, results will be those of the corresponding index otherwise it'll be those of the root index See: [Search results structure](https://community.algolia.com/algoliasearch-helper-js/reference.html#searchresults)
* @providedPropType {object} allSearchResults - In case of multiple indices you can retrieve all the results
* @providedPropType {string} error - If the search failed, the error will be logged here.
* @providedPropType {boolean} searching - If there is a search in progress.
* @providedPropType {boolean} isSearchStalled - Flag that indicates if React InstantSearch has detected that searches are stalled.
* @providedPropType {boolean} searchingForFacetValues - If there is a search in a list in progress.
* @providedPropType {object} props - component props.
* @example
* import React from 'react';
* import algoliasearch from 'algoliasearch/lite';
* import { InstantSearch, SearchBox, Hits, connectStateResults } from 'react-instantsearch-dom';
*
* const searchClient = algoliasearch(
* 'latency',
* '6be0576ff61c053d5f9a3225e2a90f76'
* );
*
* const Content = connectStateResults(({ searchState, searchResults }) => {
* const hasResults = searchResults && searchResults.nbHits !== 0;
*
* return (
* <div>
* <div hidden={!hasResults}>
* <Hits />
* </div>
* <div hidden={hasResults}>
* <div>No results has been found for {searchState.query}</div>
* </div>
* </div>
* );
* });
*
* const App = () => (
* <InstantSearch
* searchClient={searchClient}
* indexName="instant_search"
* >
* <SearchBox />
* <Content />
* </InstantSearch>
* );
*/
var connectStateResults = createConnectorWithContext({
displayName: 'AlgoliaStateResults',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
return {
searchState: searchState,
searchResults: results,
allSearchResults: searchResults.results,
searching: searchResults.searching,
isSearchStalled: searchResults.isSearchStalled,
error: searchResults.error,
searchingForFacetValues: searchResults.searchingForFacetValues,
props: props
};
}
});
/**
* connectStats connector provides the logic to build a widget that will
* displays algolia search statistics (hits number and processing time).
* @name connectStats
* @kind connector
* @providedPropType {number} nbHits - number of hits returned by Algolia.
* @providedPropType {number} processingTimeMS - the time in ms took by Algolia to search for results.
*/
var connectStats = createConnectorWithContext({
displayName: 'AlgoliaStats',
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (!results) {
return null;
}
return {
nbHits: results.nbHits,
processingTimeMS: results.processingTimeMS
};
}
});
function getId$d(props) {
return props.attribute;
}
var namespace$6 = 'toggle';
var falsyStrings = ['0', 'false', 'null', 'undefined'];
function getCurrentRefinement$c(props, searchState, context) {
var currentRefinement = getCurrentRefinementValue(props, searchState, context, "".concat(namespace$6, ".").concat(getId$d(props)), false);
if (falsyStrings.indexOf(currentRefinement) !== -1) {
return false;
}
return Boolean(currentRefinement);
}
function _refine$a(props, searchState, nextRefinement, context) {
var id = getId$d(props);
var nextValue = _defineProperty({}, id, nextRefinement ? nextRefinement : false);
var resetPage = true;
return refineValue(searchState, nextValue, context, resetPage, namespace$6);
}
function _cleanUp$7(props, searchState, context) {
return cleanUpValue(searchState, context, "".concat(namespace$6, ".").concat(getId$d(props)));
}
/**
* connectToggleRefinement connector provides the logic to build a widget that will
* provides an on/off filtering feature based on an attribute value.
* @name connectToggleRefinement
* @kind connector
* @requirements To use this widget, you'll need an attribute to toggle on.
*
* You can't toggle on null or not-null values. If you want to address this particular use-case you'll need to compute an
* extra boolean attribute saying if the value exists or not. See this [thread](https://discourse.algolia.com/t/how-to-create-a-toggle-for-the-absence-of-a-string-attribute/2460) for more details.
*
* @propType {string} attribute - Name of the attribute on which to apply the `value` refinement. Required when `value` is present.
* @propType {string} label - Label for the toggle.
* @propType {string} value - Value of the refinement to apply on `attribute`.
* @propType {boolean} [defaultRefinement=false] - Default searchState of the widget. Should the toggle be checked by default?
* @providedPropType {boolean} currentRefinement - `true` when the refinement is applied, `false` otherwise
* @providedPropType {object} count - an object that contains the count for `checked` and `unchecked` state
* @providedPropType {function} refine - a function to toggle a refinement
* @providedPropType {function} createURL - a function to generate a URL for the corresponding search state
*/
var connectToggleRefinement = createConnectorWithContext({
displayName: 'AlgoliaToggle',
propTypes: {
label: propTypes.string.isRequired,
attribute: propTypes.string.isRequired,
value: propTypes.any.isRequired,
filter: propTypes.func,
defaultRefinement: propTypes.bool
},
getProvidedProps: function getProvidedProps(props, searchState, searchResults) {
var attribute = props.attribute,
value = props.value;
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var currentRefinement = getCurrentRefinement$c(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var allFacetValues = results && results.getFacetByName(attribute) ? results.getFacetValues(attribute) : null;
var facetValue = // Use null to always be consistent with type of the value
// count: number | null
allFacetValues && allFacetValues.length ? find(allFacetValues, function (item) {
return item.name === value.toString();
}) : null;
var facetValueCount = facetValue && facetValue.count;
var allFacetValuesCount = // Use null to always be consistent with type of the value
// count: number | null
allFacetValues && allFacetValues.length ? allFacetValues.reduce(function (acc, item) {
return acc + item.count;
}, 0) : null;
var canRefine = currentRefinement ? allFacetValuesCount !== null && allFacetValuesCount > 0 : facetValueCount !== null && facetValueCount > 0;
var count = {
checked: allFacetValuesCount,
unchecked: facetValueCount
};
return {
currentRefinement: currentRefinement,
canRefine: canRefine,
count: count
};
},
refine: function refine(props, searchState, nextRefinement) {
return _refine$a(props, searchState, nextRefinement, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
cleanUp: function cleanUp(props, searchState) {
return _cleanUp$7(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
},
getSearchParameters: function getSearchParameters(searchParameters, props, searchState) {
var attribute = props.attribute,
value = props.value,
filter = props.filter;
var checked = getCurrentRefinement$c(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var nextSearchParameters = searchParameters.addDisjunctiveFacet(attribute);
if (checked) {
nextSearchParameters = nextSearchParameters.addDisjunctiveFacetRefinement(attribute, value);
if (filter) {
nextSearchParameters = filter(nextSearchParameters);
}
}
return nextSearchParameters;
},
getMetadata: function getMetadata(props, searchState) {
var id = getId$d(props);
var checked = getCurrentRefinement$c(props, searchState, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var items = [];
var index = getIndexId({
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
if (checked) {
items.push({
label: props.label,
currentRefinement: checked,
attribute: props.attribute,
value: function value(nextState) {
return _refine$a(props, nextState, false, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
}
});
}
return {
id: id,
index: index,
items: items
};
}
});
function inferPayload(_ref) {
var method = _ref.method,
results = _ref.results,
currentHit = _ref.currentHit;
var index = results.index;
var queryID = currentHit.__queryID;
var objectIDs = [currentHit.objectID];
switch (method) {
case 'clickedObjectIDsAfterSearch':
{
var positions = [currentHit.__position];
return {
index: index,
queryID: queryID,
objectIDs: objectIDs,
positions: positions
};
}
case 'convertedObjectIDsAfterSearch':
return {
index: index,
queryID: queryID,
objectIDs: objectIDs
};
default:
throw new Error("Unsupported method \"".concat(method, "\" passed to the insights function. The supported methods are: \"clickedObjectIDsAfterSearch\", \"convertedObjectIDsAfterSearch\"."));
}
}
var wrapInsightsClient = function wrapInsightsClient(aa, results, currentHit) {
return function (method, payload) {
if (typeof aa !== 'function') {
throw new TypeError("Expected insightsClient to be a Function");
}
var inferredPayload = inferPayload({
method: method,
results: results,
currentHit: currentHit
});
aa(method, _objectSpread({}, inferredPayload, payload));
};
};
var connectHitInsights = (function (insightsClient) {
return createConnectorWithContext({
displayName: 'AlgoliaInsights',
getProvidedProps: function getProvidedProps(props, _, searchResults) {
var results = getResults(searchResults, {
ais: props.contextValue,
multiIndexContext: props.indexContextValue
});
var insights = wrapInsightsClient(insightsClient, results, props.hit);
return {
insights: insights
};
}
});
});
exports.connectAutoComplete = connectAutoComplete;
exports.connectBreadcrumb = connectBreadcrumb;
exports.connectConfigure = connectConfigure;
exports.connectCurrentRefinements = connectCurrentRefinements;
exports.connectGeoSearch = connectGeoSearch;
exports.connectHierarchicalMenu = connectHierarchicalMenu;
exports.connectHighlight = connectHighlight;
exports.connectHitInsights = connectHitInsights;
exports.connectHits = connectHits;
exports.connectHitsPerPage = connectHitsPerPage;
exports.connectInfiniteHits = connectInfiniteHits;
exports.connectMenu = connectMenu;
exports.connectNumericMenu = connectNumericMenu;
exports.connectPagination = connectPagination;
exports.connectPoweredBy = connectPoweredBy;
exports.connectRange = connectRange;
exports.connectRefinementList = connectRefinementList;
exports.connectScrollTo = connectScrollTo;
exports.connectSearchBox = connectSearchBox;
exports.connectSortBy = connectSortBy;
exports.connectStateResults = connectStateResults;
exports.connectStats = connectStats;
exports.connectToggleRefinement = connectToggleRefinement;
Object.defineProperty(exports, '__esModule', { value: true });
}));
//# sourceMappingURL=Connectors.js.map
|
ajax/libs/react-native-web/0.13.14/exports/RefreshControl/index.js | cdnjs/cdnjs | function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
/**
* Copyright (c) Nicolas Gallagher.
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import View from '../View';
import React from 'react';
function RefreshControl(props) {
var colors = props.colors,
enabled = props.enabled,
onRefresh = props.onRefresh,
progressBackgroundColor = props.progressBackgroundColor,
progressViewOffset = props.progressViewOffset,
refreshing = props.refreshing,
size = props.size,
tintColor = props.tintColor,
title = props.title,
titleColor = props.titleColor,
rest = _objectWithoutPropertiesLoose(props, ["colors", "enabled", "onRefresh", "progressBackgroundColor", "progressViewOffset", "refreshing", "size", "tintColor", "title", "titleColor"]);
return React.createElement(View, rest);
}
export default RefreshControl; |
ajax/libs/material-ui/4.9.3/esm/Stepper/Stepper.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 Paper from '../Paper';
import StepConnector from '../StepConnector';
export var styles = {
/* Styles applied to the root element. */
root: {
display: 'flex',
padding: 24
},
/* Styles applied to the root element if `orientation="horizontal"`. */
horizontal: {
flexDirection: 'row',
alignItems: 'center'
},
/* Styles applied to the root element if `orientation="vertical"`. */
vertical: {
flexDirection: 'column'
},
/* Styles applied to the root element if `alternativeLabel={true}`. */
alternativeLabel: {
alignItems: 'flex-start'
}
};
var defaultConnector = React.createElement(StepConnector, null);
var Stepper = React.forwardRef(function Stepper(props, ref) {
var _props$activeStep = props.activeStep,
activeStep = _props$activeStep === void 0 ? 0 : _props$activeStep,
_props$alternativeLab = props.alternativeLabel,
alternativeLabel = _props$alternativeLab === void 0 ? false : _props$alternativeLab,
children = props.children,
classes = props.classes,
className = props.className,
_props$connector = props.connector,
connectorProp = _props$connector === void 0 ? defaultConnector : _props$connector,
_props$nonLinear = props.nonLinear,
nonLinear = _props$nonLinear === void 0 ? false : _props$nonLinear,
_props$orientation = props.orientation,
orientation = _props$orientation === void 0 ? 'horizontal' : _props$orientation,
other = _objectWithoutProperties(props, ["activeStep", "alternativeLabel", "children", "classes", "className", "connector", "nonLinear", "orientation"]);
var connector = React.isValidElement(connectorProp) ? React.cloneElement(connectorProp, {
orientation: orientation
}) : null;
var childrenArray = React.Children.toArray(children);
var steps = childrenArray.map(function (step, index) {
var controlProps = {
alternativeLabel: alternativeLabel,
connector: connectorProp,
last: index + 1 === childrenArray.length,
orientation: orientation
};
var state = {
index: index,
active: false,
completed: false,
disabled: false
};
if (activeStep === index) {
state.active = true;
} else if (!nonLinear && activeStep > index) {
state.completed = true;
} else if (!nonLinear && activeStep < index) {
state.disabled = true;
}
return [!alternativeLabel && connector && index !== 0 && React.cloneElement(connector, _extends({
key: index
}, state)), React.cloneElement(step, _extends({}, controlProps, {}, state, {}, step.props))];
});
return React.createElement(Paper, _extends({
square: true,
elevation: 0,
className: clsx(classes.root, classes[orientation], className, alternativeLabel && classes.alternativeLabel),
ref: ref
}, other), steps);
});
process.env.NODE_ENV !== "production" ? Stepper.propTypes = {
/**
* Set the active step (zero based index).
* Set to -1 to disable all the steps.
*/
activeStep: PropTypes.number,
/**
* If set to 'true' and orientation is horizontal,
* then the step label will be positioned under the icon.
*/
alternativeLabel: PropTypes.bool,
/**
* Two or more `<Step />` components.
*/
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,
/**
* An element to be placed between each step.
*/
connector: PropTypes.element,
/**
* If set the `Stepper` will not assist in controlling steps for linear flow.
*/
nonLinear: PropTypes.bool,
/**
* The stepper orientation (layout flow direction).
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical'])
} : void 0;
export default withStyles(styles, {
name: 'MuiStepper'
})(Stepper); |
ajax/libs/boardgame-io/0.46.2/boardgameio.es.js | cdnjs/cdnjs | import { nanoid } from 'nanoid';
import { applyMiddleware, compose, createStore } from 'redux';
import produce from 'immer';
import isPlainObject from 'lodash.isplainobject';
import { applyPatch, createPatch } from 'rfc6902';
import { stringify, parse } from 'flatted';
import React from 'react';
import PropTypes from 'prop-types';
import ioNamespace__default from 'socket.io-client';
function noop() { }
const identity = x => x;
function assign(tar, src) {
// @ts-ignore
for (const k in src)
tar[k] = src[k];
return tar;
}
function run(fn) {
return fn();
}
function blank_object() {
return Object.create(null);
}
function run_all(fns) {
fns.forEach(run);
}
function is_function(thing) {
return typeof thing === 'function';
}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}
function is_empty(obj) {
return Object.keys(obj).length === 0;
}
function subscribe(store, ...callbacks) {
if (store == null) {
return noop;
}
const unsub = store.subscribe(...callbacks);
return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
function component_subscribe(component, store, callback) {
component.$$.on_destroy.push(subscribe(store, callback));
}
function create_slot(definition, ctx, $$scope, fn) {
if (definition) {
const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
return definition[0](slot_ctx);
}
}
function get_slot_context(definition, ctx, $$scope, fn) {
return definition[1] && fn
? assign($$scope.ctx.slice(), definition[1](fn(ctx)))
: $$scope.ctx;
}
function get_slot_changes(definition, $$scope, dirty, fn) {
if (definition[2] && fn) {
const lets = definition[2](fn(dirty));
if ($$scope.dirty === undefined) {
return lets;
}
if (typeof lets === 'object') {
const merged = [];
const len = Math.max($$scope.dirty.length, lets.length);
for (let i = 0; i < len; i += 1) {
merged[i] = $$scope.dirty[i] | lets[i];
}
return merged;
}
return $$scope.dirty | lets;
}
return $$scope.dirty;
}
function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
if (slot_changes) {
const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
slot.p(slot_context, slot_changes);
}
}
function get_all_dirty_from_scope($$scope) {
if ($$scope.ctx.length > 32) {
const dirty = [];
const length = $$scope.ctx.length / 32;
for (let i = 0; i < length; i++) {
dirty[i] = -1;
}
return dirty;
}
return -1;
}
function exclude_internal_props(props) {
const result = {};
for (const k in props)
if (k[0] !== '$')
result[k] = props[k];
return result;
}
function null_to_empty(value) {
return value == null ? '' : value;
}
const is_client = typeof window !== 'undefined';
let now = is_client
? () => window.performance.now()
: () => Date.now();
let raf = is_client ? cb => requestAnimationFrame(cb) : noop;
const tasks = new Set();
function run_tasks(now) {
tasks.forEach(task => {
if (!task.c(now)) {
tasks.delete(task);
task.f();
}
});
if (tasks.size !== 0)
raf(run_tasks);
}
/**
* Creates a new task that runs on each raf frame
* until it returns a falsy value or is aborted
*/
function loop(callback) {
let task;
if (tasks.size === 0)
raf(run_tasks);
return {
promise: new Promise(fulfill => {
tasks.add(task = { c: callback, f: fulfill });
}),
abort() {
tasks.delete(task);
}
};
}
function append(target, node) {
target.appendChild(node);
}
function append_styles(target, style_sheet_id, styles) {
const append_styles_to = get_root_for_style(target);
if (!append_styles_to.getElementById(style_sheet_id)) {
const style = element('style');
style.id = style_sheet_id;
style.textContent = styles;
append_stylesheet(append_styles_to, style);
}
}
function get_root_for_style(node) {
if (!node)
return document;
const root = node.getRootNode ? node.getRootNode() : node.ownerDocument;
if (root.host) {
return root;
}
return document;
}
function append_empty_stylesheet(node) {
const style_element = element('style');
append_stylesheet(get_root_for_style(node), style_element);
return style_element;
}
function append_stylesheet(node, style) {
append(node.head || node, style);
}
function insert(target, node, anchor) {
target.insertBefore(node, anchor || null);
}
function detach(node) {
node.parentNode.removeChild(node);
}
function destroy_each(iterations, detaching) {
for (let i = 0; i < iterations.length; i += 1) {
if (iterations[i])
iterations[i].d(detaching);
}
}
function element(name) {
return document.createElement(name);
}
function svg_element(name) {
return document.createElementNS('http://www.w3.org/2000/svg', name);
}
function text(data) {
return document.createTextNode(data);
}
function space() {
return text(' ');
}
function empty() {
return text('');
}
function listen(node, event, handler, options) {
node.addEventListener(event, handler, options);
return () => node.removeEventListener(event, handler, options);
}
function stop_propagation(fn) {
return function (event) {
event.stopPropagation();
// @ts-ignore
return fn.call(this, event);
};
}
function attr(node, attribute, value) {
if (value == null)
node.removeAttribute(attribute);
else if (node.getAttribute(attribute) !== value)
node.setAttribute(attribute, value);
}
function to_number(value) {
return value === '' ? null : +value;
}
function children(element) {
return Array.from(element.childNodes);
}
function set_data(text, data) {
data = '' + data;
if (text.wholeText !== data)
text.data = data;
}
function set_input_value(input, value) {
input.value = value == null ? '' : value;
}
function select_option(select, value) {
for (let i = 0; i < select.options.length; i += 1) {
const option = select.options[i];
if (option.__value === value) {
option.selected = true;
return;
}
}
}
function select_value(select) {
const selected_option = select.querySelector(':checked') || select.options[0];
return selected_option && selected_option.__value;
}
function toggle_class(element, name, toggle) {
element.classList[toggle ? 'add' : 'remove'](name);
}
function custom_event(type, detail, bubbles = false) {
const e = document.createEvent('CustomEvent');
e.initCustomEvent(type, bubbles, false, detail);
return e;
}
const active_docs = new Set();
let active = 0;
// https://github.com/darkskyapp/string-hash/blob/master/index.js
function hash(str) {
let hash = 5381;
let i = str.length;
while (i--)
hash = ((hash << 5) - hash) ^ str.charCodeAt(i);
return hash >>> 0;
}
function create_rule(node, a, b, duration, delay, ease, fn, uid = 0) {
const step = 16.666 / duration;
let keyframes = '{\n';
for (let p = 0; p <= 1; p += step) {
const t = a + (b - a) * ease(p);
keyframes += p * 100 + `%{${fn(t, 1 - t)}}\n`;
}
const rule = keyframes + `100% {${fn(b, 1 - b)}}\n}`;
const name = `__svelte_${hash(rule)}_${uid}`;
const doc = get_root_for_style(node);
active_docs.add(doc);
const stylesheet = doc.__svelte_stylesheet || (doc.__svelte_stylesheet = append_empty_stylesheet(node).sheet);
const current_rules = doc.__svelte_rules || (doc.__svelte_rules = {});
if (!current_rules[name]) {
current_rules[name] = true;
stylesheet.insertRule(`@keyframes ${name} ${rule}`, stylesheet.cssRules.length);
}
const animation = node.style.animation || '';
node.style.animation = `${animation ? `${animation}, ` : ''}${name} ${duration}ms linear ${delay}ms 1 both`;
active += 1;
return name;
}
function delete_rule(node, name) {
const previous = (node.style.animation || '').split(', ');
const next = previous.filter(name
? anim => anim.indexOf(name) < 0 // remove specific animation
: anim => anim.indexOf('__svelte') === -1 // remove all Svelte animations
);
const deleted = previous.length - next.length;
if (deleted) {
node.style.animation = next.join(', ');
active -= deleted;
if (!active)
clear_rules();
}
}
function clear_rules() {
raf(() => {
if (active)
return;
active_docs.forEach(doc => {
const stylesheet = doc.__svelte_stylesheet;
let i = stylesheet.cssRules.length;
while (i--)
stylesheet.deleteRule(i);
doc.__svelte_rules = {};
});
active_docs.clear();
});
}
let current_component;
function set_current_component(component) {
current_component = component;
}
function get_current_component() {
if (!current_component)
throw new Error('Function called outside component initialization');
return current_component;
}
function afterUpdate(fn) {
get_current_component().$$.after_update.push(fn);
}
function onDestroy(fn) {
get_current_component().$$.on_destroy.push(fn);
}
function createEventDispatcher() {
const component = get_current_component();
return (type, detail) => {
const callbacks = component.$$.callbacks[type];
if (callbacks) {
// TODO are there situations where events could be dispatched
// in a server (non-DOM) environment?
const event = custom_event(type, detail);
callbacks.slice().forEach(fn => {
fn.call(component, event);
});
}
};
}
function setContext(key, context) {
get_current_component().$$.context.set(key, context);
}
function getContext(key) {
return get_current_component().$$.context.get(key);
}
// TODO figure out if we still want to support
// shorthand events, or if we want to implement
// a real bubbling mechanism
function bubble(component, event) {
const callbacks = component.$$.callbacks[event.type];
if (callbacks) {
// @ts-ignore
callbacks.slice().forEach(fn => fn.call(this, event));
}
}
const dirty_components = [];
const binding_callbacks = [];
const render_callbacks = [];
const flush_callbacks = [];
const resolved_promise = Promise.resolve();
let update_scheduled = false;
function schedule_update() {
if (!update_scheduled) {
update_scheduled = true;
resolved_promise.then(flush);
}
}
function add_render_callback(fn) {
render_callbacks.push(fn);
}
let flushing = false;
const seen_callbacks = new Set();
function flush() {
if (flushing)
return;
flushing = true;
do {
// first, call beforeUpdate functions
// and update components
for (let i = 0; i < dirty_components.length; i += 1) {
const component = dirty_components[i];
set_current_component(component);
update(component.$$);
}
set_current_component(null);
dirty_components.length = 0;
while (binding_callbacks.length)
binding_callbacks.pop()();
// then, once components are updated, call
// afterUpdate functions. This may cause
// subsequent updates...
for (let i = 0; i < render_callbacks.length; i += 1) {
const callback = render_callbacks[i];
if (!seen_callbacks.has(callback)) {
// ...so guard against infinite loops
seen_callbacks.add(callback);
callback();
}
}
render_callbacks.length = 0;
} while (dirty_components.length);
while (flush_callbacks.length) {
flush_callbacks.pop()();
}
update_scheduled = false;
flushing = false;
seen_callbacks.clear();
}
function update($$) {
if ($$.fragment !== null) {
$$.update();
run_all($$.before_update);
const dirty = $$.dirty;
$$.dirty = [-1];
$$.fragment && $$.fragment.p($$.ctx, dirty);
$$.after_update.forEach(add_render_callback);
}
}
let promise;
function wait() {
if (!promise) {
promise = Promise.resolve();
promise.then(() => {
promise = null;
});
}
return promise;
}
function dispatch(node, direction, kind) {
node.dispatchEvent(custom_event(`${direction ? 'intro' : 'outro'}${kind}`));
}
const outroing = new Set();
let outros;
function group_outros() {
outros = {
r: 0,
c: [],
p: outros // parent group
};
}
function check_outros() {
if (!outros.r) {
run_all(outros.c);
}
outros = outros.p;
}
function transition_in(block, local) {
if (block && block.i) {
outroing.delete(block);
block.i(local);
}
}
function transition_out(block, local, detach, callback) {
if (block && block.o) {
if (outroing.has(block))
return;
outroing.add(block);
outros.c.push(() => {
outroing.delete(block);
if (callback) {
if (detach)
block.d(1);
callback();
}
});
block.o(local);
}
}
const null_transition = { duration: 0 };
function create_bidirectional_transition(node, fn, params, intro) {
let config = fn(node, params);
let t = intro ? 0 : 1;
let running_program = null;
let pending_program = null;
let animation_name = null;
function clear_animation() {
if (animation_name)
delete_rule(node, animation_name);
}
function init(program, duration) {
const d = (program.b - t);
duration *= Math.abs(d);
return {
a: t,
b: program.b,
d,
duration,
start: program.start,
end: program.start + duration,
group: program.group
};
}
function go(b) {
const { delay = 0, duration = 300, easing = identity, tick = noop, css } = config || null_transition;
const program = {
start: now() + delay,
b
};
if (!b) {
// @ts-ignore todo: improve typings
program.group = outros;
outros.r += 1;
}
if (running_program || pending_program) {
pending_program = program;
}
else {
// if this is an intro, and there's a delay, we need to do
// an initial tick and/or apply CSS animation immediately
if (css) {
clear_animation();
animation_name = create_rule(node, t, b, duration, delay, easing, css);
}
if (b)
tick(0, 1);
running_program = init(program, duration);
add_render_callback(() => dispatch(node, b, 'start'));
loop(now => {
if (pending_program && now > pending_program.start) {
running_program = init(pending_program, duration);
pending_program = null;
dispatch(node, running_program.b, 'start');
if (css) {
clear_animation();
animation_name = create_rule(node, t, running_program.b, running_program.duration, 0, easing, config.css);
}
}
if (running_program) {
if (now >= running_program.end) {
tick(t = running_program.b, 1 - t);
dispatch(node, running_program.b, 'end');
if (!pending_program) {
// we're done
if (running_program.b) {
// intro — we can tidy up immediately
clear_animation();
}
else {
// outro — needs to be coordinated
if (!--running_program.group.r)
run_all(running_program.group.c);
}
}
running_program = null;
}
else if (now >= running_program.start) {
const p = now - running_program.start;
t = running_program.a + running_program.d * easing(p / running_program.duration);
tick(t, 1 - t);
}
}
return !!(running_program || pending_program);
});
}
}
return {
run(b) {
if (is_function(config)) {
wait().then(() => {
// @ts-ignore
config = config();
go(b);
});
}
else {
go(b);
}
},
end() {
clear_animation();
running_program = pending_program = null;
}
};
}
function get_spread_update(levels, updates) {
const update = {};
const to_null_out = {};
const accounted_for = { $$scope: 1 };
let i = levels.length;
while (i--) {
const o = levels[i];
const n = updates[i];
if (n) {
for (const key in o) {
if (!(key in n))
to_null_out[key] = 1;
}
for (const key in n) {
if (!accounted_for[key]) {
update[key] = n[key];
accounted_for[key] = 1;
}
}
levels[i] = n;
}
else {
for (const key in o) {
accounted_for[key] = 1;
}
}
}
for (const key in to_null_out) {
if (!(key in update))
update[key] = undefined;
}
return update;
}
function get_spread_object(spread_props) {
return typeof spread_props === 'object' && spread_props !== null ? spread_props : {};
}
function create_component(block) {
block && block.c();
}
function mount_component(component, target, anchor, customElement) {
const { fragment, on_mount, on_destroy, after_update } = component.$$;
fragment && fragment.m(target, anchor);
if (!customElement) {
// onMount happens before the initial afterUpdate
add_render_callback(() => {
const new_on_destroy = on_mount.map(run).filter(is_function);
if (on_destroy) {
on_destroy.push(...new_on_destroy);
}
else {
// Edge case - component was destroyed immediately,
// most likely as a result of a binding initialising
run_all(new_on_destroy);
}
component.$$.on_mount = [];
});
}
after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
const $$ = component.$$;
if ($$.fragment !== null) {
run_all($$.on_destroy);
$$.fragment && $$.fragment.d(detaching);
// TODO null out other refs, including component.$$ (but need to
// preserve final state?)
$$.on_destroy = $$.fragment = null;
$$.ctx = [];
}
}
function make_dirty(component, i) {
if (component.$$.dirty[0] === -1) {
dirty_components.push(component);
schedule_update();
component.$$.dirty.fill(0);
}
component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
}
function init(component, options, instance, create_fragment, not_equal, props, append_styles, dirty = [-1]) {
const parent_component = current_component;
set_current_component(component);
const $$ = component.$$ = {
fragment: null,
ctx: null,
// state
props,
update: noop,
not_equal,
bound: blank_object(),
// lifecycle
on_mount: [],
on_destroy: [],
on_disconnect: [],
before_update: [],
after_update: [],
context: new Map(parent_component ? parent_component.$$.context : options.context || []),
// everything else
callbacks: blank_object(),
dirty,
skip_bound: false,
root: options.target || parent_component.$$.root
};
append_styles && append_styles($$.root);
let ready = false;
$$.ctx = instance
? instance(component, options.props || {}, (i, ret, ...rest) => {
const value = rest.length ? rest[0] : ret;
if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
if (!$$.skip_bound && $$.bound[i])
$$.bound[i](value);
if (ready)
make_dirty(component, i);
}
return ret;
})
: [];
$$.update();
ready = true;
run_all($$.before_update);
// `false` as a special case of no DOM component
$$.fragment = create_fragment ? create_fragment($$.ctx) : false;
if (options.target) {
if (options.hydrate) {
const nodes = children(options.target);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.l(nodes);
nodes.forEach(detach);
}
else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.c();
}
if (options.intro)
transition_in(component.$$.fragment);
mount_component(component, options.target, options.anchor, options.customElement);
flush();
}
set_current_component(parent_component);
}
/**
* Base class for Svelte components. Used when dev=false.
*/
class SvelteComponent {
$destroy() {
destroy_component(this, 1);
this.$destroy = noop;
}
$on(type, callback) {
const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index !== -1)
callbacks.splice(index, 1);
};
}
$set($$props) {
if (this.$$set && !is_empty($$props)) {
this.$$.skip_bound = true;
this.$$set($$props);
this.$$.skip_bound = false;
}
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const MAKE_MOVE = 'MAKE_MOVE';
const GAME_EVENT = 'GAME_EVENT';
const REDO = 'REDO';
const RESET = 'RESET';
const SYNC = 'SYNC';
const UNDO = 'UNDO';
const UPDATE = 'UPDATE';
const PATCH = 'PATCH';
const PLUGIN = 'PLUGIN';
const STRIP_TRANSIENTS = 'STRIP_TRANSIENTS';
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Generate a move to be dispatched to the game move reducer.
*
* @param {string} type - The move type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const makeMove = (type, args, playerID, credentials) => ({
type: MAKE_MOVE,
payload: { type, args, playerID, credentials },
});
/**
* Generate a game event to be dispatched to the flow reducer.
*
* @param {string} type - The event type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const gameEvent = (type, args, playerID, credentials) => ({
type: GAME_EVENT,
payload: { type, args, playerID, credentials },
});
/**
* Generate an automatic game event that is a side-effect of a move.
* @param {string} type - The event type.
* @param {Array} args - Additional arguments.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const automaticGameEvent = (type, args, playerID, credentials) => ({
type: GAME_EVENT,
payload: { type, args, playerID, credentials },
automatic: true,
});
const sync = (info) => ({
type: SYNC,
state: info.state,
log: info.log,
initialState: info.initialState,
clientOnly: true,
});
/**
* Used to update the Redux store's state with patch in response to
* an action coming from another player.
* @param prevStateID previous stateID
* @param stateID stateID after this patch
* @param {Operation[]} patch - The patch to apply.
* @param {LogEntry[]} deltalog - A log delta.
*/
const patch = (prevStateID, stateID, patch, deltalog) => ({
type: PATCH,
prevStateID,
stateID,
patch,
deltalog,
clientOnly: true,
});
/**
* Used to update the Redux store's state in response to
* an action coming from another player.
* @param {object} state - The state to restore.
* @param {Array} deltalog - A log delta.
*/
const update$1 = (state, deltalog) => ({
type: UPDATE,
state,
deltalog,
clientOnly: true,
});
/**
* Used to reset the game state.
* @param {object} state - The initial state.
*/
const reset = (state) => ({
type: RESET,
state,
clientOnly: true,
});
/**
* Used to undo the last move.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const undo = (playerID, credentials) => ({
type: UNDO,
payload: { type: null, args: null, playerID, credentials },
});
/**
* Used to redo the last undone move.
* @param {string} playerID - The ID of the player making this action.
* @param {string} credentials - (optional) The credentials for the player making this action.
*/
const redo = (playerID, credentials) => ({
type: REDO,
payload: { type: null, args: null, playerID, credentials },
});
/**
* Allows plugins to define their own actions and intercept them.
*/
const plugin = (type, args, playerID, credentials) => ({
type: PLUGIN,
payload: { type, args, playerID, credentials },
});
/**
* Private action used to strip transient metadata (e.g. errors) from the game
* state.
*/
const stripTransients = () => ({
type: STRIP_TRANSIENTS,
});
var ActionCreators = /*#__PURE__*/Object.freeze({
makeMove: makeMove,
gameEvent: gameEvent,
automaticGameEvent: automaticGameEvent,
sync: sync,
patch: patch,
update: update$1,
reset: reset,
undo: undo,
redo: redo,
plugin: plugin,
stripTransients: stripTransients
});
/**
* Moves can return this when they want to indicate
* that the combination of arguments is illegal and
* the move ought to be discarded.
*/
const INVALID_MOVE = 'INVALID_MOVE';
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Plugin that allows using Immer to make immutable changes
* to G by just mutating it.
*/
const ImmerPlugin = {
name: 'plugin-immer',
fnWrap: (move) => (G, ctx, ...args) => {
let isInvalid = false;
const newG = produce(G, (G) => {
const result = move(G, ctx, ...args);
if (result === INVALID_MOVE) {
isInvalid = true;
return;
}
return result;
});
if (isInvalid)
return INVALID_MOVE;
return newG;
},
};
// Inlined version of Alea from https://github.com/davidbau/seedrandom.
// Converted to Typescript October 2020.
class Alea {
constructor(seed) {
const mash = Mash();
// Apply the seeding algorithm from Baagoe.
this.c = 1;
this.s0 = mash(' ');
this.s1 = mash(' ');
this.s2 = mash(' ');
this.s0 -= mash(seed);
if (this.s0 < 0) {
this.s0 += 1;
}
this.s1 -= mash(seed);
if (this.s1 < 0) {
this.s1 += 1;
}
this.s2 -= mash(seed);
if (this.s2 < 0) {
this.s2 += 1;
}
}
next() {
const t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
this.s0 = this.s1;
this.s1 = this.s2;
return (this.s2 = t - (this.c = Math.trunc(t)));
}
}
function Mash() {
let n = 0xefc8249d;
const mash = function (data) {
const str = data.toString();
for (let i = 0; i < str.length; i++) {
n += str.charCodeAt(i);
let h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
return mash;
}
function copy(f, t) {
t.c = f.c;
t.s0 = f.s0;
t.s1 = f.s1;
t.s2 = f.s2;
return t;
}
function alea(seed, state) {
const xg = new Alea(seed);
const prng = xg.next.bind(xg);
if (state)
copy(state, xg);
prng.state = () => copy(xg, {});
return prng;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Random
*
* Calls that require a pseudorandom number generator.
* Uses a seed from ctx, and also persists the PRNG
* state in ctx so that moves can stay pure.
*/
class Random {
/**
* constructor
* @param {object} ctx - The ctx object to initialize from.
*/
constructor(state) {
// If we are on the client, the seed is not present.
// Just use a temporary seed to execute the move without
// crashing it. The move state itself is discarded,
// so the actual value doesn't matter.
this.state = state || { seed: '0' };
this.used = false;
}
/**
* Generates a new seed from the current date / time.
*/
static seed() {
return Date.now().toString(36).slice(-10);
}
isUsed() {
return this.used;
}
getState() {
return this.state;
}
/**
* Generate a random number.
*/
_random() {
this.used = true;
const R = this.state;
const seed = R.prngstate ? '' : R.seed;
const rand = alea(seed, R.prngstate);
const number = rand();
this.state = {
...R,
prngstate: rand.state(),
};
return number;
}
api() {
const random = this._random.bind(this);
const SpotValue = {
D4: 4,
D6: 6,
D8: 8,
D10: 10,
D12: 12,
D20: 20,
};
// Generate functions for predefined dice values D4 - D20.
const predefined = {};
for (const key in SpotValue) {
const spotvalue = SpotValue[key];
predefined[key] = (diceCount) => {
return diceCount === undefined
? Math.floor(random() * spotvalue) + 1
: Array.from({ length: diceCount }).map(() => Math.floor(random() * spotvalue) + 1);
};
}
function Die(spotvalue = 6, diceCount) {
return diceCount === undefined
? Math.floor(random() * spotvalue) + 1
: Array.from({ length: diceCount }).map(() => Math.floor(random() * spotvalue) + 1);
}
return {
/**
* Similar to Die below, but with fixed spot values.
* Supports passing a diceCount
* if not defined, defaults to 1 and returns the value directly.
* if defined, returns an array containing the random dice values.
*
* D4: (diceCount) => value
* D6: (diceCount) => value
* D8: (diceCount) => value
* D10: (diceCount) => value
* D12: (diceCount) => value
* D20: (diceCount) => value
*/
...predefined,
/**
* Roll a die of specified spot value.
*
* @param {number} spotvalue - The die dimension (default: 6).
* @param {number} diceCount - number of dice to throw.
* if not defined, defaults to 1 and returns the value directly.
* if defined, returns an array containing the random dice values.
*/
Die,
/**
* Generate a random number between 0 and 1.
*/
Number: () => {
return random();
},
/**
* Shuffle an array.
*
* @param {Array} deck - The array to shuffle. Does not mutate
* the input, but returns the shuffled array.
*/
Shuffle: (deck) => {
const clone = [...deck];
let sourceIndex = deck.length;
let destinationIndex = 0;
const shuffled = Array.from({ length: sourceIndex });
while (sourceIndex) {
const randomIndex = Math.trunc(sourceIndex * random());
shuffled[destinationIndex++] = clone[randomIndex];
clone[randomIndex] = clone[--sourceIndex];
}
return shuffled;
},
_obj: this,
};
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const RandomPlugin = {
name: 'random',
noClient: ({ api }) => {
return api._obj.isUsed();
},
flush: ({ api }) => {
return api._obj.getState();
},
api: ({ data }) => {
const random = new Random(data);
return random.api();
},
setup: ({ game }) => {
let { seed } = game;
if (seed === undefined) {
seed = Random.seed();
}
return { seed };
},
playerView: () => undefined,
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Events
*/
class Events {
constructor(flow, ctx, playerID) {
this.flow = flow;
this.playerID = playerID;
this.dispatch = [];
this.initialTurn = ctx.turn;
this.updateTurnContext(ctx);
// This is an arbitrarily large upper threshold, which could be made
// configurable via a game option if the need arises.
this.maxEndedTurnsPerAction = ctx.numPlayers * 100;
}
api() {
const events = {
_obj: this,
};
for (const type of this.flow.eventNames) {
events[type] = (...args) => {
this.dispatch.push({
type,
args,
phase: this.currentPhase,
turn: this.currentTurn,
});
};
}
return events;
}
isUsed() {
return this.dispatch.length > 0;
}
updateTurnContext(ctx) {
this.currentPhase = ctx.phase;
this.currentTurn = ctx.turn;
}
stateWithError(state) {
return {
...state,
plugins: {
...state.plugins,
events: {
...state.plugins.events,
data: {
error: 'Maximum number of turn endings exceeded for this update.\n' +
'This likely means game code is triggering an infinite loop.',
},
},
},
};
}
/**
* Updates ctx with the triggered events.
* @param {object} state - The state object { G, ctx }.
*/
update(state) {
const initialState = state;
for (let i = 0; i < this.dispatch.length; i++) {
const endedTurns = this.currentTurn - this.initialTurn;
// This protects against potential infinite loops if specific events are called on hooks.
// The moment we exceed the defined threshold, we just bail out of all phases.
if (endedTurns >= this.maxEndedTurnsPerAction) {
return this.stateWithError(initialState);
}
const event = this.dispatch[i];
// If the turn already ended, don't try to process stage events.
if ((event.type === 'endStage' ||
event.type === 'setStage' ||
event.type === 'setActivePlayers') &&
event.turn !== state.ctx.turn) {
continue;
}
// If the turn already ended some other way,
// don't try to end the turn again.
if (event.type === 'endTurn' && event.turn !== state.ctx.turn) {
continue;
}
// If the phase already ended some other way,
// don't try to end the phase again.
if ((event.type === 'endPhase' || event.type === 'setPhase') &&
event.phase !== state.ctx.phase) {
continue;
}
const action = automaticGameEvent(event.type, event.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 }) => api._obj.isUsed(),
isInvalid: ({ data }) => data.error || false,
// Update the events plugin’s internal turn context each time a move
// or hook is called. This allows events called after turn or phase
// endings to dispatch the current turn and phase correctly.
fnWrap: (fn) => (G, ctx, ...args) => {
const api = ctx.events;
if (api)
api._obj.updateTurnContext(ctx);
G = fn(G, ctx, ...args);
return G;
},
dangerouslyFlushRawState: ({ state, api }) => api._obj.update(state),
api: ({ game, ctx, playerID }) => new Events(game.flow, ctx, playerID).api(),
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Plugin that makes it possible to add metadata to log entries.
* During a move, you can set metadata using ctx.log.setMetadata and it will be
* available on the log entry for that move.
*/
const LogPlugin = {
name: 'log',
flush: () => ({}),
api: ({ data }) => {
return {
setMetadata: (metadata) => {
data.metadata = metadata;
},
};
},
setup: () => ({}),
};
/**
* Check if a value can be serialized (e.g. using `JSON.stringify`).
* Adapted from: https://stackoverflow.com/a/30712764/3829557
*/
function isSerializable(value) {
// Primitives are OK.
if (value === undefined ||
value === null ||
typeof value === 'boolean' ||
typeof value === 'number' ||
typeof value === 'string') {
return true;
}
// A non-primitive value that is neither a POJO or an array cannot be serialized.
if (!isPlainObject(value) && !Array.isArray(value)) {
return false;
}
// Recurse entries if the value is an object or array.
for (const key in value) {
if (!isSerializable(value[key]))
return false;
}
return true;
}
/**
* Plugin that checks whether state is serializable, in order to avoid
* network serialization bugs.
*/
const SerializablePlugin = {
name: 'plugin-serializable',
fnWrap: (move) => (G, ctx, ...args) => {
const result = move(G, ctx, ...args);
// Check state in non-production environments.
if (process.env.NODE_ENV !== 'production' && !isSerializable(result)) {
throw new Error('Move state is not JSON-serialiazable.\n' +
'See https://boardgame.io/documentation/#/?id=state for more information.');
}
return result;
},
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const production = process.env.NODE_ENV === 'production';
const logfn = production ? () => { } : (...msg) => console.log(...msg);
const errorfn = (...msg) => console.error(...msg);
function info(msg) {
logfn(`INFO: ${msg}`);
}
function error(error) {
errorfn('ERROR:', error);
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* List of plugins that are always added.
*/
const CORE_PLUGINS = [ImmerPlugin, RandomPlugin, LogPlugin, SerializablePlugin];
const DEFAULT_PLUGINS = [...CORE_PLUGINS, EventsPlugin];
/**
* Allow plugins to intercept actions and process them.
*/
const ProcessAction = (state, action, opts) => {
// TODO(#723): Extend error handling to plugins.
opts.game.plugins
.filter((plugin) => plugin.action !== undefined)
.filter((plugin) => plugin.name === action.payload.type)
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
const data = plugin.action(pluginState.data, action.payload);
state = {
...state,
plugins: {
...state.plugins,
[name]: { ...pluginState, data },
},
};
});
return state;
};
/**
* The API's created by various plugins are stored in the plugins
* section of the state object:
*
* {
* G: {},
* ctx: {},
* plugins: {
* plugin-a: {
* data: {}, // this is generated by the plugin at Setup / Flush.
* api: {}, // this is ephemeral and generated by Enhance.
* }
* }
* }
*
* This function takes these API's and stuffs them back into
* ctx for consumption inside a move function or hook.
*/
const EnhanceCtx = (state) => {
const ctx = { ...state.ctx };
const plugins = state.plugins || {};
Object.entries(plugins).forEach(([name, { api }]) => {
ctx[name] = api;
});
return ctx;
};
/**
* Applies the provided plugins to the given move / flow function.
*
* @param {function} functionToWrap - The move function or trigger to apply the plugins to.
* @param {object} plugins - The list of plugins.
*/
const FnWrap = (functionToWrap, plugins) => {
return [...DEFAULT_PLUGINS, ...plugins]
.filter((plugin) => plugin.fnWrap !== undefined)
.reduce((fn, { fnWrap }) => fnWrap(fn), functionToWrap);
};
/**
* Allows the plugin to generate its initial state.
*/
const Setup = (state, opts) => {
[...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.setup !== undefined)
.forEach((plugin) => {
const name = plugin.name;
const data = plugin.setup({
G: state.G,
ctx: state.ctx,
game: opts.game,
});
state = {
...state,
plugins: {
...state.plugins,
[name]: { data },
},
};
});
return state;
};
/**
* Invokes the plugin before a move or event.
* The API that the plugin generates is stored inside
* the `plugins` section of the state (which is subsequently
* merged into ctx).
*/
const Enhance = (state, opts) => {
[...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.api !== undefined)
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
const api = plugin.api({
G: state.G,
ctx: state.ctx,
data: pluginState.data,
game: opts.game,
playerID: opts.playerID,
});
state = {
...state,
plugins: {
...state.plugins,
[name]: { ...pluginState, api },
},
};
});
return state;
};
/**
* Allows plugins to update their state after a move / event.
*/
const Flush = (state, opts) => {
// We flush the events plugin first, then custom plugins and the core plugins.
// This means custom plugins cannot use the events API but will be available in event hooks.
// Note that plugins are flushed in reverse, to allow custom plugins calling each other.
[...CORE_PLUGINS, ...opts.game.plugins, EventsPlugin]
.reverse()
.forEach((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name] || { data: {} };
if (plugin.flush) {
const newData = plugin.flush({
G: state.G,
ctx: state.ctx,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
state = {
...state,
plugins: {
...state.plugins,
[plugin.name]: { data: newData },
},
};
}
else if (plugin.dangerouslyFlushRawState) {
state = plugin.dangerouslyFlushRawState({
state,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
// Remove everything other than data.
const data = state.plugins[name].data;
state = {
...state,
plugins: {
...state.plugins,
[plugin.name]: { data },
},
};
}
});
return state;
};
/**
* Allows plugins to indicate if they should not be materialized on the client.
* This will cause the client to discard the state update and wait for the
* master instead.
*/
const NoClient = (state, opts) => {
return [...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.noClient !== undefined)
.map((plugin) => {
const name = plugin.name;
const pluginState = state.plugins[name];
if (pluginState) {
return plugin.noClient({
G: state.G,
ctx: state.ctx,
game: opts.game,
api: pluginState.api,
data: pluginState.data,
});
}
return false;
})
.includes(true);
};
/**
* Allows plugins to indicate if the entire action should be thrown out
* as invalid. This will cancel the entire state update.
*/
const IsInvalid = (state, opts) => {
const firstInvalidReturn = [...DEFAULT_PLUGINS, ...opts.game.plugins]
.filter((plugin) => plugin.isInvalid !== undefined)
.map((plugin) => {
const { name } = plugin;
const pluginState = state.plugins[name];
const message = plugin.isInvalid({
G: state.G,
ctx: state.ctx,
game: opts.game,
data: pluginState && pluginState.data,
});
return message ? { plugin: name, message } : false;
})
.find((value) => value);
return firstInvalidReturn || false;
};
/**
* Update plugin state after move/event & check if plugins consider the update to be valid.
* @returns Tuple of `[updatedState]` or `[originalState, invalidError]`.
*/
const FlushAndValidate = (state, opts) => {
const updatedState = Flush(state, opts);
const isInvalid = IsInvalid(updatedState, opts);
if (!isInvalid)
return [updatedState];
const { plugin, message } = isInvalid;
error(`${plugin} plugin declared action invalid:\n${message}`);
return [state, isInvalid];
};
/**
* Allows plugins to customize their data for specific players.
* For example, a plugin may want to share no data with the client, or
* want to keep some player data secret from opponents.
*/
const PlayerView = ({ G, ctx, plugins = {} }, { game, playerID }) => {
[...DEFAULT_PLUGINS, ...game.plugins].forEach(({ name, playerView }) => {
if (!playerView)
return;
const { data } = plugins[name] || { data: {} };
const newData = playerView({ G, ctx, game, data, playerID });
plugins = {
...plugins,
[name]: { data: newData },
};
});
return plugins;
};
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function SetActivePlayers(ctx, arg) {
let activePlayers = {};
let _prevActivePlayers = [];
let _nextActivePlayers = null;
let _activePlayersMoveLimit = {};
if (Array.isArray(arg)) {
// support a simple array of player IDs as active players
const value = {};
arg.forEach((v) => (value[v] = Stage.NULL));
activePlayers = value;
}
else {
// process active players argument object
if (arg.next) {
_nextActivePlayers = arg.next;
}
if (arg.revert) {
_prevActivePlayers = [
...ctx._prevActivePlayers,
{
activePlayers: ctx.activePlayers,
_activePlayersMoveLimit: ctx._activePlayersMoveLimit,
_activePlayersNumMoves: ctx._activePlayersNumMoves,
},
];
}
if (arg.currentPlayer !== undefined) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, ctx.currentPlayer, arg.currentPlayer);
}
if (arg.others !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
if (id !== ctx.currentPlayer) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.others);
}
}
}
if (arg.all !== undefined) {
for (let i = 0; i < ctx.playOrder.length; i++) {
const id = ctx.playOrder[i];
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.all);
}
}
if (arg.value) {
for (const id in arg.value) {
ApplyActivePlayerArgument(activePlayers, _activePlayersMoveLimit, id, arg.value[id]);
}
}
if (arg.moveLimit) {
for (const id in activePlayers) {
if (_activePlayersMoveLimit[id] === undefined) {
_activePlayersMoveLimit[id] = arg.moveLimit;
}
}
}
}
if (Object.keys(activePlayers).length === 0) {
activePlayers = null;
}
if (Object.keys(_activePlayersMoveLimit).length === 0) {
_activePlayersMoveLimit = null;
}
const _activePlayersNumMoves = {};
for (const id in activePlayers) {
_activePlayersNumMoves[id] = 0;
}
return {
...ctx,
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
_prevActivePlayers,
_nextActivePlayers,
};
}
/**
* Update activePlayers, setting it to previous, next or null values
* when it becomes empty.
* @param ctx
*/
function UpdateActivePlayersOnceEmpty(ctx) {
let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves, _prevActivePlayers, _nextActivePlayers, } = ctx;
if (activePlayers && Object.keys(activePlayers).length === 0) {
if (_nextActivePlayers) {
ctx = SetActivePlayers(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 { numPlayers } = ctx;
const ctxWithAPI = EnhanceCtx(state);
const order = turn.order;
let playOrder = [...Array.from({ length: numPlayers })].map((_, i) => i + '');
if (order.playOrder !== undefined) {
playOrder = order.playOrder(G, ctxWithAPI);
}
const playOrderPos = order.first(G, ctxWithAPI);
const posType = typeof playOrderPos;
if (posType !== 'number') {
error(`invalid value returned by turn.order.first — expected number got ${posType} “${playOrderPos}”.`);
}
const currentPlayer = getCurrentPlayer(playOrder, playOrderPos);
ctx = { ...ctx, currentPlayer, playOrderPos, playOrder };
ctx = SetActivePlayers(ctx, turn.activePlayers || {});
return ctx;
}
/**
* Called at the end of each turn to update the turn order state.
* @param {object} G - The game object G.
* @param {object} ctx - The game object ctx.
* @param {object} turn - A turn object for this phase.
* @param {string} endTurnArg - An optional argument to endTurn that
may specify the next player.
*/
function UpdateTurnOrderState(state, currentPlayer, turn, endTurnArg) {
const order = turn.order;
let { G, ctx } = state;
let playOrderPos = ctx.playOrderPos;
let endPhase = false;
if (endTurnArg && endTurnArg !== true) {
if (typeof endTurnArg !== 'object') {
error(`invalid argument to endTurn: ${endTurnArg}`);
}
Object.keys(endTurnArg).forEach((arg) => {
switch (arg) {
case 'remove':
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
break;
case 'next':
playOrderPos = ctx.playOrder.indexOf(endTurnArg.next);
currentPlayer = endTurnArg.next;
break;
default:
error(`invalid argument to endTurn: ${arg}`);
}
});
}
else {
const ctxWithAPI = EnhanceCtx(state);
const t = order.next(G, ctxWithAPI);
const type = typeof t;
if (t !== undefined && type !== 'number') {
error(`invalid value returned by turn.order.next — expected number or undefined got ${type} “${t}”.`);
}
if (t === undefined) {
endPhase = true;
}
else {
playOrderPos = t;
currentPlayer = getCurrentPlayer(ctx.playOrder, playOrderPos);
}
}
ctx = {
...ctx,
playOrderPos,
currentPlayer,
};
return { endPhase, ctx };
}
/**
* Set of different turn orders possible in a phase.
* These are meant to be passed to the `turn` setting
* in the flow objects.
*
* Each object defines the first player when the phase / game
* begins, and also a function `next` to determine who the
* next player is when the turn ends.
*
* The phase ends if next() returns undefined.
*/
const TurnOrder = {
/**
* DEFAULT
*
* The default round-robin turn order.
*/
DEFAULT: {
first: (G, ctx) => ctx.turn === 0
? ctx.playOrderPos
: (ctx.playOrderPos + 1) % ctx.playOrder.length,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* RESET
*
* Similar to DEFAULT, but starts from 0 each time.
*/
RESET: {
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* CONTINUE
*
* Similar to DEFAULT, but starts with the player who ended the last phase.
*/
CONTINUE: {
first: (G, ctx) => ctx.playOrderPos,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
},
/**
* ONCE
*
* Another round-robin turn order, but goes around just once.
* The phase ends after all players have played.
*/
ONCE: {
first: () => 0,
next: (G, ctx) => {
if (ctx.playOrderPos < ctx.playOrder.length - 1) {
return ctx.playOrderPos + 1;
}
},
},
/**
* CUSTOM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase.
*
* @param {Array} playOrder - The play order.
*/
CUSTOM: (playOrder) => ({
playOrder: () => playOrder,
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
/**
* CUSTOM_FROM
*
* Identical to DEFAULT, but also sets playOrder at the
* beginning of the phase to a value specified by a field
* in G.
*
* @param {string} playOrderField - Field in G.
*/
CUSTOM_FROM: (playOrderField) => ({
playOrder: (G) => G[playOrderField],
first: () => 0,
next: (G, ctx) => (ctx.playOrderPos + 1) % ctx.playOrder.length,
}),
};
const Stage = {
NULL: null,
};
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Flow
*
* Creates a reducer that updates ctx (analogous to how moves update G).
*/
function Flow({ moves, phases, endIf, onEnd, turn, events, plugins, }) {
// Attach defaults.
if (moves === undefined) {
moves = {};
}
if (events === undefined) {
events = {};
}
if (plugins === undefined) {
plugins = [];
}
if (phases === undefined) {
phases = {};
}
if (!endIf)
endIf = () => undefined;
if (!onEnd)
onEnd = (G) => G;
if (!turn)
turn = {};
const phaseMap = { ...phases };
if ('' in phaseMap) {
error('cannot specify phase with empty name');
}
phaseMap[''] = {};
const moveMap = {};
const moveNames = new Set();
let startingPhase = null;
Object.keys(moves).forEach((name) => moveNames.add(name));
const HookWrapper = (fn) => {
const withPlugins = FnWrap(fn, plugins);
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return withPlugins(state.G, ctxWithAPI);
};
};
const TriggerWrapper = (endIf) => {
return (state) => {
const ctxWithAPI = EnhanceCtx(state);
return endIf(state.G, ctxWithAPI);
};
};
const wrapped = {
onEnd: HookWrapper(onEnd),
endIf: TriggerWrapper(endIf),
};
for (const phase in phaseMap) {
const phaseConfig = phaseMap[phase];
if (phaseConfig.start === true) {
startingPhase = phase;
}
if (phaseConfig.moves !== undefined) {
for (const move of Object.keys(phaseConfig.moves)) {
moveMap[phase + '.' + move] = phaseConfig.moves[move];
moveNames.add(move);
}
}
if (phaseConfig.endIf === undefined) {
phaseConfig.endIf = () => undefined;
}
if (phaseConfig.onBegin === undefined) {
phaseConfig.onBegin = (G) => G;
}
if (phaseConfig.onEnd === undefined) {
phaseConfig.onEnd = (G) => G;
}
if (phaseConfig.turn === undefined) {
phaseConfig.turn = turn;
}
if (phaseConfig.turn.order === undefined) {
phaseConfig.turn.order = TurnOrder.DEFAULT;
}
if (phaseConfig.turn.onBegin === undefined) {
phaseConfig.turn.onBegin = (G) => G;
}
if (phaseConfig.turn.onEnd === undefined) {
phaseConfig.turn.onEnd = (G) => G;
}
if (phaseConfig.turn.endIf === undefined) {
phaseConfig.turn.endIf = () => false;
}
if (phaseConfig.turn.onMove === undefined) {
phaseConfig.turn.onMove = (G) => G;
}
if (phaseConfig.turn.stages === undefined) {
phaseConfig.turn.stages = {};
}
for (const stage in phaseConfig.turn.stages) {
const stageConfig = phaseConfig.turn.stages[stage];
const moves = stageConfig.moves || {};
for (const move of Object.keys(moves)) {
const key = phase + '.' + stage + '.' + move;
moveMap[key] = moves[move];
moveNames.add(move);
}
}
phaseConfig.wrapped = {
onBegin: HookWrapper(phaseConfig.onBegin),
onEnd: HookWrapper(phaseConfig.onEnd),
endIf: TriggerWrapper(phaseConfig.endIf),
};
phaseConfig.turn.wrapped = {
onMove: HookWrapper(phaseConfig.turn.onMove),
onBegin: HookWrapper(phaseConfig.turn.onBegin),
onEnd: HookWrapper(phaseConfig.turn.onEnd),
endIf: TriggerWrapper(phaseConfig.turn.endIf),
};
if (typeof phaseConfig.next !== 'function') {
const { next } = phaseConfig;
phaseConfig.next = () => next || null;
}
phaseConfig.wrapped.next = HookWrapper(phaseConfig.next);
}
function GetPhase(ctx) {
return ctx.phase ? phaseMap[ctx.phase] : phaseMap[''];
}
function OnMove(s) {
return s;
}
function Process(state, events) {
const phasesEnded = new Set();
const turnsEnded = new Set();
for (let i = 0; i < events.length; i++) {
const { fn, arg, ...rest } = events[i];
// Detect a loop of EndPhase calls.
// This could potentially even be an infinite loop
// if the endIf condition of each phase blindly
// returns true. The moment we detect a single
// loop, we just bail out of all phases.
if (fn === EndPhase) {
turnsEnded.clear();
const phase = state.ctx.phase;
if (phasesEnded.has(phase)) {
const ctx = { ...state.ctx, phase: null };
return { ...state, ctx };
}
phasesEnded.add(phase);
}
// Process event.
const next = [];
state = fn(state, {
...rest,
arg,
next,
});
if (fn === EndGame) {
break;
}
// Check if we should end the game.
const shouldEndGame = ShouldEndGame(state);
if (shouldEndGame) {
events.push({
fn: EndGame,
arg: shouldEndGame,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the phase.
const shouldEndPhase = ShouldEndPhase(state);
if (shouldEndPhase) {
events.push({
fn: EndPhase,
arg: shouldEndPhase,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
// Check if we should end the turn.
if ([OnMove, UpdateStage, UpdateActivePlayers].includes(fn)) {
const shouldEndTurn = ShouldEndTurn(state);
if (shouldEndTurn) {
events.push({
fn: EndTurn,
arg: shouldEndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
automatic: true,
});
continue;
}
}
events.push(...next);
}
return state;
}
///////////
// Start //
///////////
function StartGame(state, { next }) {
next.push({ fn: StartPhase });
return state;
}
function StartPhase(state, { next }) {
let { G, ctx } = state;
const phaseConfig = GetPhase(ctx);
// Run any phase setup code provided by the user.
G = phaseConfig.wrapped.onBegin(state);
next.push({ fn: StartTurn });
return { ...state, G, ctx };
}
function StartTurn(state, { currentPlayer }) {
let { ctx } = state;
const phaseConfig = GetPhase(ctx);
// Initialize the turn order state.
if (currentPlayer) {
ctx = { ...ctx, currentPlayer };
if (phaseConfig.turn.activePlayers) {
ctx = SetActivePlayers(ctx, phaseConfig.turn.activePlayers);
}
}
else {
// This is only called at the beginning of the phase
// when there is no currentPlayer yet.
ctx = InitTurnOrderState(state, phaseConfig.turn);
}
const turn = ctx.turn + 1;
ctx = { ...ctx, turn, numMoves: 0, _prevActivePlayers: [] };
const G = phaseConfig.turn.wrapped.onBegin({ ...state, ctx });
return { ...state, G, ctx, _undo: [], _redo: [] };
}
////////////
// Update //
////////////
function UpdatePhase(state, { arg, next, phase }) {
const phaseConfig = GetPhase({ phase });
let { ctx } = state;
if (arg && arg.next) {
if (arg.next in phaseMap) {
ctx = { ...ctx, phase: arg.next };
}
else {
error('invalid phase: ' + arg.next);
return state;
}
}
else {
ctx = { ...ctx, phase: phaseConfig.wrapped.next(state) || null };
}
state = { ...state, ctx };
// Start the new phase.
next.push({ fn: StartPhase });
return state;
}
function UpdateTurn(state, { arg, currentPlayer, next }) {
let { G, ctx } = state;
const phaseConfig = GetPhase(ctx);
// Update turn order state.
const { endPhase, ctx: newCtx } = UpdateTurnOrderState(state, currentPlayer, phaseConfig.turn, arg);
ctx = newCtx;
state = { ...state, G, ctx };
if (endPhase) {
next.push({ fn: EndPhase, turn: ctx.turn, phase: ctx.phase });
}
else {
next.push({ fn: StartTurn, currentPlayer: ctx.currentPlayer });
}
return state;
}
function UpdateStage(state, { arg, playerID }) {
if (typeof arg === 'string' || arg === Stage.NULL) {
arg = { stage: arg };
}
if (typeof arg !== 'object')
return state;
let { ctx } = state;
let { activePlayers, _activePlayersMoveLimit, _activePlayersNumMoves } = ctx;
// Checking if stage is valid, even Stage.NULL
if (arg.stage !== undefined) {
if (activePlayers === null) {
activePlayers = {};
}
activePlayers[playerID] = arg.stage;
_activePlayersNumMoves[playerID] = 0;
if (arg.moveLimit) {
if (_activePlayersMoveLimit === null) {
_activePlayersMoveLimit = {};
}
_activePlayersMoveLimit[playerID] = arg.moveLimit;
}
}
ctx = {
...ctx,
activePlayers,
_activePlayersMoveLimit,
_activePlayersNumMoves,
};
return { ...state, ctx };
}
function UpdateActivePlayers(state, { arg }) {
return { ...state, ctx: SetActivePlayers(state.ctx, arg) };
}
///////////////
// ShouldEnd //
///////////////
function ShouldEndGame(state) {
return wrapped.endIf(state);
}
function ShouldEndPhase(state) {
const phaseConfig = GetPhase(state.ctx);
return phaseConfig.wrapped.endIf(state);
}
function ShouldEndTurn(state) {
const phaseConfig = GetPhase(state.ctx);
// End the turn if the required number of moves has been made.
const currentPlayerMoves = state.ctx.numMoves || 0;
if (phaseConfig.turn.moveLimit &&
currentPlayerMoves >= phaseConfig.turn.moveLimit) {
return true;
}
return phaseConfig.turn.wrapped.endIf(state);
}
/////////
// End //
/////////
function EndGame(state, { arg, phase }) {
state = EndPhase(state, { phase });
if (arg === undefined) {
arg = true;
}
state = { ...state, ctx: { ...state.ctx, gameover: arg } };
// Run game end hook.
const G = wrapped.onEnd(state);
return { ...state, G };
}
function EndPhase(state, { arg, next, turn: initialTurn, automatic }) {
// End the turn first.
state = EndTurn(state, { turn: initialTurn, force: true, automatic: true });
const { phase, turn } = state.ctx;
if (next) {
next.push({ fn: UpdatePhase, arg, phase });
}
// If we aren't in a phase, there is nothing else to do.
if (phase === null) {
return state;
}
// Run any cleanup code for the phase that is about to end.
const phaseConfig = GetPhase(state.ctx);
const G = phaseConfig.wrapped.onEnd(state);
// Reset the phase.
const ctx = { ...state.ctx, phase: null };
// Add log entry.
const action = gameEvent('endPhase', arg);
const { _stateID } = state;
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog };
}
function EndTurn(state, { arg, next, turn: initialTurn, force, automatic, playerID }) {
// This is not the turn that EndTurn was originally
// called for. The turn was probably ended some other way.
if (initialTurn !== state.ctx.turn) {
return state;
}
const { currentPlayer, numMoves, phase, turn } = state.ctx;
const phaseConfig = GetPhase(state.ctx);
// Prevent ending the turn if moveLimit hasn't been reached.
const currentPlayerMoves = numMoves || 0;
if (!force &&
phaseConfig.turn.moveLimit &&
currentPlayerMoves < phaseConfig.turn.moveLimit) {
info(`cannot end turn before making ${phaseConfig.turn.moveLimit} moves`);
return state;
}
// Run turn-end triggers.
const G = phaseConfig.turn.wrapped.onEnd(state);
if (next) {
next.push({ fn: UpdateTurn, arg, currentPlayer });
}
// Reset activePlayers.
let ctx = { ...state.ctx, activePlayers: null };
// Remove player from playerOrder
if (arg && arg.remove) {
playerID = playerID || currentPlayer;
const playOrder = ctx.playOrder.filter((i) => i != playerID);
const playOrderPos = ctx.playOrderPos > playOrder.length - 1 ? 0 : ctx.playOrderPos;
ctx = { ...ctx, playOrder, playOrderPos };
if (playOrder.length === 0) {
next.push({ fn: EndPhase, turn, phase });
return state;
}
}
// Create log entry.
const action = gameEvent('endTurn', arg);
const { _stateID } = state;
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, G, ctx, deltalog, _undo: [], _redo: [] };
}
function EndStage(state, { arg, next, automatic, playerID }) {
playerID = playerID || state.ctx.currentPlayer;
let { ctx, _stateID } = state;
let { activePlayers, _activePlayersMoveLimit, phase, turn } = ctx;
const playerInStage = activePlayers !== null && playerID in activePlayers;
if (!arg && playerInStage) {
const phaseConfig = GetPhase(ctx);
const stage = phaseConfig.turn.stages[activePlayers[playerID]];
if (stage && stage.next)
arg = stage.next;
}
// Checking if arg is a valid stage, even Stage.NULL
if (next) {
next.push({ fn: UpdateStage, arg, playerID });
}
// If player isn’t in a stage, there is nothing else to do.
if (!playerInStage)
return state;
// Remove player from activePlayers.
activePlayers = { ...activePlayers };
delete activePlayers[playerID];
if (_activePlayersMoveLimit) {
// Remove player from _activePlayersMoveLimit.
_activePlayersMoveLimit = { ..._activePlayersMoveLimit };
delete _activePlayersMoveLimit[playerID];
}
ctx = UpdateActivePlayersOnceEmpty({
...ctx,
activePlayers,
_activePlayersMoveLimit,
});
// Create log entry.
const action = gameEvent('endStage', arg);
const logEntry = { action, _stateID, turn, phase };
if (automatic)
logEntry.automatic = true;
const deltalog = [...(state.deltalog || []), logEntry];
return { ...state, ctx, deltalog };
}
/**
* Retrieves the relevant move that can be played by playerID.
*
* If ctx.activePlayers is set (i.e. one or more players are in some stage),
* then it attempts to find the move inside the stages config for
* that turn. If the stage for a player is '', then the player is
* allowed to make a move (as determined by the phase config), but
* isn't restricted to a particular set as defined in the stage config.
*
* If not, it then looks for the move inside the phase.
*
* If it doesn't find the move there, it looks at the global move definition.
*
* @param {object} ctx
* @param {string} name
* @param {string} playerID
*/
function GetMove(ctx, name, playerID) {
const phaseConfig = GetPhase(ctx);
const stages = phaseConfig.turn.stages;
const { activePlayers } = ctx;
if (activePlayers &&
activePlayers[playerID] !== undefined &&
activePlayers[playerID] !== Stage.NULL &&
stages[activePlayers[playerID]] !== undefined &&
stages[activePlayers[playerID]].moves !== undefined) {
// Check if moves are defined for the player's stage.
const stage = stages[activePlayers[playerID]];
const moves = stage.moves;
if (name in moves) {
return moves[name];
}
}
else if (phaseConfig.moves) {
// Check if moves are defined for the current phase.
if (name in phaseConfig.moves) {
return phaseConfig.moves[name];
}
}
else if (name in moves) {
// Check for the move globally.
return moves[name];
}
return null;
}
function ProcessMove(state, action) {
const { playerID, type } = action;
const { ctx } = state;
const { currentPlayer, activePlayers, _activePlayersMoveLimit } = ctx;
const move = GetMove(ctx, type, playerID);
const shouldCount = !move || typeof move === 'function' || move.noLimit !== true;
let { numMoves, _activePlayersNumMoves } = ctx;
if (shouldCount) {
if (playerID === currentPlayer)
numMoves++;
if (activePlayers)
_activePlayersNumMoves[playerID]++;
}
state = {
...state,
ctx: {
...ctx,
numMoves,
_activePlayersNumMoves,
},
};
if (_activePlayersMoveLimit &&
_activePlayersNumMoves[playerID] >= _activePlayersMoveLimit[playerID]) {
state = EndStage(state, { playerID, automatic: true });
}
const phaseConfig = GetPhase(ctx);
const G = phaseConfig.turn.wrapped.onMove(state);
state = { ...state, G };
const events = [{ fn: OnMove }];
return Process(state, events);
}
function SetStageEvent(state, playerID, arg) {
return Process(state, [{ fn: EndStage, arg, playerID }]);
}
function EndStageEvent(state, playerID) {
return Process(state, [{ fn: EndStage, playerID }]);
}
function SetActivePlayersEvent(state, _playerID, arg) {
return Process(state, [{ fn: UpdateActivePlayers, arg }]);
}
function SetPhaseEvent(state, _playerID, newPhase) {
return Process(state, [
{
fn: EndPhase,
phase: state.ctx.phase,
turn: state.ctx.turn,
arg: { next: newPhase },
},
]);
}
function EndPhaseEvent(state) {
return Process(state, [
{ fn: EndPhase, phase: state.ctx.phase, turn: state.ctx.turn },
]);
}
function EndTurnEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndTurn, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
function PassEvent(state, _playerID, arg) {
return Process(state, [
{
fn: EndTurn,
turn: state.ctx.turn,
phase: state.ctx.phase,
force: true,
arg,
},
]);
}
function EndGameEvent(state, _playerID, arg) {
return Process(state, [
{ fn: EndGame, turn: state.ctx.turn, phase: state.ctx.phase, arg },
]);
}
const eventHandlers = {
endStage: EndStageEvent,
setStage: SetStageEvent,
endTurn: EndTurnEvent,
pass: PassEvent,
endPhase: EndPhaseEvent,
setPhase: SetPhaseEvent,
endGame: EndGameEvent,
setActivePlayers: SetActivePlayersEvent,
};
const enabledEventNames = [];
if (events.endTurn !== false) {
enabledEventNames.push('endTurn');
}
if (events.pass !== false) {
enabledEventNames.push('pass');
}
if (events.endPhase !== false) {
enabledEventNames.push('endPhase');
}
if (events.setPhase !== false) {
enabledEventNames.push('setPhase');
}
if (events.endGame !== false) {
enabledEventNames.push('endGame');
}
if (events.setActivePlayers !== false) {
enabledEventNames.push('setActivePlayers');
}
if (events.endStage !== false) {
enabledEventNames.push('endStage');
}
if (events.setStage !== false) {
enabledEventNames.push('setStage');
}
function ProcessEvent(state, action) {
const { type, playerID, args } = action.payload;
if (typeof eventHandlers[type] !== 'function')
return state;
return eventHandlers[type](state, playerID, ...(Array.isArray(args) ? args : [args]));
}
function IsPlayerActive(_G, ctx, playerID) {
if (ctx.activePlayers) {
return playerID in ctx.activePlayers;
}
return ctx.currentPlayer === playerID;
}
return {
ctx: (numPlayers) => ({
numPlayers,
turn: 0,
currentPlayer: '0',
playOrder: [...Array.from({ length: numPlayers })].map((_, i) => i + ''),
playOrderPos: 0,
phase: startingPhase,
activePlayers: null,
}),
init: (state) => {
return Process(state, [{ fn: StartGame }]);
},
isPlayerActive: IsPlayerActive,
eventHandlers,
eventNames: Object.keys(eventHandlers),
enabledEventNames,
moveMap,
moveNames: [...moveNames.values()],
processMove: ProcessMove,
processEvent: ProcessEvent,
getMove: GetMove,
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function IsProcessed(game) {
return game.processMove !== undefined;
}
/**
* Helper to generate the game move reducer. The returned
* reducer has the following signature:
*
* (G, action, ctx) => {}
*
* You can roll your own if you like, or use any Redux
* addon to generate such a reducer.
*
* The convention used in this framework is to
* have action.type contain the name of the move, and
* action.args contain any additional arguments as an
* Array.
*/
function ProcessGameConfig(game) {
// The Game() function has already been called on this
// config object, so just pass it through.
if (IsProcessed(game)) {
return game;
}
if (game.name === undefined)
game.name = 'default';
if (game.deltaState === undefined)
game.deltaState = false;
if (game.disableUndo === undefined)
game.disableUndo = false;
if (game.setup === undefined)
game.setup = () => ({});
if (game.moves === undefined)
game.moves = {};
if (game.playerView === undefined)
game.playerView = (G) => G;
if (game.plugins === undefined)
game.plugins = [];
game.plugins.forEach((plugin) => {
if (plugin.name === undefined) {
throw new Error('Plugin missing name attribute');
}
if (plugin.name.includes(' ')) {
throw new Error(plugin.name + ': Plugin name must not include spaces');
}
});
if (game.name.includes(' ')) {
throw new Error(game.name + ': Game name must not include spaces');
}
const flow = Flow(game);
return {
...game,
flow,
moveNames: flow.moveNames,
pluginNames: game.plugins.map((p) => p.name),
processMove: (state, action) => {
let moveFn = flow.getMove(state.ctx, action.type, action.playerID);
if (IsLongFormMove(moveFn)) {
moveFn = moveFn.move;
}
if (moveFn instanceof Function) {
const fn = FnWrap(moveFn, game.plugins);
const ctxWithAPI = {
...EnhanceCtx(state),
playerID: action.playerID,
};
let args = [];
if (action.args !== undefined) {
args = Array.isArray(action.args) ? action.args : [action.args];
}
return fn(state.G, ctxWithAPI, ...args);
}
error(`invalid move object: ${action.type}`);
return state.G;
},
};
}
function IsLongFormMove(move) {
return move instanceof Object && move.move !== undefined;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
var UpdateErrorType;
(function (UpdateErrorType) {
// The action’s credentials were missing or invalid
UpdateErrorType["UnauthorizedAction"] = "update/unauthorized_action";
// The action’s matchID was not found
UpdateErrorType["MatchNotFound"] = "update/match_not_found";
// Could not apply Patch operation (rfc6902).
UpdateErrorType["PatchFailed"] = "update/patch_failed";
})(UpdateErrorType || (UpdateErrorType = {}));
var ActionErrorType;
(function (ActionErrorType) {
// The action contained a stale state ID
ActionErrorType["StaleStateId"] = "action/stale_state_id";
// The requested move is unknown or not currently available
ActionErrorType["UnavailableMove"] = "action/unavailable_move";
// The move declared it was invalid (INVALID_MOVE constant)
ActionErrorType["InvalidMove"] = "action/invalid_move";
// The player making the action is not currently active
ActionErrorType["InactivePlayer"] = "action/inactive_player";
// The game has finished
ActionErrorType["GameOver"] = "action/gameover";
// The requested action is disabled (e.g. undo/redo, events)
ActionErrorType["ActionDisabled"] = "action/action_disabled";
// The requested action is not currently possible
ActionErrorType["ActionInvalid"] = "action/action_invalid";
// The requested action was declared invalid by a plugin
ActionErrorType["PluginActionInvalid"] = "action/plugin_invalid";
})(ActionErrorType || (ActionErrorType = {}));
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Check if the payload for the passed action contains a playerID.
*/
const actionHasPlayerID = (action) => action.payload.playerID !== null && action.payload.playerID !== undefined;
/**
* Returns true if a move can be undone.
*/
const CanUndoMove = (G, ctx, move) => {
function HasUndoable(move) {
return move.undoable !== undefined;
}
function IsFunction(undoable) {
return undoable instanceof Function;
}
if (!HasUndoable(move)) {
return true;
}
if (IsFunction(move.undoable)) {
return move.undoable(G, ctx);
}
return move.undoable;
};
/**
* Update the undo and redo stacks for a move or event.
*/
function updateUndoRedoState(state, opts) {
if (opts.game.disableUndo)
return state;
const undoEntry = {
G: state.G,
ctx: state.ctx,
plugins: state.plugins,
playerID: opts.action.payload.playerID || state.ctx.currentPlayer,
};
if (opts.action.type === 'MAKE_MOVE') {
undoEntry.moveType = opts.action.payload.type;
}
return {
...state,
_undo: [...state._undo, undoEntry],
// Always reset redo stack when making a move or event
_redo: [],
};
}
/**
* Process state, adding the initial deltalog for this action.
*/
function initializeDeltalog(state, action, move) {
// Create a log entry for this action.
const logEntry = {
action,
_stateID: state._stateID,
turn: state.ctx.turn,
phase: state.ctx.phase,
};
const pluginLogMetadata = state.plugins.log.data.metadata;
if (pluginLogMetadata !== undefined) {
logEntry.metadata = pluginLogMetadata;
}
if (typeof move === 'object' && move.redact === true) {
logEntry.redact = true;
}
return {
...state,
deltalog: [logEntry],
};
}
/**
* Update plugin state after move/event & check if plugins consider the action to be valid.
* @param state Current version of state in the reducer.
* @param oldState State to revert to in case of error.
* @param pluginOpts Plugin configuration options.
* @returns Tuple of the new state updated after flushing plugins and the old
* state augmented with an error if a plugin declared the action invalid.
*/
function flushAndValidatePlugins(state, oldState, pluginOpts) {
const [newState, isInvalid] = FlushAndValidate(state, pluginOpts);
if (!isInvalid)
return [newState];
return [
newState,
WithError(oldState, ActionErrorType.PluginActionInvalid, isInvalid),
];
}
/**
* ExtractTransientsFromState
*
* Split out transients from the a TransientState
*/
function ExtractTransients(transientState) {
if (!transientState) {
// We preserve null for the state for legacy callers, but the transient
// field should be undefined if not present to be consistent with the
// code path below.
return [null, undefined];
}
const { transients, ...state } = transientState;
return [state, transients];
}
/**
* WithError
*
* Augment a State instance with transient error information.
*/
function WithError(state, errorType, payload) {
const error = {
type: errorType,
payload,
};
return {
...state,
transients: {
error,
},
};
}
/**
* Middleware for processing TransientState associated with the reducer
* returned by CreateGameReducer.
* This should pretty much be used everywhere you want realistic state
* transitions and error handling.
*/
const TransientHandlingMiddleware = (store) => (next) => (action) => {
const result = next(action);
switch (action.type) {
case STRIP_TRANSIENTS: {
return result;
}
default: {
const [, transients] = ExtractTransients(store.getState());
if (typeof transients !== 'undefined') {
store.dispatch(stripTransients());
// Dev Note: If parent middleware needs to correlate the spawned
// StripTransients action to the triggering action, instrument here.
//
// This is a bit tricky; for more details, see:
// https://github.com/boardgameio/boardgame.io/pull/940#discussion_r636200648
return {
...result,
transients,
};
}
return result;
}
}
};
/**
* CreateGameReducer
*
* Creates the main game state reducer.
*/
function CreateGameReducer({ game, isClient, }) {
game = ProcessGameConfig(game);
/**
* GameReducer
*
* Redux reducer that maintains the overall game state.
* @param {object} state - The state before the action.
* @param {object} action - A Redux action.
*/
return (stateWithTransients = null, action) => {
let [state /*, transients */] = ExtractTransients(stateWithTransients);
switch (action.type) {
case STRIP_TRANSIENTS: {
// This action indicates that transient metadata in the state has been
// consumed and should now be stripped from the state..
return state;
}
case GAME_EVENT: {
state = { ...state, deltalog: [] };
// Process game events only on the server.
// These events like `endTurn` typically
// contain code that may rely on secret state
// and cannot be computed on the client.
if (isClient) {
return state;
}
// Disallow events once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot call event after game end`);
return WithError(state, ActionErrorType.GameOver);
}
// Ignore the event if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed event: ${action.payload.type}`);
return WithError(state, ActionErrorType.InactivePlayer);
}
// Execute plugins.
state = Enhance(state, {
game,
isClient: false,
playerID: action.payload.playerID,
});
// Process event.
let newState = game.flow.processEvent(state, action);
// Execute plugins.
let stateWithError;
[newState, stateWithError] = flushAndValidatePlugins(newState, state, {
game,
isClient: false,
});
if (stateWithError)
return stateWithError;
// Update undo / redo state.
newState = updateUndoRedoState(newState, { game, action });
return { ...newState, _stateID: state._stateID + 1 };
}
case MAKE_MOVE: {
const oldState = (state = { ...state, deltalog: [] });
// Check whether the move is allowed at this time.
const move = game.flow.getMove(state.ctx, action.payload.type, action.payload.playerID || state.ctx.currentPlayer);
if (move === null) {
error(`disallowed move: ${action.payload.type}`);
return WithError(state, ActionErrorType.UnavailableMove);
}
// Don't run move on client if move says so.
if (isClient && move.client === false) {
return state;
}
// Disallow moves once the game is over.
if (state.ctx.gameover !== undefined) {
error(`cannot make move after game end`);
return WithError(state, ActionErrorType.GameOver);
}
// Ignore the move if the player isn't active.
if (actionHasPlayerID(action) &&
!game.flow.isPlayerActive(state.G, state.ctx, action.payload.playerID)) {
error(`disallowed move: ${action.payload.type}`);
return WithError(state, ActionErrorType.InactivePlayer);
}
// Execute plugins.
state = Enhance(state, {
game,
isClient,
playerID: action.payload.playerID,
});
// Process the move.
const G = game.processMove(state, action.payload);
// The game declared the move as invalid.
if (G === INVALID_MOVE) {
error(`invalid move: ${action.payload.type} args: ${action.payload.args}`);
// TODO(#723): Marshal a nice error payload with the processed move.
return WithError(state, ActionErrorType.InvalidMove);
}
const newState = { ...state, G };
// Some plugin indicated that it is not suitable to be
// materialized on the client (and must wait for the server
// response instead).
if (isClient && NoClient(newState, { game })) {
return state;
}
state = newState;
// If we're on the client, just process the move
// and no triggers in multiplayer mode.
// These will be processed on the server, which
// will send back a state update.
if (isClient) {
let stateWithError;
[state, stateWithError] = flushAndValidatePlugins(state, oldState, {
game,
isClient: true,
});
if (stateWithError)
return stateWithError;
return {
...state,
_stateID: state._stateID + 1,
};
}
// On the server, construct the deltalog.
state = initializeDeltalog(state, action, move);
// Allow the flow reducer to process any triggers that happen after moves.
state = game.flow.processMove(state, action.payload);
let stateWithError;
[state, stateWithError] = flushAndValidatePlugins(state, oldState, {
game,
});
if (stateWithError)
return stateWithError;
// Update undo / redo state.
state = updateUndoRedoState(state, { game, action });
return {
...state,
_stateID: state._stateID + 1,
};
}
case RESET:
case UPDATE:
case SYNC: {
return action.state;
}
case UNDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Undo is not enabled');
return WithError(state, ActionErrorType.ActionDisabled);
}
const { G, ctx, _undo, _redo, _stateID } = state;
if (_undo.length < 2) {
error(`No moves to undo`);
return WithError(state, ActionErrorType.ActionInvalid);
}
const last = _undo[_undo.length - 1];
const restore = _undo[_undo.length - 2];
// Only allow players to undo their own moves.
if (actionHasPlayerID(action) &&
action.payload.playerID !== last.playerID) {
error(`Cannot undo other players' moves`);
return WithError(state, ActionErrorType.ActionInvalid);
}
// If undoing a move, check it is undoable.
if (last.moveType) {
const lastMove = game.flow.getMove(restore.ctx, last.moveType, last.playerID);
if (!CanUndoMove(G, ctx, lastMove)) {
error(`Move cannot be undone`);
return WithError(state, ActionErrorType.ActionInvalid);
}
}
state = initializeDeltalog(state, action);
return {
...state,
G: restore.G,
ctx: restore.ctx,
plugins: restore.plugins,
_stateID: _stateID + 1,
_undo: _undo.slice(0, -1),
_redo: [last, ..._redo],
};
}
case REDO: {
state = { ...state, deltalog: [] };
if (game.disableUndo) {
error('Redo is not enabled');
return WithError(state, ActionErrorType.ActionDisabled);
}
const { _undo, _redo, _stateID } = state;
if (_redo.length === 0) {
error(`No moves to redo`);
return WithError(state, ActionErrorType.ActionInvalid);
}
const first = _redo[0];
// Only allow players to redo their own undos.
if (actionHasPlayerID(action) &&
action.payload.playerID !== first.playerID) {
error(`Cannot redo other players' moves`);
return WithError(state, ActionErrorType.ActionInvalid);
}
state = initializeDeltalog(state, action);
return {
...state,
G: first.G,
ctx: first.ctx,
plugins: first.plugins,
_stateID: _stateID + 1,
_undo: [..._undo, first],
_redo: _redo.slice(1),
};
}
case PLUGIN: {
// TODO(#723): Expose error semantics to plugin processing.
return ProcessAction(state, action, { game });
}
case PATCH: {
const oldState = state;
const newState = JSON.parse(JSON.stringify(oldState));
const patchError = applyPatch(newState, action.patch);
const hasError = patchError.some((entry) => entry !== null);
if (hasError) {
error(`Patch ${JSON.stringify(action.patch)} apply failed`);
return WithError(oldState, UpdateErrorType.PatchFailed, patchError);
}
else {
return newState;
}
}
default: {
return state;
}
}
};
}
/*
* Copyright 2020 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Creates the initial game state.
*/
function InitializeGame({ game, numPlayers, setupData, }) {
game = ProcessGameConfig(game);
if (!numPlayers) {
numPlayers = 2;
}
const ctx = game.flow.ctx(numPlayers);
let state = {
// User managed state.
G: {},
// Framework managed state.
ctx,
// Plugin related state.
plugins: {},
};
// Run plugins over initial state.
state = Setup(state, { game });
state = Enhance(state, { game, playerID: undefined });
const enhancedCtx = EnhanceCtx(state);
state.G = game.setup(enhancedCtx, setupData);
let initial = {
...state,
// List of {G, ctx} pairs that can be undone.
_undo: [],
// List of {G, ctx} pairs that can be redone.
_redo: [],
// A monotonically non-decreasing ID to ensure that
// state updates are only allowed from clients that
// are at the same version that the server.
_stateID: 0,
};
initial = game.flow.init(initial);
[initial] = FlushAndValidate(initial, { game });
// Initialize undo stack.
if (!game.disableUndo) {
initial._undo = [
{
G: initial.G,
ctx: initial.ctx,
plugins: initial.plugins,
},
];
}
return initial;
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
class Transport {
constructor({ store, gameName, playerID, matchID, credentials, numPlayers, }) {
this.store = store;
this.gameName = gameName || 'default';
this.playerID = playerID || null;
this.matchID = matchID || 'default';
this.credentials = credentials;
this.numPlayers = numPlayers || 2;
}
}
/**
* This class doesn’t do anything, but simplifies the client class by providing
* dummy functions to call, so we don’t need to mock them in the client.
*/
class DummyImpl extends Transport {
connect() { }
disconnect() { }
onAction() { }
onChatMessage() { }
subscribe() { }
subscribeChatMessage() { }
subscribeMatchData() { }
updateCredentials() { }
updateMatchID() { }
updatePlayerID() { }
}
const DummyTransport = (opts) => new DummyImpl(opts);
const subscriber_queue = [];
/**
* Create a `Writable` store that allows both updating and reading by subscription.
* @param {*=}value initial value
* @param {StartStopNotifier=}start start and stop notifications for subscriptions
*/
function writable(value, start = noop) {
let stop;
const subscribers = new Set();
function set(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
if (stop) { // store is ready
const run_queue = !subscriber_queue.length;
for (const subscriber of subscribers) {
subscriber[1]();
subscriber_queue.push(subscriber, value);
}
if (run_queue) {
for (let i = 0; i < subscriber_queue.length; i += 2) {
subscriber_queue[i][0](subscriber_queue[i + 1]);
}
subscriber_queue.length = 0;
}
}
}
}
function update(fn) {
set(fn(value));
}
function subscribe(run, invalidate = noop) {
const subscriber = [run, invalidate];
subscribers.add(subscriber);
if (subscribers.size === 1) {
stop = start(set) || noop;
}
run(value);
return () => {
subscribers.delete(subscriber);
if (subscribers.size === 0) {
stop();
stop = null;
}
};
}
return { set, update, subscribe };
}
function cubicOut(t) {
const f = t - 1.0;
return f * f * f + 1.0;
}
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.41.0 */
function add_css(target) {
append_styles(target, "svelte-14p9tpy", ".menu.svelte-14p9tpy{display:flex;margin-top:-10px;flex-direction:row-reverse;border:1px solid #ccc;border-radius:5px 5px 0 0;height:25px;line-height:25px;margin-right:-500px;transform-origin:bottom right;transform:rotate(-90deg) translate(0, -500px)}.menu-item.svelte-14p9tpy{line-height:25px;cursor:pointer;border:0;background:#fefefe;color:#555;padding-left:15px;padding-right:15px;text-align:center}.menu-item.svelte-14p9tpy:first-child{border-radius:0 5px 0 0}.menu-item.svelte-14p9tpy:last-child{border-radius:5px 0 0 0}.menu-item.active.svelte-14p9tpy{cursor:default;font-weight:bold;background:#ddd;color:#555}.menu-item.svelte-14p9tpy:hover,.menu-item.svelte-14p9tpy:focus{background:#eee;color:#555}");
}
function get_each_context(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[4] = list[i][0];
child_ctx[5] = list[i][1].label;
return child_ctx;
}
// (57:2) {#each Object.entries(panes) as [key, {label}
function create_each_block(ctx) {
let button;
let t0_value = /*label*/ ctx[5] + "";
let t0;
let t1;
let mounted;
let dispose;
function click_handler() {
return /*click_handler*/ ctx[3](/*key*/ ctx[4]);
}
return {
c() {
button = element("button");
t0 = text(t0_value);
t1 = space();
attr(button, "class", "menu-item svelte-14p9tpy");
toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, t0);
append(button, t1);
if (!mounted) {
dispose = listen(button, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*panes*/ 2 && t0_value !== (t0_value = /*label*/ ctx[5] + "")) set_data(t0, t0_value);
if (dirty & /*pane, Object, panes*/ 3) {
toggle_class(button, "active", /*pane*/ ctx[0] == /*key*/ ctx[4]);
}
},
d(detaching) {
if (detaching) detach(button);
mounted = false;
dispose();
}
};
}
function create_fragment(ctx) {
let nav;
let each_value = Object.entries(/*panes*/ ctx[1]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block(get_each_context(ctx, each_value, i));
}
return {
c() {
nav = element("nav");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(nav, "class", "menu svelte-14p9tpy");
},
m(target, anchor) {
insert(target, nav, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(nav, null);
}
},
p(ctx, [dirty]) {
if (dirty & /*pane, Object, panes, dispatch*/ 7) {
each_value = Object.entries(/*panes*/ ctx[1]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block(child_ctx);
each_blocks[i].c();
each_blocks[i].m(nav, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(nav);
destroy_each(each_blocks, detaching);
}
};
}
function instance($$self, $$props, $$invalidate) {
let { pane } = $$props;
let { panes } = $$props;
const dispatch = createEventDispatcher();
const click_handler = key => dispatch('change', key);
$$self.$$set = $$props => {
if ('pane' in $$props) $$invalidate(0, pane = $$props.pane);
if ('panes' in $$props) $$invalidate(1, panes = $$props.panes);
};
return [pane, panes, dispatch, click_handler];
}
class Menu extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, create_fragment, safe_not_equal, { pane: 0, panes: 1 }, add_css);
}
}
var contextKey = {};
/* node_modules/svelte-json-tree-auto/src/JSONArrow.svelte generated by Svelte v3.41.0 */
function add_css$1(target) {
append_styles(target, "svelte-1vyml86", ".container.svelte-1vyml86{display:inline-block;cursor:pointer;transform:translate(calc(0px - var(--li-identation)), -50%);position:absolute;top:50%;padding-right:100%}.arrow.svelte-1vyml86{transform-origin:25% 50%;position:relative;line-height:1.1em;font-size:0.75em;margin-left:0;transition:150ms;color:var(--arrow-sign);user-select:none;font-family:'Courier New', Courier, monospace}.expanded.svelte-1vyml86{transform:rotateZ(90deg) translateX(-3px)}");
}
function create_fragment$1(ctx) {
let div1;
let div0;
let mounted;
let dispose;
return {
c() {
div1 = element("div");
div0 = element("div");
div0.textContent = `${'\u25B6'}`;
attr(div0, "class", "arrow svelte-1vyml86");
toggle_class(div0, "expanded", /*expanded*/ ctx[0]);
attr(div1, "class", "container svelte-1vyml86");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, div0);
if (!mounted) {
dispose = listen(div1, "click", /*click_handler*/ ctx[1]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*expanded*/ 1) {
toggle_class(div0, "expanded", /*expanded*/ ctx[0]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div1);
mounted = false;
dispose();
}
};
}
function instance$1($$self, $$props, $$invalidate) {
let { expanded } = $$props;
function click_handler(event) {
bubble.call(this, $$self, event);
}
$$self.$$set = $$props => {
if ('expanded' in $$props) $$invalidate(0, expanded = $$props.expanded);
};
return [expanded, click_handler];
}
class JSONArrow extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$1, create_fragment$1, safe_not_equal, { expanded: 0 }, add_css$1);
}
}
/* node_modules/svelte-json-tree-auto/src/JSONKey.svelte generated by Svelte v3.41.0 */
function add_css$2(target) {
append_styles(target, "svelte-1vlbacg", "label.svelte-1vlbacg{display:inline-block;color:var(--label-color);padding:0}.spaced.svelte-1vlbacg{padding-right:var(--li-colon-space)}");
}
// (16:0) {#if showKey && key}
function create_if_block(ctx) {
let label;
let span;
let t0;
let t1;
let mounted;
let dispose;
return {
c() {
label = element("label");
span = element("span");
t0 = text(/*key*/ ctx[0]);
t1 = text(/*colon*/ ctx[2]);
attr(label, "class", "svelte-1vlbacg");
toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]);
},
m(target, anchor) {
insert(target, label, anchor);
append(label, span);
append(span, t0);
append(span, t1);
if (!mounted) {
dispose = listen(label, "click", /*click_handler*/ ctx[5]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*key*/ 1) set_data(t0, /*key*/ ctx[0]);
if (dirty & /*colon*/ 4) set_data(t1, /*colon*/ ctx[2]);
if (dirty & /*isParentExpanded*/ 2) {
toggle_class(label, "spaced", /*isParentExpanded*/ ctx[1]);
}
},
d(detaching) {
if (detaching) detach(label);
mounted = false;
dispose();
}
};
}
function create_fragment$2(ctx) {
let if_block_anchor;
let if_block = /*showKey*/ ctx[3] && /*key*/ ctx[0] && create_if_block(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*showKey*/ ctx[3] && /*key*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop,
o: noop,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function instance$2($$self, $$props, $$invalidate) {
let showKey;
let { key, isParentExpanded, isParentArray = false, colon = ':' } = $$props;
function click_handler(event) {
bubble.call(this, $$self, event);
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ('colon' in $$props) $$invalidate(2, colon = $$props.colon);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*isParentExpanded, isParentArray, key*/ 19) {
$: $$invalidate(3, showKey = isParentExpanded || !isParentArray || key != +key);
}
};
return [key, isParentExpanded, colon, showKey, isParentArray, click_handler];
}
class JSONKey extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$2,
create_fragment$2,
safe_not_equal,
{
key: 0,
isParentExpanded: 1,
isParentArray: 4,
colon: 2
},
add_css$2
);
}
}
/* node_modules/svelte-json-tree-auto/src/JSONNested.svelte generated by Svelte v3.41.0 */
function add_css$3(target) {
append_styles(target, "svelte-rwxv37", "label.svelte-rwxv37{display:inline-block}.indent.svelte-rwxv37{padding-left:var(--li-identation)}.collapse.svelte-rwxv37{--li-display:inline;display:inline;font-style:italic}.comma.svelte-rwxv37{margin-left:-0.5em;margin-right:0.5em}label.svelte-rwxv37{position:relative}");
}
function get_each_context$1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[12] = list[i];
child_ctx[20] = i;
return child_ctx;
}
// (57:4) {#if expandable && isParentExpanded}
function create_if_block_3(ctx) {
let jsonarrow;
let current;
jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } });
jsonarrow.$on("click", /*toggleExpand*/ ctx[15]);
return {
c() {
create_component(jsonarrow.$$.fragment);
},
m(target, anchor) {
mount_component(jsonarrow, target, anchor);
current = true;
},
p(ctx, dirty) {
const jsonarrow_changes = {};
if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0];
jsonarrow.$set(jsonarrow_changes);
},
i(local) {
if (current) return;
transition_in(jsonarrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonarrow.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonarrow, detaching);
}
};
}
// (75:4) {:else}
function create_else_block(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = "…";
},
m(target, anchor) {
insert(target, span, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(span);
}
};
}
// (63:4) {#if isParentExpanded}
function create_if_block$1(ctx) {
let ul;
let t;
let current;
let mounted;
let dispose;
let each_value = /*slicedKeys*/ ctx[13];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$1(get_each_context$1(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block = /*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length && create_if_block_1();
return {
c() {
ul = element("ul");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t = space();
if (if_block) if_block.c();
attr(ul, "class", "svelte-rwxv37");
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
},
m(target, anchor) {
insert(target, ul, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(ul, null);
}
append(ul, t);
if (if_block) if_block.m(ul, null);
current = true;
if (!mounted) {
dispose = listen(ul, "click", /*expand*/ ctx[16]);
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*expanded, previewKeys, getKey, slicedKeys, isArray, getValue, getPreviewValue*/ 10129) {
each_value = /*slicedKeys*/ ctx[13];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$1(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$1(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(ul, t);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*slicedKeys*/ ctx[13].length < /*previewKeys*/ ctx[7].length) {
if (if_block) ; else {
if_block = create_if_block_1();
if_block.c();
if_block.m(ul, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*expanded*/ 1) {
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_each(each_blocks, detaching);
if (if_block) if_block.d();
mounted = false;
dispose();
}
};
}
// (67:10) {#if !expanded && index < previewKeys.length - 1}
function create_if_block_2(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = ",";
attr(span, "class", "comma svelte-rwxv37");
},
m(target, anchor) {
insert(target, span, anchor);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
// (65:8) {#each slicedKeys as key, index}
function create_each_block$1(ctx) {
let jsonnode;
let t;
let if_block_anchor;
let current;
jsonnode = new JSONNode({
props: {
key: /*getKey*/ ctx[8](/*key*/ ctx[12]),
isParentExpanded: /*expanded*/ ctx[0],
isParentArray: /*isArray*/ ctx[4],
value: /*expanded*/ ctx[0]
? /*getValue*/ ctx[9](/*key*/ ctx[12])
: /*getPreviewValue*/ ctx[10](/*key*/ ctx[12])
}
});
let if_block = !/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1 && create_if_block_2();
return {
c() {
create_component(jsonnode.$$.fragment);
t = space();
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
mount_component(jsonnode, target, anchor);
insert(target, t, anchor);
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const jsonnode_changes = {};
if (dirty & /*getKey, slicedKeys*/ 8448) jsonnode_changes.key = /*getKey*/ ctx[8](/*key*/ ctx[12]);
if (dirty & /*expanded*/ 1) jsonnode_changes.isParentExpanded = /*expanded*/ ctx[0];
if (dirty & /*isArray*/ 16) jsonnode_changes.isParentArray = /*isArray*/ ctx[4];
if (dirty & /*expanded, getValue, slicedKeys, getPreviewValue*/ 9729) jsonnode_changes.value = /*expanded*/ ctx[0]
? /*getValue*/ ctx[9](/*key*/ ctx[12])
: /*getPreviewValue*/ ctx[10](/*key*/ ctx[12]);
jsonnode.$set(jsonnode_changes);
if (!/*expanded*/ ctx[0] && /*index*/ ctx[20] < /*previewKeys*/ ctx[7].length - 1) {
if (if_block) ; else {
if_block = create_if_block_2();
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnode, detaching);
if (detaching) detach(t);
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (71:8) {#if slicedKeys.length < previewKeys.length }
function create_if_block_1(ctx) {
let span;
return {
c() {
span = element("span");
span.textContent = "…";
},
m(target, anchor) {
insert(target, span, anchor);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
function create_fragment$3(ctx) {
let li;
let label_1;
let t0;
let jsonkey;
let t1;
let span1;
let span0;
let t2;
let t3;
let t4;
let current_block_type_index;
let if_block1;
let t5;
let span2;
let t6;
let current;
let mounted;
let dispose;
let if_block0 = /*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2] && create_if_block_3(ctx);
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[12],
colon: /*context*/ ctx[14].colon,
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3]
}
});
jsonkey.$on("click", /*toggleExpand*/ ctx[15]);
const if_block_creators = [create_if_block$1, create_else_block];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*isParentExpanded*/ ctx[2]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
li = element("li");
label_1 = element("label");
if (if_block0) if_block0.c();
t0 = space();
create_component(jsonkey.$$.fragment);
t1 = space();
span1 = element("span");
span0 = element("span");
t2 = text(/*label*/ ctx[1]);
t3 = text(/*bracketOpen*/ ctx[5]);
t4 = space();
if_block1.c();
t5 = space();
span2 = element("span");
t6 = text(/*bracketClose*/ ctx[6]);
attr(label_1, "class", "svelte-rwxv37");
attr(li, "class", "svelte-rwxv37");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]);
},
m(target, anchor) {
insert(target, li, anchor);
append(li, label_1);
if (if_block0) if_block0.m(label_1, null);
append(label_1, t0);
mount_component(jsonkey, label_1, null);
append(label_1, t1);
append(label_1, span1);
append(span1, span0);
append(span0, t2);
append(span1, t3);
append(li, t4);
if_blocks[current_block_type_index].m(li, null);
append(li, t5);
append(li, span2);
append(span2, t6);
current = true;
if (!mounted) {
dispose = listen(span1, "click", /*toggleExpand*/ ctx[15]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*expandable*/ ctx[11] && /*isParentExpanded*/ ctx[2]) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*expandable, isParentExpanded*/ 2052) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_3(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(label_1, t0);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
const jsonkey_changes = {};
if (dirty & /*key*/ 4096) jsonkey_changes.key = /*key*/ ctx[12];
if (dirty & /*isParentExpanded*/ 4) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[3];
jsonkey.$set(jsonkey_changes);
if (!current || dirty & /*label*/ 2) set_data(t2, /*label*/ ctx[1]);
if (!current || dirty & /*bracketOpen*/ 32) set_data(t3, /*bracketOpen*/ ctx[5]);
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block1 = if_blocks[current_block_type_index];
if (!if_block1) {
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block1.c();
} else {
if_block1.p(ctx, dirty);
}
transition_in(if_block1, 1);
if_block1.m(li, t5);
}
if (!current || dirty & /*bracketClose*/ 64) set_data(t6, /*bracketClose*/ ctx[6]);
if (dirty & /*isParentExpanded*/ 4) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[2]);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(jsonkey.$$.fragment, local);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(jsonkey.$$.fragment, local);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (detaching) detach(li);
if (if_block0) if_block0.d();
destroy_component(jsonkey);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$3($$self, $$props, $$invalidate) {
let slicedKeys;
let { key, keys, colon = ':', label = '', isParentExpanded, isParentArray, isArray = false, bracketOpen, bracketClose } = $$props;
let { previewKeys = keys } = $$props;
let { getKey = key => key } = $$props;
let { getValue = key => key } = $$props;
let { getPreviewValue = getValue } = $$props;
let { expanded = false, expandable = true } = $$props;
const context = getContext(contextKey);
setContext(contextKey, { ...context, colon });
function toggleExpand() {
$$invalidate(0, expanded = !expanded);
}
function expand() {
$$invalidate(0, expanded = true);
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(12, key = $$props.key);
if ('keys' in $$props) $$invalidate(17, keys = $$props.keys);
if ('colon' in $$props) $$invalidate(18, colon = $$props.colon);
if ('label' in $$props) $$invalidate(1, label = $$props.label);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ('isArray' in $$props) $$invalidate(4, isArray = $$props.isArray);
if ('bracketOpen' in $$props) $$invalidate(5, bracketOpen = $$props.bracketOpen);
if ('bracketClose' in $$props) $$invalidate(6, bracketClose = $$props.bracketClose);
if ('previewKeys' in $$props) $$invalidate(7, previewKeys = $$props.previewKeys);
if ('getKey' in $$props) $$invalidate(8, getKey = $$props.getKey);
if ('getValue' in $$props) $$invalidate(9, getValue = $$props.getValue);
if ('getPreviewValue' in $$props) $$invalidate(10, getPreviewValue = $$props.getPreviewValue);
if ('expanded' in $$props) $$invalidate(0, expanded = $$props.expanded);
if ('expandable' in $$props) $$invalidate(11, expandable = $$props.expandable);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*isParentExpanded*/ 4) {
$: if (!isParentExpanded) {
$$invalidate(0, expanded = false);
}
}
if ($$self.$$.dirty & /*expanded, keys, previewKeys*/ 131201) {
$: $$invalidate(13, slicedKeys = expanded ? keys : previewKeys.slice(0, 5));
}
};
return [
expanded,
label,
isParentExpanded,
isParentArray,
isArray,
bracketOpen,
bracketClose,
previewKeys,
getKey,
getValue,
getPreviewValue,
expandable,
key,
slicedKeys,
context,
toggleExpand,
expand,
keys,
colon
];
}
class JSONNested extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$3,
create_fragment$3,
safe_not_equal,
{
key: 12,
keys: 17,
colon: 18,
label: 1,
isParentExpanded: 2,
isParentArray: 3,
isArray: 4,
bracketOpen: 5,
bracketClose: 6,
previewKeys: 7,
getKey: 8,
getValue: 9,
getPreviewValue: 10,
expanded: 0,
expandable: 11
},
add_css$3
);
}
}
/* node_modules/svelte-json-tree-auto/src/JSONObjectNode.svelte generated by Svelte v3.41.0 */
function create_fragment$4(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[5],
previewKeys: /*keys*/ ctx[5],
getValue: /*getValue*/ ctx[6],
label: "" + (/*nodeType*/ ctx[3] + " "),
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5];
if (dirty & /*keys*/ 32) jsonnested_changes.previewKeys = /*keys*/ ctx[5];
if (dirty & /*nodeType*/ 8) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + " ");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$4($$self, $$props, $$invalidate) {
let keys;
let { key, value, isParentExpanded, isParentArray, nodeType } = $$props;
let { expanded = true } = $$props;
function getValue(key) {
return value[key];
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(7, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(3, nodeType = $$props.nodeType);
if ('expanded' in $$props) $$invalidate(4, expanded = $$props.expanded);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 128) {
$: $$invalidate(5, keys = Object.getOwnPropertyNames(value));
}
};
return [
key,
isParentExpanded,
isParentArray,
nodeType,
expanded,
keys,
getValue,
value
];
}
class JSONObjectNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$4, create_fragment$4, safe_not_equal, {
key: 0,
value: 7,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONArrayNode.svelte generated by Svelte v3.41.0 */
function create_fragment$5(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
isArray: true,
keys: /*keys*/ ctx[5],
previewKeys: /*previewKeys*/ ctx[6],
getValue: /*getValue*/ ctx[7],
label: "Array(" + /*value*/ ctx[1].length + ")",
bracketOpen: "[",
bracketClose: "]"
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*keys*/ 32) jsonnested_changes.keys = /*keys*/ ctx[5];
if (dirty & /*previewKeys*/ 64) jsonnested_changes.previewKeys = /*previewKeys*/ ctx[6];
if (dirty & /*value*/ 2) jsonnested_changes.label = "Array(" + /*value*/ ctx[1].length + ")";
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$5($$self, $$props, $$invalidate) {
let keys;
let previewKeys;
let { key, value, isParentExpanded, isParentArray } = $$props;
let { expanded = JSON.stringify(value).length < 1024 } = $$props;
const filteredKey = new Set(['length']);
function getValue(key) {
return value[key];
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ('expanded' in $$props) $$invalidate(4, expanded = $$props.expanded);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 2) {
$: $$invalidate(5, keys = Object.getOwnPropertyNames(value));
}
if ($$self.$$.dirty & /*keys*/ 32) {
$: $$invalidate(6, previewKeys = keys.filter(key => !filteredKey.has(key)));
}
};
return [
key,
value,
isParentExpanded,
isParentArray,
expanded,
keys,
previewKeys,
getValue
];
}
class JSONArrayNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$5, create_fragment$5, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONIterableArrayNode.svelte generated by Svelte v3.41.0 */
function create_fragment$6(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[4],
getKey,
getValue,
isArray: true,
label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"),
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4];
if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function getKey(key) {
return String(key[0]);
}
function getValue(key) {
return key[1];
}
function instance$6($$self, $$props, $$invalidate) {
let { key, value, isParentExpanded, isParentArray, nodeType } = $$props;
let keys = [];
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(5, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(3, nodeType = $$props.nodeType);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 32) {
$: {
let result = [];
let i = 0;
for (const entry of value) {
result.push([i++, entry]);
}
$$invalidate(4, keys = result);
}
}
};
return [key, isParentExpanded, isParentArray, nodeType, keys, value];
}
class JSONIterableArrayNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$6, create_fragment$6, safe_not_equal, {
key: 0,
value: 5,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3
});
}
}
class MapEntry {
constructor(key, value) {
this.key = key;
this.value = value;
}
}
/* node_modules/svelte-json-tree-auto/src/JSONIterableMapNode.svelte generated by Svelte v3.41.0 */
function create_fragment$7(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
key: /*key*/ ctx[0],
isParentExpanded: /*isParentExpanded*/ ctx[1],
isParentArray: /*isParentArray*/ ctx[2],
keys: /*keys*/ ctx[4],
getKey: getKey$1,
getValue: getValue$1,
label: "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")"),
colon: "",
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*key*/ 1) jsonnested_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 2) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[1];
if (dirty & /*isParentArray*/ 4) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[2];
if (dirty & /*keys*/ 16) jsonnested_changes.keys = /*keys*/ ctx[4];
if (dirty & /*nodeType, keys*/ 24) jsonnested_changes.label = "" + (/*nodeType*/ ctx[3] + "(" + /*keys*/ ctx[4].length + ")");
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function getKey$1(entry) {
return entry[0];
}
function getValue$1(entry) {
return entry[1];
}
function instance$7($$self, $$props, $$invalidate) {
let { key, value, isParentExpanded, isParentArray, nodeType } = $$props;
let keys = [];
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(5, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(1, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(2, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(3, nodeType = $$props.nodeType);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 32) {
$: {
let result = [];
let i = 0;
for (const entry of value) {
result.push([i++, new MapEntry(entry[0], entry[1])]);
}
$$invalidate(4, keys = result);
}
}
};
return [key, isParentExpanded, isParentArray, nodeType, keys, value];
}
class JSONIterableMapNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$7, create_fragment$7, safe_not_equal, {
key: 0,
value: 5,
isParentExpanded: 1,
isParentArray: 2,
nodeType: 3
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONMapEntryNode.svelte generated by Svelte v3.41.0 */
function create_fragment$8(ctx) {
let jsonnested;
let current;
jsonnested = new JSONNested({
props: {
expanded: /*expanded*/ ctx[4],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
key: /*isParentExpanded*/ ctx[2]
? String(/*key*/ ctx[0])
: /*value*/ ctx[1].key,
keys: /*keys*/ ctx[5],
getValue: /*getValue*/ ctx[6],
label: /*isParentExpanded*/ ctx[2] ? 'Entry ' : '=> ',
bracketOpen: '{',
bracketClose: '}'
}
});
return {
c() {
create_component(jsonnested.$$.fragment);
},
m(target, anchor) {
mount_component(jsonnested, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const jsonnested_changes = {};
if (dirty & /*expanded*/ 16) jsonnested_changes.expanded = /*expanded*/ ctx[4];
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) jsonnested_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*isParentExpanded, key, value*/ 7) jsonnested_changes.key = /*isParentExpanded*/ ctx[2]
? String(/*key*/ ctx[0])
: /*value*/ ctx[1].key;
if (dirty & /*isParentExpanded*/ 4) jsonnested_changes.label = /*isParentExpanded*/ ctx[2] ? 'Entry ' : '=> ';
jsonnested.$set(jsonnested_changes);
},
i(local) {
if (current) return;
transition_in(jsonnested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnested, detaching);
}
};
}
function instance$8($$self, $$props, $$invalidate) {
let { key, value, isParentExpanded, isParentArray } = $$props;
let { expanded = false } = $$props;
const keys = ['key', 'value'];
function getValue(key) {
return value[key];
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
if ('expanded' in $$props) $$invalidate(4, expanded = $$props.expanded);
};
return [key, value, isParentExpanded, isParentArray, expanded, keys, getValue];
}
class JSONMapEntryNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$8, create_fragment$8, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3,
expanded: 4
});
}
}
/* node_modules/svelte-json-tree-auto/src/JSONValueNode.svelte generated by Svelte v3.41.0 */
function add_css$4(target) {
append_styles(target, "svelte-3bjyvl", "li.svelte-3bjyvl{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-3bjyvl{padding-left:var(--li-identation)}.String.svelte-3bjyvl{color:var(--string-color)}.Date.svelte-3bjyvl{color:var(--date-color)}.Number.svelte-3bjyvl{color:var(--number-color)}.Boolean.svelte-3bjyvl{color:var(--boolean-color)}.Null.svelte-3bjyvl{color:var(--null-color)}.Undefined.svelte-3bjyvl{color:var(--undefined-color)}.Function.svelte-3bjyvl{color:var(--function-color);font-style:italic}.Symbol.svelte-3bjyvl{color:var(--symbol-color)}");
}
function create_fragment$9(ctx) {
let li;
let jsonkey;
let t0;
let span;
let t1_value = (/*valueGetter*/ ctx[2]
? /*valueGetter*/ ctx[2](/*value*/ ctx[1])
: /*value*/ ctx[1]) + "";
let t1;
let span_class_value;
let current;
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[0],
colon: /*colon*/ ctx[6],
isParentExpanded: /*isParentExpanded*/ ctx[3],
isParentArray: /*isParentArray*/ ctx[4]
}
});
return {
c() {
li = element("li");
create_component(jsonkey.$$.fragment);
t0 = space();
span = element("span");
t1 = text(t1_value);
attr(span, "class", span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl"));
attr(li, "class", "svelte-3bjyvl");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(jsonkey, li, null);
append(li, t0);
append(li, span);
append(span, t1);
current = true;
},
p(ctx, [dirty]) {
const jsonkey_changes = {};
if (dirty & /*key*/ 1) jsonkey_changes.key = /*key*/ ctx[0];
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4];
jsonkey.$set(jsonkey_changes);
if ((!current || dirty & /*valueGetter, value*/ 6) && t1_value !== (t1_value = (/*valueGetter*/ ctx[2]
? /*valueGetter*/ ctx[2](/*value*/ ctx[1])
: /*value*/ ctx[1]) + "")) set_data(t1, t1_value);
if (!current || dirty & /*nodeType*/ 32 && span_class_value !== (span_class_value = "" + (null_to_empty(/*nodeType*/ ctx[5]) + " svelte-3bjyvl"))) {
attr(span, "class", span_class_value);
}
if (dirty & /*isParentExpanded*/ 8) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
}
},
i(local) {
if (current) return;
transition_in(jsonkey.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonkey.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(jsonkey);
}
};
}
function instance$9($$self, $$props, $$invalidate) {
let { key, value, valueGetter = null, isParentExpanded, isParentArray, nodeType } = $$props;
const { colon } = getContext(contextKey);
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('valueGetter' in $$props) $$invalidate(2, valueGetter = $$props.valueGetter);
if ('isParentExpanded' in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ('nodeType' in $$props) $$invalidate(5, nodeType = $$props.nodeType);
};
return [key, value, valueGetter, isParentExpanded, isParentArray, nodeType, colon];
}
class JSONValueNode extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$9,
create_fragment$9,
safe_not_equal,
{
key: 0,
value: 1,
valueGetter: 2,
isParentExpanded: 3,
isParentArray: 4,
nodeType: 5
},
add_css$4
);
}
}
/* node_modules/svelte-json-tree-auto/src/ErrorNode.svelte generated by Svelte v3.41.0 */
function add_css$5(target) {
append_styles(target, "svelte-1ca3gb2", "li.svelte-1ca3gb2{user-select:text;word-wrap:break-word;word-break:break-all}.indent.svelte-1ca3gb2{padding-left:var(--li-identation)}.collapse.svelte-1ca3gb2{--li-display:inline;display:inline;font-style:italic}");
}
function get_each_context$2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[8] = list[i];
child_ctx[10] = i;
return child_ctx;
}
// (40:2) {#if isParentExpanded}
function create_if_block_2$1(ctx) {
let jsonarrow;
let current;
jsonarrow = new JSONArrow({ props: { expanded: /*expanded*/ ctx[0] } });
jsonarrow.$on("click", /*toggleExpand*/ ctx[7]);
return {
c() {
create_component(jsonarrow.$$.fragment);
},
m(target, anchor) {
mount_component(jsonarrow, target, anchor);
current = true;
},
p(ctx, dirty) {
const jsonarrow_changes = {};
if (dirty & /*expanded*/ 1) jsonarrow_changes.expanded = /*expanded*/ ctx[0];
jsonarrow.$set(jsonarrow_changes);
},
i(local) {
if (current) return;
transition_in(jsonarrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonarrow.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonarrow, detaching);
}
};
}
// (45:2) {#if isParentExpanded}
function create_if_block$2(ctx) {
let ul;
let current;
let if_block = /*expanded*/ ctx[0] && create_if_block_1$1(ctx);
return {
c() {
ul = element("ul");
if (if_block) if_block.c();
attr(ul, "class", "svelte-1ca3gb2");
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
},
m(target, anchor) {
insert(target, ul, anchor);
if (if_block) if_block.m(ul, null);
current = true;
},
p(ctx, dirty) {
if (/*expanded*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*expanded*/ 1) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$1(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(ul, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
if (dirty & /*expanded*/ 1) {
toggle_class(ul, "collapse", !/*expanded*/ ctx[0]);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
if (if_block) if_block.d();
}
};
}
// (47:6) {#if expanded}
function create_if_block_1$1(ctx) {
let jsonnode;
let t0;
let li;
let jsonkey;
let t1;
let span;
let current;
jsonnode = new JSONNode({
props: {
key: "message",
value: /*value*/ ctx[2].message
}
});
jsonkey = new JSONKey({
props: {
key: "stack",
colon: ":",
isParentExpanded: /*isParentExpanded*/ ctx[3]
}
});
let each_value = /*stack*/ ctx[5];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$2(get_each_context$2(ctx, each_value, i));
}
return {
c() {
create_component(jsonnode.$$.fragment);
t0 = space();
li = element("li");
create_component(jsonkey.$$.fragment);
t1 = space();
span = element("span");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(li, "class", "svelte-1ca3gb2");
},
m(target, anchor) {
mount_component(jsonnode, target, anchor);
insert(target, t0, anchor);
insert(target, li, anchor);
mount_component(jsonkey, li, null);
append(li, t1);
append(li, span);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(span, null);
}
current = true;
},
p(ctx, dirty) {
const jsonnode_changes = {};
if (dirty & /*value*/ 4) jsonnode_changes.value = /*value*/ ctx[2].message;
jsonnode.$set(jsonnode_changes);
const jsonkey_changes = {};
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
jsonkey.$set(jsonkey_changes);
if (dirty & /*stack*/ 32) {
each_value = /*stack*/ ctx[5];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$2(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$2(child_ctx);
each_blocks[i].c();
each_blocks[i].m(span, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
transition_in(jsonkey.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
transition_out(jsonkey.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(jsonnode, detaching);
if (detaching) detach(t0);
if (detaching) detach(li);
destroy_component(jsonkey);
destroy_each(each_blocks, detaching);
}
};
}
// (52:12) {#each stack as line, index}
function create_each_block$2(ctx) {
let span;
let t_value = /*line*/ ctx[8] + "";
let t;
let br;
return {
c() {
span = element("span");
t = text(t_value);
br = element("br");
attr(span, "class", "svelte-1ca3gb2");
toggle_class(span, "indent", /*index*/ ctx[10] > 0);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
insert(target, br, anchor);
},
p(ctx, dirty) {
if (dirty & /*stack*/ 32 && t_value !== (t_value = /*line*/ ctx[8] + "")) set_data(t, t_value);
},
d(detaching) {
if (detaching) detach(span);
if (detaching) detach(br);
}
};
}
function create_fragment$a(ctx) {
let li;
let t0;
let jsonkey;
let t1;
let span;
let t2;
let t3_value = (/*expanded*/ ctx[0] ? '' : /*value*/ ctx[2].message) + "";
let t3;
let t4;
let current;
let mounted;
let dispose;
let if_block0 = /*isParentExpanded*/ ctx[3] && create_if_block_2$1(ctx);
jsonkey = new JSONKey({
props: {
key: /*key*/ ctx[1],
colon: /*context*/ ctx[6].colon,
isParentExpanded: /*isParentExpanded*/ ctx[3],
isParentArray: /*isParentArray*/ ctx[4]
}
});
let if_block1 = /*isParentExpanded*/ ctx[3] && create_if_block$2(ctx);
return {
c() {
li = element("li");
if (if_block0) if_block0.c();
t0 = space();
create_component(jsonkey.$$.fragment);
t1 = space();
span = element("span");
t2 = text("Error: ");
t3 = text(t3_value);
t4 = space();
if (if_block1) if_block1.c();
attr(li, "class", "svelte-1ca3gb2");
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
},
m(target, anchor) {
insert(target, li, anchor);
if (if_block0) if_block0.m(li, null);
append(li, t0);
mount_component(jsonkey, li, null);
append(li, t1);
append(li, span);
append(span, t2);
append(span, t3);
append(li, t4);
if (if_block1) if_block1.m(li, null);
current = true;
if (!mounted) {
dispose = listen(span, "click", /*toggleExpand*/ ctx[7]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*isParentExpanded*/ ctx[3]) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*isParentExpanded*/ 8) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_2$1(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(li, t0);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
const jsonkey_changes = {};
if (dirty & /*key*/ 2) jsonkey_changes.key = /*key*/ ctx[1];
if (dirty & /*isParentExpanded*/ 8) jsonkey_changes.isParentExpanded = /*isParentExpanded*/ ctx[3];
if (dirty & /*isParentArray*/ 16) jsonkey_changes.isParentArray = /*isParentArray*/ ctx[4];
jsonkey.$set(jsonkey_changes);
if ((!current || dirty & /*expanded, value*/ 5) && t3_value !== (t3_value = (/*expanded*/ ctx[0] ? '' : /*value*/ ctx[2].message) + "")) set_data(t3, t3_value);
if (/*isParentExpanded*/ ctx[3]) {
if (if_block1) {
if_block1.p(ctx, dirty);
if (dirty & /*isParentExpanded*/ 8) {
transition_in(if_block1, 1);
}
} else {
if_block1 = create_if_block$2(ctx);
if_block1.c();
transition_in(if_block1, 1);
if_block1.m(li, null);
}
} else if (if_block1) {
group_outros();
transition_out(if_block1, 1, 1, () => {
if_block1 = null;
});
check_outros();
}
if (dirty & /*isParentExpanded*/ 8) {
toggle_class(li, "indent", /*isParentExpanded*/ ctx[3]);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(jsonkey.$$.fragment, local);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(jsonkey.$$.fragment, local);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (detaching) detach(li);
if (if_block0) if_block0.d();
destroy_component(jsonkey);
if (if_block1) if_block1.d();
mounted = false;
dispose();
}
};
}
function instance$a($$self, $$props, $$invalidate) {
let stack;
let { key, value, isParentExpanded, isParentArray } = $$props;
let { expanded = false } = $$props;
const context = getContext(contextKey);
setContext(contextKey, { ...context, colon: ':' });
function toggleExpand() {
$$invalidate(0, expanded = !expanded);
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(1, key = $$props.key);
if ('value' in $$props) $$invalidate(2, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(3, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(4, isParentArray = $$props.isParentArray);
if ('expanded' in $$props) $$invalidate(0, expanded = $$props.expanded);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 4) {
$: $$invalidate(5, stack = value.stack.split('\n'));
}
if ($$self.$$.dirty & /*isParentExpanded*/ 8) {
$: if (!isParentExpanded) {
$$invalidate(0, expanded = false);
}
}
};
return [
expanded,
key,
value,
isParentExpanded,
isParentArray,
stack,
context,
toggleExpand
];
}
class ErrorNode extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$a,
create_fragment$a,
safe_not_equal,
{
key: 1,
value: 2,
isParentExpanded: 3,
isParentArray: 4,
expanded: 0
},
add_css$5
);
}
}
function objType(obj) {
const type = Object.prototype.toString.call(obj).slice(8, -1);
if (type === 'Object') {
if (typeof obj[Symbol.iterator] === 'function') {
return 'Iterable';
}
return obj.constructor.name;
}
return type;
}
/* node_modules/svelte-json-tree-auto/src/JSONNode.svelte generated by Svelte v3.41.0 */
function create_fragment$b(ctx) {
let switch_instance;
let switch_instance_anchor;
let current;
var switch_value = /*componentType*/ ctx[6];
function switch_props(ctx) {
return {
props: {
key: /*key*/ ctx[0],
value: /*value*/ ctx[1],
isParentExpanded: /*isParentExpanded*/ ctx[2],
isParentArray: /*isParentArray*/ ctx[3],
nodeType: /*nodeType*/ ctx[4],
valueGetter: /*valueGetter*/ ctx[5]
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
if (switch_instance) create_component(switch_instance.$$.fragment);
switch_instance_anchor = empty();
},
m(target, anchor) {
if (switch_instance) {
mount_component(switch_instance, target, anchor);
}
insert(target, switch_instance_anchor, anchor);
current = true;
},
p(ctx, [dirty]) {
const switch_instance_changes = {};
if (dirty & /*key*/ 1) switch_instance_changes.key = /*key*/ ctx[0];
if (dirty & /*value*/ 2) switch_instance_changes.value = /*value*/ ctx[1];
if (dirty & /*isParentExpanded*/ 4) switch_instance_changes.isParentExpanded = /*isParentExpanded*/ ctx[2];
if (dirty & /*isParentArray*/ 8) switch_instance_changes.isParentArray = /*isParentArray*/ ctx[3];
if (dirty & /*nodeType*/ 16) switch_instance_changes.nodeType = /*nodeType*/ ctx[4];
if (dirty & /*valueGetter*/ 32) switch_instance_changes.valueGetter = /*valueGetter*/ ctx[5];
if (switch_value !== (switch_value = /*componentType*/ ctx[6])) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(switch_instance_anchor);
if (switch_instance) destroy_component(switch_instance, detaching);
}
};
}
function instance$b($$self, $$props, $$invalidate) {
let nodeType;
let componentType;
let valueGetter;
let { key, value, isParentExpanded, isParentArray } = $$props;
function getComponent(nodeType) {
switch (nodeType) {
case 'Object':
return JSONObjectNode;
case 'Error':
return ErrorNode;
case 'Array':
return JSONArrayNode;
case 'Iterable':
case 'Map':
case 'Set':
return typeof value.set === 'function'
? JSONIterableMapNode
: JSONIterableArrayNode;
case 'MapEntry':
return JSONMapEntryNode;
default:
return JSONValueNode;
}
}
function getValueGetter(nodeType) {
switch (nodeType) {
case 'Object':
case 'Error':
case 'Array':
case 'Iterable':
case 'Map':
case 'Set':
case 'MapEntry':
case 'Number':
return undefined;
case 'String':
return raw => `"${raw}"`;
case 'Boolean':
return raw => raw ? 'true' : 'false';
case 'Date':
return raw => raw.toISOString();
case 'Null':
return () => 'null';
case 'Undefined':
return () => 'undefined';
case 'Function':
case 'Symbol':
return raw => raw.toString();
default:
return () => `<${nodeType}>`;
}
}
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
if ('isParentExpanded' in $$props) $$invalidate(2, isParentExpanded = $$props.isParentExpanded);
if ('isParentArray' in $$props) $$invalidate(3, isParentArray = $$props.isParentArray);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*value*/ 2) {
$: $$invalidate(4, nodeType = objType(value));
}
if ($$self.$$.dirty & /*nodeType*/ 16) {
$: $$invalidate(6, componentType = getComponent(nodeType));
}
if ($$self.$$.dirty & /*nodeType*/ 16) {
$: $$invalidate(5, valueGetter = getValueGetter(nodeType));
}
};
return [
key,
value,
isParentExpanded,
isParentArray,
nodeType,
valueGetter,
componentType
];
}
class JSONNode extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$b, create_fragment$b, safe_not_equal, {
key: 0,
value: 1,
isParentExpanded: 2,
isParentArray: 3
});
}
}
/* node_modules/svelte-json-tree-auto/src/Root.svelte generated by Svelte v3.41.0 */
function add_css$6(target) {
append_styles(target, "svelte-773n60", "ul.svelte-773n60{--string-color:var(--json-tree-string-color, #cb3f41);--symbol-color:var(--json-tree-symbol-color, #cb3f41);--boolean-color:var(--json-tree-boolean-color, #112aa7);--function-color:var(--json-tree-function-color, #112aa7);--number-color:var(--json-tree-number-color, #3029cf);--label-color:var(--json-tree-label-color, #871d8f);--arrow-color:var(--json-tree-arrow-color, #727272);--null-color:var(--json-tree-null-color, #8d8d8d);--undefined-color:var(--json-tree-undefined-color, #8d8d8d);--date-color:var(--json-tree-date-color, #8d8d8d);--li-identation:var(--json-tree-li-indentation, 1em);--li-line-height:var(--json-tree-li-line-height, 1.3);--li-colon-space:0.3em;font-size:var(--json-tree-font-size, 12px);font-family:var(--json-tree-font-family, 'Courier New', Courier, monospace)}ul.svelte-773n60 li{line-height:var(--li-line-height);display:var(--li-display, list-item);list-style:none}ul.svelte-773n60,ul.svelte-773n60 ul{padding:0;margin:0}");
}
function create_fragment$c(ctx) {
let ul;
let jsonnode;
let current;
jsonnode = new JSONNode({
props: {
key: /*key*/ ctx[0],
value: /*value*/ ctx[1],
isParentExpanded: true,
isParentArray: false
}
});
return {
c() {
ul = element("ul");
create_component(jsonnode.$$.fragment);
attr(ul, "class", "svelte-773n60");
},
m(target, anchor) {
insert(target, ul, anchor);
mount_component(jsonnode, ul, null);
current = true;
},
p(ctx, [dirty]) {
const jsonnode_changes = {};
if (dirty & /*key*/ 1) jsonnode_changes.key = /*key*/ ctx[0];
if (dirty & /*value*/ 2) jsonnode_changes.value = /*value*/ ctx[1];
jsonnode.$set(jsonnode_changes);
},
i(local) {
if (current) return;
transition_in(jsonnode.$$.fragment, local);
current = true;
},
o(local) {
transition_out(jsonnode.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_component(jsonnode);
}
};
}
function instance$c($$self, $$props, $$invalidate) {
setContext(contextKey, {});
let { key = '', value } = $$props;
$$self.$$set = $$props => {
if ('key' in $$props) $$invalidate(0, key = $$props.key);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
};
return [key, value];
}
class Root extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$c, create_fragment$c, safe_not_equal, { key: 0, value: 1 }, add_css$6);
}
}
/* src/client/debug/main/ClientSwitcher.svelte generated by Svelte v3.41.0 */
function add_css$7(target) {
append_styles(target, "svelte-jvfq3i", ".svelte-jvfq3i{box-sizing:border-box}section.switcher.svelte-jvfq3i{position:sticky;bottom:0;transform:translateY(20px);margin:40px -20px 0;border-top:1px solid #999;padding:20px;background:#fff}label.svelte-jvfq3i{display:flex;align-items:baseline;gap:5px;font-weight:bold}select.svelte-jvfq3i{min-width:140px}");
}
function get_each_context$3(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
child_ctx[9] = i;
return child_ctx;
}
// (42:0) {#if debuggableClients.length > 1}
function create_if_block$3(ctx) {
let section;
let label;
let t;
let select;
let mounted;
let dispose;
let each_value = /*debuggableClients*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$3(get_each_context$3(ctx, each_value, i));
}
return {
c() {
section = element("section");
label = element("label");
t = text("Client\n \n ");
select = element("select");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(select, "id", selectId);
attr(select, "class", "svelte-jvfq3i");
if (/*selected*/ ctx[2] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[6].call(select));
attr(label, "class", "svelte-jvfq3i");
attr(section, "class", "switcher svelte-jvfq3i");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, label);
append(label, t);
append(label, select);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(select, null);
}
select_option(select, /*selected*/ ctx[2]);
if (!mounted) {
dispose = [
listen(select, "change", /*handleSelection*/ ctx[3]),
listen(select, "change", /*select_change_handler*/ ctx[6])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*debuggableClients, JSON*/ 2) {
each_value = /*debuggableClients*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$3(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$3(child_ctx);
each_blocks[i].c();
each_blocks[i].m(select, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (dirty & /*selected*/ 4) {
select_option(select, /*selected*/ ctx[2]);
}
},
d(detaching) {
if (detaching) detach(section);
destroy_each(each_blocks, detaching);
mounted = false;
run_all(dispose);
}
};
}
// (48:8) {#each debuggableClients as clientOption, index}
function create_each_block$3(ctx) {
let option;
let t0;
let t1;
let t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + "";
let t2;
let t3;
let t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + "";
let t4;
let t5;
let t6_value = /*clientOption*/ ctx[7].game.name + "";
let t6;
let t7;
let option_value_value;
return {
c() {
option = element("option");
t0 = text(/*index*/ ctx[9]);
t1 = text(" —\n playerID: ");
t2 = text(t2_value);
t3 = text(",\n matchID: ");
t4 = text(t4_value);
t5 = text("\n (");
t6 = text(t6_value);
t7 = text(")\n ");
option.__value = option_value_value = /*index*/ ctx[9];
option.value = option.__value;
attr(option, "class", "svelte-jvfq3i");
},
m(target, anchor) {
insert(target, option, anchor);
append(option, t0);
append(option, t1);
append(option, t2);
append(option, t3);
append(option, t4);
append(option, t5);
append(option, t6);
append(option, t7);
},
p(ctx, dirty) {
if (dirty & /*debuggableClients*/ 2 && t2_value !== (t2_value = JSON.stringify(/*clientOption*/ ctx[7].playerID) + "")) set_data(t2, t2_value);
if (dirty & /*debuggableClients*/ 2 && t4_value !== (t4_value = JSON.stringify(/*clientOption*/ ctx[7].matchID) + "")) set_data(t4, t4_value);
if (dirty & /*debuggableClients*/ 2 && t6_value !== (t6_value = /*clientOption*/ ctx[7].game.name + "")) set_data(t6, t6_value);
},
d(detaching) {
if (detaching) detach(option);
}
};
}
function create_fragment$d(ctx) {
let if_block_anchor;
let if_block = /*debuggableClients*/ ctx[1].length > 1 && create_if_block$3(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
},
p(ctx, [dirty]) {
if (/*debuggableClients*/ ctx[1].length > 1) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$3(ctx);
if_block.c();
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i: noop,
o: noop,
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
const selectId = 'bgio-debug-select-client';
function instance$d($$self, $$props, $$invalidate) {
let client;
let debuggableClients;
let selected;
let $clientManager,
$$unsubscribe_clientManager = noop,
$$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(5, $clientManager = $$value)), clientManager);
$$self.$$.on_destroy.push(() => $$unsubscribe_clientManager());
let { clientManager } = $$props;
$$subscribe_clientManager();
const handleSelection = e => {
// Request to switch to the selected client.
const selectedClient = debuggableClients[e.target.value];
clientManager.switchToClient(selectedClient);
// Maintain focus on the client select menu after switching clients.
// Necessary because switching clients will usually trigger a mount/unmount.
const select = document.getElementById(selectId);
if (select) select.focus();
};
function select_change_handler() {
selected = select_value(this);
((($$invalidate(2, selected), $$invalidate(1, debuggableClients)), $$invalidate(4, client)), $$invalidate(5, $clientManager));
}
$$self.$$set = $$props => {
if ('clientManager' in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager));
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$clientManager*/ 32) {
$: $$invalidate(4, { client, debuggableClients } = $clientManager, client, ($$invalidate(1, debuggableClients), $$invalidate(5, $clientManager)));
}
if ($$self.$$.dirty & /*debuggableClients, client*/ 18) {
$: $$invalidate(2, selected = debuggableClients.indexOf(client));
}
};
return [
clientManager,
debuggableClients,
selected,
handleSelection,
client,
$clientManager,
select_change_handler
];
}
class ClientSwitcher extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$d, create_fragment$d, safe_not_equal, { clientManager: 0 }, add_css$7);
}
}
/* src/client/debug/main/Hotkey.svelte generated by Svelte v3.41.0 */
function add_css$8(target) {
append_styles(target, "svelte-1vfj1mn", ".key.svelte-1vfj1mn.svelte-1vfj1mn{display:flex;flex-direction:row;align-items:center}button.svelte-1vfj1mn.svelte-1vfj1mn{cursor:pointer;min-width:10px;padding-left:5px;padding-right:5px;height:20px;line-height:20px;text-align:center;border:1px solid #ccc;box-shadow:1px 1px 1px #888;background:#eee;color:#444}button.svelte-1vfj1mn.svelte-1vfj1mn:hover{background:#ddd}.key.active.svelte-1vfj1mn button.svelte-1vfj1mn{background:#ddd;border:1px solid #999;box-shadow:none}label.svelte-1vfj1mn.svelte-1vfj1mn{margin-left:10px}");
}
// (78:2) {#if label}
function create_if_block$4(ctx) {
let label_1;
let t0;
let t1;
let span;
let t2_value = `(shortcut: ${/*value*/ ctx[0]})` + "";
let t2;
return {
c() {
label_1 = element("label");
t0 = text(/*label*/ ctx[1]);
t1 = space();
span = element("span");
t2 = text(t2_value);
attr(span, "class", "screen-reader-only");
attr(label_1, "for", /*id*/ ctx[5]);
attr(label_1, "class", "svelte-1vfj1mn");
},
m(target, anchor) {
insert(target, label_1, anchor);
append(label_1, t0);
append(label_1, t1);
append(label_1, span);
append(span, t2);
},
p(ctx, dirty) {
if (dirty & /*label*/ 2) set_data(t0, /*label*/ ctx[1]);
if (dirty & /*value*/ 1 && t2_value !== (t2_value = `(shortcut: ${/*value*/ ctx[0]})` + "")) set_data(t2, t2_value);
},
d(detaching) {
if (detaching) detach(label_1);
}
};
}
function create_fragment$e(ctx) {
let div;
let button;
let t0;
let t1;
let mounted;
let dispose;
let if_block = /*label*/ ctx[1] && create_if_block$4(ctx);
return {
c() {
div = element("div");
button = element("button");
t0 = text(/*value*/ ctx[0]);
t1 = space();
if (if_block) if_block.c();
attr(button, "id", /*id*/ ctx[5]);
button.disabled = /*disable*/ ctx[2];
attr(button, "class", "svelte-1vfj1mn");
attr(div, "class", "key svelte-1vfj1mn");
toggle_class(div, "active", /*active*/ ctx[3]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, button);
append(button, t0);
append(div, t1);
if (if_block) if_block.m(div, null);
if (!mounted) {
dispose = [
listen(window, "keydown", /*Keypress*/ ctx[7]),
listen(button, "click", /*Activate*/ ctx[6])
];
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*value*/ 1) set_data(t0, /*value*/ ctx[0]);
if (dirty & /*disable*/ 4) {
button.disabled = /*disable*/ ctx[2];
}
if (/*label*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$4(ctx);
if_block.c();
if_block.m(div, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (dirty & /*active*/ 8) {
toggle_class(div, "active", /*active*/ ctx[3]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
if (if_block) if_block.d();
mounted = false;
run_all(dispose);
}
};
}
function instance$e($$self, $$props, $$invalidate) {
let $disableHotkeys;
let { value } = $$props;
let { onPress = null } = $$props;
let { label = null } = $$props;
let { disable = false } = $$props;
const { disableHotkeys } = getContext('hotkeys');
component_subscribe($$self, disableHotkeys, value => $$invalidate(9, $disableHotkeys = value));
let active = false;
let id = `key-${value}`;
function Deactivate() {
$$invalidate(3, active = false);
}
function Activate() {
$$invalidate(3, active = true);
setTimeout(Deactivate, 200);
if (onPress) {
setTimeout(onPress, 1);
}
}
function Keypress(e) {
if (!$disableHotkeys && !disable && !e.ctrlKey && !e.metaKey && e.key == value) {
e.preventDefault();
Activate();
}
}
$$self.$$set = $$props => {
if ('value' in $$props) $$invalidate(0, value = $$props.value);
if ('onPress' in $$props) $$invalidate(8, onPress = $$props.onPress);
if ('label' in $$props) $$invalidate(1, label = $$props.label);
if ('disable' in $$props) $$invalidate(2, disable = $$props.disable);
};
return [value, label, disable, active, disableHotkeys, id, Activate, Keypress, onPress];
}
class Hotkey extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$e,
create_fragment$e,
safe_not_equal,
{
value: 0,
onPress: 8,
label: 1,
disable: 2
},
add_css$8
);
}
}
/* src/client/debug/main/InteractiveFunction.svelte generated by Svelte v3.41.0 */
function add_css$9(target) {
append_styles(target, "svelte-1mppqmp", ".move.svelte-1mppqmp{display:flex;flex-direction:row;cursor:pointer;margin-left:10px;color:#666}.move.svelte-1mppqmp:hover{color:#333}.move.active.svelte-1mppqmp{color:#111;font-weight:bold}.arg-field.svelte-1mppqmp{outline:none;font-family:monospace}");
}
function create_fragment$f(ctx) {
let div;
let span0;
let t0;
let t1;
let span1;
let t3;
let span2;
let t4;
let span3;
let mounted;
let dispose;
return {
c() {
div = element("div");
span0 = element("span");
t0 = text(/*name*/ ctx[2]);
t1 = space();
span1 = element("span");
span1.textContent = "(";
t3 = space();
span2 = element("span");
t4 = space();
span3 = element("span");
span3.textContent = ")";
attr(span2, "class", "arg-field svelte-1mppqmp");
attr(span2, "contenteditable", "");
attr(div, "class", "move svelte-1mppqmp");
toggle_class(div, "active", /*active*/ ctx[3]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, span0);
append(span0, t0);
append(div, t1);
append(div, span1);
append(div, t3);
append(div, span2);
/*span2_binding*/ ctx[6](span2);
append(div, t4);
append(div, span3);
if (!mounted) {
dispose = [
listen(span2, "focus", function () {
if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments);
}),
listen(span2, "blur", function () {
if (is_function(/*Deactivate*/ ctx[1])) /*Deactivate*/ ctx[1].apply(this, arguments);
}),
listen(span2, "keypress", stop_propagation(keypress_handler)),
listen(span2, "keydown", /*OnKeyDown*/ ctx[5]),
listen(div, "click", function () {
if (is_function(/*Activate*/ ctx[0])) /*Activate*/ ctx[0].apply(this, arguments);
})
];
mounted = true;
}
},
p(new_ctx, [dirty]) {
ctx = new_ctx;
if (dirty & /*name*/ 4) set_data(t0, /*name*/ ctx[2]);
if (dirty & /*active*/ 8) {
toggle_class(div, "active", /*active*/ ctx[3]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
/*span2_binding*/ ctx[6](null);
mounted = false;
run_all(dispose);
}
};
}
const keypress_handler = () => {
};
function instance$f($$self, $$props, $$invalidate) {
let { Activate } = $$props;
let { Deactivate } = $$props;
let { name } = $$props;
let { active } = $$props;
let span;
const dispatch = createEventDispatcher();
function Submit() {
try {
const value = span.innerText;
let argArray = new Function(`return [${value}]`)();
dispatch('submit', argArray);
} catch(error) {
dispatch('error', error);
}
$$invalidate(4, span.innerText = '', span);
}
function OnKeyDown(e) {
if (e.key == 'Enter') {
e.preventDefault();
Submit();
}
if (e.key == 'Escape') {
e.preventDefault();
Deactivate();
}
}
afterUpdate(() => {
if (active) {
span.focus();
} else {
span.blur();
}
});
function span2_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
span = $$value;
$$invalidate(4, span);
});
}
$$self.$$set = $$props => {
if ('Activate' in $$props) $$invalidate(0, Activate = $$props.Activate);
if ('Deactivate' in $$props) $$invalidate(1, Deactivate = $$props.Deactivate);
if ('name' in $$props) $$invalidate(2, name = $$props.name);
if ('active' in $$props) $$invalidate(3, active = $$props.active);
};
return [Activate, Deactivate, name, active, span, OnKeyDown, span2_binding];
}
class InteractiveFunction extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$f,
create_fragment$f,
safe_not_equal,
{
Activate: 0,
Deactivate: 1,
name: 2,
active: 3
},
add_css$9
);
}
}
/* src/client/debug/main/Move.svelte generated by Svelte v3.41.0 */
function add_css$a(target) {
append_styles(target, "svelte-smqssc", ".move-error.svelte-smqssc{color:#a00;font-weight:bold}.wrapper.svelte-smqssc{display:flex;flex-direction:row;align-items:center}");
}
// (65:2) {#if error}
function create_if_block$5(ctx) {
let span;
let t;
return {
c() {
span = element("span");
t = text(/*error*/ ctx[2]);
attr(span, "class", "move-error svelte-smqssc");
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t);
},
p(ctx, dirty) {
if (dirty & /*error*/ 4) set_data(t, /*error*/ ctx[2]);
},
d(detaching) {
if (detaching) detach(span);
}
};
}
function create_fragment$g(ctx) {
let div1;
let div0;
let hotkey;
let t0;
let interactivefunction;
let t1;
let current;
hotkey = new Hotkey({
props: {
value: /*shortcut*/ ctx[0],
onPress: /*Activate*/ ctx[4]
}
});
interactivefunction = new InteractiveFunction({
props: {
Activate: /*Activate*/ ctx[4],
Deactivate: /*Deactivate*/ ctx[5],
name: /*name*/ ctx[1],
active: /*active*/ ctx[3]
}
});
interactivefunction.$on("submit", /*Submit*/ ctx[6]);
interactivefunction.$on("error", /*Error*/ ctx[7]);
let if_block = /*error*/ ctx[2] && create_if_block$5(ctx);
return {
c() {
div1 = element("div");
div0 = element("div");
create_component(hotkey.$$.fragment);
t0 = space();
create_component(interactivefunction.$$.fragment);
t1 = space();
if (if_block) if_block.c();
attr(div0, "class", "wrapper svelte-smqssc");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, div0);
mount_component(hotkey, div0, null);
append(div0, t0);
mount_component(interactivefunction, div0, null);
append(div1, t1);
if (if_block) if_block.m(div1, null);
current = true;
},
p(ctx, [dirty]) {
const hotkey_changes = {};
if (dirty & /*shortcut*/ 1) hotkey_changes.value = /*shortcut*/ ctx[0];
hotkey.$set(hotkey_changes);
const interactivefunction_changes = {};
if (dirty & /*name*/ 2) interactivefunction_changes.name = /*name*/ ctx[1];
if (dirty & /*active*/ 8) interactivefunction_changes.active = /*active*/ ctx[3];
interactivefunction.$set(interactivefunction_changes);
if (/*error*/ ctx[2]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$5(ctx);
if_block.c();
if_block.m(div1, null);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
},
i(local) {
if (current) return;
transition_in(hotkey.$$.fragment, local);
transition_in(interactivefunction.$$.fragment, local);
current = true;
},
o(local) {
transition_out(hotkey.$$.fragment, local);
transition_out(interactivefunction.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div1);
destroy_component(hotkey);
destroy_component(interactivefunction);
if (if_block) if_block.d();
}
};
}
function instance$g($$self, $$props, $$invalidate) {
let { shortcut } = $$props;
let { name } = $$props;
let { fn } = $$props;
const { disableHotkeys } = getContext('hotkeys');
let error$1 = '';
let active = false;
function Activate() {
disableHotkeys.set(true);
$$invalidate(3, active = true);
}
function Deactivate() {
disableHotkeys.set(false);
$$invalidate(2, error$1 = '');
$$invalidate(3, active = false);
}
function Submit(e) {
$$invalidate(2, error$1 = '');
Deactivate();
fn.apply(this, e.detail);
}
function Error(e) {
$$invalidate(2, error$1 = e.detail);
error(e.detail);
}
$$self.$$set = $$props => {
if ('shortcut' in $$props) $$invalidate(0, shortcut = $$props.shortcut);
if ('name' in $$props) $$invalidate(1, name = $$props.name);
if ('fn' in $$props) $$invalidate(8, fn = $$props.fn);
};
return [shortcut, name, error$1, active, Activate, Deactivate, Submit, Error, fn];
}
class Move extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$g, create_fragment$g, safe_not_equal, { shortcut: 0, name: 1, fn: 8 }, add_css$a);
}
}
/* src/client/debug/main/Controls.svelte generated by Svelte v3.41.0 */
function add_css$b(target) {
append_styles(target, "svelte-c3lavh", "ul.svelte-c3lavh{padding-left:0}li.svelte-c3lavh{list-style:none;margin:none;margin-bottom:5px}");
}
function create_fragment$h(ctx) {
let ul;
let li0;
let hotkey0;
let t0;
let li1;
let hotkey1;
let t1;
let li2;
let hotkey2;
let t2;
let li3;
let hotkey3;
let current;
hotkey0 = new Hotkey({
props: {
value: "1",
onPress: /*client*/ ctx[0].reset,
label: "reset"
}
});
hotkey1 = new Hotkey({
props: {
value: "2",
onPress: /*Save*/ ctx[1],
label: "save"
}
});
hotkey2 = new Hotkey({
props: {
value: "3",
onPress: /*Restore*/ ctx[2],
label: "restore"
}
});
hotkey3 = new Hotkey({
props: { value: ".", disable: true, label: "hide" }
});
return {
c() {
ul = element("ul");
li0 = element("li");
create_component(hotkey0.$$.fragment);
t0 = space();
li1 = element("li");
create_component(hotkey1.$$.fragment);
t1 = space();
li2 = element("li");
create_component(hotkey2.$$.fragment);
t2 = space();
li3 = element("li");
create_component(hotkey3.$$.fragment);
attr(li0, "class", "svelte-c3lavh");
attr(li1, "class", "svelte-c3lavh");
attr(li2, "class", "svelte-c3lavh");
attr(li3, "class", "svelte-c3lavh");
attr(ul, "id", "debug-controls");
attr(ul, "class", "controls svelte-c3lavh");
},
m(target, anchor) {
insert(target, ul, anchor);
append(ul, li0);
mount_component(hotkey0, li0, null);
append(ul, t0);
append(ul, li1);
mount_component(hotkey1, li1, null);
append(ul, t1);
append(ul, li2);
mount_component(hotkey2, li2, null);
append(ul, t2);
append(ul, li3);
mount_component(hotkey3, li3, null);
current = true;
},
p(ctx, [dirty]) {
const hotkey0_changes = {};
if (dirty & /*client*/ 1) hotkey0_changes.onPress = /*client*/ ctx[0].reset;
hotkey0.$set(hotkey0_changes);
},
i(local) {
if (current) return;
transition_in(hotkey0.$$.fragment, local);
transition_in(hotkey1.$$.fragment, local);
transition_in(hotkey2.$$.fragment, local);
transition_in(hotkey3.$$.fragment, local);
current = true;
},
o(local) {
transition_out(hotkey0.$$.fragment, local);
transition_out(hotkey1.$$.fragment, local);
transition_out(hotkey2.$$.fragment, local);
transition_out(hotkey3.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(ul);
destroy_component(hotkey0);
destroy_component(hotkey1);
destroy_component(hotkey2);
destroy_component(hotkey3);
}
};
}
function instance$h($$self, $$props, $$invalidate) {
let { client } = $$props;
function Save() {
// get state to persist and overwrite deltalog, _undo, and _redo
const state = client.getState();
const json = stringify({
...state,
_undo: [],
_redo: [],
deltalog: []
});
window.localStorage.setItem('gamestate', json);
window.localStorage.setItem('initialState', stringify(client.initialState));
}
function Restore() {
const gamestateJSON = window.localStorage.getItem('gamestate');
const initialStateJSON = window.localStorage.getItem('initialState');
if (gamestateJSON !== null && initialStateJSON !== null) {
const gamestate = parse(gamestateJSON);
const initialState = parse(initialStateJSON);
client.store.dispatch(sync({ state: gamestate, initialState }));
}
}
$$self.$$set = $$props => {
if ('client' in $$props) $$invalidate(0, client = $$props.client);
};
return [client, Save, Restore];
}
class Controls extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$h, create_fragment$h, safe_not_equal, { client: 0 }, add_css$b);
}
}
/* src/client/debug/main/PlayerInfo.svelte generated by Svelte v3.41.0 */
function add_css$c(target) {
append_styles(target, "svelte-19aan9p", ".player-box.svelte-19aan9p{display:flex;flex-direction:row}.player.svelte-19aan9p{cursor:pointer;text-align:center;width:30px;height:30px;line-height:30px;background:#eee;border:3px solid #fefefe;box-sizing:content-box;padding:0}.player.current.svelte-19aan9p{background:#555;color:#eee;font-weight:bold}.player.active.svelte-19aan9p{border:3px solid #ff7f50}");
}
function get_each_context$4(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
return child_ctx;
}
// (59:2) {#each players as player}
function create_each_block$4(ctx) {
let button;
let t0_value = /*player*/ ctx[7] + "";
let t0;
let t1;
let button_aria_label_value;
let mounted;
let dispose;
function click_handler() {
return /*click_handler*/ ctx[5](/*player*/ ctx[7]);
}
return {
c() {
button = element("button");
t0 = text(t0_value);
t1 = space();
attr(button, "class", "player svelte-19aan9p");
attr(button, "aria-label", button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7]));
toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer);
toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, t0);
append(button, t1);
if (!mounted) {
dispose = listen(button, "click", click_handler);
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*players*/ 4 && t0_value !== (t0_value = /*player*/ ctx[7] + "")) set_data(t0, t0_value);
if (dirty & /*players*/ 4 && button_aria_label_value !== (button_aria_label_value = /*playerLabel*/ ctx[4](/*player*/ ctx[7]))) {
attr(button, "aria-label", button_aria_label_value);
}
if (dirty & /*players, ctx*/ 5) {
toggle_class(button, "current", /*player*/ ctx[7] == /*ctx*/ ctx[0].currentPlayer);
}
if (dirty & /*players, playerID*/ 6) {
toggle_class(button, "active", /*player*/ ctx[7] == /*playerID*/ ctx[1]);
}
},
d(detaching) {
if (detaching) detach(button);
mounted = false;
dispose();
}
};
}
function create_fragment$i(ctx) {
let div;
let each_value = /*players*/ ctx[2];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$4(get_each_context$4(ctx, each_value, i));
}
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "player-box svelte-19aan9p");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
},
p(ctx, [dirty]) {
if (dirty & /*playerLabel, players, ctx, playerID, OnClick*/ 31) {
each_value = /*players*/ ctx[2];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$4(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$4(child_ctx);
each_blocks[i].c();
each_blocks[i].m(div, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
}
};
}
function instance$i($$self, $$props, $$invalidate) {
let { ctx } = $$props;
let { playerID } = $$props;
const dispatch = createEventDispatcher();
function OnClick(player) {
if (player == playerID) {
dispatch("change", { playerID: null });
} else {
dispatch("change", { playerID: player });
}
}
function playerLabel(player) {
const properties = [];
if (player == ctx.currentPlayer) properties.push('current');
if (player == playerID) properties.push('active');
let label = `Player ${player}`;
if (properties.length) label += ` (${properties.join(', ')})`;
return label;
}
let players;
const click_handler = player => OnClick(player);
$$self.$$set = $$props => {
if ('ctx' in $$props) $$invalidate(0, ctx = $$props.ctx);
if ('playerID' in $$props) $$invalidate(1, playerID = $$props.playerID);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*ctx*/ 1) {
$: $$invalidate(2, players = ctx
? [...Array(ctx.numPlayers).keys()].map(i => i.toString())
: []);
}
};
return [ctx, playerID, players, OnClick, playerLabel, click_handler];
}
class PlayerInfo extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$i, create_fragment$i, safe_not_equal, { ctx: 0, playerID: 1 }, add_css$c);
}
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = it.call(o);
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
function AssignShortcuts(moveNames, blacklist) {
var shortcuts = {};
var taken = {};
var _iterator = _createForOfIteratorHelper(blacklist),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var c = _step.value;
taken[c] = true;
} // Try assigning the first char of each move as the shortcut.
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
var t = taken;
var canUseFirstChar = true;
for (var name in moveNames) {
var shortcut = name[0];
if (t[shortcut]) {
canUseFirstChar = false;
break;
}
t[shortcut] = true;
shortcuts[name] = shortcut;
}
if (canUseFirstChar) {
return shortcuts;
} // If those aren't unique, use a-z.
t = taken;
var next = 97;
shortcuts = {};
for (var _name in moveNames) {
var _shortcut = String.fromCharCode(next);
while (t[_shortcut]) {
next++;
_shortcut = String.fromCharCode(next);
}
t[_shortcut] = true;
shortcuts[_name] = _shortcut;
}
return shortcuts;
}
/* src/client/debug/main/Main.svelte generated by Svelte v3.41.0 */
function add_css$d(target) {
append_styles(target, "svelte-146sq5f", ".tree.svelte-146sq5f{--json-tree-font-family:monospace;--json-tree-font-size:14px;--json-tree-null-color:#757575}.label.svelte-146sq5f{margin-bottom:0;text-transform:none}h3.svelte-146sq5f{text-transform:uppercase}ul.svelte-146sq5f{padding-left:0}li.svelte-146sq5f{list-style:none;margin:0;margin-bottom:5px}");
}
function get_each_context$5(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[9] = list[i][0];
child_ctx[10] = list[i][1];
return child_ctx;
}
// (77:4) {#each Object.entries(moves) as [name, fn]}
function create_each_block$5(ctx) {
let li;
let move;
let t;
let current;
move = new Move({
props: {
shortcut: /*shortcuts*/ ctx[7][/*name*/ ctx[9]],
fn: /*fn*/ ctx[10],
name: /*name*/ ctx[9]
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
t = space();
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
append(li, t);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*moves*/ 8) move_changes.shortcut = /*shortcuts*/ ctx[7][/*name*/ ctx[9]];
if (dirty & /*moves*/ 8) move_changes.fn = /*fn*/ ctx[10];
if (dirty & /*moves*/ 8) move_changes.name = /*name*/ ctx[9];
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (89:2) {#if ctx.activePlayers && events.endStage}
function create_if_block_2$2(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endStage",
shortcut: 7,
fn: /*events*/ ctx[4].endStage
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endStage;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (94:2) {#if events.endTurn}
function create_if_block_1$2(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endTurn",
shortcut: 8,
fn: /*events*/ ctx[4].endTurn
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endTurn;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
// (99:2) {#if ctx.phase && events.endPhase}
function create_if_block$6(ctx) {
let li;
let move;
let current;
move = new Move({
props: {
name: "endPhase",
shortcut: 9,
fn: /*events*/ ctx[4].endPhase
}
});
return {
c() {
li = element("li");
create_component(move.$$.fragment);
attr(li, "class", "svelte-146sq5f");
},
m(target, anchor) {
insert(target, li, anchor);
mount_component(move, li, null);
current = true;
},
p(ctx, dirty) {
const move_changes = {};
if (dirty & /*events*/ 16) move_changes.fn = /*events*/ ctx[4].endPhase;
move.$set(move_changes);
},
i(local) {
if (current) return;
transition_in(move.$$.fragment, local);
current = true;
},
o(local) {
transition_out(move.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(li);
destroy_component(move);
}
};
}
function create_fragment$j(ctx) {
let section0;
let h30;
let t1;
let controls;
let t2;
let section1;
let h31;
let t4;
let playerinfo;
let t5;
let section2;
let h32;
let t7;
let ul0;
let t8;
let section3;
let h33;
let t10;
let ul1;
let t11;
let t12;
let t13;
let section4;
let h34;
let t15;
let jsontree0;
let t16;
let section5;
let h35;
let t18;
let jsontree1;
let t19;
let clientswitcher;
let current;
controls = new Controls({ props: { client: /*client*/ ctx[0] } });
playerinfo = new PlayerInfo({
props: {
ctx: /*ctx*/ ctx[5],
playerID: /*playerID*/ ctx[2]
}
});
playerinfo.$on("change", /*change_handler*/ ctx[8]);
let each_value = Object.entries(/*moves*/ ctx[3]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$5(get_each_context$5(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block0 = /*ctx*/ ctx[5].activePlayers && /*events*/ ctx[4].endStage && create_if_block_2$2(ctx);
let if_block1 = /*events*/ ctx[4].endTurn && create_if_block_1$2(ctx);
let if_block2 = /*ctx*/ ctx[5].phase && /*events*/ ctx[4].endPhase && create_if_block$6(ctx);
jsontree0 = new Root({ props: { value: /*G*/ ctx[6] } });
jsontree1 = new Root({
props: { value: SanitizeCtx(/*ctx*/ ctx[5]) }
});
clientswitcher = new ClientSwitcher({
props: { clientManager: /*clientManager*/ ctx[1] }
});
return {
c() {
section0 = element("section");
h30 = element("h3");
h30.textContent = "Controls";
t1 = space();
create_component(controls.$$.fragment);
t2 = space();
section1 = element("section");
h31 = element("h3");
h31.textContent = "Players";
t4 = space();
create_component(playerinfo.$$.fragment);
t5 = space();
section2 = element("section");
h32 = element("h3");
h32.textContent = "Moves";
t7 = space();
ul0 = element("ul");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t8 = space();
section3 = element("section");
h33 = element("h3");
h33.textContent = "Events";
t10 = space();
ul1 = element("ul");
if (if_block0) if_block0.c();
t11 = space();
if (if_block1) if_block1.c();
t12 = space();
if (if_block2) if_block2.c();
t13 = space();
section4 = element("section");
h34 = element("h3");
h34.textContent = "G";
t15 = space();
create_component(jsontree0.$$.fragment);
t16 = space();
section5 = element("section");
h35 = element("h3");
h35.textContent = "ctx";
t18 = space();
create_component(jsontree1.$$.fragment);
t19 = space();
create_component(clientswitcher.$$.fragment);
attr(h30, "class", "svelte-146sq5f");
attr(h31, "class", "svelte-146sq5f");
attr(h32, "class", "svelte-146sq5f");
attr(ul0, "class", "svelte-146sq5f");
attr(h33, "class", "svelte-146sq5f");
attr(ul1, "class", "svelte-146sq5f");
attr(h34, "class", "label svelte-146sq5f");
attr(section4, "class", "tree svelte-146sq5f");
attr(h35, "class", "label svelte-146sq5f");
attr(section5, "class", "tree svelte-146sq5f");
},
m(target, anchor) {
insert(target, section0, anchor);
append(section0, h30);
append(section0, t1);
mount_component(controls, section0, null);
insert(target, t2, anchor);
insert(target, section1, anchor);
append(section1, h31);
append(section1, t4);
mount_component(playerinfo, section1, null);
insert(target, t5, anchor);
insert(target, section2, anchor);
append(section2, h32);
append(section2, t7);
append(section2, ul0);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(ul0, null);
}
insert(target, t8, anchor);
insert(target, section3, anchor);
append(section3, h33);
append(section3, t10);
append(section3, ul1);
if (if_block0) if_block0.m(ul1, null);
append(ul1, t11);
if (if_block1) if_block1.m(ul1, null);
append(ul1, t12);
if (if_block2) if_block2.m(ul1, null);
insert(target, t13, anchor);
insert(target, section4, anchor);
append(section4, h34);
append(section4, t15);
mount_component(jsontree0, section4, null);
insert(target, t16, anchor);
insert(target, section5, anchor);
append(section5, h35);
append(section5, t18);
mount_component(jsontree1, section5, null);
insert(target, t19, anchor);
mount_component(clientswitcher, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const controls_changes = {};
if (dirty & /*client*/ 1) controls_changes.client = /*client*/ ctx[0];
controls.$set(controls_changes);
const playerinfo_changes = {};
if (dirty & /*ctx*/ 32) playerinfo_changes.ctx = /*ctx*/ ctx[5];
if (dirty & /*playerID*/ 4) playerinfo_changes.playerID = /*playerID*/ ctx[2];
playerinfo.$set(playerinfo_changes);
if (dirty & /*shortcuts, Object, moves*/ 136) {
each_value = Object.entries(/*moves*/ ctx[3]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$5(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$5(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(ul0, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*ctx*/ ctx[5].activePlayers && /*events*/ ctx[4].endStage) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*ctx, events*/ 48) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_2$2(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(ul1, t11);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
if (/*events*/ ctx[4].endTurn) {
if (if_block1) {
if_block1.p(ctx, dirty);
if (dirty & /*events*/ 16) {
transition_in(if_block1, 1);
}
} else {
if_block1 = create_if_block_1$2(ctx);
if_block1.c();
transition_in(if_block1, 1);
if_block1.m(ul1, t12);
}
} else if (if_block1) {
group_outros();
transition_out(if_block1, 1, 1, () => {
if_block1 = null;
});
check_outros();
}
if (/*ctx*/ ctx[5].phase && /*events*/ ctx[4].endPhase) {
if (if_block2) {
if_block2.p(ctx, dirty);
if (dirty & /*ctx, events*/ 48) {
transition_in(if_block2, 1);
}
} else {
if_block2 = create_if_block$6(ctx);
if_block2.c();
transition_in(if_block2, 1);
if_block2.m(ul1, null);
}
} else if (if_block2) {
group_outros();
transition_out(if_block2, 1, 1, () => {
if_block2 = null;
});
check_outros();
}
const jsontree0_changes = {};
if (dirty & /*G*/ 64) jsontree0_changes.value = /*G*/ ctx[6];
jsontree0.$set(jsontree0_changes);
const jsontree1_changes = {};
if (dirty & /*ctx*/ 32) jsontree1_changes.value = SanitizeCtx(/*ctx*/ ctx[5]);
jsontree1.$set(jsontree1_changes);
const clientswitcher_changes = {};
if (dirty & /*clientManager*/ 2) clientswitcher_changes.clientManager = /*clientManager*/ ctx[1];
clientswitcher.$set(clientswitcher_changes);
},
i(local) {
if (current) return;
transition_in(controls.$$.fragment, local);
transition_in(playerinfo.$$.fragment, local);
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
transition_in(if_block0);
transition_in(if_block1);
transition_in(if_block2);
transition_in(jsontree0.$$.fragment, local);
transition_in(jsontree1.$$.fragment, local);
transition_in(clientswitcher.$$.fragment, local);
current = true;
},
o(local) {
transition_out(controls.$$.fragment, local);
transition_out(playerinfo.$$.fragment, local);
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
transition_out(if_block0);
transition_out(if_block1);
transition_out(if_block2);
transition_out(jsontree0.$$.fragment, local);
transition_out(jsontree1.$$.fragment, local);
transition_out(clientswitcher.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(section0);
destroy_component(controls);
if (detaching) detach(t2);
if (detaching) detach(section1);
destroy_component(playerinfo);
if (detaching) detach(t5);
if (detaching) detach(section2);
destroy_each(each_blocks, detaching);
if (detaching) detach(t8);
if (detaching) detach(section3);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
if (if_block2) if_block2.d();
if (detaching) detach(t13);
if (detaching) detach(section4);
destroy_component(jsontree0);
if (detaching) detach(t16);
if (detaching) detach(section5);
destroy_component(jsontree1);
if (detaching) detach(t19);
destroy_component(clientswitcher, detaching);
}
};
}
function SanitizeCtx(ctx) {
let r = {};
for (const key in ctx) {
if (!key.startsWith('_')) {
r[key] = ctx[key];
}
}
return r;
}
function instance$j($$self, $$props, $$invalidate) {
let { client } = $$props;
let { clientManager } = $$props;
const shortcuts = AssignShortcuts(client.moves, 'mlia');
let { playerID, moves, events } = client;
let ctx = {};
let G = {};
client.subscribe(state => {
if (state) $$invalidate(6, { G, ctx } = state, G, $$invalidate(5, ctx));
$$invalidate(2, { playerID, moves, events } = client, playerID, $$invalidate(3, moves), $$invalidate(4, events));
});
const change_handler = e => clientManager.switchPlayerID(e.detail.playerID);
$$self.$$set = $$props => {
if ('client' in $$props) $$invalidate(0, client = $$props.client);
if ('clientManager' in $$props) $$invalidate(1, clientManager = $$props.clientManager);
};
return [
client,
clientManager,
playerID,
moves,
events,
ctx,
G,
shortcuts,
change_handler
];
}
class Main extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$j, create_fragment$j, safe_not_equal, { client: 0, clientManager: 1 }, add_css$d);
}
}
/* src/client/debug/info/Item.svelte generated by Svelte v3.41.0 */
function add_css$e(target) {
append_styles(target, "svelte-13qih23", ".item.svelte-13qih23.svelte-13qih23{padding:10px}.item.svelte-13qih23.svelte-13qih23:not(:first-child){border-top:1px dashed #aaa}.item.svelte-13qih23 div.svelte-13qih23{float:right;text-align:right}");
}
function create_fragment$k(ctx) {
let div1;
let strong;
let t0;
let t1;
let div0;
let t2_value = JSON.stringify(/*value*/ ctx[1]) + "";
let t2;
return {
c() {
div1 = element("div");
strong = element("strong");
t0 = text(/*name*/ ctx[0]);
t1 = space();
div0 = element("div");
t2 = text(t2_value);
attr(div0, "class", "svelte-13qih23");
attr(div1, "class", "item svelte-13qih23");
},
m(target, anchor) {
insert(target, div1, anchor);
append(div1, strong);
append(strong, t0);
append(div1, t1);
append(div1, div0);
append(div0, t2);
},
p(ctx, [dirty]) {
if (dirty & /*name*/ 1) set_data(t0, /*name*/ ctx[0]);
if (dirty & /*value*/ 2 && t2_value !== (t2_value = JSON.stringify(/*value*/ ctx[1]) + "")) set_data(t2, t2_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div1);
}
};
}
function instance$k($$self, $$props, $$invalidate) {
let { name } = $$props;
let { value } = $$props;
$$self.$$set = $$props => {
if ('name' in $$props) $$invalidate(0, name = $$props.name);
if ('value' in $$props) $$invalidate(1, value = $$props.value);
};
return [name, value];
}
class Item extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$k, create_fragment$k, safe_not_equal, { name: 0, value: 1 }, add_css$e);
}
}
/* src/client/debug/info/Info.svelte generated by Svelte v3.41.0 */
function add_css$f(target) {
append_styles(target, "svelte-1yzq5o8", ".gameinfo.svelte-1yzq5o8{padding:10px}");
}
// (18:2) {#if client.multiplayer}
function create_if_block$7(ctx) {
let item;
let current;
item = new Item({
props: {
name: "isConnected",
value: /*$client*/ ctx[1].isConnected
}
});
return {
c() {
create_component(item.$$.fragment);
},
m(target, anchor) {
mount_component(item, target, anchor);
current = true;
},
p(ctx, dirty) {
const item_changes = {};
if (dirty & /*$client*/ 2) item_changes.value = /*$client*/ ctx[1].isConnected;
item.$set(item_changes);
},
i(local) {
if (current) return;
transition_in(item.$$.fragment, local);
current = true;
},
o(local) {
transition_out(item.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(item, detaching);
}
};
}
function create_fragment$l(ctx) {
let section;
let item0;
let t0;
let item1;
let t1;
let item2;
let t2;
let current;
item0 = new Item({
props: {
name: "matchID",
value: /*client*/ ctx[0].matchID
}
});
item1 = new Item({
props: {
name: "playerID",
value: /*client*/ ctx[0].playerID
}
});
item2 = new Item({
props: {
name: "isActive",
value: /*$client*/ ctx[1].isActive
}
});
let if_block = /*client*/ ctx[0].multiplayer && create_if_block$7(ctx);
return {
c() {
section = element("section");
create_component(item0.$$.fragment);
t0 = space();
create_component(item1.$$.fragment);
t1 = space();
create_component(item2.$$.fragment);
t2 = space();
if (if_block) if_block.c();
attr(section, "class", "gameinfo svelte-1yzq5o8");
},
m(target, anchor) {
insert(target, section, anchor);
mount_component(item0, section, null);
append(section, t0);
mount_component(item1, section, null);
append(section, t1);
mount_component(item2, section, null);
append(section, t2);
if (if_block) if_block.m(section, null);
current = true;
},
p(ctx, [dirty]) {
const item0_changes = {};
if (dirty & /*client*/ 1) item0_changes.value = /*client*/ ctx[0].matchID;
item0.$set(item0_changes);
const item1_changes = {};
if (dirty & /*client*/ 1) item1_changes.value = /*client*/ ctx[0].playerID;
item1.$set(item1_changes);
const item2_changes = {};
if (dirty & /*$client*/ 2) item2_changes.value = /*$client*/ ctx[1].isActive;
item2.$set(item2_changes);
if (/*client*/ ctx[0].multiplayer) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*client*/ 1) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$7(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(section, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(item0.$$.fragment, local);
transition_in(item1.$$.fragment, local);
transition_in(item2.$$.fragment, local);
transition_in(if_block);
current = true;
},
o(local) {
transition_out(item0.$$.fragment, local);
transition_out(item1.$$.fragment, local);
transition_out(item2.$$.fragment, local);
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(item0);
destroy_component(item1);
destroy_component(item2);
if (if_block) if_block.d();
}
};
}
function instance$l($$self, $$props, $$invalidate) {
let $client,
$$unsubscribe_client = noop,
$$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(1, $client = $$value)), client);
$$self.$$.on_destroy.push(() => $$unsubscribe_client());
let { client } = $$props;
$$subscribe_client();
let { clientManager } = $$props;
$$self.$$set = $$props => {
if ('client' in $$props) $$subscribe_client($$invalidate(0, client = $$props.client));
if ('clientManager' in $$props) $$invalidate(2, clientManager = $$props.clientManager);
};
return [client, $client, clientManager];
}
class Info extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$l, create_fragment$l, safe_not_equal, { client: 0, clientManager: 2 }, add_css$f);
}
}
/* src/client/debug/log/TurnMarker.svelte generated by Svelte v3.41.0 */
function add_css$g(target) {
append_styles(target, "svelte-6eza86", ".turn-marker.svelte-6eza86{display:flex;justify-content:center;align-items:center;grid-column:1;background:#555;color:#eee;text-align:center;font-weight:bold;border:1px solid #888}");
}
function create_fragment$m(ctx) {
let div;
let t;
return {
c() {
div = element("div");
t = text(/*turn*/ ctx[0]);
attr(div, "class", "turn-marker svelte-6eza86");
attr(div, "style", /*style*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*turn*/ 1) set_data(t, /*turn*/ ctx[0]);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$m($$self, $$props, $$invalidate) {
let { turn } = $$props;
let { numEvents } = $$props;
const style = `grid-row: span ${numEvents}`;
$$self.$$set = $$props => {
if ('turn' in $$props) $$invalidate(0, turn = $$props.turn);
if ('numEvents' in $$props) $$invalidate(2, numEvents = $$props.numEvents);
};
return [turn, style, numEvents];
}
class TurnMarker extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$m, create_fragment$m, safe_not_equal, { turn: 0, numEvents: 2 }, add_css$g);
}
}
/* src/client/debug/log/PhaseMarker.svelte generated by Svelte v3.41.0 */
function add_css$h(target) {
append_styles(target, "svelte-1t4xap", ".phase-marker.svelte-1t4xap{grid-column:3;background:#555;border:1px solid #888;color:#eee;text-align:center;font-weight:bold;padding-top:10px;padding-bottom:10px;text-orientation:sideways;writing-mode:vertical-rl;line-height:30px;width:100%}");
}
function create_fragment$n(ctx) {
let div;
let t_value = (/*phase*/ ctx[0] || '') + "";
let t;
return {
c() {
div = element("div");
t = text(t_value);
attr(div, "class", "phase-marker svelte-1t4xap");
attr(div, "style", /*style*/ ctx[1]);
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*phase*/ 1 && t_value !== (t_value = (/*phase*/ ctx[0] || '') + "")) set_data(t, t_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$n($$self, $$props, $$invalidate) {
let { phase } = $$props;
let { numEvents } = $$props;
const style = `grid-row: span ${numEvents}`;
$$self.$$set = $$props => {
if ('phase' in $$props) $$invalidate(0, phase = $$props.phase);
if ('numEvents' in $$props) $$invalidate(2, numEvents = $$props.numEvents);
};
return [phase, style, numEvents];
}
class PhaseMarker extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$n, create_fragment$n, safe_not_equal, { phase: 0, numEvents: 2 }, add_css$h);
}
}
/* src/client/debug/log/LogMetadata.svelte generated by Svelte v3.41.0 */
function create_fragment$o(ctx) {
let div;
return {
c() {
div = element("div");
div.textContent = `${/*renderedMetadata*/ ctx[0]}`;
},
m(target, anchor) {
insert(target, div, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$o($$self, $$props, $$invalidate) {
let { metadata } = $$props;
const renderedMetadata = metadata !== undefined
? JSON.stringify(metadata, null, 4)
: '';
$$self.$$set = $$props => {
if ('metadata' in $$props) $$invalidate(1, metadata = $$props.metadata);
};
return [renderedMetadata, metadata];
}
class LogMetadata extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$o, create_fragment$o, safe_not_equal, { metadata: 1 });
}
}
/* src/client/debug/log/LogEvent.svelte generated by Svelte v3.41.0 */
function add_css$i(target) {
append_styles(target, "svelte-vajd9z", ".log-event.svelte-vajd9z{grid-column:2;cursor:pointer;overflow:hidden;display:flex;flex-direction:column;justify-content:center;background:#fff;border:1px dotted #ccc;border-left:5px solid #ccc;padding:5px;text-align:center;color:#666;font-size:14px;min-height:25px;line-height:25px}.log-event.svelte-vajd9z:hover,.log-event.svelte-vajd9z:focus{border-style:solid;background:#eee}.log-event.pinned.svelte-vajd9z{border-style:solid;background:#eee;opacity:1}.args.svelte-vajd9z{text-align:left;white-space:pre-wrap}.player0.svelte-vajd9z{border-left-color:#ff851b}.player1.svelte-vajd9z{border-left-color:#7fdbff}.player2.svelte-vajd9z{border-left-color:#0074d9}.player3.svelte-vajd9z{border-left-color:#39cccc}.player4.svelte-vajd9z{border-left-color:#3d9970}.player5.svelte-vajd9z{border-left-color:#2ecc40}.player6.svelte-vajd9z{border-left-color:#01ff70}.player7.svelte-vajd9z{border-left-color:#ffdc00}.player8.svelte-vajd9z{border-left-color:#001f3f}.player9.svelte-vajd9z{border-left-color:#ff4136}.player10.svelte-vajd9z{border-left-color:#85144b}.player11.svelte-vajd9z{border-left-color:#f012be}.player12.svelte-vajd9z{border-left-color:#b10dc9}.player13.svelte-vajd9z{border-left-color:#111111}.player14.svelte-vajd9z{border-left-color:#aaaaaa}.player15.svelte-vajd9z{border-left-color:#dddddd}");
}
// (146:2) {:else}
function create_else_block$1(ctx) {
let logmetadata;
let current;
logmetadata = new LogMetadata({ props: { metadata: /*metadata*/ ctx[2] } });
return {
c() {
create_component(logmetadata.$$.fragment);
},
m(target, anchor) {
mount_component(logmetadata, target, anchor);
current = true;
},
p(ctx, dirty) {
const logmetadata_changes = {};
if (dirty & /*metadata*/ 4) logmetadata_changes.metadata = /*metadata*/ ctx[2];
logmetadata.$set(logmetadata_changes);
},
i(local) {
if (current) return;
transition_in(logmetadata.$$.fragment, local);
current = true;
},
o(local) {
transition_out(logmetadata.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(logmetadata, detaching);
}
};
}
// (144:2) {#if metadataComponent}
function create_if_block$8(ctx) {
let switch_instance;
let switch_instance_anchor;
let current;
var switch_value = /*metadataComponent*/ ctx[3];
function switch_props(ctx) {
return { props: { metadata: /*metadata*/ ctx[2] } };
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
if (switch_instance) create_component(switch_instance.$$.fragment);
switch_instance_anchor = empty();
},
m(target, anchor) {
if (switch_instance) {
mount_component(switch_instance, target, anchor);
}
insert(target, switch_instance_anchor, anchor);
current = true;
},
p(ctx, dirty) {
const switch_instance_changes = {};
if (dirty & /*metadata*/ 4) switch_instance_changes.metadata = /*metadata*/ ctx[2];
if (switch_value !== (switch_value = /*metadataComponent*/ ctx[3])) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, switch_instance_anchor.parentNode, switch_instance_anchor);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(switch_instance_anchor);
if (switch_instance) destroy_component(switch_instance, detaching);
}
};
}
function create_fragment$p(ctx) {
let button;
let div;
let t0;
let t1;
let t2;
let t3;
let t4;
let current_block_type_index;
let if_block;
let button_class_value;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$8, create_else_block$1];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*metadataComponent*/ ctx[3]) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
button = element("button");
div = element("div");
t0 = text(/*actionType*/ ctx[4]);
t1 = text("(");
t2 = text(/*renderedArgs*/ ctx[6]);
t3 = text(")");
t4 = space();
if_block.c();
attr(div, "class", "args svelte-vajd9z");
attr(button, "class", button_class_value = "log-event player" + /*playerID*/ ctx[7] + " svelte-vajd9z");
toggle_class(button, "pinned", /*pinned*/ ctx[1]);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, div);
append(div, t0);
append(div, t1);
append(div, t2);
append(div, t3);
append(button, t4);
if_blocks[current_block_type_index].m(button, null);
current = true;
if (!mounted) {
dispose = [
listen(button, "click", /*click_handler*/ ctx[9]),
listen(button, "mouseenter", /*mouseenter_handler*/ ctx[10]),
listen(button, "focus", /*focus_handler*/ ctx[11]),
listen(button, "mouseleave", /*mouseleave_handler*/ ctx[12]),
listen(button, "blur", /*blur_handler*/ ctx[13])
];
mounted = true;
}
},
p(ctx, [dirty]) {
if (!current || dirty & /*actionType*/ 16) set_data(t0, /*actionType*/ ctx[4]);
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
} else {
if_block.p(ctx, dirty);
}
transition_in(if_block, 1);
if_block.m(button, null);
}
if (dirty & /*pinned*/ 2) {
toggle_class(button, "pinned", /*pinned*/ ctx[1]);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(button);
if_blocks[current_block_type_index].d();
mounted = false;
run_all(dispose);
}
};
}
function instance$p($$self, $$props, $$invalidate) {
let { logIndex } = $$props;
let { action } = $$props;
let { pinned } = $$props;
let { metadata } = $$props;
let { metadataComponent } = $$props;
const dispatch = createEventDispatcher();
const args = action.payload.args;
const renderedArgs = Array.isArray(args)
? args.map(arg => JSON.stringify(arg, null, 2)).join(',')
: JSON.stringify(args, null, 2) || '';
const playerID = action.payload.playerID;
let actionType;
switch (action.type) {
case 'UNDO':
actionType = 'undo';
break;
case 'REDO':
actionType = 'redo';
case 'GAME_EVENT':
case 'MAKE_MOVE':
default:
actionType = action.payload.type;
break;
}
const click_handler = () => dispatch('click', { logIndex });
const mouseenter_handler = () => dispatch('mouseenter', { logIndex });
const focus_handler = () => dispatch('mouseenter', { logIndex });
const mouseleave_handler = () => dispatch('mouseleave');
const blur_handler = () => dispatch('mouseleave');
$$self.$$set = $$props => {
if ('logIndex' in $$props) $$invalidate(0, logIndex = $$props.logIndex);
if ('action' in $$props) $$invalidate(8, action = $$props.action);
if ('pinned' in $$props) $$invalidate(1, pinned = $$props.pinned);
if ('metadata' in $$props) $$invalidate(2, metadata = $$props.metadata);
if ('metadataComponent' in $$props) $$invalidate(3, metadataComponent = $$props.metadataComponent);
};
return [
logIndex,
pinned,
metadata,
metadataComponent,
actionType,
dispatch,
renderedArgs,
playerID,
action,
click_handler,
mouseenter_handler,
focus_handler,
mouseleave_handler,
blur_handler
];
}
class LogEvent extends SvelteComponent {
constructor(options) {
super();
init(
this,
options,
instance$p,
create_fragment$p,
safe_not_equal,
{
logIndex: 0,
action: 8,
pinned: 1,
metadata: 2,
metadataComponent: 3
},
add_css$i
);
}
}
/* node_modules/svelte-icons/components/IconBase.svelte generated by Svelte v3.41.0 */
function add_css$j(target) {
append_styles(target, "svelte-c8tyih", "svg.svelte-c8tyih{stroke:currentColor;fill:currentColor;stroke-width:0;width:100%;height:auto;max-height:100%}");
}
// (18:2) {#if title}
function create_if_block$9(ctx) {
let title_1;
let t;
return {
c() {
title_1 = svg_element("title");
t = text(/*title*/ ctx[0]);
},
m(target, anchor) {
insert(target, title_1, anchor);
append(title_1, t);
},
p(ctx, dirty) {
if (dirty & /*title*/ 1) set_data(t, /*title*/ ctx[0]);
},
d(detaching) {
if (detaching) detach(title_1);
}
};
}
function create_fragment$q(ctx) {
let svg;
let if_block_anchor;
let current;
let if_block = /*title*/ ctx[0] && create_if_block$9(ctx);
const default_slot_template = /*#slots*/ ctx[3].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[2], null);
return {
c() {
svg = svg_element("svg");
if (if_block) if_block.c();
if_block_anchor = empty();
if (default_slot) default_slot.c();
attr(svg, "xmlns", "http://www.w3.org/2000/svg");
attr(svg, "viewBox", /*viewBox*/ ctx[1]);
attr(svg, "class", "svelte-c8tyih");
},
m(target, anchor) {
insert(target, svg, anchor);
if (if_block) if_block.m(svg, null);
append(svg, if_block_anchor);
if (default_slot) {
default_slot.m(svg, null);
}
current = true;
},
p(ctx, [dirty]) {
if (/*title*/ ctx[0]) {
if (if_block) {
if_block.p(ctx, dirty);
} else {
if_block = create_if_block$9(ctx);
if_block.c();
if_block.m(svg, if_block_anchor);
}
} else if (if_block) {
if_block.d(1);
if_block = null;
}
if (default_slot) {
if (default_slot.p && (!current || dirty & /*$$scope*/ 4)) {
update_slot_base(
default_slot,
default_slot_template,
ctx,
/*$$scope*/ ctx[2],
!current
? get_all_dirty_from_scope(/*$$scope*/ ctx[2])
: get_slot_changes(default_slot_template, /*$$scope*/ ctx[2], dirty, null),
null
);
}
}
if (!current || dirty & /*viewBox*/ 2) {
attr(svg, "viewBox", /*viewBox*/ ctx[1]);
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (detaching) detach(svg);
if (if_block) if_block.d();
if (default_slot) default_slot.d(detaching);
}
};
}
function instance$q($$self, $$props, $$invalidate) {
let { $$slots: slots = {}, $$scope } = $$props;
let { title = null } = $$props;
let { viewBox } = $$props;
$$self.$$set = $$props => {
if ('title' in $$props) $$invalidate(0, title = $$props.title);
if ('viewBox' in $$props) $$invalidate(1, viewBox = $$props.viewBox);
if ('$$scope' in $$props) $$invalidate(2, $$scope = $$props.$$scope);
};
return [title, viewBox, $$scope, slots];
}
class IconBase extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$q, create_fragment$q, safe_not_equal, { title: 0, viewBox: 1 }, add_css$j);
}
}
/* node_modules/svelte-icons/fa/FaArrowAltCircleDown.svelte generated by Svelte v3.41.0 */
function create_default_slot(ctx) {
let path;
return {
c() {
path = svg_element("path");
attr(path, "d", "M504 256c0 137-111 248-248 248S8 393 8 256 119 8 256 8s248 111 248 248zM212 140v116h-70.9c-10.7 0-16.1 13-8.5 20.5l114.9 114.3c4.7 4.7 12.2 4.7 16.9 0l114.9-114.3c7.6-7.6 2.2-20.5-8.5-20.5H300V140c0-6.6-5.4-12-12-12h-64c-6.6 0-12 5.4-12 12z");
},
m(target, anchor) {
insert(target, path, anchor);
},
d(detaching) {
if (detaching) detach(path);
}
};
}
function create_fragment$r(ctx) {
let iconbase;
let current;
const iconbase_spread_levels = [{ viewBox: "0 0 512 512" }, /*$$props*/ ctx[0]];
let iconbase_props = {
$$slots: { default: [create_default_slot] },
$$scope: { ctx }
};
for (let i = 0; i < iconbase_spread_levels.length; i += 1) {
iconbase_props = assign(iconbase_props, iconbase_spread_levels[i]);
}
iconbase = new IconBase({ props: iconbase_props });
return {
c() {
create_component(iconbase.$$.fragment);
},
m(target, anchor) {
mount_component(iconbase, target, anchor);
current = true;
},
p(ctx, [dirty]) {
const iconbase_changes = (dirty & /*$$props*/ 1)
? get_spread_update(iconbase_spread_levels, [iconbase_spread_levels[0], get_spread_object(/*$$props*/ ctx[0])])
: {};
if (dirty & /*$$scope*/ 2) {
iconbase_changes.$$scope = { dirty, ctx };
}
iconbase.$set(iconbase_changes);
},
i(local) {
if (current) return;
transition_in(iconbase.$$.fragment, local);
current = true;
},
o(local) {
transition_out(iconbase.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(iconbase, detaching);
}
};
}
function instance$r($$self, $$props, $$invalidate) {
$$self.$$set = $$new_props => {
$$invalidate(0, $$props = assign(assign({}, $$props), exclude_internal_props($$new_props)));
};
$$props = exclude_internal_props($$props);
return [$$props];
}
class FaArrowAltCircleDown extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$r, create_fragment$r, safe_not_equal, {});
}
}
/* src/client/debug/mcts/Action.svelte generated by Svelte v3.41.0 */
function add_css$k(target) {
append_styles(target, "svelte-1a7time", "div.svelte-1a7time{white-space:nowrap;text-overflow:ellipsis;overflow:hidden;max-width:500px}");
}
function create_fragment$s(ctx) {
let div;
let t;
return {
c() {
div = element("div");
t = text(/*text*/ ctx[0]);
attr(div, "alt", /*text*/ ctx[0]);
attr(div, "class", "svelte-1a7time");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, t);
},
p(ctx, [dirty]) {
if (dirty & /*text*/ 1) set_data(t, /*text*/ ctx[0]);
if (dirty & /*text*/ 1) {
attr(div, "alt", /*text*/ ctx[0]);
}
},
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(div);
}
};
}
function instance$s($$self, $$props, $$invalidate) {
let { action } = $$props;
let text;
$$self.$$set = $$props => {
if ('action' in $$props) $$invalidate(1, action = $$props.action);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*action*/ 2) {
$: {
const { type, args } = action.payload;
const argsFormatted = (args || []).join(',');
$$invalidate(0, text = `${type}(${argsFormatted})`);
}
}
};
return [text, action];
}
class Action extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$s, create_fragment$s, safe_not_equal, { action: 1 }, add_css$k);
}
}
/* src/client/debug/mcts/Table.svelte generated by Svelte v3.41.0 */
function add_css$l(target) {
append_styles(target, "svelte-ztcwsu", "table.svelte-ztcwsu.svelte-ztcwsu{font-size:12px;border-collapse:collapse;border:1px solid #ddd;padding:0}tr.svelte-ztcwsu.svelte-ztcwsu{cursor:pointer}tr.svelte-ztcwsu:hover td.svelte-ztcwsu{background:#eee}tr.selected.svelte-ztcwsu td.svelte-ztcwsu{background:#eee}td.svelte-ztcwsu.svelte-ztcwsu{padding:10px;height:10px;line-height:10px;font-size:12px;border:none}th.svelte-ztcwsu.svelte-ztcwsu{background:#888;color:#fff;padding:10px;text-align:center}");
}
function get_each_context$6(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[10] = list[i];
child_ctx[12] = i;
return child_ctx;
}
// (86:2) {#each children as child, i}
function create_each_block$6(ctx) {
let tr;
let td0;
let t0_value = /*child*/ ctx[10].value + "";
let t0;
let t1;
let td1;
let t2_value = /*child*/ ctx[10].visits + "";
let t2;
let t3;
let td2;
let action;
let t4;
let current;
let mounted;
let dispose;
action = new Action({
props: { action: /*child*/ ctx[10].parentAction }
});
function click_handler() {
return /*click_handler*/ ctx[6](/*child*/ ctx[10], /*i*/ ctx[12]);
}
function mouseout_handler() {
return /*mouseout_handler*/ ctx[7](/*i*/ ctx[12]);
}
function mouseover_handler() {
return /*mouseover_handler*/ ctx[8](/*child*/ ctx[10], /*i*/ ctx[12]);
}
return {
c() {
tr = element("tr");
td0 = element("td");
t0 = text(t0_value);
t1 = space();
td1 = element("td");
t2 = text(t2_value);
t3 = space();
td2 = element("td");
create_component(action.$$.fragment);
t4 = space();
attr(td0, "class", "svelte-ztcwsu");
attr(td1, "class", "svelte-ztcwsu");
attr(td2, "class", "svelte-ztcwsu");
attr(tr, "class", "svelte-ztcwsu");
toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0);
toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]);
},
m(target, anchor) {
insert(target, tr, anchor);
append(tr, td0);
append(td0, t0);
append(tr, t1);
append(tr, td1);
append(td1, t2);
append(tr, t3);
append(tr, td2);
mount_component(action, td2, null);
append(tr, t4);
current = true;
if (!mounted) {
dispose = [
listen(tr, "click", click_handler),
listen(tr, "mouseout", mouseout_handler),
listen(tr, "mouseover", mouseover_handler)
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if ((!current || dirty & /*children*/ 2) && t0_value !== (t0_value = /*child*/ ctx[10].value + "")) set_data(t0, t0_value);
if ((!current || dirty & /*children*/ 2) && t2_value !== (t2_value = /*child*/ ctx[10].visits + "")) set_data(t2, t2_value);
const action_changes = {};
if (dirty & /*children*/ 2) action_changes.action = /*child*/ ctx[10].parentAction;
action.$set(action_changes);
if (dirty & /*children*/ 2) {
toggle_class(tr, "clickable", /*children*/ ctx[1].length > 0);
}
if (dirty & /*selectedIndex*/ 1) {
toggle_class(tr, "selected", /*i*/ ctx[12] === /*selectedIndex*/ ctx[0]);
}
},
i(local) {
if (current) return;
transition_in(action.$$.fragment, local);
current = true;
},
o(local) {
transition_out(action.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(tr);
destroy_component(action);
mounted = false;
run_all(dispose);
}
};
}
function create_fragment$t(ctx) {
let table;
let thead;
let t5;
let tbody;
let current;
let each_value = /*children*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$6(get_each_context$6(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
table = element("table");
thead = element("thead");
thead.innerHTML = `<th class="svelte-ztcwsu">Value</th>
<th class="svelte-ztcwsu">Visits</th>
<th class="svelte-ztcwsu">Action</th>`;
t5 = space();
tbody = element("tbody");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(table, "class", "svelte-ztcwsu");
},
m(target, anchor) {
insert(target, table, anchor);
append(table, thead);
append(table, t5);
append(table, tbody);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(tbody, null);
}
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*children, selectedIndex, Select, Preview*/ 15) {
each_value = /*children*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$6(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$6(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(tbody, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(table);
destroy_each(each_blocks, detaching);
}
};
}
function instance$t($$self, $$props, $$invalidate) {
let { root } = $$props;
let { selectedIndex = null } = $$props;
const dispatch = createEventDispatcher();
let parents = [];
let children = [];
function Select(node, i) {
dispatch('select', { node, selectedIndex: i });
}
function Preview(node, i) {
if (selectedIndex === null) {
dispatch('preview', { node });
}
}
const click_handler = (child, i) => Select(child, i);
const mouseout_handler = i => Preview(null);
const mouseover_handler = (child, i) => Preview(child);
$$self.$$set = $$props => {
if ('root' in $$props) $$invalidate(4, root = $$props.root);
if ('selectedIndex' in $$props) $$invalidate(0, selectedIndex = $$props.selectedIndex);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*root, parents*/ 48) {
$: {
let t = root;
$$invalidate(5, parents = []);
while (t.parent) {
const parent = t.parent;
const { type, args } = t.parentAction.payload;
const argsFormatted = (args || []).join(',');
const arrowText = `${type}(${argsFormatted})`;
parents.push({ parent, arrowText });
t = parent;
}
parents.reverse();
$$invalidate(1, children = [...root.children].sort((a, b) => a.visits < b.visits ? 1 : -1).slice(0, 50));
}
}
};
return [
selectedIndex,
children,
Select,
Preview,
root,
parents,
click_handler,
mouseout_handler,
mouseover_handler
];
}
class Table extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$t, create_fragment$t, safe_not_equal, { root: 4, selectedIndex: 0 }, add_css$l);
}
}
/* src/client/debug/mcts/MCTS.svelte generated by Svelte v3.41.0 */
function add_css$m(target) {
append_styles(target, "svelte-1f0amz4", ".visualizer.svelte-1f0amz4{display:flex;flex-direction:column;align-items:center;padding:50px}.preview.svelte-1f0amz4{opacity:0.5}.icon.svelte-1f0amz4{color:#777;width:32px;height:32px;margin-bottom:20px}");
}
function get_each_context$7(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[9] = list[i].node;
child_ctx[10] = list[i].selectedIndex;
child_ctx[12] = i;
return child_ctx;
}
// (50:4) {#if i !== 0}
function create_if_block_2$3(ctx) {
let div;
let arrow;
let current;
arrow = new FaArrowAltCircleDown({});
return {
c() {
div = element("div");
create_component(arrow.$$.fragment);
attr(div, "class", "icon svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
mount_component(arrow, div, null);
current = true;
},
i(local) {
if (current) return;
transition_in(arrow.$$.fragment, local);
current = true;
},
o(local) {
transition_out(arrow.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_component(arrow);
}
};
}
// (61:6) {:else}
function create_else_block$2(ctx) {
let table;
let current;
function select_handler_1(...args) {
return /*select_handler_1*/ ctx[7](/*i*/ ctx[12], ...args);
}
table = new Table({
props: {
root: /*node*/ ctx[9],
selectedIndex: /*selectedIndex*/ ctx[10]
}
});
table.$on("select", select_handler_1);
return {
c() {
create_component(table.$$.fragment);
},
m(target, anchor) {
mount_component(table, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const table_changes = {};
if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9];
if (dirty & /*nodes*/ 1) table_changes.selectedIndex = /*selectedIndex*/ ctx[10];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(table, detaching);
}
};
}
// (57:6) {#if i === nodes.length - 1}
function create_if_block_1$3(ctx) {
let table;
let current;
function select_handler(...args) {
return /*select_handler*/ ctx[5](/*i*/ ctx[12], ...args);
}
function preview_handler(...args) {
return /*preview_handler*/ ctx[6](/*i*/ ctx[12], ...args);
}
table = new Table({ props: { root: /*node*/ ctx[9] } });
table.$on("select", select_handler);
table.$on("preview", preview_handler);
return {
c() {
create_component(table.$$.fragment);
},
m(target, anchor) {
mount_component(table, target, anchor);
current = true;
},
p(new_ctx, dirty) {
ctx = new_ctx;
const table_changes = {};
if (dirty & /*nodes*/ 1) table_changes.root = /*node*/ ctx[9];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(table, detaching);
}
};
}
// (49:2) {#each nodes as { node, selectedIndex }
function create_each_block$7(ctx) {
let t;
let section;
let current_block_type_index;
let if_block1;
let current;
let if_block0 = /*i*/ ctx[12] !== 0 && create_if_block_2$3();
const if_block_creators = [create_if_block_1$3, create_else_block$2];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*i*/ ctx[12] === /*nodes*/ ctx[0].length - 1) return 0;
return 1;
}
current_block_type_index = select_block_type(ctx);
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
if (if_block0) if_block0.c();
t = space();
section = element("section");
if_block1.c();
},
m(target, anchor) {
if (if_block0) if_block0.m(target, anchor);
insert(target, t, anchor);
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
},
p(ctx, dirty) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block1 = if_blocks[current_block_type_index];
if (!if_block1) {
if_block1 = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block1.c();
} else {
if_block1.p(ctx, dirty);
}
transition_in(if_block1, 1);
if_block1.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block0);
transition_in(if_block1);
current = true;
},
o(local) {
transition_out(if_block0);
transition_out(if_block1);
current = false;
},
d(detaching) {
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t);
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
}
};
}
// (69:2) {#if preview}
function create_if_block$a(ctx) {
let div;
let arrow;
let t;
let section;
let table;
let current;
arrow = new FaArrowAltCircleDown({});
table = new Table({ props: { root: /*preview*/ ctx[1] } });
return {
c() {
div = element("div");
create_component(arrow.$$.fragment);
t = space();
section = element("section");
create_component(table.$$.fragment);
attr(div, "class", "icon svelte-1f0amz4");
attr(section, "class", "preview svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
mount_component(arrow, div, null);
insert(target, t, anchor);
insert(target, section, anchor);
mount_component(table, section, null);
current = true;
},
p(ctx, dirty) {
const table_changes = {};
if (dirty & /*preview*/ 2) table_changes.root = /*preview*/ ctx[1];
table.$set(table_changes);
},
i(local) {
if (current) return;
transition_in(arrow.$$.fragment, local);
transition_in(table.$$.fragment, local);
current = true;
},
o(local) {
transition_out(arrow.$$.fragment, local);
transition_out(table.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_component(arrow);
if (detaching) detach(t);
if (detaching) detach(section);
destroy_component(table);
}
};
}
function create_fragment$u(ctx) {
let div;
let t;
let current;
let each_value = /*nodes*/ ctx[0];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$7(get_each_context$7(ctx, each_value, i));
}
const out = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
let if_block = /*preview*/ ctx[1] && create_if_block$a(ctx);
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t = space();
if (if_block) if_block.c();
attr(div, "class", "visualizer svelte-1f0amz4");
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
append(div, t);
if (if_block) if_block.m(div, null);
current = true;
},
p(ctx, [dirty]) {
if (dirty & /*nodes, SelectNode, PreviewNode*/ 13) {
each_value = /*nodes*/ ctx[0];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$7(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$7(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div, t);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out(i);
}
check_outros();
}
if (/*preview*/ ctx[1]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*preview*/ 2) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$a(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(div, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
transition_in(if_block);
current = true;
},
o(local) {
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks, detaching);
if (if_block) if_block.d();
}
};
}
function instance$u($$self, $$props, $$invalidate) {
let { metadata } = $$props;
let nodes = [];
let preview = null;
function SelectNode({ node, selectedIndex }, i) {
$$invalidate(1, preview = null);
$$invalidate(0, nodes[i].selectedIndex = selectedIndex, nodes);
$$invalidate(0, nodes = [...nodes.slice(0, i + 1), { node }]);
}
function PreviewNode({ node }, i) {
$$invalidate(1, preview = node);
}
const select_handler = (i, e) => SelectNode(e.detail, i);
const preview_handler = (i, e) => PreviewNode(e.detail);
const select_handler_1 = (i, e) => SelectNode(e.detail, i);
$$self.$$set = $$props => {
if ('metadata' in $$props) $$invalidate(4, metadata = $$props.metadata);
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*metadata*/ 16) {
$: {
$$invalidate(0, nodes = [{ node: metadata }]);
}
}
};
return [
nodes,
preview,
SelectNode,
PreviewNode,
metadata,
select_handler,
preview_handler,
select_handler_1
];
}
class MCTS extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$u, create_fragment$u, safe_not_equal, { metadata: 4 }, add_css$m);
}
}
/* src/client/debug/log/Log.svelte generated by Svelte v3.41.0 */
function add_css$n(target) {
append_styles(target, "svelte-1pq5e4b", ".gamelog.svelte-1pq5e4b{display:grid;grid-template-columns:30px 1fr 30px;grid-auto-rows:auto;grid-auto-flow:column}");
}
function get_each_context$8(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[16] = list[i].phase;
child_ctx[18] = i;
return child_ctx;
}
function get_each_context_1(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[19] = list[i].action;
child_ctx[20] = list[i].metadata;
child_ctx[18] = i;
return child_ctx;
}
function get_each_context_2(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[22] = list[i].turn;
child_ctx[18] = i;
return child_ctx;
}
// (136:4) {#if i in turnBoundaries}
function create_if_block_1$4(ctx) {
let turnmarker;
let current;
turnmarker = new TurnMarker({
props: {
turn: /*turn*/ ctx[22],
numEvents: /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]]
}
});
return {
c() {
create_component(turnmarker.$$.fragment);
},
m(target, anchor) {
mount_component(turnmarker, target, anchor);
current = true;
},
p(ctx, dirty) {
const turnmarker_changes = {};
if (dirty & /*renderedLogEntries*/ 2) turnmarker_changes.turn = /*turn*/ ctx[22];
if (dirty & /*turnBoundaries*/ 8) turnmarker_changes.numEvents = /*turnBoundaries*/ ctx[3][/*i*/ ctx[18]];
turnmarker.$set(turnmarker_changes);
},
i(local) {
if (current) return;
transition_in(turnmarker.$$.fragment, local);
current = true;
},
o(local) {
transition_out(turnmarker.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(turnmarker, detaching);
}
};
}
// (135:2) {#each renderedLogEntries as { turn }
function create_each_block_2(ctx) {
let if_block_anchor;
let current;
let if_block = /*i*/ ctx[18] in /*turnBoundaries*/ ctx[3] && create_if_block_1$4(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
if (/*i*/ ctx[18] in /*turnBoundaries*/ ctx[3]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*turnBoundaries*/ 8) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$4(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
// (141:2) {#each renderedLogEntries as { action, metadata }
function create_each_block_1(ctx) {
let logevent;
let current;
logevent = new LogEvent({
props: {
pinned: /*i*/ ctx[18] === /*pinned*/ ctx[2],
logIndex: /*i*/ ctx[18],
action: /*action*/ ctx[19],
metadata: /*metadata*/ ctx[20]
}
});
logevent.$on("click", /*OnLogClick*/ ctx[5]);
logevent.$on("mouseenter", /*OnMouseEnter*/ ctx[6]);
logevent.$on("mouseleave", /*OnMouseLeave*/ ctx[7]);
return {
c() {
create_component(logevent.$$.fragment);
},
m(target, anchor) {
mount_component(logevent, target, anchor);
current = true;
},
p(ctx, dirty) {
const logevent_changes = {};
if (dirty & /*pinned*/ 4) logevent_changes.pinned = /*i*/ ctx[18] === /*pinned*/ ctx[2];
if (dirty & /*renderedLogEntries*/ 2) logevent_changes.action = /*action*/ ctx[19];
if (dirty & /*renderedLogEntries*/ 2) logevent_changes.metadata = /*metadata*/ ctx[20];
logevent.$set(logevent_changes);
},
i(local) {
if (current) return;
transition_in(logevent.$$.fragment, local);
current = true;
},
o(local) {
transition_out(logevent.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(logevent, detaching);
}
};
}
// (153:4) {#if i in phaseBoundaries}
function create_if_block$b(ctx) {
let phasemarker;
let current;
phasemarker = new PhaseMarker({
props: {
phase: /*phase*/ ctx[16],
numEvents: /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]]
}
});
return {
c() {
create_component(phasemarker.$$.fragment);
},
m(target, anchor) {
mount_component(phasemarker, target, anchor);
current = true;
},
p(ctx, dirty) {
const phasemarker_changes = {};
if (dirty & /*renderedLogEntries*/ 2) phasemarker_changes.phase = /*phase*/ ctx[16];
if (dirty & /*phaseBoundaries*/ 16) phasemarker_changes.numEvents = /*phaseBoundaries*/ ctx[4][/*i*/ ctx[18]];
phasemarker.$set(phasemarker_changes);
},
i(local) {
if (current) return;
transition_in(phasemarker.$$.fragment, local);
current = true;
},
o(local) {
transition_out(phasemarker.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(phasemarker, detaching);
}
};
}
// (152:2) {#each renderedLogEntries as { phase }
function create_each_block$8(ctx) {
let if_block_anchor;
let current;
let if_block = /*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4] && create_if_block$b(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
},
p(ctx, dirty) {
if (/*i*/ ctx[18] in /*phaseBoundaries*/ ctx[4]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*phaseBoundaries*/ 16) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$b(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
}
};
}
function create_fragment$v(ctx) {
let div;
let t0;
let t1;
let current;
let mounted;
let dispose;
let each_value_2 = /*renderedLogEntries*/ ctx[1];
let each_blocks_2 = [];
for (let i = 0; i < each_value_2.length; i += 1) {
each_blocks_2[i] = create_each_block_2(get_each_context_2(ctx, each_value_2, i));
}
const out = i => transition_out(each_blocks_2[i], 1, 1, () => {
each_blocks_2[i] = null;
});
let each_value_1 = /*renderedLogEntries*/ ctx[1];
let each_blocks_1 = [];
for (let i = 0; i < each_value_1.length; i += 1) {
each_blocks_1[i] = create_each_block_1(get_each_context_1(ctx, each_value_1, i));
}
const out_1 = i => transition_out(each_blocks_1[i], 1, 1, () => {
each_blocks_1[i] = null;
});
let each_value = /*renderedLogEntries*/ ctx[1];
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$8(get_each_context$8(ctx, each_value, i));
}
const out_2 = i => transition_out(each_blocks[i], 1, 1, () => {
each_blocks[i] = null;
});
return {
c() {
div = element("div");
for (let i = 0; i < each_blocks_2.length; i += 1) {
each_blocks_2[i].c();
}
t0 = space();
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].c();
}
t1 = space();
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
attr(div, "class", "gamelog svelte-1pq5e4b");
toggle_class(div, "pinned", /*pinned*/ ctx[2]);
},
m(target, anchor) {
insert(target, div, anchor);
for (let i = 0; i < each_blocks_2.length; i += 1) {
each_blocks_2[i].m(div, null);
}
append(div, t0);
for (let i = 0; i < each_blocks_1.length; i += 1) {
each_blocks_1[i].m(div, null);
}
append(div, t1);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(div, null);
}
current = true;
if (!mounted) {
dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[8]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*renderedLogEntries, turnBoundaries*/ 10) {
each_value_2 = /*renderedLogEntries*/ ctx[1];
let i;
for (i = 0; i < each_value_2.length; i += 1) {
const child_ctx = get_each_context_2(ctx, each_value_2, i);
if (each_blocks_2[i]) {
each_blocks_2[i].p(child_ctx, dirty);
transition_in(each_blocks_2[i], 1);
} else {
each_blocks_2[i] = create_each_block_2(child_ctx);
each_blocks_2[i].c();
transition_in(each_blocks_2[i], 1);
each_blocks_2[i].m(div, t0);
}
}
group_outros();
for (i = each_value_2.length; i < each_blocks_2.length; i += 1) {
out(i);
}
check_outros();
}
if (dirty & /*pinned, renderedLogEntries, OnLogClick, OnMouseEnter, OnMouseLeave*/ 230) {
each_value_1 = /*renderedLogEntries*/ ctx[1];
let i;
for (i = 0; i < each_value_1.length; i += 1) {
const child_ctx = get_each_context_1(ctx, each_value_1, i);
if (each_blocks_1[i]) {
each_blocks_1[i].p(child_ctx, dirty);
transition_in(each_blocks_1[i], 1);
} else {
each_blocks_1[i] = create_each_block_1(child_ctx);
each_blocks_1[i].c();
transition_in(each_blocks_1[i], 1);
each_blocks_1[i].m(div, t1);
}
}
group_outros();
for (i = each_value_1.length; i < each_blocks_1.length; i += 1) {
out_1(i);
}
check_outros();
}
if (dirty & /*renderedLogEntries, phaseBoundaries*/ 18) {
each_value = /*renderedLogEntries*/ ctx[1];
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$8(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
transition_in(each_blocks[i], 1);
} else {
each_blocks[i] = create_each_block$8(child_ctx);
each_blocks[i].c();
transition_in(each_blocks[i], 1);
each_blocks[i].m(div, null);
}
}
group_outros();
for (i = each_value.length; i < each_blocks.length; i += 1) {
out_2(i);
}
check_outros();
}
if (dirty & /*pinned*/ 4) {
toggle_class(div, "pinned", /*pinned*/ ctx[2]);
}
},
i(local) {
if (current) return;
for (let i = 0; i < each_value_2.length; i += 1) {
transition_in(each_blocks_2[i]);
}
for (let i = 0; i < each_value_1.length; i += 1) {
transition_in(each_blocks_1[i]);
}
for (let i = 0; i < each_value.length; i += 1) {
transition_in(each_blocks[i]);
}
current = true;
},
o(local) {
each_blocks_2 = each_blocks_2.filter(Boolean);
for (let i = 0; i < each_blocks_2.length; i += 1) {
transition_out(each_blocks_2[i]);
}
each_blocks_1 = each_blocks_1.filter(Boolean);
for (let i = 0; i < each_blocks_1.length; i += 1) {
transition_out(each_blocks_1[i]);
}
each_blocks = each_blocks.filter(Boolean);
for (let i = 0; i < each_blocks.length; i += 1) {
transition_out(each_blocks[i]);
}
current = false;
},
d(detaching) {
if (detaching) detach(div);
destroy_each(each_blocks_2, detaching);
destroy_each(each_blocks_1, detaching);
destroy_each(each_blocks, detaching);
mounted = false;
dispose();
}
};
}
function instance$v($$self, $$props, $$invalidate) {
let $client,
$$unsubscribe_client = noop,
$$subscribe_client = () => ($$unsubscribe_client(), $$unsubscribe_client = subscribe(client, $$value => $$invalidate(10, $client = $$value)), client);
$$self.$$.on_destroy.push(() => $$unsubscribe_client());
let { client } = $$props;
$$subscribe_client();
const { secondaryPane } = getContext('secondaryPane');
const reducer = CreateGameReducer({ game: client.game });
const initialState = client.getInitialState();
let { log } = $client;
let pinned = null;
function rewind(logIndex) {
let state = initialState;
for (let i = 0; i < log.length; i++) {
const { action, automatic } = log[i];
if (!automatic) {
state = reducer(state, action);
if (logIndex == 0) {
break;
}
logIndex--;
}
}
return {
G: state.G,
ctx: state.ctx,
plugins: state.plugins
};
}
function OnLogClick(e) {
const { logIndex } = e.detail;
const state = rewind(logIndex);
const renderedLogEntries = log.filter(e => !e.automatic);
client.overrideGameState(state);
if (pinned == logIndex) {
$$invalidate(2, pinned = null);
secondaryPane.set(null);
} else {
$$invalidate(2, pinned = logIndex);
const { metadata } = renderedLogEntries[logIndex].action.payload;
if (metadata) {
secondaryPane.set({ component: MCTS, metadata });
}
}
}
function OnMouseEnter(e) {
const { logIndex } = e.detail;
if (pinned === null) {
const state = rewind(logIndex);
client.overrideGameState(state);
}
}
function OnMouseLeave() {
if (pinned === null) {
client.overrideGameState(null);
}
}
function Reset() {
$$invalidate(2, pinned = null);
client.overrideGameState(null);
secondaryPane.set(null);
}
onDestroy(Reset);
function OnKeyDown(e) {
// ESC.
if (e.keyCode == 27) {
Reset();
}
}
let renderedLogEntries;
let turnBoundaries = {};
let phaseBoundaries = {};
$$self.$$set = $$props => {
if ('client' in $$props) $$subscribe_client($$invalidate(0, client = $$props.client));
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$client, log, renderedLogEntries*/ 1538) {
$: {
$$invalidate(9, log = $client.log);
$$invalidate(1, renderedLogEntries = log.filter(e => !e.automatic));
let eventsInCurrentPhase = 0;
let eventsInCurrentTurn = 0;
$$invalidate(3, turnBoundaries = {});
$$invalidate(4, phaseBoundaries = {});
for (let i = 0; i < renderedLogEntries.length; i++) {
const { action, payload, turn, phase } = renderedLogEntries[i];
eventsInCurrentTurn++;
eventsInCurrentPhase++;
if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].turn != turn) {
$$invalidate(3, turnBoundaries[i] = eventsInCurrentTurn, turnBoundaries);
eventsInCurrentTurn = 0;
}
if (i == renderedLogEntries.length - 1 || renderedLogEntries[i + 1].phase != phase) {
$$invalidate(4, phaseBoundaries[i] = eventsInCurrentPhase, phaseBoundaries);
eventsInCurrentPhase = 0;
}
}
}
}
};
return [
client,
renderedLogEntries,
pinned,
turnBoundaries,
phaseBoundaries,
OnLogClick,
OnMouseEnter,
OnMouseLeave,
OnKeyDown,
log,
$client
];
}
class Log extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$v, create_fragment$v, safe_not_equal, { client: 0 }, add_css$n);
}
}
/* src/client/debug/ai/Options.svelte generated by Svelte v3.41.0 */
function add_css$o(target) {
append_styles(target, "svelte-1fu900w", "label.svelte-1fu900w{color:#666}.option.svelte-1fu900w{margin-bottom:20px}.value.svelte-1fu900w{font-weight:bold;color:#000}input[type='checkbox'].svelte-1fu900w{vertical-align:middle}");
}
function get_each_context$9(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[5] = list[i][0];
child_ctx[6] = list[i][1];
child_ctx[7] = list;
child_ctx[8] = i;
return child_ctx;
}
// (39:4) {#if value.range}
function create_if_block_1$5(ctx) {
let span;
let t0_value = /*values*/ ctx[1][/*key*/ ctx[5]] + "";
let t0;
let t1;
let input;
let input_min_value;
let input_max_value;
let mounted;
let dispose;
function input_change_input_handler() {
/*input_change_input_handler*/ ctx[3].call(input, /*key*/ ctx[5]);
}
return {
c() {
span = element("span");
t0 = text(t0_value);
t1 = space();
input = element("input");
attr(span, "class", "value svelte-1fu900w");
attr(input, "type", "range");
attr(input, "min", input_min_value = /*value*/ ctx[6].range.min);
attr(input, "max", input_max_value = /*value*/ ctx[6].range.max);
},
m(target, anchor) {
insert(target, span, anchor);
append(span, t0);
insert(target, t1, anchor);
insert(target, input, anchor);
set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[5]]);
if (!mounted) {
dispose = [
listen(input, "change", input_change_input_handler),
listen(input, "input", input_change_input_handler),
listen(input, "change", /*OnChange*/ ctx[2])
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*values, bot*/ 3 && t0_value !== (t0_value = /*values*/ ctx[1][/*key*/ ctx[5]] + "")) set_data(t0, t0_value);
if (dirty & /*bot*/ 1 && input_min_value !== (input_min_value = /*value*/ ctx[6].range.min)) {
attr(input, "min", input_min_value);
}
if (dirty & /*bot*/ 1 && input_max_value !== (input_max_value = /*value*/ ctx[6].range.max)) {
attr(input, "max", input_max_value);
}
if (dirty & /*values, Object, bot*/ 3) {
set_input_value(input, /*values*/ ctx[1][/*key*/ ctx[5]]);
}
},
d(detaching) {
if (detaching) detach(span);
if (detaching) detach(t1);
if (detaching) detach(input);
mounted = false;
run_all(dispose);
}
};
}
// (44:4) {#if typeof value.value === 'boolean'}
function create_if_block$c(ctx) {
let input;
let mounted;
let dispose;
function input_change_handler() {
/*input_change_handler*/ ctx[4].call(input, /*key*/ ctx[5]);
}
return {
c() {
input = element("input");
attr(input, "type", "checkbox");
attr(input, "class", "svelte-1fu900w");
},
m(target, anchor) {
insert(target, input, anchor);
input.checked = /*values*/ ctx[1][/*key*/ ctx[5]];
if (!mounted) {
dispose = [
listen(input, "change", input_change_handler),
listen(input, "change", /*OnChange*/ ctx[2])
];
mounted = true;
}
},
p(new_ctx, dirty) {
ctx = new_ctx;
if (dirty & /*values, Object, bot*/ 3) {
input.checked = /*values*/ ctx[1][/*key*/ ctx[5]];
}
},
d(detaching) {
if (detaching) detach(input);
mounted = false;
run_all(dispose);
}
};
}
// (35:0) {#each Object.entries(bot.opts()) as [key, value]}
function create_each_block$9(ctx) {
let div;
let label;
let t0_value = /*key*/ ctx[5] + "";
let t0;
let t1;
let t2;
let t3;
let if_block0 = /*value*/ ctx[6].range && create_if_block_1$5(ctx);
let if_block1 = typeof /*value*/ ctx[6].value === 'boolean' && create_if_block$c(ctx);
return {
c() {
div = element("div");
label = element("label");
t0 = text(t0_value);
t1 = space();
if (if_block0) if_block0.c();
t2 = space();
if (if_block1) if_block1.c();
t3 = space();
attr(label, "class", "svelte-1fu900w");
attr(div, "class", "option svelte-1fu900w");
},
m(target, anchor) {
insert(target, div, anchor);
append(div, label);
append(label, t0);
append(div, t1);
if (if_block0) if_block0.m(div, null);
append(div, t2);
if (if_block1) if_block1.m(div, null);
append(div, t3);
},
p(ctx, dirty) {
if (dirty & /*bot*/ 1 && t0_value !== (t0_value = /*key*/ ctx[5] + "")) set_data(t0, t0_value);
if (/*value*/ ctx[6].range) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_1$5(ctx);
if_block0.c();
if_block0.m(div, t2);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (typeof /*value*/ ctx[6].value === 'boolean') {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block$c(ctx);
if_block1.c();
if_block1.m(div, t3);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
d(detaching) {
if (detaching) detach(div);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
}
};
}
function create_fragment$w(ctx) {
let each_1_anchor;
let each_value = Object.entries(/*bot*/ ctx[0].opts());
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$9(get_each_context$9(ctx, each_value, i));
}
return {
c() {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
each_1_anchor = empty();
},
m(target, anchor) {
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(target, anchor);
}
insert(target, each_1_anchor, anchor);
},
p(ctx, [dirty]) {
if (dirty & /*values, Object, bot, OnChange*/ 7) {
each_value = Object.entries(/*bot*/ ctx[0].opts());
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$9(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$9(child_ctx);
each_blocks[i].c();
each_blocks[i].m(each_1_anchor.parentNode, each_1_anchor);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
},
i: noop,
o: noop,
d(detaching) {
destroy_each(each_blocks, detaching);
if (detaching) detach(each_1_anchor);
}
};
}
function instance$w($$self, $$props, $$invalidate) {
let { bot } = $$props;
let values = {};
for (let [key, value] of Object.entries(bot.opts())) {
values[key] = value.value;
}
function OnChange() {
for (let [key, value] of Object.entries(values)) {
bot.setOpt(key, value);
}
}
function input_change_input_handler(key) {
values[key] = to_number(this.value);
$$invalidate(1, values);
$$invalidate(0, bot);
}
function input_change_handler(key) {
values[key] = this.checked;
$$invalidate(1, values);
$$invalidate(0, bot);
}
$$self.$$set = $$props => {
if ('bot' in $$props) $$invalidate(0, bot = $$props.bot);
};
return [bot, values, OnChange, input_change_input_handler, input_change_handler];
}
class Options extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$w, create_fragment$w, safe_not_equal, { bot: 0 }, add_css$o);
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Base class that bots can extend.
*/
class Bot {
constructor({ enumerate, seed, }) {
this.enumerateFn = enumerate;
this.seed = seed;
this.iterationCounter = 0;
this._opts = {};
}
addOpt({ key, range, initial, }) {
this._opts[key] = {
range,
value: initial,
};
}
getOpt(key) {
return this._opts[key].value;
}
setOpt(key, value) {
if (key in this._opts) {
this._opts[key].value = value;
}
}
opts() {
return this._opts;
}
enumerate(G, ctx, playerID) {
const actions = this.enumerateFn(G, ctx, playerID);
return actions.map((a) => {
if ('payload' in a) {
return a;
}
if ('move' in a) {
return makeMove(a.move, a.args, playerID);
}
if ('event' in a) {
return gameEvent(a.event, a.args, playerID);
}
});
}
random(arg) {
let number;
if (this.seed !== undefined) {
const seed = this.prngstate ? '' : this.seed;
const rand = alea(seed, this.prngstate);
number = rand();
this.prngstate = rand.state();
}
else {
number = Math.random();
}
if (arg) {
if (Array.isArray(arg)) {
const id = Math.floor(number * arg.length);
return arg[id];
}
else {
return Math.floor(number * arg);
}
}
return number;
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* The number of iterations to run before yielding to
* the JS event loop (in async mode).
*/
const CHUNK_SIZE = 25;
/**
* Bot that uses Monte-Carlo Tree Search to find promising moves.
*/
class MCTSBot extends Bot {
constructor({ enumerate, seed, objectives, game, iterations, playoutDepth, iterationCallback, }) {
super({ enumerate, seed });
if (objectives === undefined) {
objectives = () => ({});
}
this.objectives = objectives;
this.iterationCallback = iterationCallback || (() => { });
this.reducer = CreateGameReducer({ game });
this.iterations = iterations;
this.playoutDepth = playoutDepth;
this.addOpt({
key: 'async',
initial: false,
});
this.addOpt({
key: 'iterations',
initial: typeof iterations === 'number' ? iterations : 1000,
range: { min: 1, max: 2000 },
});
this.addOpt({
key: 'playoutDepth',
initial: typeof playoutDepth === 'number' ? playoutDepth : 50,
range: { min: 1, max: 100 },
});
}
createNode({ state, parentAction, parent, playerID, }) {
const { G, ctx } = state;
let actions = [];
let objectives = [];
if (playerID !== undefined) {
actions = this.enumerate(G, ctx, playerID);
objectives = this.objectives(G, ctx, playerID);
}
else if (ctx.activePlayers) {
for (const playerID in ctx.activePlayers) {
actions.push(...this.enumerate(G, ctx, playerID));
objectives.push(this.objectives(G, ctx, playerID));
}
}
else {
actions = this.enumerate(G, ctx, ctx.currentPlayer);
objectives = this.objectives(G, ctx, ctx.currentPlayer);
}
return {
state,
parent,
parentAction,
actions,
objectives,
children: [],
visits: 0,
value: 0,
};
}
select(node) {
// This node has unvisited children.
if (node.actions.length > 0) {
return node;
}
// This is a terminal node.
if (node.children.length === 0) {
return node;
}
let selectedChild = null;
let best = 0;
for (const child of node.children) {
const childVisits = child.visits + Number.EPSILON;
const uct = child.value / childVisits +
Math.sqrt((2 * Math.log(node.visits)) / childVisits);
if (selectedChild == null || uct > best) {
best = uct;
selectedChild = child;
}
}
return this.select(selectedChild);
}
expand(node) {
const actions = node.actions;
if (actions.length === 0 || node.state.ctx.gameover !== undefined) {
return node;
}
const id = this.random(actions.length);
const action = actions[id];
node.actions.splice(id, 1);
const childState = this.reducer(node.state, action);
const childNode = this.createNode({
state: childState,
parentAction: action,
parent: node,
});
node.children.push(childNode);
return childNode;
}
playout({ state }) {
let playoutDepth = this.getOpt('playoutDepth');
if (typeof this.playoutDepth === 'function') {
playoutDepth = this.playoutDepth(state.G, state.ctx);
}
for (let i = 0; i < playoutDepth && state.ctx.gameover === undefined; i++) {
const { G, ctx } = state;
let playerID = ctx.currentPlayer;
if (ctx.activePlayers) {
playerID = Object.keys(ctx.activePlayers)[0];
}
const moves = this.enumerate(G, ctx, playerID);
// Check if any objectives are met.
const objectives = this.objectives(G, ctx, playerID);
const score = Object.keys(objectives).reduce((score, key) => {
const objective = objectives[key];
if (objective.checker(G, ctx)) {
return score + objective.weight;
}
return score;
}, 0);
// If so, stop and return the score.
if (score > 0) {
return { score };
}
if (!moves || moves.length === 0) {
return undefined;
}
const id = this.random(moves.length);
const childState = this.reducer(state, moves[id]);
state = childState;
}
return state.ctx.gameover;
}
backpropagate(node, result = {}) {
node.visits++;
if (result.score !== undefined) {
node.value += result.score;
}
if (result.draw === true) {
node.value += 0.5;
}
if (node.parentAction &&
result.winner === node.parentAction.payload.playerID) {
node.value++;
}
if (node.parent) {
this.backpropagate(node.parent, result);
}
}
play(state, playerID) {
const root = this.createNode({ state, playerID });
let numIterations = this.getOpt('iterations');
if (typeof this.iterations === 'function') {
numIterations = this.iterations(state.G, state.ctx);
}
const getResult = () => {
let selectedChild = null;
for (const child of root.children) {
if (selectedChild == null || child.visits > selectedChild.visits) {
selectedChild = child;
}
}
const action = selectedChild && selectedChild.parentAction;
const metadata = root;
return { action, metadata };
};
return new Promise((resolve) => {
const iteration = () => {
for (let i = 0; i < CHUNK_SIZE && this.iterationCounter < numIterations; i++) {
const leaf = this.select(root);
const child = this.expand(leaf);
const result = this.playout(child);
this.backpropagate(child, result);
this.iterationCounter++;
}
this.iterationCallback({
iterationCounter: this.iterationCounter,
numIterations,
metadata: root,
});
};
this.iterationCounter = 0;
if (this.getOpt('async')) {
const asyncIteration = () => {
if (this.iterationCounter < numIterations) {
iteration();
setTimeout(asyncIteration, 0);
}
else {
resolve(getResult());
}
};
asyncIteration();
}
else {
while (this.iterationCounter < numIterations) {
iteration();
}
resolve(getResult());
}
});
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Bot that picks a move at random.
*/
class RandomBot extends Bot {
play({ G, ctx }, playerID) {
const moves = this.enumerate(G, ctx, playerID);
return Promise.resolve({ action: this.random(moves) });
}
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Make a single move on the client with a bot.
*
* @param {...object} client - The game client.
* @param {...object} bot - The bot.
*/
async function Step(client, bot) {
const state = client.store.getState();
let playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
const { action, metadata } = await bot.play(state, playerID);
if (action) {
const a = {
...action,
payload: {
...action.payload,
metadata,
},
};
client.store.dispatch(a);
return a;
}
}
/**
* Simulates the game till the end or a max depth.
*
* @param {...object} game - The game object.
* @param {...object} bots - An array of bots.
* @param {...object} state - The game state to start from.
*/
async function Simulate({ game, bots, state, depth, }) {
if (depth === undefined)
depth = 10000;
const reducer = CreateGameReducer({ game });
let metadata = null;
let iter = 0;
while (state.ctx.gameover === undefined && iter < depth) {
let playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
const bot = bots instanceof Bot ? bots : bots[playerID];
const t = await bot.play(state, playerID);
if (!t.action) {
break;
}
metadata = t.metadata;
state = reducer(state, t.action);
iter++;
}
return { state, metadata };
}
/* src/client/debug/ai/AI.svelte generated by Svelte v3.41.0 */
function add_css$p(target) {
append_styles(target, "svelte-lifdi8", "ul.svelte-lifdi8{padding-left:0}li.svelte-lifdi8{list-style:none;margin:none;margin-bottom:5px}h3.svelte-lifdi8{text-transform:uppercase}label.svelte-lifdi8{color:#666}input[type='checkbox'].svelte-lifdi8{vertical-align:middle}");
}
function get_each_context$a(ctx, list, i) {
const child_ctx = ctx.slice();
child_ctx[7] = list[i];
return child_ctx;
}
// (201:4) {:else}
function create_else_block$3(ctx) {
let p0;
let t1;
let p1;
return {
c() {
p0 = element("p");
p0.textContent = "No bots available.";
t1 = space();
p1 = element("p");
p1.innerHTML = `Follow the instructions
<a href="https://boardgame.io/documentation/#/tutorial?id=bots" target="_blank">here</a>
to set up bots.`;
},
m(target, anchor) {
insert(target, p0, anchor);
insert(target, t1, anchor);
insert(target, p1, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(p0);
if (detaching) detach(t1);
if (detaching) detach(p1);
}
};
}
// (199:4) {#if client.multiplayer}
function create_if_block_5(ctx) {
let p;
return {
c() {
p = element("p");
p.textContent = "The bot debugger is only available in singleplayer mode.";
},
m(target, anchor) {
insert(target, p, anchor);
},
p: noop,
i: noop,
o: noop,
d(detaching) {
if (detaching) detach(p);
}
};
}
// (149:2) {#if client.game.ai && !client.multiplayer}
function create_if_block$d(ctx) {
let section0;
let h30;
let t1;
let ul;
let li0;
let hotkey0;
let t2;
let li1;
let hotkey1;
let t3;
let li2;
let hotkey2;
let t4;
let section1;
let h31;
let t6;
let select;
let t7;
let show_if = Object.keys(/*bot*/ ctx[7].opts()).length;
let t8;
let if_block1_anchor;
let current;
let mounted;
let dispose;
hotkey0 = new Hotkey({
props: {
value: "1",
onPress: /*Reset*/ ctx[13],
label: "reset"
}
});
hotkey1 = new Hotkey({
props: {
value: "2",
onPress: /*Step*/ ctx[11],
label: "play"
}
});
hotkey2 = new Hotkey({
props: {
value: "3",
onPress: /*Simulate*/ ctx[12],
label: "simulate"
}
});
let each_value = Object.keys(/*bots*/ ctx[8]);
let each_blocks = [];
for (let i = 0; i < each_value.length; i += 1) {
each_blocks[i] = create_each_block$a(get_each_context$a(ctx, each_value, i));
}
let if_block0 = show_if && create_if_block_4(ctx);
let if_block1 = (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) && create_if_block_1$6(ctx);
return {
c() {
section0 = element("section");
h30 = element("h3");
h30.textContent = "Controls";
t1 = space();
ul = element("ul");
li0 = element("li");
create_component(hotkey0.$$.fragment);
t2 = space();
li1 = element("li");
create_component(hotkey1.$$.fragment);
t3 = space();
li2 = element("li");
create_component(hotkey2.$$.fragment);
t4 = space();
section1 = element("section");
h31 = element("h3");
h31.textContent = "Bot";
t6 = space();
select = element("select");
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].c();
}
t7 = space();
if (if_block0) if_block0.c();
t8 = space();
if (if_block1) if_block1.c();
if_block1_anchor = empty();
attr(h30, "class", "svelte-lifdi8");
attr(li0, "class", "svelte-lifdi8");
attr(li1, "class", "svelte-lifdi8");
attr(li2, "class", "svelte-lifdi8");
attr(ul, "class", "svelte-lifdi8");
attr(h31, "class", "svelte-lifdi8");
if (/*selectedBot*/ ctx[4] === void 0) add_render_callback(() => /*select_change_handler*/ ctx[16].call(select));
},
m(target, anchor) {
insert(target, section0, anchor);
append(section0, h30);
append(section0, t1);
append(section0, ul);
append(ul, li0);
mount_component(hotkey0, li0, null);
append(ul, t2);
append(ul, li1);
mount_component(hotkey1, li1, null);
append(ul, t3);
append(ul, li2);
mount_component(hotkey2, li2, null);
insert(target, t4, anchor);
insert(target, section1, anchor);
append(section1, h31);
append(section1, t6);
append(section1, select);
for (let i = 0; i < each_blocks.length; i += 1) {
each_blocks[i].m(select, null);
}
select_option(select, /*selectedBot*/ ctx[4]);
insert(target, t7, anchor);
if (if_block0) if_block0.m(target, anchor);
insert(target, t8, anchor);
if (if_block1) if_block1.m(target, anchor);
insert(target, if_block1_anchor, anchor);
current = true;
if (!mounted) {
dispose = [
listen(select, "change", /*select_change_handler*/ ctx[16]),
listen(select, "change", /*ChangeBot*/ ctx[10])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*Object, bots*/ 256) {
each_value = Object.keys(/*bots*/ ctx[8]);
let i;
for (i = 0; i < each_value.length; i += 1) {
const child_ctx = get_each_context$a(ctx, each_value, i);
if (each_blocks[i]) {
each_blocks[i].p(child_ctx, dirty);
} else {
each_blocks[i] = create_each_block$a(child_ctx);
each_blocks[i].c();
each_blocks[i].m(select, null);
}
}
for (; i < each_blocks.length; i += 1) {
each_blocks[i].d(1);
}
each_blocks.length = each_value.length;
}
if (dirty & /*selectedBot, Object, bots*/ 272) {
select_option(select, /*selectedBot*/ ctx[4]);
}
if (dirty & /*bot*/ 128) show_if = Object.keys(/*bot*/ ctx[7].opts()).length;
if (show_if) {
if (if_block0) {
if_block0.p(ctx, dirty);
if (dirty & /*bot*/ 128) {
transition_in(if_block0, 1);
}
} else {
if_block0 = create_if_block_4(ctx);
if_block0.c();
transition_in(if_block0, 1);
if_block0.m(t8.parentNode, t8);
}
} else if (if_block0) {
group_outros();
transition_out(if_block0, 1, 1, () => {
if_block0 = null;
});
check_outros();
}
if (/*botAction*/ ctx[5] || /*iterationCounter*/ ctx[3]) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_1$6(ctx);
if_block1.c();
if_block1.m(if_block1_anchor.parentNode, if_block1_anchor);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
i(local) {
if (current) return;
transition_in(hotkey0.$$.fragment, local);
transition_in(hotkey1.$$.fragment, local);
transition_in(hotkey2.$$.fragment, local);
transition_in(if_block0);
current = true;
},
o(local) {
transition_out(hotkey0.$$.fragment, local);
transition_out(hotkey1.$$.fragment, local);
transition_out(hotkey2.$$.fragment, local);
transition_out(if_block0);
current = false;
},
d(detaching) {
if (detaching) detach(section0);
destroy_component(hotkey0);
destroy_component(hotkey1);
destroy_component(hotkey2);
if (detaching) detach(t4);
if (detaching) detach(section1);
destroy_each(each_blocks, detaching);
if (detaching) detach(t7);
if (if_block0) if_block0.d(detaching);
if (detaching) detach(t8);
if (if_block1) if_block1.d(detaching);
if (detaching) detach(if_block1_anchor);
mounted = false;
run_all(dispose);
}
};
}
// (168:8) {#each Object.keys(bots) as bot}
function create_each_block$a(ctx) {
let option;
let t_value = /*bot*/ ctx[7] + "";
let t;
let option_value_value;
return {
c() {
option = element("option");
t = text(t_value);
option.__value = option_value_value = /*bot*/ ctx[7];
option.value = option.__value;
},
m(target, anchor) {
insert(target, option, anchor);
append(option, t);
},
p: noop,
d(detaching) {
if (detaching) detach(option);
}
};
}
// (174:4) {#if Object.keys(bot.opts()).length}
function create_if_block_4(ctx) {
let section;
let h3;
let t1;
let label;
let t3;
let input;
let t4;
let options;
let current;
let mounted;
let dispose;
options = new Options({ props: { bot: /*bot*/ ctx[7] } });
return {
c() {
section = element("section");
h3 = element("h3");
h3.textContent = "Options";
t1 = space();
label = element("label");
label.textContent = "debug";
t3 = space();
input = element("input");
t4 = space();
create_component(options.$$.fragment);
attr(h3, "class", "svelte-lifdi8");
attr(label, "class", "svelte-lifdi8");
attr(input, "type", "checkbox");
attr(input, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, h3);
append(section, t1);
append(section, label);
append(section, t3);
append(section, input);
input.checked = /*debug*/ ctx[1];
append(section, t4);
mount_component(options, section, null);
current = true;
if (!mounted) {
dispose = [
listen(input, "change", /*input_change_handler*/ ctx[17]),
listen(input, "change", /*OnDebug*/ ctx[9])
];
mounted = true;
}
},
p(ctx, dirty) {
if (dirty & /*debug*/ 2) {
input.checked = /*debug*/ ctx[1];
}
const options_changes = {};
if (dirty & /*bot*/ 128) options_changes.bot = /*bot*/ ctx[7];
options.$set(options_changes);
},
i(local) {
if (current) return;
transition_in(options.$$.fragment, local);
current = true;
},
o(local) {
transition_out(options.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(options);
mounted = false;
run_all(dispose);
}
};
}
// (183:4) {#if botAction || iterationCounter}
function create_if_block_1$6(ctx) {
let section;
let h3;
let t1;
let t2;
let if_block0 = /*progress*/ ctx[2] && /*progress*/ ctx[2] < 1.0 && create_if_block_3$1(ctx);
let if_block1 = /*botAction*/ ctx[5] && create_if_block_2$4(ctx);
return {
c() {
section = element("section");
h3 = element("h3");
h3.textContent = "Result";
t1 = space();
if (if_block0) if_block0.c();
t2 = space();
if (if_block1) if_block1.c();
attr(h3, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, section, anchor);
append(section, h3);
append(section, t1);
if (if_block0) if_block0.m(section, null);
append(section, t2);
if (if_block1) if_block1.m(section, null);
},
p(ctx, dirty) {
if (/*progress*/ ctx[2] && /*progress*/ ctx[2] < 1.0) {
if (if_block0) {
if_block0.p(ctx, dirty);
} else {
if_block0 = create_if_block_3$1(ctx);
if_block0.c();
if_block0.m(section, t2);
}
} else if (if_block0) {
if_block0.d(1);
if_block0 = null;
}
if (/*botAction*/ ctx[5]) {
if (if_block1) {
if_block1.p(ctx, dirty);
} else {
if_block1 = create_if_block_2$4(ctx);
if_block1.c();
if_block1.m(section, null);
}
} else if (if_block1) {
if_block1.d(1);
if_block1 = null;
}
},
d(detaching) {
if (detaching) detach(section);
if (if_block0) if_block0.d();
if (if_block1) if_block1.d();
}
};
}
// (186:6) {#if progress && progress < 1.0}
function create_if_block_3$1(ctx) {
let progress_1;
return {
c() {
progress_1 = element("progress");
progress_1.value = /*progress*/ ctx[2];
},
m(target, anchor) {
insert(target, progress_1, anchor);
},
p(ctx, dirty) {
if (dirty & /*progress*/ 4) {
progress_1.value = /*progress*/ ctx[2];
}
},
d(detaching) {
if (detaching) detach(progress_1);
}
};
}
// (190:6) {#if botAction}
function create_if_block_2$4(ctx) {
let ul;
let li0;
let t0;
let t1;
let t2;
let li1;
let t3;
let t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + "";
let t4;
return {
c() {
ul = element("ul");
li0 = element("li");
t0 = text("Action: ");
t1 = text(/*botAction*/ ctx[5]);
t2 = space();
li1 = element("li");
t3 = text("Args: ");
t4 = text(t4_value);
attr(li0, "class", "svelte-lifdi8");
attr(li1, "class", "svelte-lifdi8");
attr(ul, "class", "svelte-lifdi8");
},
m(target, anchor) {
insert(target, ul, anchor);
append(ul, li0);
append(li0, t0);
append(li0, t1);
append(ul, t2);
append(ul, li1);
append(li1, t3);
append(li1, t4);
},
p(ctx, dirty) {
if (dirty & /*botAction*/ 32) set_data(t1, /*botAction*/ ctx[5]);
if (dirty & /*botActionArgs*/ 64 && t4_value !== (t4_value = JSON.stringify(/*botActionArgs*/ ctx[6]) + "")) set_data(t4, t4_value);
},
d(detaching) {
if (detaching) detach(ul);
}
};
}
function create_fragment$x(ctx) {
let section;
let current_block_type_index;
let if_block;
let current;
let mounted;
let dispose;
const if_block_creators = [create_if_block$d, create_if_block_5, create_else_block$3];
const if_blocks = [];
function select_block_type(ctx, dirty) {
if (/*client*/ ctx[0].game.ai && !/*client*/ ctx[0].multiplayer) return 0;
if (/*client*/ ctx[0].multiplayer) return 1;
return 2;
}
current_block_type_index = select_block_type(ctx);
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
return {
c() {
section = element("section");
if_block.c();
},
m(target, anchor) {
insert(target, section, anchor);
if_blocks[current_block_type_index].m(section, null);
current = true;
if (!mounted) {
dispose = listen(window, "keydown", /*OnKeyDown*/ ctx[14]);
mounted = true;
}
},
p(ctx, [dirty]) {
let previous_block_index = current_block_type_index;
current_block_type_index = select_block_type(ctx);
if (current_block_type_index === previous_block_index) {
if_blocks[current_block_type_index].p(ctx, dirty);
} else {
group_outros();
transition_out(if_blocks[previous_block_index], 1, 1, () => {
if_blocks[previous_block_index] = null;
});
check_outros();
if_block = if_blocks[current_block_type_index];
if (!if_block) {
if_block = if_blocks[current_block_type_index] = if_block_creators[current_block_type_index](ctx);
if_block.c();
} else {
if_block.p(ctx, dirty);
}
transition_in(if_block, 1);
if_block.m(section, null);
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (detaching) detach(section);
if_blocks[current_block_type_index].d();
mounted = false;
dispose();
}
};
}
function instance$x($$self, $$props, $$invalidate) {
let { client } = $$props;
let { clientManager } = $$props;
const { secondaryPane } = getContext('secondaryPane');
const bots = { 'MCTS': MCTSBot, 'Random': RandomBot };
let debug = false;
let progress = null;
let iterationCounter = 0;
let metadata = null;
const iterationCallback = ({ iterationCounter: c, numIterations, metadata: m }) => {
$$invalidate(3, iterationCounter = c);
$$invalidate(2, progress = c / numIterations);
metadata = m;
if (debug && metadata) {
secondaryPane.set({ component: MCTS, metadata });
}
};
function OnDebug() {
if (debug && metadata) {
secondaryPane.set({ component: MCTS, metadata });
} else {
secondaryPane.set(null);
}
}
let bot;
if (client.game.ai) {
bot = new MCTSBot({
game: client.game,
enumerate: client.game.ai.enumerate,
iterationCallback
});
bot.setOpt('async', true);
}
let selectedBot;
let botAction;
let botActionArgs;
function ChangeBot() {
const botConstructor = bots[selectedBot];
$$invalidate(7, bot = new botConstructor({
game: client.game,
enumerate: client.game.ai.enumerate,
iterationCallback
}));
bot.setOpt('async', true);
$$invalidate(5, botAction = null);
metadata = null;
secondaryPane.set(null);
$$invalidate(3, iterationCounter = 0);
}
async function Step$1() {
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
const t = await Step(client, bot);
if (t) {
$$invalidate(5, botAction = t.payload.type);
$$invalidate(6, botActionArgs = t.payload.args);
}
}
function Simulate(iterations = 10000, sleepTimeout = 100) {
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
const step = async () => {
for (let i = 0; i < iterations; i++) {
const action = await Step(client, bot);
if (!action) break;
await new Promise(resolve => setTimeout(resolve, sleepTimeout));
}
};
return step();
}
function Exit() {
client.overrideGameState(null);
secondaryPane.set(null);
$$invalidate(1, debug = false);
}
function Reset() {
client.reset();
$$invalidate(5, botAction = null);
metadata = null;
$$invalidate(3, iterationCounter = 0);
Exit();
}
function OnKeyDown(e) {
// ESC.
if (e.keyCode == 27) {
Exit();
}
}
onDestroy(Exit);
function select_change_handler() {
selectedBot = select_value(this);
$$invalidate(4, selectedBot);
$$invalidate(8, bots);
}
function input_change_handler() {
debug = this.checked;
$$invalidate(1, debug);
}
$$self.$$set = $$props => {
if ('client' in $$props) $$invalidate(0, client = $$props.client);
if ('clientManager' in $$props) $$invalidate(15, clientManager = $$props.clientManager);
};
return [
client,
debug,
progress,
iterationCounter,
selectedBot,
botAction,
botActionArgs,
bot,
bots,
OnDebug,
ChangeBot,
Step$1,
Simulate,
Reset,
OnKeyDown,
clientManager,
select_change_handler,
input_change_handler
];
}
class AI extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$x, create_fragment$x, safe_not_equal, { client: 0, clientManager: 15 }, add_css$p);
}
}
/* src/client/debug/Debug.svelte generated by Svelte v3.41.0 */
function add_css$q(target) {
append_styles(target, "svelte-1dhkl71", ".debug-panel.svelte-1dhkl71{position:fixed;color:#555;font-family:monospace;display:flex;flex-direction:row;text-align:left;right:0;top:0;height:100%;font-size:14px;box-sizing:border-box;opacity:0.9;z-index:99999}.pane.svelte-1dhkl71{flex-grow:2;overflow-x:hidden;overflow-y:scroll;background:#fefefe;padding:20px;border-left:1px solid #ccc;box-shadow:-1px 0 5px rgba(0, 0, 0, 0.2);box-sizing:border-box;width:280px}.secondary-pane.svelte-1dhkl71{background:#fefefe;overflow-y:scroll}.debug-panel.svelte-1dhkl71 button,.debug-panel.svelte-1dhkl71 select{cursor:pointer;font-size:14px;font-family:monospace}.debug-panel.svelte-1dhkl71 select{background:#eee;border:1px solid #bbb;color:#555;padding:3px;border-radius:3px}.debug-panel.svelte-1dhkl71 section{margin-bottom:20px}.debug-panel.svelte-1dhkl71 .screen-reader-only{clip:rect(0 0 0 0);clip-path:inset(50%);height:1px;overflow:hidden;position:absolute;white-space:nowrap;width:1px}");
}
// (118:0) {#if visible}
function create_if_block$e(ctx) {
let section;
let menu;
let t0;
let div;
let switch_instance;
let t1;
let section_transition;
let current;
menu = new Menu({
props: {
panes: /*panes*/ ctx[6],
pane: /*pane*/ ctx[2]
}
});
menu.$on("change", /*MenuChange*/ ctx[8]);
var switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component;
function switch_props(ctx) {
return {
props: {
client: /*client*/ ctx[4],
clientManager: /*clientManager*/ ctx[0]
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
let if_block = /*$secondaryPane*/ ctx[5] && create_if_block_1$7(ctx);
return {
c() {
section = element("section");
create_component(menu.$$.fragment);
t0 = space();
div = element("div");
if (switch_instance) create_component(switch_instance.$$.fragment);
t1 = space();
if (if_block) if_block.c();
attr(div, "class", "pane svelte-1dhkl71");
attr(div, "role", "region");
attr(div, "aria-label", /*pane*/ ctx[2]);
attr(div, "tabindex", "-1");
attr(section, "aria-label", "boardgame.io Debug Panel");
attr(section, "class", "debug-panel svelte-1dhkl71");
},
m(target, anchor) {
insert(target, section, anchor);
mount_component(menu, section, null);
append(section, t0);
append(section, div);
if (switch_instance) {
mount_component(switch_instance, div, null);
}
/*div_binding*/ ctx[11](div);
append(section, t1);
if (if_block) if_block.m(section, null);
current = true;
},
p(ctx, dirty) {
const menu_changes = {};
if (dirty & /*pane*/ 4) menu_changes.pane = /*pane*/ ctx[2];
menu.$set(menu_changes);
const switch_instance_changes = {};
if (dirty & /*client*/ 16) switch_instance_changes.client = /*client*/ ctx[4];
if (dirty & /*clientManager*/ 1) switch_instance_changes.clientManager = /*clientManager*/ ctx[0];
if (switch_value !== (switch_value = /*panes*/ ctx[6][/*pane*/ ctx[2]].component)) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, div, null);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
if (!current || dirty & /*pane*/ 4) {
attr(div, "aria-label", /*pane*/ ctx[2]);
}
if (/*$secondaryPane*/ ctx[5]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*$secondaryPane*/ 32) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block_1$7(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(section, null);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(menu.$$.fragment, local);
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
transition_in(if_block);
add_render_callback(() => {
if (!section_transition) section_transition = create_bidirectional_transition(section, fly, { x: 400 }, true);
section_transition.run(1);
});
current = true;
},
o(local) {
transition_out(menu.$$.fragment, local);
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
transition_out(if_block);
if (!section_transition) section_transition = create_bidirectional_transition(section, fly, { x: 400 }, false);
section_transition.run(0);
current = false;
},
d(detaching) {
if (detaching) detach(section);
destroy_component(menu);
if (switch_instance) destroy_component(switch_instance);
/*div_binding*/ ctx[11](null);
if (if_block) if_block.d();
if (detaching && section_transition) section_transition.end();
}
};
}
// (130:4) {#if $secondaryPane}
function create_if_block_1$7(ctx) {
let div;
let switch_instance;
let current;
var switch_value = /*$secondaryPane*/ ctx[5].component;
function switch_props(ctx) {
return {
props: {
metadata: /*$secondaryPane*/ ctx[5].metadata
}
};
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
}
return {
c() {
div = element("div");
if (switch_instance) create_component(switch_instance.$$.fragment);
attr(div, "class", "secondary-pane svelte-1dhkl71");
},
m(target, anchor) {
insert(target, div, anchor);
if (switch_instance) {
mount_component(switch_instance, div, null);
}
current = true;
},
p(ctx, dirty) {
const switch_instance_changes = {};
if (dirty & /*$secondaryPane*/ 32) switch_instance_changes.metadata = /*$secondaryPane*/ ctx[5].metadata;
if (switch_value !== (switch_value = /*$secondaryPane*/ ctx[5].component)) {
if (switch_instance) {
group_outros();
const old_component = switch_instance;
transition_out(old_component.$$.fragment, 1, 0, () => {
destroy_component(old_component, 1);
});
check_outros();
}
if (switch_value) {
switch_instance = new switch_value(switch_props(ctx));
create_component(switch_instance.$$.fragment);
transition_in(switch_instance.$$.fragment, 1);
mount_component(switch_instance, div, null);
} else {
switch_instance = null;
}
} else if (switch_value) {
switch_instance.$set(switch_instance_changes);
}
},
i(local) {
if (current) return;
if (switch_instance) transition_in(switch_instance.$$.fragment, local);
current = true;
},
o(local) {
if (switch_instance) transition_out(switch_instance.$$.fragment, local);
current = false;
},
d(detaching) {
if (detaching) detach(div);
if (switch_instance) destroy_component(switch_instance);
}
};
}
function create_fragment$y(ctx) {
let if_block_anchor;
let current;
let mounted;
let dispose;
let if_block = /*visible*/ ctx[3] && create_if_block$e(ctx);
return {
c() {
if (if_block) if_block.c();
if_block_anchor = empty();
},
m(target, anchor) {
if (if_block) if_block.m(target, anchor);
insert(target, if_block_anchor, anchor);
current = true;
if (!mounted) {
dispose = listen(window, "keypress", /*Keypress*/ ctx[9]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (/*visible*/ ctx[3]) {
if (if_block) {
if_block.p(ctx, dirty);
if (dirty & /*visible*/ 8) {
transition_in(if_block, 1);
}
} else {
if_block = create_if_block$e(ctx);
if_block.c();
transition_in(if_block, 1);
if_block.m(if_block_anchor.parentNode, if_block_anchor);
}
} else if (if_block) {
group_outros();
transition_out(if_block, 1, 1, () => {
if_block = null;
});
check_outros();
}
},
i(local) {
if (current) return;
transition_in(if_block);
current = true;
},
o(local) {
transition_out(if_block);
current = false;
},
d(detaching) {
if (if_block) if_block.d(detaching);
if (detaching) detach(if_block_anchor);
mounted = false;
dispose();
}
};
}
function instance$y($$self, $$props, $$invalidate) {
let client;
let $clientManager,
$$unsubscribe_clientManager = noop,
$$subscribe_clientManager = () => ($$unsubscribe_clientManager(), $$unsubscribe_clientManager = subscribe(clientManager, $$value => $$invalidate(10, $clientManager = $$value)), clientManager);
let $secondaryPane;
$$self.$$.on_destroy.push(() => $$unsubscribe_clientManager());
let { clientManager } = $$props;
$$subscribe_clientManager();
const panes = {
main: {
label: 'Main',
shortcut: 'm',
component: Main
},
log: {
label: 'Log',
shortcut: 'l',
component: Log
},
info: {
label: 'Info',
shortcut: 'i',
component: Info
},
ai: {
label: 'AI',
shortcut: 'a',
component: AI
}
};
const disableHotkeys = writable(false);
const secondaryPane = writable(null);
component_subscribe($$self, secondaryPane, value => $$invalidate(5, $secondaryPane = value));
setContext('hotkeys', { disableHotkeys });
setContext('secondaryPane', { secondaryPane });
let paneDiv;
let pane = 'main';
function MenuChange(e) {
$$invalidate(2, pane = e.detail);
paneDiv.focus();
}
let visible = true;
function Keypress(e) {
// Toggle debugger visibilty
if (e.key == '.') {
$$invalidate(3, visible = !visible);
return;
}
// Set displayed pane
if (!visible) return;
Object.entries(panes).forEach(([key, { shortcut }]) => {
if (e.key == shortcut) {
$$invalidate(2, pane = key);
}
});
}
function div_binding($$value) {
binding_callbacks[$$value ? 'unshift' : 'push'](() => {
paneDiv = $$value;
$$invalidate(1, paneDiv);
});
}
$$self.$$set = $$props => {
if ('clientManager' in $$props) $$subscribe_clientManager($$invalidate(0, clientManager = $$props.clientManager));
};
$$self.$$.update = () => {
if ($$self.$$.dirty & /*$clientManager*/ 1024) {
$: $$invalidate(4, client = $clientManager.client);
}
};
return [
clientManager,
paneDiv,
pane,
visible,
client,
$secondaryPane,
panes,
secondaryPane,
MenuChange,
Keypress,
$clientManager,
div_binding
];
}
class Debug extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$y, create_fragment$y, safe_not_equal, { clientManager: 0 }, add_css$q);
}
}
/**
* Class to manage boardgame.io clients and limit debug panel rendering.
*/
class ClientManager {
constructor() {
this.debugPanel = null;
this.currentClient = null;
this.clients = new Map();
this.subscribers = new Map();
}
/**
* Register a client with the client manager.
*/
register(client) {
// Add client to clients map.
this.clients.set(client, client);
// Mount debug for this client (no-op if another debug is already mounted).
this.mountDebug(client);
this.notifySubscribers();
}
/**
* Unregister a client from the client manager.
*/
unregister(client) {
// Remove client from clients map.
this.clients.delete(client);
if (this.currentClient === client) {
// If the removed client owned the debug panel, unmount it.
this.unmountDebug();
// Mount debug panel for next available client.
for (const [client] of this.clients) {
if (this.debugPanel)
break;
this.mountDebug(client);
}
}
this.notifySubscribers();
}
/**
* Subscribe to the client manager state.
* Calls the passed callback each time the current client changes or a client
* registers/unregisters.
* Returns a function to unsubscribe from the state updates.
*/
subscribe(callback) {
const id = Symbol();
this.subscribers.set(id, callback);
callback(this.getState());
return () => {
this.subscribers.delete(id);
};
}
/**
* Switch to a client with a matching playerID.
*/
switchPlayerID(playerID) {
// For multiplayer clients, try switching control to a different client
// that is using the same transport layer.
if (this.currentClient.multiplayer) {
for (const [client] of this.clients) {
if (client.playerID === playerID &&
client.debugOpt !== false &&
client.multiplayer === this.currentClient.multiplayer) {
this.switchToClient(client);
return;
}
}
}
// If no client matches, update the playerID for the current client.
this.currentClient.updatePlayerID(playerID);
this.notifySubscribers();
}
/**
* Set the passed client as the active client for debugging.
*/
switchToClient(client) {
if (client === this.currentClient)
return;
this.unmountDebug();
this.mountDebug(client);
this.notifySubscribers();
}
/**
* Notify all subscribers of changes to the client manager state.
*/
notifySubscribers() {
const arg = this.getState();
this.subscribers.forEach((cb) => {
cb(arg);
});
}
/**
* Get the client manager state.
*/
getState() {
return {
client: this.currentClient,
debuggableClients: this.getDebuggableClients(),
};
}
/**
* Get an array of the registered clients that haven’t disabled the debug panel.
*/
getDebuggableClients() {
return [...this.clients.values()].filter((client) => client.debugOpt !== false);
}
/**
* Mount the debug panel using the passed client.
*/
mountDebug(client) {
if (client.debugOpt === false ||
this.debugPanel !== null ||
typeof document === 'undefined') {
return;
}
let DebugImpl;
let target = document.body;
if (process.env.NODE_ENV !== 'production') {
DebugImpl = Debug;
}
if (client.debugOpt && client.debugOpt !== true) {
DebugImpl = client.debugOpt.impl || DebugImpl;
target = client.debugOpt.target || target;
}
if (DebugImpl) {
this.currentClient = client;
this.debugPanel = new DebugImpl({
target,
props: { clientManager: this },
});
}
}
/**
* Unmount the debug panel.
*/
unmountDebug() {
this.debugPanel.$destroy();
this.debugPanel = null;
this.currentClient = null;
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Global client manager instance that all clients register with.
*/
const GlobalClientManager = new ClientManager();
/**
* Standardise the passed playerID, using currentPlayer if appropriate.
*/
function assumedPlayerID(playerID, store, multiplayer) {
// In singleplayer mode, if the client does not have a playerID
// associated with it, we attach the currentPlayer as playerID.
if (!multiplayer && (playerID === null || playerID === undefined)) {
const state = store.getState();
playerID = state.ctx.currentPlayer;
}
return playerID;
}
/**
* createDispatchers
*
* Create action dispatcher wrappers with bound playerID and credentials
*/
function createDispatchers(storeActionType, innerActionNames, store, playerID, credentials, multiplayer) {
const dispatchers = {};
for (const name of innerActionNames) {
dispatchers[name] = (...args) => {
const action = ActionCreators[storeActionType](name, args, assumedPlayerID(playerID, store, multiplayer), credentials);
store.dispatch(action);
};
}
return dispatchers;
}
// Creates a set of dispatchers to make moves.
const createMoveDispatchers = createDispatchers.bind(null, 'makeMove');
// Creates a set of dispatchers to dispatch game flow events.
const createEventDispatchers = createDispatchers.bind(null, 'gameEvent');
// Creates a set of dispatchers to dispatch actions to plugins.
const createPluginDispatchers = createDispatchers.bind(null, 'plugin');
/**
* Implementation of Client (see below).
*/
class _ClientImpl {
constructor({ game, debug, numPlayers, multiplayer, matchID: matchID, playerID, credentials, enhancer, }) {
this.game = ProcessGameConfig(game);
this.playerID = playerID;
this.matchID = matchID;
this.credentials = credentials;
this.multiplayer = multiplayer;
this.debugOpt = debug;
this.manager = GlobalClientManager;
this.gameStateOverride = null;
this.subscribers = {};
this._running = false;
this.reducer = CreateGameReducer({
game: this.game,
isClient: multiplayer !== undefined,
});
this.initialState = null;
if (!multiplayer) {
this.initialState = InitializeGame({ game: this.game, numPlayers });
}
this.reset = () => {
this.store.dispatch(reset(this.initialState));
};
this.undo = () => {
const undo$1 = undo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials);
this.store.dispatch(undo$1);
};
this.redo = () => {
const redo$1 = redo(assumedPlayerID(this.playerID, this.store, this.multiplayer), this.credentials);
this.store.dispatch(redo$1);
};
this.log = [];
/**
* Middleware that manages the log object.
* Reducers generate deltalogs, which are log events
* that are the result of application of a single action.
* The master may also send back a deltalog or the entire
* log depending on the type of request.
* The middleware below takes care of all these cases while
* managing the log object.
*/
const LogMiddleware = (store) => (next) => (action) => {
const result = next(action);
const state = store.getState();
switch (action.type) {
case MAKE_MOVE:
case GAME_EVENT:
case UNDO:
case REDO: {
const deltalog = state.deltalog;
this.log = [...this.log, ...deltalog];
break;
}
case RESET: {
this.log = [];
break;
}
case PATCH:
case UPDATE: {
let id = -1;
if (this.log.length > 0) {
id = this.log[this.log.length - 1]._stateID;
}
let deltalog = action.deltalog || [];
// Filter out actions that are already present
// in the current log. This may occur when the
// client adds an entry to the log followed by
// the update from the master here.
deltalog = deltalog.filter((l) => l._stateID > id);
this.log = [...this.log, ...deltalog];
break;
}
case SYNC: {
this.initialState = action.initialState;
this.log = action.log || [];
break;
}
}
return result;
};
/**
* Middleware that intercepts actions and sends them to the master,
* which keeps the authoritative version of the state.
*/
const TransportMiddleware = (store) => (next) => (action) => {
const baseState = store.getState();
const result = next(action);
if (!('clientOnly' in action) &&
action.type !== STRIP_TRANSIENTS) {
this.transport.onAction(baseState, action);
}
return result;
};
/**
* Middleware that intercepts actions and invokes the subscription callback.
*/
const SubscriptionMiddleware = () => (next) => (action) => {
const result = next(action);
this.notifySubscribers();
return result;
};
const middleware = applyMiddleware(TransientHandlingMiddleware, SubscriptionMiddleware, TransportMiddleware, LogMiddleware);
enhancer =
enhancer !== undefined ? compose(middleware, enhancer) : middleware;
this.store = createStore(this.reducer, this.initialState, enhancer);
if (!multiplayer)
multiplayer = DummyTransport;
this.transport = multiplayer({
gameKey: game,
game: this.game,
store: this.store,
matchID,
playerID,
credentials,
gameName: this.game.name,
numPlayers,
});
this.createDispatchers();
this.transport.subscribeMatchData((metadata) => {
this.matchData = metadata;
this.notifySubscribers();
});
this.chatMessages = [];
this.sendChatMessage = (payload) => {
this.transport.onChatMessage(this.matchID, {
id: nanoid(7),
sender: this.playerID,
payload: payload,
});
};
this.transport.subscribeChatMessage((message) => {
this.chatMessages = [...this.chatMessages, message];
this.notifySubscribers();
});
}
notifySubscribers() {
Object.values(this.subscribers).forEach((fn) => fn(this.getState()));
}
overrideGameState(state) {
this.gameStateOverride = state;
this.notifySubscribers();
}
start() {
this.transport.connect();
this._running = true;
this.manager.register(this);
}
stop() {
this.transport.disconnect();
this._running = false;
this.manager.unregister(this);
}
subscribe(fn) {
const id = Object.keys(this.subscribers).length;
this.subscribers[id] = fn;
this.transport.subscribe(() => this.notifySubscribers());
if (this._running || !this.multiplayer) {
fn(this.getState());
}
// Return a handle that allows the caller to unsubscribe.
return () => {
delete this.subscribers[id];
};
}
getInitialState() {
return this.initialState;
}
getState() {
let state = this.store.getState();
if (this.gameStateOverride !== null) {
state = this.gameStateOverride;
}
// This is the state before a sync with the game master.
if (state === null) {
return state;
}
// isActive.
let isActive = true;
const isPlayerActive = this.game.flow.isPlayerActive(state.G, state.ctx, this.playerID);
if (this.multiplayer && !isPlayerActive) {
isActive = false;
}
if (!this.multiplayer &&
this.playerID !== null &&
this.playerID !== undefined &&
!isPlayerActive) {
isActive = false;
}
if (state.ctx.gameover !== undefined) {
isActive = false;
}
// Secrets are normally stripped on the server,
// but we also strip them here so that game developers
// can see their effects while prototyping.
// Do not strip again if this is a multiplayer game
// since the server has already stripped secret info. (issue #818)
if (!this.multiplayer) {
state = {
...state,
G: this.game.playerView(state.G, state.ctx, this.playerID),
plugins: PlayerView(state, this),
};
}
// Combine into return value.
return {
...state,
log: this.log,
isActive,
isConnected: this.transport.isConnected,
};
}
createDispatchers() {
this.moves = createMoveDispatchers(this.game.moveNames, this.store, this.playerID, this.credentials, this.multiplayer);
this.events = createEventDispatchers(this.game.flow.enabledEventNames, this.store, this.playerID, this.credentials, this.multiplayer);
this.plugins = createPluginDispatchers(this.game.pluginNames, this.store, this.playerID, this.credentials, this.multiplayer);
}
updatePlayerID(playerID) {
this.playerID = playerID;
this.createDispatchers();
this.transport.updatePlayerID(playerID);
this.notifySubscribers();
}
updateMatchID(matchID) {
this.matchID = matchID;
this.createDispatchers();
this.transport.updateMatchID(matchID);
this.notifySubscribers();
}
updateCredentials(credentials) {
this.credentials = credentials;
this.createDispatchers();
this.transport.updateCredentials(credentials);
this.notifySubscribers();
}
}
/**
* Client
*
* boardgame.io JS client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} matchID - The matchID that you want to connect to.
* @param {...object} playerID - The playerID associated with this client.
* @param {...string} credentials - The authentication credentials associated with this client.
*
* Returns:
* A JS object that provides an API to interact with the
* game by dispatching moves and events.
*/
function Client(opts) {
return new _ClientImpl(opts);
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Client
*
* boardgame.io React client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} debug - Enables the Debug UI.
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET,
* UNDO and REDO.
*/
function Client$1(opts) {
var _a;
let { game, numPlayers, loading, board, multiplayer, enhancer, debug } = opts;
// Component that is displayed before the client has synced
// with the game master.
if (loading === undefined) {
const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting...");
loading = Loading;
}
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _a = class WrappedBoard extends React.Component {
constructor(props) {
super(props);
if (debug === undefined) {
debug = props.debug;
}
this.client = Client({
game,
debug,
numPlayers,
multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
enhancer,
});
}
componentDidMount() {
this.unsubscribe = this.client.subscribe(() => this.forceUpdate());
this.client.start();
}
componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
componentDidUpdate(prevProps) {
if (this.props.matchID != prevProps.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (this.props.playerID != prevProps.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (this.props.credentials != prevProps.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
render() {
const state = this.client.getState();
if (state === null) {
return React.createElement(loading);
}
let _board = null;
if (board) {
_board = React.createElement(board, {
...state,
...this.props,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
matchID: this.client.matchID,
playerID: this.client.playerID,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
log: this.client.log,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages,
});
}
return React.createElement("div", { className: "bgio-client" }, _board);
}
},
_a.propTypes = {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string,
// Enable / disable the Debug UI.
debug: PropTypes.any,
},
_a.defaultProps = {
matchID: 'default',
playerID: null,
credentials: null,
debug: true,
},
_a;
}
var _excluded = ["matchID", "playerID"];
/**
* Client
*
* boardgame.io React Native client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React Native component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE.
*/
function Client$2(opts) {
var _class, _temp;
var game = opts.game,
numPlayers = opts.numPlayers,
board = opts.board,
multiplayer = opts.multiplayer,
enhancer = opts.enhancer;
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _temp = _class = /*#__PURE__*/function (_React$Component) {
_inherits(WrappedBoard, _React$Component);
var _super = _createSuper(WrappedBoard);
function WrappedBoard(props) {
var _this;
_classCallCheck(this, WrappedBoard);
_this = _super.call(this, props);
_this.client = Client({
game: game,
numPlayers: numPlayers,
multiplayer: multiplayer,
matchID: props.matchID,
playerID: props.playerID,
credentials: props.credentials,
debug: false,
enhancer: enhancer
});
return _this;
}
_createClass(WrappedBoard, [{
key: "componentDidMount",
value: function componentDidMount() {
var _this2 = this;
this.unsubscribe = this.client.subscribe(function () {
return _this2.forceUpdate();
});
this.client.start();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.matchID != this.props.matchID) {
this.client.updateMatchID(this.props.matchID);
}
if (prevProps.playerID != this.props.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (prevProps.credentials != this.props.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
}, {
key: "render",
value: function render() {
var _board = null;
var state = this.client.getState();
var _this$props = this.props,
matchID = _this$props.matchID,
playerID = _this$props.playerID,
rest = _objectWithoutProperties(_this$props, _excluded);
if (board) {
_board = /*#__PURE__*/React.createElement(board, _objectSpread2(_objectSpread2(_objectSpread2({}, state), rest), {}, {
matchID: matchID,
playerID: playerID,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
step: this.client.step,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
matchData: this.client.matchData,
sendChatMessage: this.client.sendChatMessage,
chatMessages: this.client.chatMessages
}));
}
return _board;
}
}]);
return WrappedBoard;
}(React.Component), _defineProperty(_class, "propTypes", {
// The ID of a game to connect to.
// Only relevant in multiplayer.
matchID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string
}), _defineProperty(_class, "defaultProps", {
matchID: 'default',
playerID: null,
credentials: null
}), _temp;
}
var Type;
(function (Type) {
Type[Type["SYNC"] = 0] = "SYNC";
Type[Type["ASYNC"] = 1] = "ASYNC";
})(Type || (Type = {}));
/**
* Type guard that checks if a storage implementation is synchronous.
*/
function isSynchronous(storageAPI) {
return storageAPI.type() === Type.SYNC;
}
class Sync {
type() {
return Type.SYNC;
}
/**
* Connect.
*/
connect() {
return;
}
/**
* Create a new match.
*
* This might just need to call setState and setMetadata in
* most implementations.
*
* However, it exists as a separate call so that the
* implementation can provision things differently when
* a match is created. For example, it might stow away the
* initial match state in a separate field for easier retrieval.
*/
/* istanbul ignore next */
createMatch(matchID, opts) {
if (this.createGame) {
console.warn('The database connector does not implement a createMatch method.', '\nUsing the deprecated createGame method instead.');
return this.createGame(matchID, opts);
}
else {
console.error('The database connector does not implement a createMatch method.');
}
}
/**
* Return all matches.
*/
/* istanbul ignore next */
listMatches(opts) {
if (this.listGames) {
console.warn('The database connector does not implement a listMatches method.', '\nUsing the deprecated listGames method instead.');
return this.listGames(opts);
}
else {
console.error('The database connector does not implement a listMatches method.');
}
}
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* InMemory data storage.
*/
class InMemory extends Sync {
/**
* Creates a new InMemory storage.
*/
constructor() {
super();
this.state = new Map();
this.initial = new Map();
this.metadata = new Map();
this.log = new Map();
}
/**
* Create a new match.
*
* @override
*/
createMatch(matchID, opts) {
this.initial.set(matchID, opts.initialState);
this.setState(matchID, opts.initialState);
this.setMetadata(matchID, opts.metadata);
}
/**
* Write the match metadata to the in-memory object.
*/
setMetadata(matchID, metadata) {
this.metadata.set(matchID, metadata);
}
/**
* Write the match state to the in-memory object.
*/
setState(matchID, state, deltalog) {
if (deltalog && deltalog.length > 0) {
const log = this.log.get(matchID) || [];
this.log.set(matchID, [...log, ...deltalog]);
}
this.state.set(matchID, state);
}
/**
* Fetches state for a particular matchID.
*/
fetch(matchID, opts) {
const result = {};
if (opts.state) {
result.state = this.state.get(matchID);
}
if (opts.metadata) {
result.metadata = this.metadata.get(matchID);
}
if (opts.log) {
result.log = this.log.get(matchID) || [];
}
if (opts.initialState) {
result.initialState = this.initial.get(matchID);
}
return result;
}
/**
* Remove the match state from the in-memory object.
*/
wipe(matchID) {
this.state.delete(matchID);
this.metadata.delete(matchID);
}
/**
* Return all keys.
*
* @override
*/
listMatches(opts) {
return [...this.metadata.entries()]
.filter(([, metadata]) => {
if (!opts) {
return true;
}
if (opts.gameName !== undefined &&
metadata.gameName !== opts.gameName) {
return false;
}
if (opts.where !== undefined) {
if (opts.where.isGameover !== undefined) {
const isGameover = metadata.gameover !== undefined;
if (isGameover !== opts.where.isGameover) {
return false;
}
}
if (opts.where.updatedBefore !== undefined &&
metadata.updatedAt >= opts.where.updatedBefore) {
return false;
}
if (opts.where.updatedAfter !== undefined &&
metadata.updatedAt <= opts.where.updatedAfter) {
return false;
}
}
return true;
})
.map(([key]) => key);
}
}
class WithLocalStorageMap extends Map {
constructor(key) {
super();
this.key = key;
const cache = JSON.parse(localStorage.getItem(this.key)) || [];
cache.forEach((entry) => this.set(...entry));
}
sync() {
const entries = [...this.entries()];
localStorage.setItem(this.key, JSON.stringify(entries));
}
set(key, value) {
super.set(key, value);
this.sync();
return this;
}
delete(key) {
const result = super.delete(key);
this.sync();
return result;
}
}
/**
* locaStorage data storage.
*/
class LocalStorage extends InMemory {
constructor(storagePrefix = 'bgio') {
super();
const StorageMap = (stateKey) => new WithLocalStorageMap(`${storagePrefix}_${stateKey}`);
this.state = StorageMap('state');
this.initial = StorageMap('initial');
this.metadata = StorageMap('metadata');
this.log = StorageMap('log');
}
}
/**
* Creates a new match metadata object.
*/
const createMetadata = ({ game, unlisted, setupData, numPlayers, }) => {
const metadata = {
gameName: game.name,
unlisted: !!unlisted,
players: {},
createdAt: Date.now(),
updatedAt: Date.now(),
};
if (setupData !== undefined)
metadata.setupData = setupData;
for (let playerIndex = 0; playerIndex < numPlayers; playerIndex++) {
metadata.players[playerIndex] = { id: playerIndex };
}
return metadata;
};
/**
* Creates matchID, initial state and metadata for a new match.
* If the provided `setupData` doesn’t pass the game’s validation,
* an error object is returned instead.
*/
const createMatch = ({ game, numPlayers, setupData, unlisted, }) => {
if (!numPlayers || typeof numPlayers !== 'number')
numPlayers = 2;
const setupDataError = game.validateSetupData && game.validateSetupData(setupData, numPlayers);
if (setupDataError !== undefined)
return { setupDataError };
const metadata = createMetadata({ game, numPlayers, setupData, unlisted });
const initialState = InitializeGame({ game, numPlayers, setupData });
return { metadata, initialState };
};
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Filter match data to get a player metadata object with credentials stripped.
*/
const filterMatchData = (matchData) => Object.values(matchData.players).map((player) => {
const { credentials, ...filteredData } = player;
return filteredData;
});
/**
* Remove player credentials from action payload
*/
const stripCredentialsFromAction = (action) => {
const { credentials, ...payload } = action.payload;
return { ...action, payload };
};
/**
* Master
*
* Class that runs the game and maintains the authoritative state.
* It uses the transportAPI to communicate with clients and the
* storageAPI to communicate with the database.
*/
class Master {
constructor(game, storageAPI, transportAPI, auth) {
this.game = ProcessGameConfig(game);
this.storageAPI = storageAPI;
this.transportAPI = transportAPI;
this.subscribeCallback = () => { };
this.auth = auth;
}
subscribe(fn) {
this.subscribeCallback = fn;
}
/**
* Called on each move / event made by the client.
* Computes the new value of the game state and returns it
* along with a deltalog.
*/
async onUpdate(credAction, stateID, matchID, playerID) {
if (!credAction || !credAction.payload) {
return { error: 'missing action or action payload' };
}
let metadata;
if (isSynchronous(this.storageAPI)) {
({ metadata } = this.storageAPI.fetch(matchID, { metadata: true }));
}
else {
({ metadata } = await this.storageAPI.fetch(matchID, { metadata: true }));
}
if (this.auth) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials: credAction.payload.credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized action' };
}
}
const action = stripCredentialsFromAction(credAction);
const key = matchID;
let state;
if (isSynchronous(this.storageAPI)) {
({ state } = this.storageAPI.fetch(key, { state: true }));
}
else {
({ state } = await this.storageAPI.fetch(key, { state: true }));
}
if (state === undefined) {
error(`game not found, matchID=[${key}]`);
return { error: 'game not found' };
}
if (state.ctx.gameover !== undefined) {
error(`game over - matchID=[${key}] - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
const reducer = CreateGameReducer({
game: this.game,
});
const middleware = applyMiddleware(TransientHandlingMiddleware);
const store = createStore(reducer, state, middleware);
// Only allow UNDO / REDO if there is exactly one player
// that can make moves right now and the person doing the
// action is that player.
if (action.type == UNDO || action.type == REDO) {
const hasActivePlayers = state.ctx.activePlayers !== null;
const isCurrentPlayer = state.ctx.currentPlayer === playerID;
if (
// If activePlayers is empty, non-current players can’t undo.
(!hasActivePlayers && !isCurrentPlayer) ||
// If player is not active or multiple players are active, can’t undo.
(hasActivePlayers &&
(state.ctx.activePlayers[playerID] === undefined ||
Object.keys(state.ctx.activePlayers).length > 1))) {
error(`playerID=[${playerID}] cannot undo / redo right now`);
return;
}
}
// Check whether the player is active.
if (!this.game.flow.isPlayerActive(state.G, state.ctx, playerID)) {
error(`player not active - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
// Get move for further checks
const move = action.type == MAKE_MOVE
? this.game.flow.getMove(state.ctx, action.payload.type, playerID)
: null;
// Check whether the player is allowed to make the move.
if (action.type == MAKE_MOVE && !move) {
error(`move not processed - canPlayerMakeMove=false - playerID=[${playerID}]` +
` - action[${action.payload.type}]`);
return;
}
// Check if action's stateID is different than store's stateID
// and if move does not have ignoreStaleStateID truthy.
if (state._stateID !== stateID &&
!(move && IsLongFormMove(move) && move.ignoreStaleStateID)) {
error(`invalid stateID, was=[${stateID}], expected=[${state._stateID}]` +
` - playerID=[${playerID}] - action[${action.payload.type}]`);
return;
}
const prevState = store.getState();
// Update server's version of the store.
store.dispatch(action);
state = store.getState();
this.subscribeCallback({
state,
action,
matchID,
});
if (this.game.deltaState) {
this.transportAPI.sendAll({
type: 'patch',
args: [matchID, stateID, prevState, state],
});
}
else {
this.transportAPI.sendAll({
type: 'update',
args: [matchID, state],
});
}
const { deltalog, ...stateWithoutDeltalog } = state;
let newMetadata;
if (metadata && !('gameover' in metadata)) {
newMetadata = {
...metadata,
updatedAt: Date.now(),
};
if (state.ctx.gameover !== undefined) {
newMetadata.gameover = state.ctx.gameover;
}
}
if (isSynchronous(this.storageAPI)) {
this.storageAPI.setState(key, stateWithoutDeltalog, deltalog);
if (newMetadata)
this.storageAPI.setMetadata(key, newMetadata);
}
else {
const writes = [
this.storageAPI.setState(key, stateWithoutDeltalog, deltalog),
];
if (newMetadata) {
writes.push(this.storageAPI.setMetadata(key, newMetadata));
}
await Promise.all(writes);
}
}
/**
* Called when the client connects / reconnects.
* Returns the latest game state and the entire log.
*/
async onSync(matchID, playerID, credentials, numPlayers = 2) {
const key = matchID;
const fetchOpts = {
state: true,
metadata: true,
log: true,
initialState: true,
};
const fetchResult = isSynchronous(this.storageAPI)
? this.storageAPI.fetch(key, fetchOpts)
: await this.storageAPI.fetch(key, fetchOpts);
let { state, initialState, log, metadata } = fetchResult;
if (this.auth && playerID !== undefined && playerID !== null) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
// If the game doesn't exist, then create one on demand.
// TODO: Move this out of the sync call.
if (state === undefined) {
const match = createMatch({
game: this.game,
unlisted: true,
numPlayers,
setupData: undefined,
});
if ('setupDataError' in match) {
return { error: 'game requires setupData' };
}
initialState = state = match.initialState;
metadata = match.metadata;
this.subscribeCallback({ state, matchID });
if (isSynchronous(this.storageAPI)) {
this.storageAPI.createMatch(key, { initialState, metadata });
}
else {
await this.storageAPI.createMatch(key, { initialState, metadata });
}
}
const filteredMetadata = metadata ? filterMatchData(metadata) : undefined;
const syncInfo = {
state,
log,
filteredMetadata,
initialState,
};
this.transportAPI.send({
playerID,
type: 'sync',
args: [matchID, syncInfo],
});
return;
}
/**
* Called when a client connects or disconnects.
* Updates and sends out metadata to reflect the player’s connection status.
*/
async onConnectionChange(matchID, playerID, credentials, connected) {
const key = matchID;
// Ignore changes for clients without a playerID, e.g. spectators.
if (playerID === undefined || playerID === null) {
return;
}
let metadata;
if (isSynchronous(this.storageAPI)) {
({ metadata } = this.storageAPI.fetch(key, { metadata: true }));
}
else {
({ metadata } = await this.storageAPI.fetch(key, { metadata: true }));
}
if (metadata === undefined) {
error(`metadata not found for matchID=[${key}]`);
return { error: 'metadata not found' };
}
if (metadata.players[playerID] === undefined) {
error(`Player not in the match, matchID=[${key}] playerID=[${playerID}]`);
return { error: 'player not in the match' };
}
if (this.auth) {
const isAuthentic = await this.auth.authenticateCredentials({
playerID,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
metadata.players[playerID].isConnected = connected;
const filteredMetadata = filterMatchData(metadata);
this.transportAPI.sendAll({
type: 'matchData',
args: [matchID, filteredMetadata],
});
if (isSynchronous(this.storageAPI)) {
this.storageAPI.setMetadata(key, metadata);
}
else {
await this.storageAPI.setMetadata(key, metadata);
}
}
async onChatMessage(matchID, chatMessage, credentials) {
const key = matchID;
if (this.auth) {
const { metadata } = await this.storageAPI.fetch(key, {
metadata: true,
});
const isAuthentic = await this.auth.authenticateCredentials({
playerID: chatMessage.sender,
credentials,
metadata,
});
if (!isAuthentic) {
return { error: 'unauthorized' };
}
}
this.transportAPI.sendAll({
type: 'chat',
args: [matchID, chatMessage],
});
}
}
const applyPlayerView = (game, playerID, state) => ({
...state,
G: game.playerView(state.G, state.ctx, playerID),
plugins: PlayerView(state, { playerID, game }),
deltalog: undefined,
_undo: [],
_redo: [],
});
/** Gets a function that filters the TransportData for a given player and game. */
const getFilterPlayerView = (game) => (playerID, payload) => {
switch (payload.type) {
case 'patch': {
const [matchID, stateID, prevState, state] = payload.args;
const log = redactLog(state.deltalog, playerID);
const filteredState = applyPlayerView(game, playerID, state);
const newStateID = state._stateID;
const prevFilteredState = applyPlayerView(game, playerID, prevState);
const patch = createPatch(prevFilteredState, filteredState);
return {
type: 'patch',
args: [matchID, stateID, newStateID, patch, log],
};
}
case 'update': {
const [matchID, state] = payload.args;
const log = redactLog(state.deltalog, playerID);
const filteredState = applyPlayerView(game, playerID, state);
return {
type: 'update',
args: [matchID, filteredState, log],
};
}
case 'sync': {
const [matchID, syncInfo] = payload.args;
const filteredState = applyPlayerView(game, playerID, syncInfo.state);
const log = redactLog(syncInfo.log, playerID);
const newSyncInfo = {
...syncInfo,
state: filteredState,
log,
};
return {
type: 'sync',
args: [matchID, newSyncInfo],
};
}
default: {
return payload;
}
}
};
/**
* Redact the log.
*
* @param {Array} log - The game log (or deltalog).
* @param {String} playerID - The playerID that this log is
* to be sent to.
*/
function redactLog(log, playerID) {
if (log === undefined) {
return log;
}
return log.map((logEvent) => {
// filter for all other players and spectators.
if (playerID !== null && +playerID === +logEvent.action.payload.playerID) {
return logEvent;
}
if (logEvent.redact !== true) {
return logEvent;
}
const payload = {
...logEvent.action.payload,
args: null,
};
const filteredEvent = {
...logEvent,
action: { ...logEvent.action, payload },
};
const { redact, ...remaining } = filteredEvent;
return remaining;
});
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Returns null if it is not a bot's turn.
* Otherwise, returns a playerID of a bot that may play now.
*/
function GetBotPlayer(state, bots) {
if (state.ctx.gameover !== undefined) {
return null;
}
if (state.ctx.activePlayers) {
for (const key of Object.keys(bots)) {
if (key in state.ctx.activePlayers) {
return key;
}
}
}
else if (state.ctx.currentPlayer in bots) {
return state.ctx.currentPlayer;
}
return null;
}
/**
* Creates a local version of the master that the client
* can interact with.
*/
class LocalMaster extends Master {
constructor({ game, bots, storageKey, persist }) {
const clientCallbacks = {};
const initializedBots = {};
if (game && game.ai && bots) {
for (const playerID in bots) {
const bot = bots[playerID];
initializedBots[playerID] = new bot({
game,
enumerate: game.ai.enumerate,
seed: game.seed,
});
}
}
const send = ({ playerID, ...data }) => {
const callback = clientCallbacks[playerID];
if (callback !== undefined) {
callback(filterPlayerView(playerID, data));
}
};
const filterPlayerView = getFilterPlayerView(game);
const transportAPI = {
send,
sendAll: (payload) => {
for (const playerID in clientCallbacks) {
send({ playerID, ...payload });
}
},
};
const storage = persist ? new LocalStorage(storageKey) : new InMemory();
super(game, storage, transportAPI);
this.connect = (matchID, playerID, callback) => {
clientCallbacks[playerID] = callback;
};
this.subscribe(({ state, matchID }) => {
if (!bots) {
return;
}
const botPlayer = GetBotPlayer(state, initializedBots);
if (botPlayer !== null) {
setTimeout(async () => {
const botAction = await initializedBots[botPlayer].play(state, botPlayer);
await this.onUpdate(botAction.action, state._stateID, matchID, botAction.action.payload.playerID);
}, 100);
}
});
}
}
/**
* Local
*
* Transport interface that embeds a GameMaster within it
* that you can connect multiple clients to.
*/
class LocalTransport extends Transport {
/**
* Creates a new Mutiplayer instance.
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
*/
constructor({ master, ...opts }) {
super(opts);
this.master = master;
this.isConnected = true;
}
/**
* Called when any player sends a chat message and the
* master broadcasts the update to other clients (including
* this one).
*/
onChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.master.onChatMessage(...args);
}
/**
* Called when another player makes a move and the
* master broadcasts the update to other clients (including
* this one).
*/
async onUpdate(matchID, state, deltalog) {
const currentState = this.store.getState();
if (matchID == this.matchID && state._stateID >= currentState._stateID) {
const action = update$1(state, deltalog);
this.store.dispatch(action);
}
}
/**
* Called when the client first connects to the master
* and requests the current game state.
*/
onSync(matchID, syncInfo) {
if (matchID == this.matchID) {
const action = sync(syncInfo);
this.store.dispatch(action);
}
}
/**
* Called when an action that has to be relayed to the
* game master is made.
*/
onAction(state, action) {
this.master.onUpdate(action, state._stateID, this.matchID, this.playerID);
}
/**
* Connect to the master.
*/
connect() {
this.master.connect(this.matchID, this.playerID, (data) => {
switch (data.type) {
case 'sync':
return this.onSync(...data.args);
case 'update':
return this.onUpdate(...data.args);
case 'chat':
return this.chatMessageCallback(data.args[1]);
}
});
this.master.onSync(this.matchID, this.playerID, this.credentials, this.numPlayers);
}
/**
* Disconnect from the master.
*/
disconnect() { }
/**
* Subscribe to connection state changes.
*/
subscribe() { }
subscribeMatchData() { }
subscribeChatMessage(fn) {
this.chatMessageCallback = fn;
}
/**
* Dispatches a reset action, then requests a fresh sync from the master.
*/
resetAndSync() {
const action = reset(null);
this.store.dispatch(action);
this.connect();
}
/**
* Updates the game id.
* @param {string} id - The new game id.
*/
updateMatchID(id) {
this.matchID = id;
this.resetAndSync();
}
/**
* Updates the player associated with this client.
* @param {string} id - The new player id.
*/
updatePlayerID(id) {
this.playerID = id;
this.resetAndSync();
}
/**
* Updates the credentials associated with this client.
* @param {string|undefined} credentials - The new credentials to use.
*/
updateCredentials(credentials) {
this.credentials = credentials;
this.resetAndSync();
}
}
/**
* Global map storing local master instances.
*/
const localMasters = new Map();
/**
* Create a local transport.
*/
function Local({ bots, persist, storageKey } = {}) {
return (transportOpts) => {
const { gameKey, game } = transportOpts;
let master;
const instance = localMasters.get(gameKey);
if (instance &&
instance.bots === bots &&
instance.storageKey === storageKey &&
instance.persist === persist) {
master = instance.master;
}
if (!master) {
master = new LocalMaster({ game, bots, persist, storageKey });
localMasters.set(gameKey, { master, bots, persist, storageKey });
}
return new LocalTransport({ master, ...transportOpts });
};
}
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
const io = ioNamespace__default;
/**
* SocketIO
*
* Transport interface that interacts with the Master via socket.io.
*/
class SocketIOTransport extends Transport {
/**
* Creates a new Multiplayer instance.
* @param {object} socket - Override for unit tests.
* @param {object} socketOpts - Options to pass to socket.io.
* @param {object} store - Redux store
* @param {string} matchID - The game ID to connect to.
* @param {string} playerID - The player ID associated with this client.
* @param {string} credentials - Authentication credentials
* @param {string} gameName - The game type (the `name` field in `Game`).
* @param {string} numPlayers - The number of players.
* @param {string} server - The game server in the form of 'hostname:port'. Defaults to the server serving the client if not provided.
*/
constructor({ socket, socketOpts, server, ...opts } = {}) {
super(opts);
this.server = server;
this.socket = socket;
this.socketOpts = socketOpts;
this.isConnected = false;
this.callback = () => { };
this.matchDataCallback = () => { };
this.chatMessageCallback = () => { };
}
/**
* Called when an action that has to be relayed to the
* game master is made.
*/
onAction(state, action) {
const args = [
action,
state._stateID,
this.matchID,
this.playerID,
];
this.socket.emit('update', ...args);
}
onChatMessage(matchID, chatMessage) {
const args = [
matchID,
chatMessage,
this.credentials,
];
this.socket.emit('chat', ...args);
}
/**
* Connect to the server.
*/
connect() {
if (!this.socket) {
if (this.server) {
let server = this.server;
if (server.search(/^https?:\/\//) == -1) {
server = 'http://' + this.server;
}
if (server.slice(-1) != '/') {
// add trailing slash if not already present
server = server + '/';
}
this.socket = io(server + this.gameName, this.socketOpts);
}
else {
this.socket = io('/' + this.gameName, this.socketOpts);
}
}
// Called when another player makes a move and the
// master broadcasts the update as a patch to other clients (including
// this one).
this.socket.on('patch', (matchID, prevStateID, stateID, patch$1, deltalog) => {
const currentStateID = this.store.getState()._stateID;
if (matchID === this.matchID && prevStateID === currentStateID) {
const action = patch(prevStateID, stateID, patch$1, deltalog);
this.store.dispatch(action);
// emit sync if patch apply failed
if (this.store.getState()._stateID === currentStateID) {
this.sync();
}
}
});
// Called when another player makes a move and the
// master broadcasts the update to other clients (including
// this one).
this.socket.on('update', (matchID, state, deltalog) => {
const currentState = this.store.getState();
if (matchID == this.matchID &&
state._stateID >= currentState._stateID) {
const action = update$1(state, deltalog);
this.store.dispatch(action);
}
});
// Called when the client first connects to the master
// and requests the current game state.
this.socket.on('sync', (matchID, syncInfo) => {
if (matchID == this.matchID) {
const action = sync(syncInfo);
this.matchDataCallback(syncInfo.filteredMetadata);
this.store.dispatch(action);
}
});
// Called when new player joins the match or changes
// it's connection status
this.socket.on('matchData', (matchID, matchData) => {
if (matchID == this.matchID) {
this.matchDataCallback(matchData);
}
});
this.socket.on('chat', (matchID, chatMessage) => {
if (matchID === this.matchID) {
this.chatMessageCallback(chatMessage);
}
});
// Keep track of connection status.
this.socket.on('connect', () => {
// Initial sync to get game state.
this.sync();
this.isConnected = true;
this.callback();
});
this.socket.on('disconnect', () => {
this.isConnected = false;
this.callback();
});
}
/**
* Disconnect from the server.
*/
disconnect() {
this.socket.close();
this.socket = null;
this.isConnected = false;
this.callback();
}
/**
* Subscribe to connection state changes.
*/
subscribe(fn) {
this.callback = fn;
}
subscribeMatchData(fn) {
this.matchDataCallback = fn;
}
subscribeChatMessage(fn) {
this.chatMessageCallback = fn;
}
/**
* Send a “sync” event to the server.
*/
sync() {
if (this.socket) {
const args = [
this.matchID,
this.playerID,
this.credentials,
this.numPlayers,
];
this.socket.emit('sync', ...args);
}
}
/**
* Dispatches a reset action, then requests a fresh sync from the server.
*/
resetAndSync() {
const action = reset(null);
this.store.dispatch(action);
this.sync();
}
/**
* Updates the game id.
* @param {string} id - The new game id.
*/
updateMatchID(id) {
this.matchID = id;
this.resetAndSync();
}
/**
* Updates the player associated with this client.
* @param {string} id - The new player id.
*/
updatePlayerID(id) {
this.playerID = id;
this.resetAndSync();
}
/**
* Updates the credentials associated with this client.
* @param {string|undefined} credentials - The new credentials to use.
*/
updateCredentials(credentials) {
this.credentials = credentials;
this.resetAndSync();
}
}
function SocketIO({ server, socketOpts } = {}) {
return (transportOpts) => new SocketIOTransport({
server,
socketOpts,
...transportOpts,
});
}
export { Client, Local, MCTSBot, RandomBot, Client$1 as ReactClient, Client$2 as ReactNativeClient, Simulate, SocketIO, Step, TurnOrder };
|
ajax/libs/react-extras/3.0.0/choose.js | cdnjs/cdnjs | import React from 'react';
import PropTypes from 'prop-types';
import If from './if.js';
const Choose = props => {
let when = null;
let otherwise = null;
React.Children.forEach(props.children, children => {
if (children.props.condition === undefined) {
otherwise = children;
} else if (!when && children.props.condition === true) {
when = children;
}
});
return when || otherwise;
};
Choose.propTypes = {
children: PropTypes.node
};
Choose.When = If;
Choose.Otherwise = ({
render,
children
}) => render ? render() : children;
Choose.Otherwise.propTypes = {
children: PropTypes.node,
render: PropTypes.func
};
export default Choose; |
ajax/libs/material-ui/4.9.14/RootRef/RootRef.js | cdnjs/cdnjs | "use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var React = _interopRequireWildcard(require("react"));
var ReactDOM = _interopRequireWildcard(require("react-dom"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _utils = require("@material-ui/utils");
var _setRef = _interopRequireDefault(require("../utils/setRef"));
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
/**
* ⚠️⚠️⚠️
* If you want the DOM element of a Material-UI component check out
* [FAQ: How can I access the DOM element?](/getting-started/faq/#how-can-i-access-the-dom-element)
* first.
*
* This component uses `findDOMNode` which is deprecated in React.StrictMode.
*
* Helper component to allow attaching a ref to a
* wrapped element to access the underlying DOM element.
*
* It's highly inspired by https://github.com/facebook/react/issues/11401#issuecomment-340543801.
* For example:
* ```jsx
* import React from 'react';
* import RootRef from '@material-ui/core/RootRef';
*
* function MyComponent() {
* const domRef = React.useRef();
*
* React.useEffect(() => {
* console.log(domRef.current); // DOM node
* }, []);
*
* return (
* <RootRef rootRef={domRef}>
* <SomeChildComponent />
* </RootRef>
* );
* }
* ```
*/
var RootRef = /*#__PURE__*/function (_React$Component) {
(0, _inherits2.default)(RootRef, _React$Component);
var _super = _createSuper(RootRef);
function RootRef() {
(0, _classCallCheck2.default)(this, RootRef);
return _super.apply(this, arguments);
}
(0, _createClass2.default)(RootRef, [{
key: "componentDidMount",
value: function componentDidMount() {
this.ref = ReactDOM.findDOMNode(this);
(0, _setRef.default)(this.props.rootRef, this.ref);
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
var ref = ReactDOM.findDOMNode(this);
if (prevProps.rootRef !== this.props.rootRef || this.ref !== ref) {
if (prevProps.rootRef !== this.props.rootRef) {
(0, _setRef.default)(prevProps.rootRef, null);
}
this.ref = ref;
(0, _setRef.default)(this.props.rootRef, this.ref);
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
this.ref = null;
(0, _setRef.default)(this.props.rootRef, null);
}
}, {
key: "render",
value: function render() {
return this.props.children;
}
}]);
return RootRef;
}(React.Component);
process.env.NODE_ENV !== "production" ? RootRef.propTypes = {
/**
* The wrapped element.
*/
children: _propTypes.default.element.isRequired,
/**
* A ref that points to the first DOM node of the wrapped element.
*/
rootRef: _utils.refType.isRequired
} : void 0;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== "production" ? RootRef.propTypes = (0, _utils.exactProp)(RootRef.propTypes) : void 0;
}
var _default = RootRef;
exports.default = _default; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.